wrong-notebook 2026.10.23 → 2026.10.25-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +0 -1
- package/.next/build-manifest.json +208 -9
- package/.next/prerender-manifest.json +4 -4
- package/.next/required-server-files.json +16 -1
- package/.next/routes-manifest.json +0 -6
- package/.next/server/app/_global-error/page/build-manifest.json +8 -6
- package/.next/server/app/_global-error/page.js +9 -8
- package/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +18 -14
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +20 -16
- package/.next/server/app/_global-error.segments/_full.segment.rsc +18 -14
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +2 -1
- package/.next/server/app/_not-found/page/build-manifest.json +8 -6
- package/.next/server/app/_not-found/page.js +12 -12
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/admin/page/build-manifest.json +8 -6
- package/.next/server/app/admin/page.js +13 -13
- package/.next/server/app/admin/page.js.nft.json +1 -1
- package/.next/server/app/admin/page_client-reference-manifest.js +1 -1
- package/.next/server/app/admin/user/[id]/page/build-manifest.json +8 -6
- package/.next/server/app/admin/user/[id]/page.js +13 -13
- package/.next/server/app/admin/user/[id]/page.js.nft.json +1 -1
- package/.next/server/app/admin/user/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/api/admin/dashboard/route.js +20 -15
- package/.next/server/app/api/admin/dashboard/route.js.nft.json +1 -1
- package/.next/server/app/api/admin/migrate-tags/route.js +10 -8
- package/.next/server/app/api/admin/migrate-tags/route.js.nft.json +1 -1
- package/.next/server/app/api/admin/system-reset/route.js +9 -7
- package/.next/server/app/api/admin/system-reset/route.js.nft.json +1 -1
- package/.next/server/app/api/admin/users/[id]/detail/route.js +20 -15
- package/.next/server/app/api/admin/users/[id]/detail/route.js.nft.json +1 -1
- package/.next/server/app/api/admin/users/[id]/route.js +10 -7
- package/.next/server/app/api/admin/users/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/admin/users/route.js +10 -7
- package/.next/server/app/api/admin/users/route.js.nft.json +1 -1
- package/.next/server/app/api/ai/models/route.js +17 -13
- package/.next/server/app/api/ai/models/route.js.nft.json +1 -1
- package/.next/server/app/api/ai/test/route.js +18 -14
- package/.next/server/app/api/ai/test/route.js.nft.json +1 -1
- package/.next/server/app/api/analytics/route.js +12 -8
- package/.next/server/app/api/analytics/route.js.nft.json +1 -1
- package/.next/server/app/api/analyze/route.js +19 -15
- package/.next/server/app/api/analyze/route.js.nft.json +1 -1
- package/.next/server/app/api/auth/[...nextauth]/route.js +8 -6
- package/.next/server/app/api/auth/[...nextauth]/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/delete/route.js +9 -7
- package/.next/server/app/api/error-items/[id]/delete/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/figure/route.js +19 -14
- package/.next/server/app/api/error-items/[id]/figure/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/fix-latex/route.js +19 -15
- package/.next/server/app/api/error-items/[id]/fix-latex/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/geogebra/route.js +17 -13
- package/.next/server/app/api/error-items/[id]/geogebra/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/image/route.js +11 -8
- package/.next/server/app/api/error-items/[id]/image/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/notes/route.js +9 -7
- package/.next/server/app/api/error-items/[id]/notes/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/practice-records/route.js +10 -7
- package/.next/server/app/api/error-items/[id]/practice-records/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/reanswer/route.js +19 -15
- package/.next/server/app/api/error-items/[id]/reanswer/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/retag/route.js +20 -15
- package/.next/server/app/api/error-items/[id]/retag/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/route.js +8 -6
- package/.next/server/app/api/error-items/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/svg-animation/route.js +19 -15
- package/.next/server/app/api/error-items/[id]/svg-animation/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/batch-delete/route.js +9 -7
- package/.next/server/app/api/error-items/batch-delete/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/clear/route.js +9 -7
- package/.next/server/app/api/error-items/clear/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/list/route.js +12 -9
- package/.next/server/app/api/error-items/list/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/route.js +23 -16
- package/.next/server/app/api/error-items/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/short/[shortId]/route.js +10 -7
- package/.next/server/app/api/error-items/short/[shortId]/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/similarity/route.js +11 -8
- package/.next/server/app/api/error-items/similarity/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js +20 -15
- package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/results/route.js +21 -15
- package/.next/server/app/api/exams/[id]/results/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/retry/route.js +20 -15
- package/.next/server/app/api/exams/[id]/retry/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/route.js +18 -13
- package/.next/server/app/api/exams/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/route.js +20 -15
- package/.next/server/app/api/exams/route.js.nft.json +1 -1
- package/.next/server/app/api/export/route.js +12 -9
- package/.next/server/app/api/export/route.js.nft.json +1 -1
- package/.next/server/app/api/geogebra-analyze/route.js +19 -14
- package/.next/server/app/api/geogebra-analyze/route.js.nft.json +1 -1
- package/.next/server/app/api/health/route.js +7 -6
- package/.next/server/app/api/health/route.js.nft.json +1 -1
- package/.next/server/app/api/import/route.js +23 -16
- package/.next/server/app/api/import/route.js.nft.json +1 -1
- package/.next/server/app/api/logs/frontend/route.js +9 -7
- package/.next/server/app/api/logs/frontend/route.js.nft.json +1 -1
- package/.next/server/app/api/notebooks/[id]/retag/route.js +20 -15
- package/.next/server/app/api/notebooks/[id]/retag/route.js.nft.json +1 -1
- package/.next/server/app/api/notebooks/[id]/route.js +9 -8
- package/.next/server/app/api/notebooks/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/notebooks/route.js +11 -9
- package/.next/server/app/api/notebooks/route.js.nft.json +1 -1
- package/.next/server/app/api/openclaw/batch-upload/route.js +22 -14
- package/.next/server/app/api/openclaw/batch-upload/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/generate/route.js +19 -14
- package/.next/server/app/api/practice/generate/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/record/[id]/route.js +20 -14
- package/.next/server/app/api/practice/record/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/record/route.js +20 -15
- package/.next/server/app/api/practice/record/route.js.nft.json +1 -1
- package/.next/server/app/api/reanswer/route.js +19 -14
- package/.next/server/app/api/reanswer/route.js.nft.json +1 -1
- package/.next/server/app/api/register/route.js +9 -6
- package/.next/server/app/api/register/route.js.nft.json +1 -1
- package/.next/server/app/api/register/status/route.js +10 -7
- package/.next/server/app/api/register/status/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/route.js +12 -9
- package/.next/server/app/api/settings/route.js.nft.json +1 -1
- package/.next/server/app/api/stats/practice/clear/route.js +9 -7
- package/.next/server/app/api/stats/practice/clear/route.js.nft.json +1 -1
- package/.next/server/app/api/stats/practice/route.js +12 -8
- package/.next/server/app/api/stats/practice/route.js.nft.json +1 -1
- package/.next/server/app/api/tags/route.js +9 -8
- package/.next/server/app/api/tags/route.js.nft.json +1 -1
- package/.next/server/app/api/tags/stats/route.js +10 -7
- package/.next/server/app/api/tags/stats/route.js.nft.json +1 -1
- package/.next/server/app/api/tags/suggestions/route.js +9 -7
- package/.next/server/app/api/tags/suggestions/route.js.nft.json +1 -1
- package/.next/server/app/api/tasks/route.js +10 -7
- package/.next/server/app/api/tasks/route.js.nft.json +1 -1
- package/.next/server/app/api/user/route.js +11 -9
- package/.next/server/app/api/user/route.js.nft.json +1 -1
- package/.next/server/app/api/version/route.js +7 -6
- package/.next/server/app/api/version/route.js.nft.json +1 -1
- package/.next/server/app/error-items/[id]/page/build-manifest.json +8 -6
- package/.next/server/app/error-items/[id]/page.js +13 -13
- package/.next/server/app/error-items/[id]/page.js.nft.json +1 -1
- package/.next/server/app/error-items/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/[id]/page/build-manifest.json +8 -6
- package/.next/server/app/exams/[id]/page.js +13 -13
- package/.next/server/app/exams/[id]/page.js.nft.json +1 -1
- package/.next/server/app/exams/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/[id]/print/page/build-manifest.json +8 -6
- package/.next/server/app/exams/[id]/print/page.js +13 -13
- package/.next/server/app/exams/[id]/print/page.js.nft.json +1 -1
- package/.next/server/app/exams/[id]/print/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/page/build-manifest.json +8 -6
- package/.next/server/app/exams/page.js +13 -13
- package/.next/server/app/exams/page.js.nft.json +1 -1
- package/.next/server/app/exams/page_client-reference-manifest.js +1 -1
- package/.next/server/app/favicon.ico/route.js +7 -7
- package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
- package/.next/server/app/login/page/build-manifest.json +8 -6
- package/.next/server/app/login/page.js +13 -13
- package/.next/server/app/login/page.js.nft.json +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/manifest.webmanifest/route.js +7 -7
- package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
- package/.next/server/app/notebooks/[id]/add/page/build-manifest.json +8 -6
- package/.next/server/app/notebooks/[id]/add/page.js +13 -13
- package/.next/server/app/notebooks/[id]/add/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/[id]/add/page_client-reference-manifest.js +1 -1
- package/.next/server/app/notebooks/[id]/page/build-manifest.json +8 -6
- package/.next/server/app/notebooks/[id]/page.js +13 -13
- package/.next/server/app/notebooks/[id]/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/notebooks/page/build-manifest.json +8 -6
- package/.next/server/app/notebooks/page.js +13 -13
- package/.next/server/app/notebooks/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/page_client-reference-manifest.js +1 -1
- package/.next/server/app/page/build-manifest.json +8 -6
- package/.next/server/app/page.js +13 -13
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/practice/page/build-manifest.json +8 -6
- package/.next/server/app/practice/page.js +13 -13
- package/.next/server/app/practice/page.js.nft.json +1 -1
- package/.next/server/app/practice/page_client-reference-manifest.js +1 -1
- package/.next/server/app/print-preview/page/build-manifest.json +8 -6
- package/.next/server/app/print-preview/page.js +13 -13
- package/.next/server/app/print-preview/page.js.nft.json +1 -1
- package/.next/server/app/print-preview/page_client-reference-manifest.js +1 -1
- package/.next/server/app/register/page/build-manifest.json +8 -6
- package/.next/server/app/register/page.js +11 -11
- package/.next/server/app/register/page.js.nft.json +1 -1
- package/.next/server/app/register/page_client-reference-manifest.js +1 -1
- package/.next/server/app/stats/page/build-manifest.json +8 -6
- package/.next/server/app/stats/page.js +13 -13
- package/.next/server/app/stats/page.js.nft.json +1 -1
- package/.next/server/app/stats/page_client-reference-manifest.js +1 -1
- package/.next/server/app/tags/page/build-manifest.json +8 -6
- package/.next/server/app/tags/page.js +13 -13
- package/.next/server/app/tags/page.js.nft.json +1 -1
- package/.next/server/app/tags/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +0 -1
- package/.next/server/chunks/0ivl_api_exams_[id]_questions_[questionId]_regenerate_route_actions_1ggead3ywjhli.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_admin_users_[id]_detail_route_actions_0oe_wktcsiz6j.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_delete_route_actions_1w26boq5bpk6f.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_figure_route_actions_0adlts0sguhrk.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_fix-latex_route_actions_0hc7dhxtl9kc9.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_geogebra_route_actions_1-ks4uvettiij.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_practice-records_route_actions_0z2zuf1oxdmh0.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_reanswer_route_actions_1-sw0j2l65i8t.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_svg-animation_route_actions_17gckf3idsy15.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_batch-delete_route_actions_0hiq_1kd60tc2.js +3 -0
- package/.next/server/chunks/1oeh_server_app_api_error-items_short_[shortId]_route_actions_02976v-fif6-5.js +3 -0
- package/.next/server/chunks/[externals]__04n7qbralh87n._.js +3 -0
- package/.next/server/chunks/[externals]__0jzwjtlwxxyw6._.js +3 -0
- package/.next/server/chunks/[externals]__0pot68n2q47fn._.js +3 -0
- package/.next/server/chunks/[externals]__1oyo6y4k5ao25._.js +3 -0
- package/.next/server/chunks/[externals]__1yyxisf-dquqj._.js +3 -0
- package/.next/server/chunks/[externals]_assert_1pwe1ri__g5hw._.js +3 -0
- package/.next/server/chunks/[externals]_fs_0pplqgcyv2l7l._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0-g6zoywy7s9r._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0-i5scl3dk6sv._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0-odhmcsbillm._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__003ii50e63ws5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__02izfhede1ge6._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__04k4sy605shy8._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__082k83j3p6okz._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__08p0s4r9g87cn._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0_a858mm6ofp3._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0_t7bbz2btvts._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0a-kmd7e0p8db._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0an9s6-nn3kpq._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0b6q7yr-sfcet._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0g-kb21pws7qu._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0hbqxdkp_1j_7._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0hjv7gm7tjgzr._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0kva0deskq80y._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0l7y2xk1m7h84._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0l9qwcb4i27ui._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0ld-3rbaj1m8-._.js +56 -0
- package/.next/server/chunks/[root-of-the-server]__0majzhfobp3nf._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0mc5h4iz6ua87._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0nrxl8lqbzwov._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0nzkvmeik_rk5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0pqggfowif112._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0qvrt0t4xthie._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0rbqws43qszln._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0rg4hkgdxbjou._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0rk_yxyba4meu._.js +9 -0
- package/.next/server/chunks/[root-of-the-server]__0ssrmihfi_u6m._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0w2rkt8xlhqw8._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0ycg3q_q562tz._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0ystefe8_e0es._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0zjg773epx4r_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__122xu-0xjk0q5._.js +32 -0
- package/.next/server/chunks/[root-of-the-server]__139pkgh2w4wv7._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__13fue_8ln57sk._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__14-kwm6jhtwo2._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__15nya_6vffdj1._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__15s-n6e06wf6g._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__15tkoe60wvpdf._.js +10 -0
- package/.next/server/chunks/[root-of-the-server]__17rozs-xk_dqd._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__17xqc8-y_hmhm._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__18j9-n7s671bt._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1_gkx5xy1-3em._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1_kq0iosz0cgh._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1a8nqxs0k1ue0._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1biigyx-bi52y._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1bmd4mech7kzj._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1bswuhivogp5u._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1e_3xwt459gzy._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1epfgldsr-ls5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1fc23i58z_ao2._.js +122 -0
- package/.next/server/chunks/[root-of-the-server]__1hejjxeb6bmtm._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1iydd43toz2hx._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1j6jbtj3gauq_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1jfwn22nquvq-._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1jtd2ara5taim._.js +6 -0
- package/.next/server/chunks/[root-of-the-server]__1k73w0dqrm6gg._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1k_8n_p3i4my_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1msj6a3i2of1g._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1nmtv65uajre3._.js +10 -0
- package/.next/server/chunks/[root-of-the-server]__1q6zz6-dwz42t._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1qv23loqhxkcf._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1rcitv6tfajfz._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1tczl61nfeymj._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1ve3j8ooyhjgv._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1vgkjjilvagrv._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1vj-su-vkz4ng._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1vw740yzcybw7._.js +32 -0
- package/.next/server/chunks/[root-of-the-server]__1y_u-tq43pxmc._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1yva3qsip39_n._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1zyka21s1ahtj._.js +3 -0
- package/.next/server/chunks/[turbopack]_runtime.js +146 -16
- package/.next/server/chunks/_0-ne-bwuvd_6w._.js +3 -0
- package/.next/server/chunks/_011-ll5i30j2e._.js +3 -0
- package/.next/server/chunks/_029zt0rilrwvt._.js +3 -0
- package/.next/server/chunks/_03ovgh1-4xf3f._.js +3 -0
- package/.next/server/chunks/_0431fxnqiloso._.js +3 -0
- package/.next/server/chunks/_07amw8ha9rney._.js +3 -0
- package/.next/server/chunks/_0_3_65z6ak-5i._.js +3 -0
- package/.next/server/chunks/_0_e736ff6uhew._.js +3 -0
- package/.next/server/chunks/_0anbzuivml30d._.js +3 -0
- package/.next/server/chunks/_0at03z7sgwdv3._.js +3 -0
- package/.next/server/chunks/_0axy8rynlghzq._.js +3 -0
- package/.next/server/chunks/_0d66myj_8567o._.js +3 -0
- package/.next/server/chunks/_0ekrwj-qx_6uh._.js +36 -0
- package/.next/server/chunks/_0geyrqrvyak26._.js +11 -0
- package/.next/server/chunks/_0gxi3zrkhyvx_._.js +3 -0
- package/.next/server/chunks/_0h1rbua_hqkox._.js +3 -0
- package/.next/server/chunks/_0kkvpy2s_y3-n._.js +11 -0
- package/.next/server/chunks/_0kreo-8xn80hb._.js +3 -0
- package/.next/server/chunks/_0l2j3br2g32zp._.js +3 -0
- package/.next/server/chunks/_0lz3t4lsygbtv._.js +19 -0
- package/.next/server/chunks/_0ne4rbj35w-io._.js +11 -0
- package/.next/server/chunks/_0qaoat396e0_3._.js +3 -0
- package/.next/server/chunks/_0qsjdkq-39qbo._.js +11 -0
- package/.next/server/chunks/_0tl0cy5j96d7h._.js +3 -0
- package/.next/server/chunks/_0uxp3uhmyw1h3._.js +3 -0
- package/.next/server/chunks/_0wegi_sv1s4wx._.js +3 -0
- package/.next/server/chunks/_0x3ltk09eli_f._.js +36 -0
- package/.next/server/chunks/_0z0zrluul2idw._.js +3 -0
- package/.next/server/chunks/_0zs7jfzzshbfq._.js +3 -0
- package/.next/server/chunks/_11w6ynlxuzl55._.js +3 -0
- package/.next/server/chunks/_12i51zlq-xxrl._.js +3 -0
- package/.next/server/chunks/_12w5k19rc45j_._.js +3 -0
- package/.next/server/chunks/_13ffmxv8qrwi0._.js +3 -0
- package/.next/server/chunks/_14tz_k9desx4n._.js +3 -0
- package/.next/server/chunks/_14w9nrdlajz24._.js +3 -0
- package/.next/server/chunks/_15fpgekhvv214._.js +3 -0
- package/.next/server/chunks/_16jdov0rxh99d._.js +3 -0
- package/.next/server/chunks/_17zw8m241gfs3._.js +3 -0
- package/.next/server/chunks/_18amra5328v90._.js +3 -0
- package/.next/server/chunks/_18hm5aaxkr500._.js +3 -0
- package/.next/server/chunks/_1_273cgnpyl9j._.js +3 -0
- package/.next/server/chunks/_1_ns7o3cqznv6._.js +3 -0
- package/.next/server/chunks/_1a1aqmie1d3u_._.js +3 -0
- package/.next/server/chunks/_1a1udq0c4_6ad._.js +3 -0
- package/.next/server/chunks/_1b0269xt-c8f7._.js +3 -0
- package/.next/server/chunks/_1b7qjlv0nxovi._.js +3 -0
- package/.next/server/chunks/_1be-y660a8z-q._.js +3 -0
- package/.next/server/chunks/_1cydcmia78z15._.js +3 -0
- package/.next/server/chunks/_1e8w9uuebtrcb._.js +3 -0
- package/.next/server/chunks/_1ex6ovo_j2jzv._.js +3 -0
- package/.next/server/chunks/_1fgb9ve_nfat4._.js +3 -0
- package/.next/server/chunks/_1hj7iit2u6xez._.js +3 -0
- package/.next/server/chunks/_1lrt8e26anbnm._.js +11 -0
- package/.next/server/chunks/_1m-yyz-pl9-03._.js +3 -0
- package/.next/server/chunks/_1pvqo-qnv-nqm._.js +3 -0
- package/.next/server/chunks/_1q65ai1_dwgjp._.js +3 -0
- package/.next/server/chunks/_1s5-ldt8xhtpp._.js +3 -0
- package/.next/server/chunks/_1sp0xk1c5jx5r._.js +3 -0
- package/.next/server/chunks/_1taeg5t2ai7_x._.js +3 -0
- package/.next/server/chunks/_1tjis3pqfxk7_._.js +3 -0
- package/.next/server/chunks/_1vtmdpk7p4al9._.js +3 -0
- package/.next/server/chunks/_1wulydy4wg9ow._.js +3 -0
- package/.next/server/chunks/_1xpj9uk-9zhl8._.js +3 -0
- package/.next/server/chunks/_1y5_49ip8l9oe._.js +3 -0
- package/.next/server/chunks/_1z_ujac_e_65s._.js +3 -0
- package/.next/server/chunks/_211va-dk9519v._.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_admin_dashboard_route_actions_1ispso-r2eove.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_admin_migrate-tags_route_actions_1ztwxhx.js → _next-internal_server_app_api_admin_migrate-tags_route_actions_1ztwxhxi2qsxd.js} +1 -1
- package/.next/server/chunks/{_next-internal_server_app_api_admin_system-reset_route_actions_15aselt.js → _next-internal_server_app_api_admin_system-reset_route_actions_15aseltajrio-.js} +1 -1
- package/.next/server/chunks/{_next-internal_server_app_api_admin_users_[id]_route_actions_1hhpuc4.js → _next-internal_server_app_api_admin_users_[id]_route_actions_1hhpuc4kr8kus.js} +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_admin_users_route_actions_0q-rtz1e15wl4.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_ai_models_route_actions_0w7iwv-_fbzuj.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_ai_test_route_actions_1p0n1q8zn22_3.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_analytics_route_actions_1e0ou17qxwn3t.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_analyze_route_actions_0lx-23h7r4czj.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_auth_[___nextauth]_route_actions_08nexdks3z54l.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_image_route_actions_1k9n5ylrz4c3i.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_error-items_[id]_notes_route_actions_1cjux7z.js → _next-internal_server_app_api_error-items_[id]_notes_route_actions_1cjux7zwbv-yr.js} +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_retag_route_actions_0ckki4nf1m1rv.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_route_actions_1kbs4uxgcnwcc.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_clear_route_actions_14t_6i-b4usht.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_list_route_actions_032x4ue0aseaq.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_route_actions_1zdvz0pe68kn6.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_error-items_similarity_route_actions_1i26if9-yrnuz.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_exams_[id]_results_route_actions_1v3vhi4.js → _next-internal_server_app_api_exams_[id]_results_route_actions_1v3vhi4cjl6y6.js} +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_exams_[id]_retry_route_actions_1fdi39f5xqz2a.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_exams_[id]_route_actions_1wuidrq8qisud.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_exams_route_actions_1c_zhtj.js → _next-internal_server_app_api_exams_route_actions_1c_zhtjquazbz.js} +2 -2
- package/.next/server/chunks/{_next-internal_server_app_api_export_route_actions_0lpcnjc.js → _next-internal_server_app_api_export_route_actions_0lpcnjc9jg57-.js} +2 -2
- package/.next/server/chunks/_next-internal_server_app_api_geogebra-analyze_route_actions_1xng0_cc6l98n.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_health_route_actions_1ryftkb.js → _next-internal_server_app_api_health_route_actions_1ryftkbeskq31.js} +2 -2
- package/.next/server/chunks/{_next-internal_server_app_api_import_route_actions_20ko04x.js → _next-internal_server_app_api_import_route_actions_20ko04xh42fpe.js} +2 -2
- package/.next/server/chunks/_next-internal_server_app_api_logs_frontend_route_actions_0nxeptyjby8s8.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_[id]_retag_route_actions_00su_t80igzxy.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_[id]_route_actions_11j3vxgeuqf90.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_route_actions_02cy45r04tykl.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_openclaw_batch-upload_route_actions_1zz3oenvuk9lp.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_practice_generate_route_actions_1krr9n_f0vpz7.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_practice_record_[id]_route_actions_0zreiomdy_l4b.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_practice_record_route_actions_0py9z__efurdf.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_reanswer_route_actions_04xweh_hfqgvy.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_register_route_actions_0vlzh_c4r8obw.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_register_status_route_actions_0b52_sjq7yjzh.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_settings_route_actions_1bpm9acuq1z18.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_stats_practice_clear_route_actions_1iz6iz0hyvj4g.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_stats_practice_route_actions_1tfoxx-2uzhl0.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_tags_route_actions_1nb9ma2.js → _next-internal_server_app_api_tags_route_actions_1nb9ma2pi6m41.js} +2 -2
- package/.next/server/chunks/_next-internal_server_app_api_tags_stats_route_actions_0fmeadc45lqi1.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_tags_suggestions_route_actions_1xpolyvywz3qh.js +3 -0
- package/.next/server/chunks/{_next-internal_server_app_api_tasks_route_actions_123tq1_.js → _next-internal_server_app_api_tasks_route_actions_123tq1_b3dlgw.js} +2 -2
- package/.next/server/chunks/{_next-internal_server_app_api_user_route_actions_1k-4clg.js → _next-internal_server_app_api_user_route_actions_1k-4clgaupijh.js} +1 -1
- package/.next/server/chunks/{_next-internal_server_app_api_version_route_actions_0kbx30h.js → _next-internal_server_app_api_version_route_actions_0kbx30hro8e93.js} +1 -1
- package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_0g2jjlssn1kss.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_manifest_webmanifest_route_actions_08hcpz02cjxld.js +3 -0
- package/.next/server/chunks/node_modules_@anthropic-ai_sdk_1nnmjtbtp2rc6._.js +3 -0
- package/.next/server/chunks/node_modules_next_1zdbrneapig6o._.js +10 -0
- package/.next/server/chunks/node_modules_node-fetch_src_utils_multipart-parser_0a9aeam58e52_.js +3 -0
- package/.next/server/chunks/node_modules_zod_v4_classic_external_19886v847zvfd.js +3 -0
- package/.next/server/chunks/node_modules_zod_v4_classic_external_1h9u5hd8e7zk0.js +57 -0
- package/.next/server/chunks/src_0tzpy5j8n_1bx._.js +3 -0
- package/.next/server/chunks/src_lib_01n35ubnvj7qr._.js +3 -0
- package/.next/server/chunks/src_lib_05svhzm9a162-._.js +3 -0
- package/.next/server/chunks/src_lib_0if7dmbrjhhw_._.js +3 -0
- package/.next/server/chunks/src_lib_0zxy_zn_mlaya._.js +3 -0
- package/.next/server/chunks/src_lib_1-tw3_3nqx6ug._.js +3 -0
- package/.next/server/chunks/src_lib_15kwif87cuv22._.js +3 -0
- package/.next/server/chunks/src_lib_1geq39r7va9gy._.js +3 -0
- package/.next/server/chunks/src_lib_1k0xki4wmn54_._.js +3 -0
- package/.next/server/chunks/src_lib_1wgxqrl1loni_._.js +3 -0
- package/.next/server/chunks/src_lib_1wh1pqmstnzzt._.js +3 -0
- package/.next/server/chunks/src_lib_1wm8ay-jqxakc._.js +3 -0
- package/.next/server/chunks/{src_lib_ai_prompts_ts_0z36zms._.js → src_lib_ai_prompts_ts_0z36zms4djibp._.js} +52 -52
- package/.next/server/chunks/src_lib_auth-utils_ts_20i7biv4dj8pm._.js +3 -0
- package/.next/server/chunks/src_lib_current-user_ts_20jgxch2zjmt3._.js +3 -0
- package/.next/server/chunks/src_lib_date-time_ts_14chb270f3epb._.js +3 -0
- package/.next/server/chunks/src_lib_exam_ts_0d3a4q4r41hcf._.js +3 -0
- package/.next/server/chunks/src_lib_logger_ts_067l8txrna0gg._.js +3 -0
- package/.next/server/chunks/src_lib_mastery_ts_0ybi94uxn8ut6._.js +3 -0
- package/.next/server/chunks/src_lib_question-deduplication_ts_1p1bik-vwl9ue._.js +3 -0
- package/.next/server/chunks/src_lib_retag_ts_0eu8ld_86kt3a._.js +3 -0
- package/.next/server/chunks/src_lib_tag-recognition_ts_1wkzrdiapau86._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__03jq7w4crcz_u._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__070lhtl_a6l81._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0egzlmtf23a_j._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0fl_sbe1q-l5j._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0i73t4kmj3-mp._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0py1t7q9ntzgc._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0s0807tegp2v8._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0snw-y9tp0_06._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0ujgpq398o2w1._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0uulvxrtw9ld4._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0x_ihemma9171._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0zqp_pztbsqqc._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__102i99h9qhhnc._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__18ej8rcn5j4hs._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__18sucwsgl0hdl._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1a50a5t_t8z_e._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1b9f3v7g4ocyf._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1gulcy2-2jrfj._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1hcwd0rtvz96c._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1i2zrji0j2c3l._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1qpe9xti5ipq0._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1qpi6ed0efnfg._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1qwt10yvul4gg._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1upv9f0hlagx7._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1uw-g6-ij61rl._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1vwegr-t8j6qe._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1xfc5gf4weasu._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1xufj5ntr9bm3._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1yy2y09x1rvba._.js +3 -0
- package/.next/server/chunks/ssr/[turbopack]_runtime.js +146 -16
- package/.next/server/chunks/ssr/_00np6xqvkg6u-._.js +32 -0
- package/.next/server/chunks/ssr/_04qlm-w8tebyc._.js +3 -0
- package/.next/server/chunks/ssr/_065hikzgj3xg_._.js +3 -0
- package/.next/server/chunks/ssr/_08fq-uch-l1g6._.js +8 -0
- package/.next/server/chunks/ssr/_0bsjhzelppbjh._.js +3 -0
- package/.next/server/chunks/ssr/_0h6qsip9mphaq._.js +3 -0
- package/.next/server/chunks/ssr/_0lloy6tp9ov8e._.js +3 -0
- package/.next/server/chunks/ssr/_0pxsg9p6gub85._.js +3 -0
- package/.next/server/chunks/ssr/_0t2jed64ec8vu._.js +3 -0
- package/.next/server/chunks/ssr/_0xey1vceqp1wd._.js +3 -0
- package/.next/server/chunks/ssr/_1-bq77e5afl30._.js +3 -0
- package/.next/server/chunks/ssr/_1-sbpqghw1pn7._.js +3 -0
- package/.next/server/chunks/ssr/_110r17vqu8gol._.js +3 -0
- package/.next/server/chunks/ssr/_14d3enlxi54zl._.js +3 -0
- package/.next/server/chunks/ssr/_17edi6l2a0p76._.js +8 -0
- package/.next/server/chunks/ssr/_17igtpd3u0nhq._.js +3 -0
- package/.next/server/chunks/ssr/_19zbvpk25l83u._.js +3 -0
- package/.next/server/chunks/ssr/_1b9b1aq5b_1sj._.js +3 -0
- package/.next/server/chunks/ssr/_1cl6e0rtwi75o._.js +3 -0
- package/.next/server/chunks/ssr/_1em_7aul52rb4._.js +3 -0
- package/.next/server/chunks/ssr/_1f1l6ubybak3a._.js +3 -0
- package/.next/server/chunks/ssr/_1g12ubvpxwe-j._.js +3 -0
- package/.next/server/chunks/ssr/_1g8mzz6qxv2mr._.js +3 -0
- package/.next/server/chunks/ssr/_1wfh-5dxhj11n._.js +3 -0
- package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-psc_d2.js +3 -0
- package/.next/server/chunks/ssr/{_next-internal_server_app__not-found_page_actions_0pt47yr.js → _next-internal_server_app__not-found_page_actions_0pt47yrisjoev.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_admin_page_actions_1mcickz.js → _next-internal_server_app_admin_page_actions_1mcickzfofbmo.js} +2 -2
- package/.next/server/chunks/ssr/_next-internal_server_app_admin_user_[id]_page_actions_0baj8gsw9br4u.js +3 -0
- package/.next/server/chunks/ssr/_next-internal_server_app_error-items_[id]_page_actions_0qla9akl69m75.js +3 -0
- package/.next/server/chunks/ssr/{_next-internal_server_app_exams_[id]_page_actions_1kushg5.js → _next-internal_server_app_exams_[id]_page_actions_1kushg5crt5ed.js} +1 -1
- package/.next/server/chunks/ssr/_next-internal_server_app_exams_[id]_print_page_actions_0pxdgxqldskme.js +3 -0
- package/.next/server/chunks/ssr/{_next-internal_server_app_exams_page_actions_0av69f-.js → _next-internal_server_app_exams_page_actions_0av69f-jb4_80.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_login_page_actions_04fnjo0.js → _next-internal_server_app_login_page_actions_04fnjo0ny9dmg.js} +2 -2
- package/.next/server/chunks/ssr/_next-internal_server_app_notebooks_[id]_add_page_actions_0275ft2lc_po5.js +3 -0
- package/.next/server/chunks/ssr/_next-internal_server_app_notebooks_[id]_page_actions_1qj0i-7tmcbrj.js +3 -0
- package/.next/server/chunks/ssr/{_next-internal_server_app_notebooks_page_actions_06x1kdz.js → _next-internal_server_app_notebooks_page_actions_06x1kdz034ff8.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_page_actions_0hhsz1j.js → _next-internal_server_app_page_actions_0hhsz1jew5ls7.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_practice_page_actions_0cy-h5n.js → _next-internal_server_app_practice_page_actions_0cy-h5n6gnmoq.js} +2 -2
- package/.next/server/chunks/ssr/_next-internal_server_app_print-preview_page_actions_1jhaalnnytwbd.js +3 -0
- package/.next/server/chunks/ssr/{_next-internal_server_app_register_page_actions_1op-s-x.js → _next-internal_server_app_register_page_actions_1op-s-xpplkgy.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_stats_page_actions_1olf1_a.js → _next-internal_server_app_stats_page_actions_1olf1_ad6s7ee.js} +2 -2
- package/.next/server/chunks/ssr/{_next-internal_server_app_tags_page_actions_20v_n--.js → _next-internal_server_app_tags_page_actions_20v_n--6ltjkg.js} +1 -1
- package/.next/server/chunks/ssr/node_modules_0gxlxpuufujz9._.js +33 -0
- package/.next/server/chunks/ssr/node_modules_1y5ym6hiirb6m._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_@radix-ui_0im69oqv_i2ki._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_@radix-ui_0zibxpne20gfo._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_@radix-ui_react-roving-focus_dist_index_mjs_0jdjq3jxbmizo._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_15-zi1i74qu9j._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_1_p6srzucwl-s._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_1g_su6v6_1gmz._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_printer_0pprvafgadlwd.js +3 -0
- package/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_wand-sparkles_1e4rylzm0nkbv.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +6 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_0ufsi7bhcumza._.js +23 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_1g0hsq_f-fygr._.js +14 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_1gey_lsf9b_wo._.js +5 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0bew68i643j53._.js +33 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j32_ibz4._.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0symwr9mbf-fh.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0q-w892nagajq.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0l_sp0xky89qu.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0-620erc29b8l.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_02t4jbzz34_x5.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_06zp_1r4dyujd.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_07zpyh6_aix9e.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_08b8vpe4ydv2l.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0927yli_zsjiv.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0ab39qicq17ku.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0dq5iwc4xesq1.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0mfa8uq-ofoud.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_14rvnul2svrv8.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_15yshykizhy_t.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_17vx074zs1h7f.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_18uzvmzy5tpu_.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_196bmtjcgr159.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1aq9r3iw9g7qi.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1e1odqisoi2pv.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1l6unubiwsg9f.js +3 -0
- package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1ya73f4o4_7mr.js +3 -0
- package/.next/server/chunks/ssr/src_13u20tdu4gmgj._.js +3 -0
- package/.next/server/chunks/ssr/src_1gayunqs8u2e2._.js +3 -0
- package/.next/server/chunks/ssr/src_app_admin_page_tsx_0ublbd0w90cx_._.js +3 -0
- package/.next/server/chunks/ssr/src_app_admin_user_[id]_page_tsx_0zidp-8hr5upa._.js +3 -0
- package/.next/server/chunks/ssr/src_app_error-items_[id]_page_tsx_04xwwdmyh7_9q._.js +3 -0
- package/.next/server/chunks/ssr/src_app_exams_[id]_page_tsx_0xcjflkgkwzgd._.js +3 -0
- package/.next/server/chunks/ssr/src_app_exams_[id]_print_page_tsx_1i-xvhk8ul1l1._.js +35 -0
- package/.next/server/chunks/ssr/src_app_exams_page_tsx_17_d4_gy2i1ds._.js +3 -0
- package/.next/server/chunks/ssr/src_app_login_page_tsx_0yrgg2z_juzv9._.js +3 -0
- package/.next/server/chunks/ssr/src_app_notebooks_[id]_add_page_tsx_179tow1ql6vc_._.js +3 -0
- package/.next/server/chunks/ssr/src_app_notebooks_[id]_page_tsx_08njm-5-txm8_._.js +3 -0
- package/.next/server/chunks/ssr/src_app_notebooks_page_tsx_1p9src5gnz_40._.js +3 -0
- package/.next/server/chunks/ssr/src_app_page_tsx_1chiuahujsxm1._.js +3 -0
- package/.next/server/chunks/ssr/src_app_practice_page_tsx_10gnx53v3kpzb._.js +3 -0
- package/.next/server/chunks/ssr/src_app_print-preview_page_tsx_001yt-fzrj7tf._.js +3 -0
- package/.next/server/chunks/ssr/src_app_register_page_tsx_0l87b3754fa2j._.js +3 -0
- package/.next/server/chunks/ssr/src_app_tags_page_tsx_1h2vkk4hv_zlp._.js +3 -0
- package/.next/server/chunks/ssr/src_components_difficulty-stars_tsx_1af9qqfurq7_t._.js +3 -0
- package/.next/server/chunks/ssr/src_components_mastery-panel_tsx_1--j5c7mhomdp._.js +3 -0
- package/.next/server/chunks/ssr/src_components_practice-result-picker_tsx_06jytymet6adu._.js +3 -0
- package/.next/server/chunks/ssr/src_components_providers_tsx_09kw-mv3nb6xs._.js +193 -0
- package/.next/server/chunks/ssr/src_components_settings_duplicate-threshold-setting_tsx_06bbmwo1pkaim._.js +3 -0
- package/.next/server/chunks/ssr/src_components_tag-input_tsx_0b9sxffna5c9i._.js +3 -0
- package/.next/server/chunks/ssr/src_components_ui_checkbox_tsx_0xdylzmai9n53._.js +3 -0
- package/.next/server/chunks/ssr/src_components_ui_dialog_tsx_1tn-i_6d3rhzt._.js +7 -0
- package/.next/server/chunks/ssr/src_components_ui_tabs_tsx_0skssvsquc-9c._.js +3 -0
- package/.next/server/chunks/ssr/src_lib_constants_pagination_ts_02h78dpuabai5._.js +3 -0
- package/.next/server/chunks/ssr/src_lib_date-time_ts_0oyqctny6_q66._.js +3 -0
- package/.next/server/edge/chunks/[root-of-the-server]__1osrt2u3yic3e._.js +3 -0
- package/.next/server/edge/chunks/_1s0wgnupch4sb._.js +3 -0
- package/.next/server/edge/chunks/node_modules_0um8zwzayafzq._.js +13 -0
- package/.next/server/edge/chunks/turbopack-node_modules_next_dist_esm_build_templates_edge-wrapper_0dxg4rr5z738i.js +3 -0
- package/.next/server/edge/chunks/turbopack-node_modules_next_dist_esm_build_templates_edge-wrapper_0dzf5yhexv02u.js +3 -0
- package/.next/server/instrumentation.js +3 -3
- package/.next/server/middleware-build-manifest.js +208 -9
- package/.next/server/middleware-manifest.json +11 -11
- package/.next/server/next-font-manifest.js +1 -1
- package/.next/server/next-font-manifest.json +0 -4
- package/.next/server/pages/500.html +1 -1
- package/.next/server/preview-props.json +5 -0
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/02arashg5z9hy.js +1 -0
- package/.next/static/chunks/030eh13-7xvy7.js +1 -0
- package/.next/static/chunks/07zxudgwttnwv.js +6 -0
- package/.next/static/chunks/089-9u4pe2h49.js +1 -0
- package/.next/static/chunks/093w4w_19h9qh.js +31 -0
- package/.next/static/chunks/0a-rekt06v0sv.js +1 -0
- package/.next/static/chunks/0dlztx_6_yfcq.js +1 -0
- package/.next/static/chunks/0e7mao0hn_nw4.js +1 -0
- package/.next/static/chunks/0fiebviba_0be.js +33 -0
- package/.next/static/chunks/0ipduzu-11mee.js +1 -0
- package/.next/static/chunks/0myk7euf03qwr.js +1 -0
- package/.next/static/chunks/0s6zcnahk3us4.js +5 -0
- package/.next/static/chunks/0ub8l5nongf_r.js +1 -0
- package/.next/static/chunks/0ykhi6pk49so-.js +1 -0
- package/.next/static/chunks/14a1tth-1ddn-.js +1 -0
- package/.next/static/chunks/15e5p9740moee.js +1 -0
- package/.next/static/chunks/19js5h26_4w0w.js +1 -0
- package/.next/static/chunks/1_h2h09t_394a.js +1 -0
- package/.next/static/chunks/1fhxsoq06x1_e.js +1 -0
- package/.next/static/chunks/1fl98iro7y1bv.js +1 -0
- package/.next/static/chunks/1kq7w30gvsyaq.js +1 -0
- package/.next/static/chunks/1wqqkfg03tuu1.js +1 -0
- package/.next/static/chunks/23v229-qd9o6o.js +1 -0
- package/.next/static/chunks/242x7dx0zu3hf.js +1 -0
- package/.next/static/chunks/26gl990fowmkx.js +1 -0
- package/.next/static/chunks/2c2gi_zxaaa-j.js +3 -0
- package/.next/static/chunks/2l-1t8-pfq4ph.js +1 -0
- package/.next/static/chunks/2tu_d3t2boag2.js +1 -0
- package/.next/static/chunks/2v3rvsf6-bnfs.js +1 -0
- package/.next/static/chunks/2xlmm9z_sr1_m.js +1 -0
- package/.next/static/chunks/2y8ek6g772mi5.js +191 -0
- package/.next/static/chunks/2ysjbje-zsbdp.js +1 -0
- package/.next/static/chunks/384cc0iojva04.css +3 -0
- package/.next/static/chunks/3mb_v650fie_i.js +22 -0
- package/.next/static/chunks/3r4z_6i5z0hd5.js +1 -0
- package/.next/static/chunks/3sqcsxnhsnxzo.js +1 -0
- package/.next/static/chunks/turbopack-2c3mg3r-05n1w.js +1 -0
- package/package.json +2 -2
- package/prisma/migrations/20261024000000_add_last_practice/migration.sql +2 -0
- package/prisma/schema.prisma +1 -0
- package/prisma/seed.db +0 -0
- package/server.js +1 -1
- package/.next/server/app/latex-test/page/app-paths-manifest.json +0 -3
- package/.next/server/app/latex-test/page/build-manifest.json +0 -20
- package/.next/server/app/latex-test/page/next-font-manifest.json +0 -11
- package/.next/server/app/latex-test/page/react-loadable-manifest.json +0 -1
- package/.next/server/app/latex-test/page/server-reference-manifest.json +0 -4
- package/.next/server/app/latex-test/page.js +0 -14
- package/.next/server/app/latex-test/page.js.map +0 -5
- package/.next/server/app/latex-test/page.js.nft.json +0 -1
- package/.next/server/app/latex-test/page_client-reference-manifest.js +0 -3
- package/.next/server/chunks/1jng_app_api_exams_[id]_questions_[questionId]_regenerate_route_actions_1ggead3.js +0 -3
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_practice-records_route_actions_0z2zuf1.js +0 -3
- package/.next/server/chunks/1oeh_server_app_api_error-items_[id]_svg-animation_route_actions_17gckf3.js +0 -3
- package/.next/server/chunks/[externals]__04n7qbr._.js +0 -3
- package/.next/server/chunks/[externals]__0jzwjtl._.js +0 -3
- package/.next/server/chunks/[externals]__0pot68n._.js +0 -3
- package/.next/server/chunks/[externals]_assert_1pwe1ri._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0-2l_pu._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__00_hq9v._.js +0 -153
- package/.next/server/chunks/[root-of-the-server]__00moo9h._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__012xcq-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__01bzczj._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__02pqrw_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__033ri9p._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__04pjde6._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__064krqp._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__07iraov._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__07jl92a._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__07q7nsp._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0_t7bbz._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0_unb90._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0a1zwxf._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0aefi10._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0akadps._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0cfjgye._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0d-37yj._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0d2kpnm._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0dqgi36._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0dz5c04._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0e_u82_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0f3jyg0._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0gwwa9b._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0hars8c._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0iozebm._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0k-5uu2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0k3mm05._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0l-xu_t._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0lggrcf._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0m0eall._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0m37xyb._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0m8p-6f._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0pa47kn._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0r42_o7._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0rgjh3q._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0rk_yxy._.js +0 -9
- package/.next/server/chunks/[root-of-the-server]__0scij0p._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0sixhu9._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0sj18kk._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0sp4_zo._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0t2o8v-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0w58v6b._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0wp40ty._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0wsj4a_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0wvvsah._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0xg5h56._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0zpazf3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__10hs-qn._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__119xork._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__11_-ncy._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__11jhplo._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__122xu-0._.js +0 -32
- package/.next/server/chunks/[root-of-the-server]__15tkoe6._.js +0 -10
- package/.next/server/chunks/[root-of-the-server]__15y1l96._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__16hnc6-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__17i9sje._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__19_wn9u._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1_gkx5x._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1_hp3ol._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1_ogacf._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1a4-26x._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1b6i9mu._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1b_y2wk._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1bl7t8i._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1c0vatt._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1c7a0rs._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1chx4lo._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1cngnud._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1d82zkk._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1ezju_2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1fc23i5._.js +0 -122
- package/.next/server/chunks/[root-of-the-server]__1flnfu4._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1gya7jq._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1hng_h2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1i40psm._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1ijkds_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1j4v2e3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1jtd2ar._.js +0 -6
- package/.next/server/chunks/[root-of-the-server]__1kpo44g._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1lbcdia._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1m86czr._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1mnpqkx._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1n4b6nb._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1nmrlew._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1nmtv65._.js +0 -10
- package/.next/server/chunks/[root-of-the-server]__1o34kp3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1q7yl7l._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1qv60vg._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1ry8uat._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1s2rww3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1svvf40._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1tk0-4v._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1v-71me._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1vw740y._.js +0 -32
- package/.next/server/chunks/[root-of-the-server]__1x_ud_-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1yt_xxr._.js +0 -3
- package/.next/server/chunks/_0-eguqv._.js +0 -3
- package/.next/server/chunks/_008zx49._.js +0 -3
- package/.next/server/chunks/_011-ll5._.js +0 -3
- package/.next/server/chunks/_0389uce._.js +0 -3
- package/.next/server/chunks/_0431fxn._.js +0 -3
- package/.next/server/chunks/_0ekrwj-._.js +0 -36
- package/.next/server/chunks/_0gwg6ba._.js +0 -3
- package/.next/server/chunks/_0gxi3zr._.js +0 -3
- package/.next/server/chunks/_0lz3t4l._.js +0 -19
- package/.next/server/chunks/_0n36ev0._.js +0 -3
- package/.next/server/chunks/_0oc8oe4._.js +0 -3
- package/.next/server/chunks/_0rjzgi0._.js +0 -3
- package/.next/server/chunks/_0uxp3uh._.js +0 -3
- package/.next/server/chunks/_0x3ltk0._.js +0 -36
- package/.next/server/chunks/_10y361h._.js +0 -3
- package/.next/server/chunks/_12w5k19._.js +0 -3
- package/.next/server/chunks/_13ffmxv._.js +0 -3
- package/.next/server/chunks/_14tz_k9._.js +0 -3
- package/.next/server/chunks/_15neond._.js +0 -11
- package/.next/server/chunks/_16jdov0._.js +0 -3
- package/.next/server/chunks/_18amra5._.js +0 -3
- package/.next/server/chunks/_1_ns7o3._.js +0 -3
- package/.next/server/chunks/_1a1aqmi._.js +0 -3
- package/.next/server/chunks/_1a1udq0._.js +0 -3
- package/.next/server/chunks/_1b0269x._.js +0 -3
- package/.next/server/chunks/_1b7qjlv._.js +0 -3
- package/.next/server/chunks/_1be-y66._.js +0 -3
- package/.next/server/chunks/_1ex6ovo._.js +0 -3
- package/.next/server/chunks/_1fgb9ve._.js +0 -3
- package/.next/server/chunks/_1m-yyz-._.js +0 -3
- package/.next/server/chunks/_1n1xsqj._.js +0 -3
- package/.next/server/chunks/_1oj6gy_._.js +0 -3
- package/.next/server/chunks/_1pvqo-q._.js +0 -3
- package/.next/server/chunks/_1z_ujac._.js +0 -3
- package/.next/server/chunks/_211va-d._.js +0 -3
- package/.next/server/chunks/_2194yr7._.js +0 -11
- package/.next/server/chunks/_next-internal_server_app_api_admin_dashboard_route_actions_1ispso-.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_admin_users_[id]_detail_route_actions_0oe_wkt.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_admin_users_route_actions_0q-rtz1.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_ai_models_route_actions_0w7iwv-.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_ai_test_route_actions_1p0n1q8.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_analytics_route_actions_1e0ou17.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_analyze_route_actions_0lx-23h.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_auth_[___nextauth]_route_actions_08nexdk.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_delete_route_actions_1w26boq.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_figure_route_actions_0adlts0.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_fix-latex_route_actions_0hc7dhx.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_geogebra_route_actions_1-ks4uv.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_image_route_actions_1k9n5yl.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_reanswer_route_actions_1-sw0j2.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_retag_route_actions_0ckki4n.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_[id]_route_actions_1kbs4ux.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_batch-delete_route_actions_0hiq_1k.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_clear_route_actions_14t_6i-.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_list_route_actions_032x4ue.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_route_actions_1zdvz0p.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_short_[shortId]_route_actions_02976v-.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_error-items_similarity_route_actions_1i26if9.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_exams_[id]_retry_route_actions_1fdi39f.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_exams_[id]_route_actions_1wuidrq.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_geogebra-analyze_route_actions_1xng0_c.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_logs_frontend_route_actions_0nxepty.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_[id]_retag_route_actions_00su_t8.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_[id]_route_actions_11j3vxg.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_notebooks_route_actions_02cy45r.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_openclaw_batch-upload_route_actions_1zz3oen.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_practice_generate_route_actions_1krr9n_.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_practice_record_[id]_route_actions_0zreiom.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_practice_record_route_actions_0py9z__.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_reanswer_route_actions_04xweh_.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_register_route_actions_0vlzh_c.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_register_status_route_actions_0b52_sj.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_settings_route_actions_1bpm9ac.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_stats_practice_clear_route_actions_1iz6iz0.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_stats_practice_route_actions_1tfoxx-.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_tags_stats_route_actions_0fmeadc.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_tags_suggestions_route_actions_1xpolyv.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_0g2jjls.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_manifest_webmanifest_route_actions_08hcpz0.js +0 -3
- package/.next/server/chunks/node_modules_next_1zdbrne._.js +0 -10
- package/.next/server/chunks/node_modules_zod_v4_classic_external_1-pw2v2.js +0 -22
- package/.next/server/chunks/src_0tzpy5j._.js +0 -3
- package/.next/server/chunks/src_lib_date-time_ts_14chb27._.js +0 -3
- package/.next/server/chunks/src_lib_question-deduplication_ts_1p1bik-._.js +0 -3
- package/.next/server/chunks/ssr/[externals]_fs_0pplqgc._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__00gewu3._.js +0 -35
- package/.next/server/chunks/ssr/[root-of-the-server]__03psbtz._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__05f8wbh._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0a0nty7._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0ax9dog._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0bvtza7._.js +0 -33
- package/.next/server/chunks/ssr/[root-of-the-server]__0g_-bym._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0gwwr7e._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0hzktoi._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0koj8h0._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0s87xha._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0skyo1a._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0snpjfe._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0y_e9do._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0ybs_4c._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__14l7peq._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1507q8a._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__15ppb9j._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__191jn5n._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1f2jx51._.js +0 -33
- package/.next/server/chunks/ssr/[root-of-the-server]__1gth76-._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1ko_dw5._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1l84pks._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1m7qw-2._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1ma2oml._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1o8jotz._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1o__w27._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1p7f0va._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1sg9eoj._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1u74hyi._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1xsovpr._.js +0 -3
- package/.next/server/chunks/ssr/_054yhx9._.js +0 -3
- package/.next/server/chunks/ssr/_07ls0n_._.js +0 -3
- package/.next/server/chunks/ssr/_0i9hwpv._.js +0 -3
- package/.next/server/chunks/ssr/_0iqp5hs._.js +0 -3
- package/.next/server/chunks/ssr/_0m1-rq-._.js +0 -3
- package/.next/server/chunks/ssr/_0mgbe2b._.js +0 -3
- package/.next/server/chunks/ssr/_0nv22wt._.js +0 -3
- package/.next/server/chunks/ssr/_0rz2_qb._.js +0 -151
- package/.next/server/chunks/ssr/_0sbbx9z._.js +0 -7
- package/.next/server/chunks/ssr/_0sf1gd9._.js +0 -3
- package/.next/server/chunks/ssr/_0uemk57._.js +0 -3
- package/.next/server/chunks/ssr/_0zj7dlu._.js +0 -3
- package/.next/server/chunks/ssr/_11ut-6_._.js +0 -3
- package/.next/server/chunks/ssr/_17igtpd._.js +0 -3
- package/.next/server/chunks/ssr/_1aot_70._.js +0 -3
- package/.next/server/chunks/ssr/_1filpif._.js +0 -3
- package/.next/server/chunks/ssr/_1jniqsj._.js +0 -3
- package/.next/server/chunks/ssr/_1kgnhmo._.js +0 -8
- package/.next/server/chunks/ssr/_1lt1lhz._.js +0 -8
- package/.next/server/chunks/ssr/_1yeu09q._.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_admin_user_[id]_page_actions_0baj8gs.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_error-items_[id]_page_actions_0qla9ak.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_exams_[id]_print_page_actions_0pxdgxq.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_latex-test_page_actions_19v7ka0.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_notebooks_[id]_add_page_actions_0275ft2.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_notebooks_[id]_page_actions_1qj0i-7.js +0 -3
- package/.next/server/chunks/ssr/_next-internal_server_app_print-preview_page_actions_1jhaaln.js +0 -3
- package/.next/server/chunks/ssr/node_modules_0o2aki7._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_1y5ym6h._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_1lnqo1a._.js +0 -5
- package/.next/server/chunks/ssr/node_modules_next_dist_077yo5w._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_dist_0nkkbfv._.js +0 -6
- package/.next/server/chunks/ssr/node_modules_next_dist_1_c-t1n._.js +0 -14
- package/.next/server/chunks/ssr/node_modules_next_dist_1v8aef8._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0bew68i._.js +0 -33
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j3._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0symwr9.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0q-w892.js +0 -3
- package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0l_sp0x.js +0 -3
- package/.next/server/chunks/ssr/src_1biegcg._.js +0 -3
- package/.next/server/chunks/ssr/src_1gayunq._.js +0 -3
- package/.next/server/chunks/ssr/src_1o363ao._.js +0 -3
- package/.next/server/chunks/ssr/src_app_admin_page_tsx_0ublbd0._.js +0 -3
- package/.next/server/chunks/ssr/src_app_error-items_[id]_page_tsx_04xwwdm._.js +0 -3
- package/.next/server/chunks/ssr/src_app_notebooks_[id]_page_tsx_08njm-5._.js +0 -3
- package/.next/server/chunks/ssr/src_app_notebooks_page_tsx_1p9src5._.js +0 -3
- package/.next/server/chunks/ssr/src_app_page_tsx_1chiuah._.js +0 -3
- package/.next/server/chunks/ssr/src_app_practice_page_tsx_10gnx53._.js +0 -3
- package/.next/server/chunks/ssr/src_app_tags_page_tsx_1h2vkk4._.js +0 -3
- package/.next/server/chunks/ssr/src_components_providers_tsx_09kw-mv._.js +0 -193
- package/.next/server/chunks/ssr/src_lib_date-time_ts_0oyqctn._.js +0 -3
- package/.next/server/edge/chunks/[root-of-the-server]__1osrt2u._.js +0 -3
- package/.next/server/edge/chunks/_1s0wgnu._.js +0 -3
- package/.next/server/edge/chunks/node_modules_0g4gi6f._.js +0 -13
- package/.next/server/edge/chunks/turbopack-node_modules_next_dist_esm_build_templates_edge-wrapper_1iafar9.js +0 -3
- package/.next/server/edge/chunks/turbopack-node_modules_next_dist_esm_build_templates_edge-wrapper_1x1n1fx.js +0 -3
- package/.next/static/chunks/03gmdewlo3s6u.js +0 -1
- package/.next/static/chunks/0_w084ms_lq25.js +0 -22
- package/.next/static/chunks/0dzfsm6h13fyr.js +0 -1
- package/.next/static/chunks/0ehjiuuxbbhq9.js +0 -1
- package/.next/static/chunks/0ij2dqb0qj5ry.js +0 -1
- package/.next/static/chunks/0iq53qkw5hvrs.js +0 -1
- package/.next/static/chunks/0m81l71kojx8j.js +0 -1
- package/.next/static/chunks/0nckb2-62ooyq.js +0 -1
- package/.next/static/chunks/0pwdmc9gw8ben.js +0 -33
- package/.next/static/chunks/0snej-v5yglxr.js +0 -1
- package/.next/static/chunks/1-7k9gbbjkcml.js +0 -1
- package/.next/static/chunks/1c92up8k2x0z4.js +0 -1
- package/.next/static/chunks/1cd32rtomdngh.js +0 -1
- package/.next/static/chunks/1io3-cth_2-cd.js +0 -1
- package/.next/static/chunks/1oiuiyv1cv06v.js +0 -31
- package/.next/static/chunks/1t4-pobw0y5cf.js +0 -1
- package/.next/static/chunks/1xg811762s1p1.js +0 -1
- package/.next/static/chunks/1z_5sj1wqi06v.js +0 -1
- package/.next/static/chunks/24dymggis4suf.css +0 -3
- package/.next/static/chunks/24jbwfpgmio7x.js +0 -1
- package/.next/static/chunks/27fr34_1v7xyh.js +0 -1
- package/.next/static/chunks/2dlme2fdlkms6.js +0 -1
- package/.next/static/chunks/2eu_bls12m1wj.js +0 -1
- package/.next/static/chunks/2pmzqbg-qabof.js +0 -1
- package/.next/static/chunks/2w2uo9jjxt-re.js +0 -1
- package/.next/static/chunks/2x8e_fbze06sd.js +0 -1
- package/.next/static/chunks/2z1_5umv36es6.js +0 -191
- package/.next/static/chunks/32bl-oqw9oso0.js +0 -1
- package/.next/static/chunks/3b-g5_r9nto3s.js +0 -6
- package/.next/static/chunks/3g1rm2suowncy.js +0 -3
- package/.next/static/chunks/3helovsg02qr4.js +0 -1
- package/.next/static/chunks/3jta6jrk-jubq.js +0 -1
- package/.next/static/chunks/3m4c1r8_2ga_1.js +0 -1
- package/.next/static/chunks/3whzkc6d8oefw.js +0 -1
- package/.next/static/chunks/3yhf6xyypekz6.js +0 -1
- package/.next/static/chunks/3z9gc_02gl8n9.js +0 -1
- package/.next/static/chunks/427wg73nuzpiz.js +0 -5
- package/.next/static/chunks/turbopack-1-0r7_puvz3eq.js +0 -1
- /package/.next/static/{Y0pwgmRdVAifh_zukihNt → 0rqQXLDvfc_jhsn1XF-zT}/_buildManifest.js +0 -0
- /package/.next/static/{Y0pwgmRdVAifh_zukihNt → 0rqQXLDvfc_jhsn1XF-zT}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{Y0pwgmRdVAifh_zukihNt → 0rqQXLDvfc_jhsn1XF-zT}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
module.exports=[[906920,(e,t,r)=>{r.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return(r+n)*3/4-n},r.toByteArray=function(e){var t,r,n=u(e),o=n[0],a=n[1],l=new s((o+a)*3/4-a),c=0,d=a>0?o-4:o;for(r=0;r<d;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,s=[],o=0,a=r-i;o<a;o+=16383)s.push(function(e,t,r){for(var i,s=[],o=t;o<r;o+=3)i=(e[o]<<16&0xff0000)+(e[o+1]<<8&65280)+(255&e[o+2]),s.push(n[i>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}(e,o,o+16383>a?a:o+16383));return 1===i?s.push(n[(t=e[r-1])>>2]+n[t<<4&63]+"=="):2===i&&s.push(n[(t=(e[r-2]<<8)+e[r-1])>>10]+n[t>>4&63]+n[t<<2&63]+"="),s.join("")};for(var n=[],i=[],s="u">typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,l=o.length;a<l;++a)n[a]=o[a],i[o.charCodeAt(a)]=a;function u(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}i[45]=62,i[95]=63},922691,(e,t,r)=>{var n=e.r(500874).Buffer,i=e.r(500874).SlowBuffer;function s(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}t.exports=s,s.install=function(){n.prototype.equal=i.prototype.equal=function(e){return s(this,e)}};var o=n.prototype.equal,a=i.prototype.equal;s.restore=function(){n.prototype.equal=o,i.prototype.equal=a}},732955,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(465880);function s(e){if(n.isBuffer(e))return e;if("string"==typeof e)return n.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function o(e,t,r){for(var n=0;t+n<r&&0===e[t+n];)++n;return e[t+n]>=128&&--n,n}t.exports={derToJose:function(e,t){e=s(e);var r=i(t),o=r+1,a=e.length,l=0;if(48!==e[l++])throw Error('Could not find expected "seq"');var u=e[l++];if(129===u&&(u=e[l++]),a-l<u)throw Error('"seq" specified length of "'+u+'", only "'+(a-l)+'" remaining');if(2!==e[l++])throw Error('Could not find expected "int" for "r"');var c=e[l++];if(a-l-2<c)throw Error('"r" specified length of "'+c+'", only "'+(a-l-2)+'" available');if(o<c)throw Error('"r" specified length of "'+c+'", max of "'+o+'" is acceptable');var d=l;if(l+=c,2!==e[l++])throw Error('Could not find expected "int" for "s"');var h=e[l++];if(a-l!==h)throw Error('"s" specified length of "'+h+'", expected "'+(a-l)+'"');if(o<h)throw Error('"s" specified length of "'+h+'", max of "'+o+'" is acceptable');var p=l;if((l+=h)!==a)throw Error('Expected to consume entire buffer, but "'+(a-l)+'" bytes remain');var f=r-c,m=r-h,g=n.allocUnsafe(f+c+m+h);for(l=0;l<f;++l)g[l]=0;e.copy(g,l,d+Math.max(-f,0),d+c),l=r;for(var y=l;l<y+m;++l)g[l]=0;return e.copy(g,l,p+Math.max(-m,0),p+h),g=(g=g.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=s(e);var r=i(t),a=e.length;if(a!==2*r)throw TypeError('"'+t+'" signatures must be "'+2*r+'" bytes, saw "'+a+'"');var l=o(e,0,r),u=o(e,r,e.length),c=r-l,d=r-u,h=2+c+1+1+d,p=h<128,f=n.allocUnsafe((p?2:3)+h),m=0;return f[m++]=48,p?f[m++]=h:(f[m++]=129,f[m++]=255&h),f[m++]=2,f[m++]=c,l<0?(f[m++]=0,m+=e.copy(f,m,0,r)):m+=e.copy(f,m,l,r),f[m++]=2,f[m++]=d,u<0?(f[m++]=0,e.copy(f,m,r)):e.copy(f,m,r+u),f}}},465880,(e,t,r)=>{function n(e){return(e/8|0)+ +(e%8!=0)}var i={ES256:n(256),ES384:n(384),ES512:n(521)};t.exports=function(e){var t=i[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}},725705,(e,t,r)=>{var n=Object.prototype.hasOwnProperty,i=Object.prototype.toString,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===i.call(e)},l=function(e){if(!e||"[object Object]"!==i.call(e))return!1;var t,r=n.call(e,"constructor"),s=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!s)return!1;for(t in e);return void 0===t||n.call(e,t)},u=function(e,t){s&&"__proto__"===t.name?s(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},c=function(e,t){if("__proto__"===t){if(!n.call(e,t))return;else if(o)return o(e,t).value}return e[t]};t.exports=function e(){var t,r,n,i,s,o,d=arguments[0],h=1,p=arguments.length,f=!1;for("boolean"==typeof d&&(f=d,d=arguments[1]||{},h=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});h<p;++h)if(t=arguments[h],null!=t)for(r in t)n=c(d,r),d!==(i=c(t,r))&&(f&&i&&(l(i)||(s=a(i)))?(s?(s=!1,o=n&&a(n)?n:[]):o=n&&l(n)?n:{},u(d,{name:r,newValue:e(f,o,i)})):void 0!==i&&u(d,{name:r,newValue:i}));return d}},527078,(e,t,r)=>{var n=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.GaxiosError=r.GAXIOS_ERROR_SYMBOL=void 0,r.defaultErrorRedactor=function e(t){let r="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach((t,n)=>{(/^authentication$/i.test(n)||/^authorization$/i.test(n)||/secret/i.test(n))&&e.set(n,r)})}function i(e,t){if("object"==typeof e&&null!==e&&"string"==typeof e[t]){let n=e[t];(/grant_type=/i.test(n)||/assertion=/i.test(n)||/secret/i.test(n))&&(e[t]=r)}}function s(e){!e||"object"!=typeof e||(e instanceof FormData||e instanceof URLSearchParams||"forEach"in e&&"set"in e?e.forEach((t,n)=>{(["grant_type","assertion"].includes(n)||/secret/.test(n))&&e.set(n,r)}):("grant_type"in e&&(e.grant_type=r),"assertion"in e&&(e.assertion=r),"client_secret"in e&&(e.client_secret=r)))}return t.config&&(n(t.config.headers),i(t.config,"data"),s(t.config.data),i(t.config,"body"),s(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",r),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",r)),t.response&&(e({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(i(t.response,"data"),s(t.response.data))),t};let i=n(e.r(725705)),s=n(e.r(861675)).default.pkg;r.GAXIOS_ERROR_SYMBOL=Symbol.for(`${s.name}-gaxios-error`);class o extends Error{config;response;code;status;error;[r.GAXIOS_ERROR_SYMBOL]=s.version;static[Symbol.hasInstance](e){return!!e&&"object"==typeof e&&r.GAXIOS_ERROR_SYMBOL in e&&e[r.GAXIOS_ERROR_SYMBOL]===s.version||Function.prototype[Symbol.hasInstance].call(o,e)}constructor(e,t,r,n){if(super(e,{cause:n}),this.config=t,this.response=r,this.error=n instanceof Error?n:void 0,this.config=(0,i.default)(!0,{},t),this.response&&(this.response.config=(0,i.default)(!0,{},this.response.config)),this.response){try{this.response.data=function(e,t){switch(e){case"stream":default:return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text())}}(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}n instanceof DOMException?this.code=n.name:n&&"object"==typeof n&&"code"in n&&("string"==typeof n.code||"number"==typeof n.code)&&(this.code=n.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let r=t;if("string"==typeof e.data&&(r=e.data),e.data&&"object"==typeof e.data&&"error"in e.data&&e.data.error&&!e.ok){if("string"==typeof e.data.error)return{message:e.data.error,code:e.status,status:e.statusText};if("object"==typeof e.data.error){r="message"in e.data.error&&"string"==typeof e.data.error.message?e.data.error.message:r;let t="status"in e.data.error&&"string"==typeof e.data.error.status?e.data.error.status:e.statusText,n="code"in e.data.error&&"number"==typeof e.data.error.code?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)"object"==typeof t&&"message"in t&&"string"==typeof t.message&&i.push(t.message);return Object.assign({message:i.join("\n")||r,code:n,status:t},e.data.error)}return Object.assign({message:r,code:n,status:t},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}}r.GaxiosError=o},580038,(e,t,r)=>{var n,i=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.Gaxios=void 0;let s=i(e.r(725705)),o=e.r(524836),a=e.r(527078),l=e.r(435156),u=e.r(688947),c=e.r(3137),d=async()=>globalThis.crypto?.randomUUID()||(await e.A(485685)).randomUUID();class h{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new c.GaxiosInterceptorManager,response:new c.GaxiosInterceptorManager}}fetch(...e){let t,r=e[0],i=e[1],s=new Headers;return("string"==typeof r?t=new URL(r):r instanceof URL?t=r:r&&r.url&&(t=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&n.mergeHeaders(s,r.headers),i&&n.mergeHeaders(s,new Headers(i.headers)),"object"!=typeof r||r instanceof URL)?this.request({...i,headers:s,url:t}):this.request({...i,...r,headers:s,url:t})}async request(e={}){let t=await this.#e(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await n.#n(),r={...e};delete r.data;let i=await t(e.url,r),s=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(i,{config:e,data:s})}async _request(e){try{let t;if(t=e.adapter?await e.adapter(e,this._defaultAdapter.bind(this)):await this._defaultAdapter(e),!e.validateStatus(t.status)){if("stream"===e.responseType){let e=[];for await(let r of t.data)e.push(r);t.data=e.toString()}let r=a.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new a.GaxiosError(r?.message,e,t,r)}return t}catch(i){let t;t=i instanceof a.GaxiosError?i:i instanceof Error?new a.GaxiosError(i.message,e,void 0,i):new a.GaxiosError("Unexpected Gaxios Error",e,void 0,i);let{shouldRetry:r,config:n}=await (0,l.getRetryConfig)(t);if(r&&n)return t.config.retryConfig.currentRetryAttempt=n.retryConfig.currentRetryAttempt,e.retryConfig=t.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(t),t}}async getResponseData(e,t){if(204===t.status)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new a.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let e=await t.text();try{return JSON.parse(e)}catch{return e}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#s(e,t=[]){let r=new URL(e),n=[...t];for(let e of(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[])n.push(e.trim());for(let e of n)if(e instanceof RegExp){if(e.test(r.toString()))return!1}else if(e instanceof URL){if(e.origin===r.origin)return!1}else if(e.startsWith("*.")||e.startsWith(".")){let t=e.replace(/^\*\./,".");if(r.hostname.endsWith(t))return!1}else if(e===r.origin||e===r.hostname||e===r.href)return!1;return!0}async #t(e){let t=Promise.resolve(e);for(let e of this.interceptors.request.values())e&&(t=t.then(e.resolved,e.rejected));return t}async #r(e){let t=Promise.resolve(e);for(let e of this.interceptors.response.values())e&&(t=t.then(e.resolved,e.rejected));return t}async #e(e){let t=new Headers(this.defaults.headers);n.mergeHeaders(t,e.headers);let r=(0,s.default)(!0,{},this.defaults,e);if(!r.url)throw Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let e=r.paramsSerializer(r.params);e.startsWith("?")&&(e=e.slice(1));let t=r.url.toString().includes("?")?"&":"?";r.url=r.url+t+e}else{let e=r.url instanceof URL?r.url:new URL(r.url);for(let[t,n]of new URLSearchParams(r.params))e.searchParams.append(t,n);r.url=e}"number"==typeof e.maxContentLength&&(r.size=e.maxContentLength),"number"==typeof e.maxRedirects&&(r.follow=e.maxRedirects);let i="string"==typeof r.data||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof u.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let e=await d();t.set("content-type",`multipart/related; boundary=${e}`),r.body=u.Readable.from(this.getMultipartRequest(r.multipart,e))}else i?r.body=r.data:"object"==typeof r.data?"application/x-www-form-urlencoded"===t.get("Content-Type")?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(t.has("content-type")||t.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",t.has("accept")||"json"!==r.responseType||t.set("accept","application/json");let l=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(r.agent);else if(l&&this.#s(r.url,r.noProxy)){let e=await n.#o();this.agentCache.has(l)?r.agent=this.agentCache.get(l):(r.agent=new e(l,{cert:r.cert,key:r.key}),this.agentCache.set(l,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new o.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return"function"!=typeof r.errorRedactor&&!1!==r.errorRedactor&&(r.errorRedactor=a.defaultErrorRedactor),!r.body||"duplex"in r||(r.duplex="half"),this.#i(r),Object.assign(r,{headers:t,url:r.url instanceof URL?r.url:new URL(r.url)})}#i(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(null===t)return e.text();if((t=t.toLowerCase()).includes("application/json")){let t=await e.text();try{t=JSON.parse(t)}catch{}return t}return t.match(/^text\//)?e.text():e.blob()}async *getMultipartRequest(e,t){let r=`--${t}--`;for(let r of e){let e=r.headers.get("Content-Type")||"application/octet-stream",n=`--${t}\r
|
|
2
|
+
Content-Type: ${e}\r
|
|
3
|
+
\r
|
|
4
|
+
`;yield n,"string"==typeof r.content?yield r.content:yield*r.content,yield"\r\n"}yield r}static #a;static #l;static async #o(){return this.#a||=(await e.A(791961)).HttpsProxyAgent,this.#a}static async #n(){return this.#l||=(await e.A(672331)).default,this.#l}static mergeHeaders(e,...t){for(let r of(e=e instanceof Headers?e:new Headers(e),t))(r instanceof Headers?r:new Headers(r)).forEach((t,r)=>{"set-cookie"===r?e.append(r,t):e.set(r,t)});return e}}r.Gaxios=h,n=h},957612,(e,t,r)=>{var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.instance=r.Gaxios=r.GaxiosError=void 0,r.request=a;let s=e.r(580038);Object.defineProperty(r,"Gaxios",{enumerable:!0,get:function(){return s.Gaxios}});var o=e.r(527078);async function a(e){return r.instance.request(e)}Object.defineProperty(r,"GaxiosError",{enumerable:!0,get:function(){return o.GaxiosError}}),i(e.r(3137),r),r.instance=new s.Gaxios},3137,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.GaxiosInterceptorManager=void 0;class n extends Set{}r.GaxiosInterceptorManager=n},435156,(e,t,r)=>{async function n(e){var t;let r=s(e);if(!e||!e.config||!r&&!e.config.retry)return{shouldRetry:!1};(r=r||{}).currentRetryAttempt=r.currentRetryAttempt||0,r.retry=void 0===r.retry||null===r.retry?3:r.retry,r.httpMethodsToRetry=r.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],r.noResponseRetries=void 0===r.noResponseRetries||null===r.noResponseRetries?2:r.noResponseRetries,r.retryDelayMultiplier=r.retryDelayMultiplier?r.retryDelayMultiplier:2,r.timeOfFirstRequest=r.timeOfFirstRequest?r.timeOfFirstRequest:Date.now(),r.totalTimeout=r.totalTimeout?r.totalTimeout:Number.MAX_SAFE_INTEGER,r.maxRetryDelay=r.maxRetryDelay?r.maxRetryDelay:Number.MAX_SAFE_INTEGER,r.statusCodesToRetry=r.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=r;let n=r.shouldRetry||i;if(!await n(e))return{shouldRetry:!1,config:e.config};let o=Math.min(((t=r).currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,t.totalTimeout-(Date.now()-t.timeOfFirstRequest),t.maxRetryDelay);e.config.retryConfig.currentRetryAttempt+=1;let a=r.retryBackoff?r.retryBackoff(e,o):new Promise(e=>{setTimeout(e,o)});return r.onRetryAttempt&&await r.onRetryAttempt(e),await a,{shouldRetry:!0,config:e.config}}function i(e){let t=s(e);if(e.config.signal?.aborted&&"TimeoutError"!==e.code||"AbortError"===e.code||!t||0===t.retry||!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries||!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let r=!1;for(let[n,i]of t.statusCodesToRetry){let t=e.response.status;if(t>=n&&t<=i){r=!0;break}}if(!r)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function s(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}Object.defineProperty(r,"__esModule",{value:!0}),r.getRetryConfig=n},861675,(e,t,r)=>{t.exports={pkg:e.r(73827)}},29077,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.GCE_LINUX_BIOS_PATHS=void 0,r.isGoogleCloudServerless=o,r.isGoogleComputeEngineLinux=a,r.isGoogleComputeEngineMACAddress=l,r.isGoogleComputeEngine=u,r.detectGCPResidency=function(){return o()||u()};let n=e.r(522734),i=e.r(446786);r.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};let s=/^42:01/;function o(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function a(){(0,i.platform)();try{(0,n.statSync)(r.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let e=(0,n.readFileSync)(r.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(e)}catch{return!1}}function l(){for(let e of Object.values((0,i.networkInterfaces)()))if(e){for(let{mac:t}of e)if(s.test(t))return!0}return!1}function u(){return a()||l()}},482e3,(e,t,r)=>{let n;var i,s=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=e.e&&e.e.__importStar||(i=function(e){return(i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n]);return o(t,e),t}),l=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.gcpResidencyCache=r.METADATA_SERVER_DETECTION=r.HEADERS=r.HEADER_VALUE=r.HEADER_NAME=r.SECONDARY_HOST_ADDRESS=r.HOST_ADDRESS=r.BASE_PATH=void 0,r.instance=function(e){return m("instance",e)},r.project=function(e){return m("project",e)},r.universe=function(e){return m("universe",e)},r.bulk=y,r.isAvailable=_,r.resetIsAvailableCache=function(){n=void 0},r.getGCPResidency=E,r.setGCPResidency=v,r.requestTimeout=b;let u=e.r(957612),c=e.r(301158),d=e.r(29077),h=a(e.r(547637));r.BASE_PATH="/computeMetadata/v1",r.HOST_ADDRESS="http://169.254.169.254",r.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.",r.HEADER_NAME="Metadata-Flavor",r.HEADER_VALUE="Google",r.HEADERS=Object.freeze({[r.HEADER_NAME]:r.HEADER_VALUE});let p=h.log("gcp-metadata");function f(e){return e||(e=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||r.HOST_ADDRESS),/^https?:\/\//.test(e)||(e=`http://${e}`),new URL(r.BASE_PATH,e).href}async function m(e,t={},n=3,i=!1){let s=new Headers(r.HEADERS),o="",a={};("object"==typeof e?(new Headers(e.headers).forEach((e,t)=>s.set(t,e)),o=e.metadataKey,a=e.params||a,n=e.noResponseRetries||n,i=e.fastFail||i):o=e,"string"==typeof t)?o+=`/${t}`:(Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${e}' is not a valid configuration option.`)}}),t.property&&(o+=`/${t.property}`),new Headers(t.headers).forEach((e,t)=>s.set(t,e)),a=t.params||a);let l=i?g:u.request,d={url:`${f()}/${o}`,headers:s,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:b()};p.info("instance request %j",d);let h=await l(d);p.info("instance metadata is %s",h.data);let y=h.headers.get(r.HEADER_NAME);if(y!==r.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${r.HEADER_NAME} header. Expected '${r.HEADER_VALUE}', got ${y?`'${y}'`:"no header"}`);if("string"==typeof h.data)try{return c.parse(h.data)}catch{}return h.data}async function g(e){let t={...e,url:e.url?.toString().replace(f(),f(r.SECONDARY_HOST_ADDRESS))};return Promise.any([(0,u.request)(e),(0,u.request)(t)])}async function y(e){let t={};return await Promise.all(e.map(e=>(async()=>{let r=await m(e);t[e.metadataKey]=r})())),t}async function _(){if(process.env.METADATA_SERVER_DETECTION){let e=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(e in r.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${e}\`, but it should be \`${Object.keys(r.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(e){case"assume-present":return!0;case"none":return!1;case"bios-only":return E()}}try{return void 0===n&&(n=m("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await n,!0}catch(e){if(process.env.DEBUG_AUTH&&console.info(e),"request-timeout"===e.type||e.response&&404===e.response.status)return!1;if(!(e.response&&404===e.response.status)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let t="UNKNOWN";e.code&&(t=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${t}`,"MetadataLookupWarning")}return!1}}function E(){return null===r.gcpResidencyCache&&v(),r.gcpResidencyCache}function v(e=null){r.gcpResidencyCache=null!==e?e:(0,d.detectGCPResidency)()}function b(){return 3e3*!E()}r.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"}),r.gcpResidencyCache=null,l(e.r(29077),r)},911656,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.AuthClient=r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=r.DEFAULT_UNIVERSE=void 0;let n=e.r(427699),i=e.r(957612),s=e.r(415733),o=e.r(547637),a=e.r(393714);r.DEFAULT_UNIVERSE="googleapis.com",r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=3e5;class l extends n.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=r.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=(0,s.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??r.DEFAULT_UNIVERSE,this.transporter=e.transporter??new i.Gaxios(e.transporterOptions),!1!==t.get("useAuthRequestParameters")&&(this.transporter.interceptors.request.add(l.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(l.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t,r=e[0],n=e[1],s=new Headers;return("string"==typeof r?t=new URL(r):r instanceof URL?t=r:r&&r.url&&(t=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&i.Gaxios.mergeHeaders(s,r.headers),n&&i.Gaxios.mergeHeaders(s,new Headers(n.headers)),"object"!=typeof r||r instanceof URL)?this.request({...n,headers:s,url:t}):this.request({...n,...r,headers:s,url:t})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){let r=t.get("x-goog-user-project"),n=t.get("authorization");return r&&e.set("x-goog-user-project",r),n&&e.set("authorization",n),e}static log=(0,o.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let t=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${t}`)}let t=e.headers.get("User-Agent");t?t.includes(`${a.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${a.USER_AGENT}`):e.headers.set("User-Agent",a.USER_AGENT);try{let t=e[l.RequestMethodNameSymbol],r=`${Math.floor(1e3*Math.random())}`;e[l.RequestLogIdSymbol]=r;let n={url:e.url,headers:e.headers};t?l.log.info("%s [%s] request %j",t,r,n):l.log.info("[%s] request %j",r,n)}catch(e){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let t=e.config,r=t[l.RequestMethodNameSymbol],n=t[l.RequestLogIdSymbol];r?l.log.info("%s [%s] response %j",r,n,e.data):l.log.info("[%s] response %j",n,e.data)}catch(e){}return e},rejected:async e=>{try{let t=e.config,r=t[l.RequestMethodNameSymbol],n=t[l.RequestLogIdSymbol];r?l.log.info("%s [%s] error %j",r,n,e.response?.data):l.log.error("[%s] error %j",n,e.response?.data)}catch(e){}throw e}};static setMethodName(e,t){try{e[l.RequestMethodNameSymbol]=t}catch(e){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}r.AuthClient=l},690220,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.AwsClient=void 0;let n=e.r(287573),i=e.r(306560),s=e.r(541033),o=e.r(415733),a=e.r(957612);class l extends i.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static #u="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let t=(0,o.originalOrCamelOptions)(e),r=t.get("credential_source"),n=t.get("aws_security_credentials_supplier");if(!r&&!n)throw Error("A credential source or AWS security credentials supplier must be specified.");if(r&&n)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(n)this.awsSecurityCredentialsSupplier=n,this.regionalCredVerificationUrl=l.#u,this.credentialSourceType="programmatic";else{let e=(0,o.originalOrCamelOptions)(r);this.environmentId=e.get("environment_id");let t=e.get("region_url"),n=e.get("url"),i=e.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new s.DefaultAwsSecurityCredentialsSupplier({regionUrl:t,securityCredentialsUrl:n,imdsV2SessionTokenUrl:i}),this.regionalCredVerificationUrl=e.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(e&&this.regionalCredVerificationUrl){if(1!==parseInt(e[2],10))throw Error(`aws version "${e[2]}" is not supported in the current build.`)}else throw Error('No valid AWS "credential_source" provided')}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new n.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...l.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return a.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((e,r)=>t.push({key:r,value:e})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}}r.AwsClient=l},287573,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.AwsRequestSigner=void 0;let n=e.r(957612),i=e.r(859501),s="AWS4-HMAC-SHA256";async function o(e,t,r){return await e.signWithHmacSha256(t,r)}async function a(e,t,r,n,i){let s=await o(e,`AWS4${t}`,r),a=await o(e,s,n),l=await o(e,a,i);return await o(e,l,"aws4_request")}async function l(e){let t=n.Gaxios.mergeHeaders(e.additionalAmzHeaders),r=e.requestPayload||"",l=e.host.split(".")[0],u=new Date,c=u.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),d=u.toISOString().replace(/[-]/g,"").replace(/T.*/,"");e.securityCredentials.token&&t.set("x-amz-security-token",e.securityCredentials.token);let h=n.Gaxios.mergeHeaders({host:e.host},t.has("date")?{}:{"x-amz-date":c},t),p="",f=[...h.keys()].sort();f.forEach(e=>{p+=`${e}:${h.get(e)}
|
|
5
|
+
`});let m=f.join(";"),g=await e.crypto.sha256DigestHex(r),y=`${e.method.toUpperCase()}
|
|
6
|
+
${e.canonicalUri}
|
|
7
|
+
${e.canonicalQuerystring}
|
|
8
|
+
${p}
|
|
9
|
+
${m}
|
|
10
|
+
${g}`,_=`${d}/${e.region}/${l}/aws4_request`,E=`${s}
|
|
11
|
+
${c}
|
|
12
|
+
${_}
|
|
13
|
+
`+await e.crypto.sha256DigestHex(y),v=await a(e.crypto,e.securityCredentials.secretAccessKey,d,e.region,l),b=await o(e.crypto,v,E),w=`${s} Credential=${e.securityCredentials.accessKeyId}/${_}, SignedHeaders=${m}, Signature=${(0,i.fromArrayBufferToHex)(b)}`;return{amzDate:t.has("date")?void 0:c,authorizationHeader:w,canonicalQuerystring:e.canonicalQuerystring}}r.AwsRequestSigner=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,i.createCrypto)()}async getRequestOptions(e){if(!e.url)throw RangeError('"url" is required in "amzOptions"');let t="object"==typeof e.data?JSON.stringify(e.data):e.data,r=e.url,i=e.method||"GET",s=e.body||t,o=e.headers,a=await this.getCredentials(),u=new URL(r);if("string"!=typeof s&&void 0!==s)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let c=await l({crypto:this.crypto,host:u.host,canonicalUri:u.pathname,canonicalQuerystring:u.search.slice(1),method:i,region:this.region,securityCredentials:a,requestPayload:s,additionalAmzHeaders:o}),d=n.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:u.host},o||{});a.token&&n.Gaxios.mergeHeaders(d,{"x-amz-security-token":a.token});let h={url:r,method:i,headers:d};return void 0!==s&&(h.body=s),h}}},306560,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.BaseExternalAccountClient=r.CLOUD_RESOURCE_MANAGER=r.EXTERNAL_ACCOUNT_TYPE=r.EXPIRATION_TIME_OFFSET=void 0;let n=e.r(957612),i=e.r(688947),s=e.r(911656),o=e.r(605332),a=e.r(415733),l=e.r(393714),u="https://www.googleapis.com/auth/cloud-platform";r.EXPIRATION_TIME_OFFSET=3e5,r.EXTERNAL_ACCOUNT_TYPE="external_account",r.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";class c extends s.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#c=null;constructor(e){super(e);let t=(0,a.originalOrCamelOptions)(e),n=t.get("type");if(n&&n!==r.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${r.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=t.get("client_id"),s=t.get("client_secret");this.tokenUrl=t.get("token_url")??"https://sts.{universeDomain}/v1/token".replace("{universeDomain}",this.universeDomain);let l=t.get("subject_token_type"),c=t.get("workforce_pool_user_project"),d=t.get("service_account_impersonation_url"),h=t.get("service_account_impersonation"),p=(0,a.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:s}),this.stsCredential=new o.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[u],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=l,this.workforcePoolUserProject=c;let f=RegExp("//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+");if(this.workforcePoolUserProject&&!this.audience.match(f))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=p,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=3600),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);let e=/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl);return e?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let t=await this.getRequestHeaders(),r={...c.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`};s.AuthClient.setMethodName(r,"getProjectId");let n=await this.transporter.request(r);return this.projectId=n.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,s=r.config.data instanceof i.Readable;if(!t&&(401===n||403===n)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){this.#c=this.#c||this.#d();try{return await this.#c}finally{this.#c=null}}async #d(){let e=await this.retrieveSubjectToken(),t={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",audience:this.audience,requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[u]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,n=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(t,n,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+1e3*i.expires_in,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let t={...c.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};s.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let r=await this.transporter.request(t),n=r.data;return{access_token:n.accessToken,expiry_date:new Date(n.expireTime).getTime(),res:r}}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}getScopesArray(){return"string"==typeof this.scopes?[this.scopes]:this.scopes||[u]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=void 0!==this.serviceAccountImpersonationUrl,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${l.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}r.BaseExternalAccountClient=c},958218,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.CertificateSubjectTokenSupplier=r.InvalidConfigurationError=r.CertificateSourceUnavailableError=r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;let n=e.r(415733),i=e.r(522734),s=e.r(254799),o=e.r(524836);r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class a extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}}r.CertificateSourceUnavailableError=a;class l extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}}r.InvalidConfigurationError=l,r.CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new l("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new l("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new l("Cannot create mTLS Agent with missing certificate or key");return new o.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#h();let{certPath:e,keyPath:t}=await this.#p();return{cert:this.cert,key:this.key}=await this.#f(e,t),await this.#m(this.cert)}async #h(){let e=this.certificateConfigPath;if(e){if(await (0,n.isValidFile)(e))return e;throw new a(`Provided certificate config path is invalid: ${e}`)}let t=process.env[r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await (0,n.isValidFile)(t))return t;throw new a(`Path from environment variable "${r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let i=(0,n.getWellKnownCertificateConfigFileLocation)();if(await (0,n.isValidFile)(i))return i;throw new a(`Could not find certificate configuration file. Searched override path, the "${r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async #p(){let e,t=this.certificateConfigPath;try{e=await i.promises.readFile(t,"utf8")}catch(e){throw new a(`Failed to read certificate config file at: ${t}`)}try{let r=JSON.parse(e),n=r?.cert_configs?.workload?.cert_path,i=r?.cert_configs?.workload?.key_path;if(!n||!i)throw new l(`Certificate config file (${t}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:n,keyPath:i}}catch(e){if(e instanceof l)throw e;throw new l(`Failed to parse certificate config from ${t}: ${e.message}`)}}async #f(e,t){let r,n;try{r=await i.promises.readFile(e),new s.X509Certificate(r)}catch(r){let t=r instanceof Error?r.message:String(r);throw new a(`Failed to read certificate file at ${e}: ${t}`)}try{n=await i.promises.readFile(t),(0,s.createPrivateKey)(n)}catch(r){let e=r instanceof Error?r.message:String(r);throw new a(`Failed to read private key file at ${t}: ${e}`)}return{cert:r,key:n}}async #m(e){let t=new s.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let e,r=((await i.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((e,t)=>{try{return new s.X509Certificate(e)}catch(r){let e=r instanceof Error?r.message:String(r);throw new l(`Failed to parse certificate at index ${t} in trust chain file ${this.trustChainPath}: ${e}`)}}),n=r.findIndex(e=>t.raw.equals(e.raw));if(-1===n)e=[t,...r];else if(0===n)e=r;else throw new l(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${n}).`);return JSON.stringify(e.map(e=>e.raw.toString("base64")))}catch(t){if(t instanceof l)throw t;let e=t instanceof Error?t.message:String(t);throw new a(`Failed to process certificate chain from ${this.trustChainPath}: ${e}`)}}}},70814,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.Compute=void 0;let n=e.r(957612),i=e.r(482e3),s=e.r(800701);class o extends s.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e,t=`service-accounts/${this.serviceAccountEmail}/token`;try{let r={property:t};this.scopes.length>0&&(r.params={scopes:this.scopes.join(",")}),e=await i.instance(r)}catch(e){throw e instanceof n.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}let r=e;return e&&e.expires_in&&(r.expiry_date=new Date().getTime()+1e3*e.expires_in,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let t,r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`;try{t=await i.instance({property:r})}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return t}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,403===t.status?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:404===t.status&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}}r.Compute=o},541033,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.DefaultAwsSecurityCredentialsSupplier=void 0;let n=e.r(911656);r.DefaultAwsSecurityCredentialsSupplier=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#g)return this.#g;let t=new Headers;if(!this.#g&&this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#y(e.transporter)),!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:t};n.AuthClient.setMethodName(r,"getAwsRegion");let i=await e.transporter.request(r);return i.data.substr(0,i.data.length-1)}async getAwsSecurityCredentials(e){if(this.#_)return this.#_;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#y(e.transporter));let r=await this.#E(t,e.transporter),n=await this.#v(r,t,e.transporter);return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,token:n.Token}}async #y(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return n.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async #E(e,t){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return n.AuthClient.setMethodName(r,"#getAwsRoleName"),(await t.request(r)).data}async #v(e,t,r){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t};return n.AuthClient.setMethodName(i,"#retrieveAwsSecurityCredentials"),(await r.request(i)).data}get #g(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get #_(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}}},956777,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.DownscopedClient=r.EXPIRATION_TIME_OFFSET=r.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;let n=e.r(957612),i=e.r(688947),s=e.r(911656),o=e.r(605332);r.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,r.EXPIRATION_TIME_OFFSET=3e5;class a extends s.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof s.AuthClient?{}:e),e instanceof s.AuthClient?(this.authClient=e,this.credentialAccessBoundary=t):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),0===this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length)throw Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>r.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${r.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let e of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(0===e.availablePermissions.length)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new o.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,s=r.config.data instanceof i.Readable;if(!t&&(401===n||403===n)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t=await this.stsCredential.exchangeToken({grantType:"urn:ietf:params:oauth:grant-type:token-exchange",requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:"urn:ietf:params:oauth:token-type:access_token"},void 0,this.credentialAccessBoundary),r=this.authClient.credentials?.expiry_date||null,n=t.expires_in?new Date().getTime()+1e3*t.expires_in:r;return this.cachedDownscopedAccessToken={access_token:t.access_token,expiry_date:n,res:t.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}}r.DownscopedClient=a},880243,(e,t,r)=>{var n,i;let s;Object.defineProperty(r,"__esModule",{value:!0}),r.GCPEnv=void 0,r.clear=function(){s=void 0},r.getEnv=a;let o=e.r(482e3);async function a(){return s||(s=l())}async function l(){n.NONE;return process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME?n.APP_ENGINE:process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET?n.CLOUD_FUNCTIONS:await c()?await u()?n.KUBERNETES_ENGINE:process.env.K_CONFIGURATION?n.CLOUD_RUN:process.env.CLOUD_RUN_JOB?n.CLOUD_RUN_JOBS:n.COMPUTE_ENGINE:n.NONE}async function u(){try{return await o.instance("attributes/cluster-name"),!0}catch(e){return!1}}async function c(){return o.isAvailable()}(i=n||(r.GCPEnv=n={})).APP_ENGINE="APP_ENGINE",i.KUBERNETES_ENGINE="KUBERNETES_ENGINE",i.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",i.COMPUTE_ENGINE="COMPUTE_ENGINE",i.CLOUD_RUN="CLOUD_RUN",i.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",i.NONE="NONE"},671006,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidSubjectTokenError=r.InvalidMessageFieldError=r.InvalidCodeFieldError=r.InvalidTokenTypeFieldError=r.InvalidExpirationTimeFieldError=r.InvalidSuccessFieldError=r.InvalidVersionFieldError=r.ExecutableResponseError=r.ExecutableResponse=void 0;let n="urn:ietf:params:oauth:token-type:saml2",i="urn:ietf:params:oauth:token-type:id_token",s="urn:ietf:params:oauth:token-type:jwt";r.ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new a("Executable response must contain a 'version' field.");if(void 0===e.success)throw new l("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==n&&this.tokenType!==i&&this.tokenType!==s)throw new u(`Executable response must contain a 'token_type' field when successful and it must be one of ${i}, ${s}, or ${n}.`);if(this.tokenType===n){if(!e.saml_response)throw new h(`Executable response must contain a 'saml_response' field when token_type=${n}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new h(`Executable response must contain a 'id_token' field when token_type=${i} or ${s}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new c("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new d("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return void 0!==this.expirationTime&&this.expirationTime<Math.round(Date.now()/1e3)}};class o extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}r.ExecutableResponseError=o;class a extends o{}r.InvalidVersionFieldError=a;class l extends o{}r.InvalidSuccessFieldError=l,r.InvalidExpirationTimeFieldError=class extends o{};class u extends o{}r.InvalidTokenTypeFieldError=u;class c extends o{}r.InvalidCodeFieldError=c;class d extends o{}r.InvalidMessageFieldError=d;class h extends o{}r.InvalidSubjectTokenError=h},348019,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.ExternalAccountAuthorizedUserClient=r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;let n=e.r(911656),i=e.r(846944),s=e.r(957612),o=e.r(688947),a=e.r(306560);r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";class l extends i.OAuthClientAuthHandler{#b;constructor(e){super(e),this.#b=e.tokenRefreshEndpoint}async refreshToken(e,t){let r={...l.RETRY_CONFIG,url:this.#b,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};n.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let e=await this.transporter.request(r),t=e.data;return t.res=e,t}catch(e){if(e instanceof s.GaxiosError&&e.response)throw(0,i.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}}class u extends n.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new l({tokenRefreshEndpoint:e.token_url??"https://sts.{universeDomain}/v1/oauthtoken".replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,"number"!=typeof e?.eagerRefreshThresholdMillis?this.eagerRefreshThresholdMillis=a.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=s.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,i=r.config.data instanceof o.Readable;if(!t&&(401===n||403===n)&&!i&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+1e3*e.expires_in,res:e.res},void 0!==e.refresh_token&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}}r.ExternalAccountAuthorizedUserClient=u},145037,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.ExternalAccountClient=void 0;let n=e.r(306560),i=e.r(176868),s=e.r(690220),o=e.r(623238);r.ExternalAccountClient=class{constructor(){throw Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===n.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new s.AwsClient(e):e.credential_source?.executable?new o.PluggableAuthClient(e):new i.IdentityPoolClient(e):null}}},237289,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.FileSubjectTokenSupplier=void 0;let n=e.r(224361),i=e.r(522734),s=(0,n.promisify)(i.readFile??(()=>{})),o=(0,n.promisify)(i.realpath??(()=>{})),a=(0,n.promisify)(i.lstat??(()=>{}));r.FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e,t=this.filePath;try{if(t=await o(t),!(await a(t)).isFile())throw Error()}catch(e){throw e instanceof Error&&(e.message=`The file at ${t} does not exist, or it is not a file. ${e.message}`),e}let r=await s(t,{encoding:"utf8"});if("text"===this.formatType?e=r:"json"===this.formatType&&this.subjectTokenFieldName&&(e=JSON.parse(r)[this.subjectTokenFieldName]),!e)throw Error("Unable to parse the subject_token from the credential_source file");return e}}},264794,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleAuth=r.GoogleAuthExceptionMessages=void 0;let n=e.r(233405),i=e.r(522734),s=e.r(957612),o=e.r(482e3),a=e.r(446786),l=e.r(814747),u=e.r(859501),c=e.r(70814),d=e.r(180732),h=e.r(880243),p=e.r(24553),f=e.r(416260),m=e.r(636126),g=e.r(145037),y=e.r(306560),_=e.r(911656),E=e.r(348019),v=e.r(415733);r.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:"Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"},r.GoogleAuth=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#w=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(r.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(!e)return this.getProjectIdAsync();this.getProjectIdAsync().then(t=>e(null,t),e)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===r.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId())return this._cachedProjectId=e,e;throw Error(r.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await o.universe("universe-domain"),e||=_.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=_.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,v.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=_.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let r;if("function"==typeof e?t=e:r=e,!t)return this.getApplicationDefaultAsync(r);this.getApplicationDefaultAsync(r).then(e=>t(null,e.credential,e.projectId),t)}async getApplicationDefaultAsync(e={}){let t;if(this.cachedCredential)return await this.#A(this.cachedCredential,null);if((t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e))||(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e)))return t instanceof p.JWT?t.scopes=this.scopes:t instanceof y.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#A(t);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#A(new c.Compute(e));throw Error(r.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async #A(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=o.getGCPResidency()||await o.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||0===t.length)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(e){throw e instanceof Error&&(e.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`),e}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let e=process.env.HOME;e&&(t=l.join(e,".config"))}return(t&&(t=l.join(t,"gcloud","application_default_credentials.json"),i.existsSync(t)||(t=null)),t)?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||0===e.length)throw Error("The file path is invalid.");try{if(e=i.realpathSync(e),!i.lstatSync(e).isFile())throw Error()}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}let r=i.createReadStream(e);return this.fromStream(r,t)}fromImpersonatedJSON(e){if(!e)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==m.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${m.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let n=(this.scopes||e.scopes||this.defaultScopes)??[];return new m.Impersonated({...e,sourceClient:t,targetPrincipal:r,targetScopes:Array.isArray(n)?n:[n]})}fromJSON(e,t={}){let r,n=(0,v.originalOrCamelOptions)(t).get("universe_domain");return e.type===f.USER_REFRESH_ACCOUNT_TYPE?(r=new f.UserRefreshClient(t)).fromJSON(e):e.type===m.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===y.EXTERNAL_ACCOUNT_TYPE?(r=g.ExternalAccountClient.fromJSON({...e,...t})).scopes=this.getAnyScopes():e.type===E.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new E.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,r=new p.JWT(t),this.setGapicJWTValues(r),r.fromJSON(e)),n&&(r.universeDomain=n),r}_cacheClientFromJSON(e,t){let r=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,t={},r){let n={};if("function"==typeof t?r=t:n=t,!r)return this.fromStreamAsync(e,n);this.fromStreamAsync(e,n).then(e=>r(null,e),r)}fromStreamAsync(e,t){return new Promise((r,n)=>{if(!e)throw Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",n).on("data",e=>i.push(e)).on("end",()=>{try{try{let e=JSON.parse(i.join("")),n=this._cacheClientFromJSON(e,t);return r(n)}catch(t){if(!this.keyFilename)throw t;let e=new p.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=e,this.setGapicJWTValues(e),r(e)}}catch(e){return n(e)}})})}fromAPIKey(e,t={}){return new p.JWT({...t,apiKey:e})}_isWindows(){let e=a.platform();return!!e&&!!(e.length>=3)&&"win"===e.substring(0,3).toLowerCase()}async getDefaultServiceProjectId(){return new Promise(e=>{(0,n.exec)("gcloud config config-helper --format json",(t,r)=>{if(!t&&r)try{let t=JSON.parse(r).configuration.properties.core.project;e(t);return}catch(e){}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let e=await this.getClient();if(e&&e.projectId)return e.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==y.EXTERNAL_ACCOUNT_TYPE)return null;let e=await this.getClient();return await e.getProjectId()}async getGCEProjectId(){try{return await o.project("project-id")}catch(e){return null}}getCredentials(e){if(!e)return this.getCredentialsAsync();this.getCredentialsAsync().then(t=>e(null,t),e)}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof m.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof y.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[e,t]=await Promise.all([o.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw Error(r.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#w=this.#w||this.#S();try{return await this.#w}finally{this.#w=null}}async #S(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=l.resolve(this.keyFilename),t=i.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#A(e);return t}{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new d.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){let e=await this.getClient();return(await e.getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,r=await this.getClient(),n=await r.getRequestHeaders(t);return e.headers=s.Gaxios.mergeHeaders(e.headers,n),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,h.getEnv)()}async sign(e,t){let r=await this.getClient(),n=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${n}/v1/projects/-/serviceAccounts/`,r instanceof m.Impersonated)return(await r.sign(e)).signedBlob;let i=(0,u.createCrypto)();if(r instanceof p.JWT&&r.key)return await i.sign(r.key,e);let s=await this.getCredentials();if(!s.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(i,s.client_email,e,t)}async signBlob(e,t,r,n){let i=new URL(n+`${t}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}},403994,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.IAMAuth=void 0,r.IAMAuth=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}},176868,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.IdentityPoolClient=void 0;let n=e.r(306560),i=e.r(415733),s=e.r(237289),o=e.r(363057),a=e.r(958218),l=e.r(605332),u=e.r(957612);class c extends n.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=(0,i.originalOrCamelOptions)(e),r=t.get("credential_source"),n=t.get("subject_token_supplier");if(!r&&!n)throw Error("A credential source or subject token supplier must be specified.");if(r&&n)throw Error("Only one of credential source or subject token supplier can be specified.");if(n)this.subjectTokenSupplier=n,this.credentialSourceType="programmatic";else{let e=(0,i.originalOrCamelOptions)(r),t=(0,i.originalOrCamelOptions)(e.get("format")),n=t.get("type")||"text",l=t.get("subject_token_field_name");if("json"!==n&&"text"!==n)throw Error(`Invalid credential_source format "${n}"`);if("json"===n&&!l)throw Error("Missing subject_token_field_name for JSON credential_source format");let u=e.get("file"),d=e.get("url"),h=e.get("certificate"),p=e.get("headers");if(u&&d||d&&h||u&&h)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(u)this.credentialSourceType="file",this.subjectTokenSupplier=new s.FileSubjectTokenSupplier({filePath:u,formatType:n,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new o.UrlSubjectTokenSupplier({url:d,formatType:n,subjectTokenFieldName:l,headers:p,additionalGaxiosOptions:c.RETRY_CONFIG});else if(h){this.credentialSourceType="certificate";let e=new a.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=e}else throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof a.CertificateSubjectTokenSupplier){let e=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new l.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new u.Gaxios({agent:e})}),this.transporter=new u.Gaxios({...this.transporter.defaults||{},agent:e})}return e}}r.IdentityPoolClient=c},180732,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.IdTokenClient=void 0;let n=e.r(800701);class i extends n.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let e=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:e,expiry_date:this.getIdTokenExpiryDate(e)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return 1e3*JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp}}r.IdTokenClient=i},636126,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.Impersonated=r.IMPERSONATED_ACCOUNT_TYPE=void 0;let n=e.r(800701),i=e.r(957612),s=e.r(415733);r.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class o extends n.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new n.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,(0,s.originalOrCamelOptions)(e).get("universe_domain")){if(this.sourceClient.universeDomain!==this.universeDomain)throw RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`)}else this.universeDomain=this.sourceClient.universeDomain;this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${t}:signBlob`,n={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...o.RETRY_CONFIG,url:r,data:n,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},n=await this.sourceClient.request({...o.RETRY_CONFIG,url:t,data:r,method:"POST"}),i=n.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:n}}catch(r){if(!(r instanceof Error))throw r;let e=0,t="";if(r instanceof i.GaxiosError&&(e=r?.response?.data?.error?.status,t=r?.response?.data?.error?.message),e&&t)throw r.message=`${e}: unable to impersonate: ${t}`,r;throw r.message=`unable to impersonate: ${r}`,r}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...o.RETRY_CONFIG,url:n,data:i,method:"POST"})).data.token}}r.Impersonated=o},910247,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.JWTAccess=void 0;let n=e.r(258184),i=e.r(415733),s={alg:"RS256",typ:"JWT"};r.JWTAccess=class e{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new i.LRUCache({capacity:500,maxAge:36e5});constructor(e,t,r,n){this.email=e,this.key=t,this.keyId=r,this.eagerRefreshThresholdMillis=n??3e5}getCachedKey(e,t){let r=e;if(t&&Array.isArray(t)&&t.length?r=e?`${e}_${t.join("_")}`:`${t.join("_")}`:"string"==typeof t&&(r=e?`${e}_${t}`:t),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(t,r,i){let o,a=this.getCachedKey(t,i),l=this.cache.get(a),u=Date.now();if(l&&l.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(l.headers);let c=Math.floor(Date.now()/1e3),d=e.getExpirationTime(c);if(Array.isArray(i)&&(i=i.join(" ")),o=i?{iss:this.email,sub:this.email,scope:i,exp:d,iat:c}:{iss:this.email,sub:this.email,aud:t,exp:d,iat:c},r){for(let e in o)if(r[e])throw Error(`The '${e}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let h=this.keyId?{...s,kid:this.keyId}:s,p=Object.assign(o,r),f=n.sign({header:h,payload:p,secret:this.key}),m=new Headers({authorization:`Bearer ${f}`});return this.cache.set(a,{expiration:1e3*d,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}fromStreamAsync(e){return new Promise((t,r)=>{e||r(Error("Must pass in a stream containing the service account auth settings."));let n="";e.setEncoding("utf8").on("data",e=>n+=e).on("error",r).on("end",()=>{try{let e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}})})}}},24553,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.JWT=void 0;let n=e.r(866667),i=e.r(910247),s=e.r(800701),o=e.r(911656);class a extends s.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new a(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==o.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==o.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${o.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:e}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${e.id_token}`}))}}else{let t;this.access||(this.access=new i.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis)),this.hasUserScopes()?t=this.scopes:e||(t=this.defaultScopes);let r=this.useJWTAccessWithScope||this.universeDomain!==o.DEFAULT_UNIVERSE,n=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,r?t:void 0);return{headers:this.addSharedMetadataHeaders(n)}}return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let t=new n.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){return!!this.scopes&&this.scopes.length>0}hasAnyScopes(){return!!this.scopes&&!!(this.scopes.length>0)||!!this.defaultScopes&&!!(this.defaultScopes.length>0)}authorize(e){if(!e)return this.authorizeAsync();this.authorizeAsync().then(t=>e(null,t),e)}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),t={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",t),{res:null,tokens:t}}createGToken(){return this.gtoken||(this.gtoken=new n.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}fromStreamAsync(e){return new Promise((t,r)=>{if(!e)throw Error("Must pass in a stream containing the service account auth settings.");let n="";e.setEncoding("utf8").on("error",r).on("data",e=>n+=e).on("end",()=>{try{let e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}})})}fromAPIKey(e){if("string"!=typeof e)throw Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),t=await e.getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}r.JWT=a},442602,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.LoginTicket=void 0,r.LoginTicket=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}},800701,(e,t,r)=>{var n,i,s,o,a,l;Object.defineProperty(r,"__esModule",{value:!0}),r.OAuth2Client=r.ClientAuthentication=r.CertificateFormat=r.CodeChallengeMethod=void 0;let u=e.r(957612),c=e.r(145706),d=e.r(688947),h=e.r(732955),p=e.r(415733),f=e.r(859501),m=e.r(911656),g=e.r(442602);(o=n||(r.CodeChallengeMethod=n={})).Plain="plain",o.S256="S256",(a=i||(r.CertificateFormat=i={})).PEM="PEM",a.JWK="JWK",(l=s||(r.ClientAuthentication=s={})).ClientSecretPost="ClientSecretPost",l.ClientSecretBasic="ClientSecretBasic",l.None="None";class y extends m.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=i.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,r){super("object"==typeof e?e:{}),"object"!=typeof e&&(e={clientId:e,clientSecret:t,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||s.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+c.stringify(e)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,f.createCrypto)(),t=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),r=(await e.sha256DigestBase64(t)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:t,codeChallenge:r}}getToken(e,t){let r="string"==typeof e?{code:e}:e;if(!t)return this.getTokenAsync(r);this.getTokenAsync(r).then(e=>t(null,e.tokens,e.res),e=>t(e,null,e.response))}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,n={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===s.ClientSecretBasic){let e=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${e.toString("base64")}`)}this.clientAuthentication===s.ClientSecretPost&&(n.client_secret=this._clientSecret);let i={...y.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,p.removeUndefinedValuesInObject)(n)),headers:r};m.AuthClient.setMethodName(i,"getTokenAsync");let o=await this.transporter.request(i),a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+1e3*o.data.expires_in,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(t=>(this.refreshTokenPromises.delete(e),t),t=>{throw this.refreshTokenPromises.delete(e),t});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){let t;if(!e)throw Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"};try{let e={...y.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,p.removeUndefinedValuesInObject)(n))};m.AuthClient.setMethodName(e,"refreshTokenNoCache"),t=await this.transporter.request(e)}catch(e){throw e instanceof u.GaxiosError&&"invalid_grant"===e.message&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}let i=t.data;return t.data&&t.data.expires_in&&(i.expiry_date=new Date().getTime()+1e3*t.data.expires_in,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:t}}refreshAccessToken(e){if(!e)return this.refreshAccessTokenAsync();this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e)}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(!e)return this.getAccessTokenAsync();this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e)}async getAccessTokenAsync(){if(!(!this.credentials.access_token||this.isTokenExpiring()))return{token:this.credentials.access_token};{if(!this.credentials.refresh_token)if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token)return this.setCredentials(e),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let e=await this.refreshAccessTokenAsync();if(!e.credentials||e.credentials&&!e.credentials.access_token)throw Error("Could not refresh access token.");return{token:e.credentials.access_token,res:e.res}}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let e=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(e)}}if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token){this.setCredentials(e);let t=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(t)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,n=null;try{n=(r=await this.refreshToken(t.refresh_token)).tokens}catch(e){throw e.response&&(403===e.response.status||404===e.response.status)&&(e.message=`Could not refresh access token: ${e.message}`),e}let i=this.credentials;i.token_type=i.token_type||"Bearer",n.refresh_token=i.refresh_token,this.credentials=n;let s=new Headers({authorization:i.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(s),res:r.res}}static getRevokeTokenUrl(e){return new y().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let r={...y.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(m.AuthClient.setMethodName(r,"revokeToken"),!t)return this.transporter.request(r);this.transporter.request(r).then(e=>t(null,e),t)}revokeCredentials(e){if(!e)return this.revokeCredentialsAsync();this.revokeCredentialsAsync().then(t=>e(null,t),e)}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw Error("No access token to revoke.")}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){try{let t=await this.getRequestMetadataAsync();return e.headers=u.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),s=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,o=r.config.data instanceof d.Readable,a=401===n||403===n;if(!t&&a&&!o&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&a&&!o&&s){let t=await this.processAndValidateRefreshHandler();return t?.access_token&&this.setCredentials(t),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&"function"!=typeof t)throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(!t)return this.verifyIdTokenAsync(e);this.verifyIdTokenAsync(e).then(e=>t(null,e),t)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...y.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+1e3*t.expires_in,scopes:t.scope.split(" ")},t);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(!e)return this.getFederatedSignonCertsAsync();this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e)}async getFederatedSignonCertsAsync(){let e,t,r=new Date().getTime(),n=(0,f.hasBrowserCrypto)()?i.JWK:i.PEM;if(this.certificateExpiry&&r<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};switch(n){case i.PEM:t=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case i.JWK:t=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${n}`)}try{let r={...y.RETRY_CONFIG,url:t};m.AuthClient.setMethodName(r,"getFederatedSignonCertsAsync"),e=await this.transporter.request(r)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}let s=e?.headers.get("cache-control"),o=-1;if(s){let e=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;e&&(o=1e3*Number(e))}let a={};switch(n){case i.PEM:a=e.data;break;case i.JWK:for(let t of e.data.keys)a[t.kid]=t;break;default:throw Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=-1===o?null:new Date(l.getTime()+o),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,format:n,res:e}}getIapPublicKeys(e){if(!e)return this.getIapPublicKeysAsync();this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e)}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...y.RETRY_CONFIG,url:t};m.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,r,n,i){let s,o,a=(0,f.createCrypto)();i||(i=y.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(3!==l.length)throw Error("Wrong number of segments in token: "+e);let u=l[0]+"."+l[1],c=l[2];try{s=JSON.parse(a.decodeBase64StringUtf8(l[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${l[0]}': ${e.message}`),e}if(!s)throw Error("Can't parse token envelope: "+l[0]);try{o=JSON.parse(a.decodeBase64StringUtf8(l[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${l[0]}`),e}if(!o)throw Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(t,s.kid))throw Error("No pem found for envelope: "+JSON.stringify(s));let d=t[s.kid];if("ES256"===s.alg&&(c=h.joseToDer(c,"ES256").toString("base64")),!await a.verify(d,u,c))throw Error("Invalid token signature: "+e);if(!o.iat)throw Error("No issue time in token: "+JSON.stringify(o));if(!o.exp)throw Error("No expiration time in token: "+JSON.stringify(o));let p=Number(o.iat);if(isNaN(p))throw Error("iat field using invalid format");let m=Number(o.exp);if(isNaN(m))throw Error("exp field using invalid format");let _=new Date().getTime()/1e3;if(m>=_+i)throw Error("Expiration time too far in future: "+JSON.stringify(o));let E=p-y.CLOCK_SKEW_SECS_,v=m+y.CLOCK_SKEW_SECS_;if(_<E)throw Error("Token used too early, "+_+" < "+E+": "+JSON.stringify(o));if(_>v)throw Error("Token used too late, "+_+" > "+v+": "+JSON.stringify(o));if(n&&0>n.indexOf(o.iss))throw Error("Invalid issuer, expected one of ["+n+"], but got "+o.iss);if(null!=r){let e=o.aud;if(!(r.constructor===Array?r.indexOf(e)>-1:e===r))throw Error("Wrong recipient, payload audience != requiredAudience")}return new g.LoginTicket(s,o)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return!!e&&e<=new Date().getTime()+this.eagerRefreshThresholdMillis}}r.OAuth2Client=y},846944,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.OAuthClientAuthHandler=void 0,r.getErrorFromOAuthErrorResponse=function(e,t){let r=e.error,n=e.error_description,i=e.error_uri,s=`Error code ${r}`;void 0!==n&&(s+=`: ${n}`),void 0!==i&&(s+=` - ${i}`);let o=Error(s);if(t){let e=Object.keys(t);t.stack&&e.push("stack"),e.forEach(e=>{"message"!==e&&Object.defineProperty(o,e,{value:t[e],writable:!1,enumerable:!0})})}return o};let n=e.r(957612),i=e.r(859501),s=["PUT","POST","PATCH"];r.OAuthClientAuthHandler=class{#T=(0,i.createCrypto)();#O;transporter;constructor(e){e&&"clientId"in e?(this.#O=e,this.transporter=new n.Gaxios):(this.#O=e?.clientAuthentication,this.transporter=e?.transporter||new n.Gaxios)}applyClientAuthenticationOptions(e,t){e.headers=n.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),t||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=n.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#O?.confidentialClientType==="basic"){e.headers=n.Gaxios.mergeHeaders(e.headers);let t=this.#O.clientId,r=this.#O.clientSecret||"",i=this.#T.encodeBase64StringUtf8(`${t}:${r}`);n.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#O?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!s.includes(t))throw Error(`${t} HTTP method does not support ${this.#O.confidentialClientType} client authentication`);let r=new Headers(e.headers).get("content-type");if(r?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let t=new URLSearchParams(e.data??"");t.append("client_id",this.#O.clientId),t.append("client_secret",this.#O.clientSecret||""),e.data=t}else if(r?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#O.clientId,client_secret:this.#O.clientSecret||""});else throw Error(`${r} content-types are not supported with ${this.#O.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}},853534,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.PassThroughClient=void 0;let n=e.r(911656);class i extends n.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}r.PassThroughClient=i},623238,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.PluggableAuthClient=r.ExecutableError=void 0;let n=e.r(306560),i=e.r(671006),s=e.r(920336);var o=e.r(920336);Object.defineProperty(r,"ExecutableError",{enumerable:!0,get:function(){return o.ExecutableError}});class a extends n.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable||(this.command=e.credential_source.executable.command,!this.command))throw Error('No valid Pluggable Auth "credential_source" provided.');if(void 0===e.credential_source.executable.timeout_millis)this.timeoutMillis=3e4;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<5e3||this.timeoutMillis>12e4)throw Error("Timeout must be between 5000 and 120000 milliseconds.");this.outputFile=e.credential_source.executable.output_file,this.handler=new s.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){let e;if("1"!==process.env.GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES)throw Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>1)throw Error("Version of executable is not currently supported, maximum supported version is 1.");if(!e.success)throw new s.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new i.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw Error("Executable response is expired.");return e.subjectToken}}r.PluggableAuthClient=a},920336,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.PluggableAuthHandler=r.ExecutableError=void 0;let n=e.r(671006),i=e.r(233405),s=e.r(522734);class o extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}r.ExecutableError=o,r.PluggableAuthHandler=class e{commandComponents;timeoutMillis;outputFile;constructor(t){if(!t.command)throw Error("No command provided.");if(this.commandComponents=e.parseCommand(t.command),this.timeoutMillis=t.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=t.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,r)=>{let s=i.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";s.stdout.on("data",e=>{a+=e}),s.stderr.on("data",e=>{a+=e});let l=setTimeout(()=>(s.removeAllListeners(),s.kill(),r(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);s.on("close",e=>{if(clearTimeout(l),0!==e)return r(new o(a,e.toString()));try{let e=JSON.parse(a),r=new n.ExecutableResponse(e);return t(r)}catch(e){if(e instanceof n.ExecutableResponseError)return r(e);return r(new n.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}})})}async retrieveCachedResponse(){let e;if(!this.outputFile||0===this.outputFile.length)return;try{e=await s.promises.realpath(this.outputFile)}catch{return}if(!(await s.promises.lstat(e)).isFile())return;let t=await s.promises.readFile(e,{encoding:"utf8"});if(""!==t)try{let e=JSON.parse(t);if(new n.ExecutableResponse(e).isValid())return new n.ExecutableResponse(e);return}catch(e){if(e instanceof n.ExecutableResponseError)throw e;throw new n.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let e=0;e<t.length;e++)'"'===t[e][0]&&'"'===t[e].slice(-1)&&(t[e]=t[e].slice(1,-1));return t}}},416260,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UserRefreshClient=r.USER_REFRESH_ACCOUNT_TYPE=void 0;let n=e.r(800701),i=e.r(911656);r.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class s extends n.OAuth2Client{_refreshToken;constructor(e,t,r,n,i){let s=e&&"object"==typeof e?e:{clientId:e,clientSecret:t,refreshToken:r,eagerRefreshThresholdMillis:n,forceRefreshOnFailure:i};super(s),this._refreshToken=s.refreshToken,this.credentials.refresh_token=s.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...s.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return i.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the user refresh token");if("authorized_user"!==e.type)throw Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}async fromStreamAsync(e){return new Promise((t,r)=>{if(!e)return r(Error("Must pass in a stream containing the user refresh token."));let n="";e.setEncoding("utf8").on("error",r).on("data",e=>n+=e).on("end",()=>{try{let e=JSON.parse(n);return this.fromJSON(e),t()}catch(e){return r(e)}})})}static fromJSON(e){let t=new s;return t.fromJSON(e),t}}r.UserRefreshClient=s},605332,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.StsCredentials=void 0;let n=e.r(957612),i=e.r(911656),s=e.r(846944),o=e.r(415733);class a extends s.OAuthClientAuthHandler{#I;constructor(e={tokenExchangeEndpoint:""},t){("object"!=typeof e||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#I=e.tokenExchangeEndpoint}async exchangeToken(e,t,r){let l={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},u={...a.RETRY_CONFIG,url:this.#I.toString(),method:"POST",headers:t,data:new URLSearchParams((0,o.removeUndefinedValuesInObject)(l))};i.AuthClient.setMethodName(u,"exchangeToken"),this.applyClientAuthenticationOptions(u);try{let e=await this.transporter.request(u),t=e.data;return t.res=e,t}catch(e){if(e instanceof n.GaxiosError&&e.response)throw(0,s.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}}r.StsCredentials=a},363057,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UrlSubjectTokenSupplier=void 0;let n=e.r(911656);r.UrlSubjectTokenSupplier=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let t,r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};if(n.AuthClient.setMethodName(r,"getSubjectToken"),"text"===this.formatType?t=(await e.transporter.request(r)).data:"json"===this.formatType&&this.subjectTokenFieldName&&(t=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!t)throw Error("Unable to parse the subject_token from the credential_source URL");return t}}},269216,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.BrowserCrypto=void 0;let n=e.r(906920),i=e.r(946902);r.BrowserCrypto=class e{constructor(){throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return n.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),n.fromByteArray(t)}static padBase64(e){for(;e.length%4!=0;)e+="=";return e}async verify(t,r,i){let s={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),a=n.toByteArray(e.padBase64(i)),l=await window.crypto.subtle.importKey("jwk",t,s,!0,["verify"]);return await window.crypto.subtle.verify(s,l,a,o)}async sign(e,t){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(t),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),o=await window.crypto.subtle.sign(r,s,i);return n.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(t){let r=n.toByteArray(e.padBase64(t));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return n.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return(0,i.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,t){let r="string"==typeof e?e:String.fromCharCode(...new Uint16Array(e)),n=new TextEncoder,i=await window.crypto.subtle.importKey("raw",n.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,n.encode(t))}}},859501,(e,t,r)=>{var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.createCrypto=function(){return new s.NodeCrypto},r.hasBrowserCrypto=function(){return!1},e.r(269216);let s=e.r(521962);i(e.r(946902),r)},521962,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.NodeCrypto=void 0;let n=e.r(254799);r.NodeCrypto=class{async sha256DigestBase64(e){return n.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return n.randomBytes(e).toString("base64")}async verify(e,t,r){let i=n.createVerify("RSA-SHA256");return i.update(t),i.end(),i.verify(e,r,"base64")}async sign(e,t){let r=n.createSign("RSA-SHA256");return r.update(t),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return n.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){var r,i;let s="string"==typeof e?e:(r=e,Buffer.from(r));return(i=n.createHmac("sha256",s).update(t).digest()).buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}}},946902,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.fromArrayBufferToHex=function(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}},947334,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleAuth=r.auth=r.PassThroughClient=r.ExternalAccountAuthorizedUserClient=r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=r.ExecutableError=r.PluggableAuthClient=r.DownscopedClient=r.BaseExternalAccountClient=r.ExternalAccountClient=r.IdentityPoolClient=r.AwsRequestSigner=r.AwsClient=r.UserRefreshClient=r.LoginTicket=r.ClientAuthentication=r.OAuth2Client=r.CodeChallengeMethod=r.Impersonated=r.JWT=r.JWTAccess=r.IdTokenClient=r.IAMAuth=r.GCPEnv=r.Compute=r.DEFAULT_UNIVERSE=r.AuthClient=r.gaxios=r.gcpMetadata=void 0;let n=e.r(264794);Object.defineProperty(r,"GoogleAuth",{enumerable:!0,get:function(){return n.GoogleAuth}}),r.gcpMetadata=e.r(482e3),r.gaxios=e.r(957612);var i=e.r(911656);Object.defineProperty(r,"AuthClient",{enumerable:!0,get:function(){return i.AuthClient}}),Object.defineProperty(r,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return i.DEFAULT_UNIVERSE}});var s=e.r(70814);Object.defineProperty(r,"Compute",{enumerable:!0,get:function(){return s.Compute}});var o=e.r(880243);Object.defineProperty(r,"GCPEnv",{enumerable:!0,get:function(){return o.GCPEnv}});var a=e.r(403994);Object.defineProperty(r,"IAMAuth",{enumerable:!0,get:function(){return a.IAMAuth}});var l=e.r(180732);Object.defineProperty(r,"IdTokenClient",{enumerable:!0,get:function(){return l.IdTokenClient}});var u=e.r(910247);Object.defineProperty(r,"JWTAccess",{enumerable:!0,get:function(){return u.JWTAccess}});var c=e.r(24553);Object.defineProperty(r,"JWT",{enumerable:!0,get:function(){return c.JWT}});var d=e.r(636126);Object.defineProperty(r,"Impersonated",{enumerable:!0,get:function(){return d.Impersonated}});var h=e.r(800701);Object.defineProperty(r,"CodeChallengeMethod",{enumerable:!0,get:function(){return h.CodeChallengeMethod}}),Object.defineProperty(r,"OAuth2Client",{enumerable:!0,get:function(){return h.OAuth2Client}}),Object.defineProperty(r,"ClientAuthentication",{enumerable:!0,get:function(){return h.ClientAuthentication}});var p=e.r(442602);Object.defineProperty(r,"LoginTicket",{enumerable:!0,get:function(){return p.LoginTicket}});var f=e.r(416260);Object.defineProperty(r,"UserRefreshClient",{enumerable:!0,get:function(){return f.UserRefreshClient}});var m=e.r(690220);Object.defineProperty(r,"AwsClient",{enumerable:!0,get:function(){return m.AwsClient}});var g=e.r(287573);Object.defineProperty(r,"AwsRequestSigner",{enumerable:!0,get:function(){return g.AwsRequestSigner}});var y=e.r(176868);Object.defineProperty(r,"IdentityPoolClient",{enumerable:!0,get:function(){return y.IdentityPoolClient}});var _=e.r(145037);Object.defineProperty(r,"ExternalAccountClient",{enumerable:!0,get:function(){return _.ExternalAccountClient}});var E=e.r(306560);Object.defineProperty(r,"BaseExternalAccountClient",{enumerable:!0,get:function(){return E.BaseExternalAccountClient}});var v=e.r(956777);Object.defineProperty(r,"DownscopedClient",{enumerable:!0,get:function(){return v.DownscopedClient}});var b=e.r(623238);Object.defineProperty(r,"PluggableAuthClient",{enumerable:!0,get:function(){return b.PluggableAuthClient}}),Object.defineProperty(r,"ExecutableError",{enumerable:!0,get:function(){return b.ExecutableError}});var w=e.r(348019);Object.defineProperty(r,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return w.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(r,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return w.ExternalAccountAuthorizedUserClient}});var A=e.r(853534);Object.defineProperty(r,"PassThroughClient",{enumerable:!0,get:function(){return A.PassThroughClient}}),r.auth=new n.GoogleAuth},393714,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.USER_AGENT=r.PRODUCT_NAME=r.pkg=void 0;let n=e.r(357660);r.pkg=n;let i="google-api-nodejs-client";r.PRODUCT_NAME=i,r.USER_AGENT=`${i}/${n.version}`},415733,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.LRUCache=void 0,r.snakeToCamel=a,r.originalOrCamelOptions=function(e){return{get:function(t){let r=e||{};return r[t]??r[a(t)]}}},r.removeUndefinedValuesInObject=function(e){return Object.entries(e).forEach(([t,r])=>{(void 0===r||"undefined"===r)&&delete e[t]}),e},r.isValidFile=l,r.getWellKnownCertificateConfigFileLocation=function(){let e=process.env.CLOUDSDK_CONFIG||(i.platform().startsWith("win")?s.join(process.env.APPDATA||"",o):s.join(process.env.HOME||"",".config",o));return s.join(e,"certificate_config.json")};let n=e.r(522734),i=e.r(446786),s=e.r(814747),o="gcloud";function a(e){return e.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}async function l(e){try{return(await n.promises.lstat(e)).isFile()}catch(e){return!1}}r.LRUCache=class{capacity;#C=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#R(e,t){this.#C.delete(e),this.#C.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#R(e,t),this.#x()}get(e){let t=this.#C.get(e);if(t)return this.#R(e,t.value),this.#x(),t.value}#x(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#C.entries().next();for(;!t.done&&(this.#C.size>this.capacity||t.value[1].lastAccessed<e);)this.#C.delete(t.value[0]),t=this.#C.entries().next()}}},106737,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.Colours=void 0;class n{static isEnabled(e){return e&&e.isTTY&&("function"!=typeof e.getColorDepth||e.getColorDepth()>2)}static refresh(){n.enabled=n.isEnabled(null==process?void 0:process.stderr),this.enabled?(n.reset="\x1b[0m",n.bright="\x1b[1m",n.dim="\x1b[2m",n.red="\x1b[31m",n.green="\x1b[32m",n.yellow="\x1b[33m",n.blue="\x1b[34m",n.magenta="\x1b[35m",n.cyan="\x1b[36m",n.white="\x1b[37m",n.grey="\x1b[90m"):(n.reset="",n.bright="",n.dim="",n.red="",n.green="",n.yellow="",n.blue="",n.magenta="",n.cyan="",n.white="",n.grey="")}}r.Colours=n,n.enabled=!1,n.reset="",n.bright="",n.dim="",n.red="",n.green="",n.yellow="",n.blue="",n.magenta="",n.cyan="",n.white="",n.grey="",n.refresh()},547637,(e,t,r)=>{var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e.r(190812),r)},190812,(e,t,r)=>{let n;var i,s,o,a=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),l=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=e.e&&e.e.__importStar||(i=function(e){return(i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),n=0;n<r.length;n++)"default"!==r[n]&&a(t,e,r[n]);return l(t,e),t});Object.defineProperty(r,"__esModule",{value:!0}),r.env=r.DebugLogBackendBase=r.placeholder=r.AdhocDebugLogger=r.LogSeverity=void 0,r.getNodeBackend=y,r.getDebugBackend=function(e){return new _(e)},r.getStructuredBackend=function(e){return new E(e)},r.setBackend=function(e){n=e,v.clear()},r.log=b;let c=e.r(427699),d=u(e.r(605365)),h=u(e.r(224361)),p=e.r(106737);(s=o||(r.LogSeverity=o={})).DEFAULT="DEFAULT",s.DEBUG="DEBUG",s.INFO="INFO",s.WARNING="WARNING",s.ERROR="ERROR";class f extends c.EventEmitter{constructor(e,t){super(),this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(e,t)=>this.on(e,t)}),this.func.debug=(...e)=>this.invokeSeverity(o.DEBUG,...e),this.func.info=(...e)=>this.invokeSeverity(o.INFO,...e),this.func.warn=(...e)=>this.invokeSeverity(o.WARNING,...e),this.func.error=(...e)=>this.invokeSeverity(o.ERROR,...e),this.func.sublog=e=>b(e,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(e){}try{this.emit("log",e,t)}catch(e){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}r.AdhocDebugLogger=f,r.placeholder=new f("",()=>{}).func;class m{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=null!=(e=d.env[r.env.nodeEnables])?e:"*";"all"===t&&(t="*"),this.filters=t.split(",")}log(e,t,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let n=this.cached.get(e);n||(n=this.makeLogger(e),this.cached.set(e,n)),n(t,...r)}catch(e){console.error(e)}}}r.DebugLogBackendBase=m;class g extends m{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...r)=>{var n;let i,s=`${p.Colours.green}${e}${p.Colours.reset}`,a=`${p.Colours.yellow}${d.pid}${p.Colours.reset}`;switch(t.severity){case o.ERROR:i=`${p.Colours.red}${t.severity}${p.Colours.reset}`;break;case o.INFO:i=`${p.Colours.magenta}${t.severity}${p.Colours.reset}`;break;case o.WARNING:i=`${p.Colours.yellow}${t.severity}${p.Colours.reset}`;break;default:i=null!=(n=t.severity)?n:o.DEFAULT}let l=h.formatWithOptions({colors:p.Colours.enabled},...r),u=Object.assign({},t);delete u.severity;let c=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=c?`${p.Colours.grey}${c}${p.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,i,l,c?` ${f}`:"")}:()=>{}}setFilters(){let e=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=RegExp(`^${e}$`,"i")}}function y(){return new g}class _ extends m{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(e,...r)=>{t(r[0],...r.slice(1))}}setFilters(){var e;let t=null!=(e=d.env.NODE_DEBUG)?e:"";d.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}}class E extends m{constructor(e){super(),this.upstream=null!=e?e:void 0}makeLogger(e){var t;let r=null==(t=this.upstream)?void 0:t.makeLogger(e);return(e,...t)=>{var n;let i=JSON.stringify(Object.assign({severity:null!=(n=e.severity)?n:o.INFO,message:h.format(...t)},e));r?r(e,i):console.log("%s",i)}}setFilters(){var e;null==(e=this.upstream)||e.setFilters()}}r.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};let v=new Map;function b(e,t){let i;if(!n&&!d.env[r.env.nodeEnables]||!e)return r.placeholder;t&&(e=`${t.instance.namespace}:${e}`);let s=v.get(e);if(s)return s.func;if(null===n)return r.placeholder;void 0===n&&(n=y());let o=new f(e,(t,...r)=>{if(i!==n){if(null===n)return;void 0===n&&(n=y()),i=n}null==n||n.log(e,t,...r)});return v.set(e,o),o.func}},866667,(e,t,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleToken=void 0;var n,i=u(e.r(522734)),s=e.r(957612),o=u(e.r(258184)),a=u(e.r(814747)),l=e.r(224361);function u(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(u=function(e,t){if(!t&&e&&e.__esModule)return e;var i,s,o={__proto__:null,default:e};if(null===e||"object"!=c(e)&&"function"!=typeof e)return o;if(i=t?n:r){if(i.has(e))return i.get(e);i.set(e,o)}for(var a in e)"default"!==a&&({}).hasOwnProperty.call(e,a)&&((s=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,a))&&(s.get||s.set)?i(o,a,s):o[a]=e[a]);return o})(e,t)}function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function d(e,t){if(t.has(e))throw TypeError("Cannot initialize the same private elements twice on an object")}function h(e,t,r){return e.set(p(e,t),r),r}function p(e,t,r){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:r;throw TypeError("Private element is not present on this object")}function f(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,w(n.key),n)}}function m(e,t,r){return t&&f(e.prototype,t),r&&f(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function g(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}function y(e){var t="function"==typeof Map?new Map:void 0;return(y=function(e){if(null===e||!function(e){try{return -1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(_())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&E(i,r.prototype),i}(e,arguments,v(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),E(r,e)})(e)}function _(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_=function(){return!!e})()}function E(e,t){return(E=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function v(e){return(v=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function b(e,t,r){return(t=w(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function w(e){var t=function(e,t){if("object"!=c(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=c(n))return n;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==c(t)?t:t+""}function A(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function s(r,n,i,s){var l=Object.create((n&&n.prototype instanceof a?n:a).prototype);return S(l,"_invoke",function(r,n,i){var s,a,l,u=0,c=i||[],d=!1,h={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return s=t,a=0,l=e,h.n=r,o}};function p(r,n){for(a=r,l=n,t=0;!d&&u&&!i&&t<c.length;t++){var i,s=c[t],p=h.p,f=s[2];r>3?(i=f===n)&&(l=s[(a=s[4])?5:(a=3,3)],s[4]=s[5]=e):s[0]<=p&&((i=r<2&&p<s[1])?(a=0,h.v=n,h.n=s[1]):p<f&&(i=r<3||s[0]>n||n>f)&&(s[4]=r,s[5]=n,h.n=f,a=0))}if(i||r>1)return o;throw d=!0,n}return function(i,c,f){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&p(c,f),a=c,l=f;(t=a<2?e:l)||!d;){s||(a?a<3?(a>1&&(h.n=-1),p(a,l)):h.n=l:h.v=l);try{if(u=2,s){if(a||(i="next"),t=s[i]){if(!(t=t.call(s,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,a<2&&(a=0)}else 1===a&&(t=s.return)&&t.call(s),a<2&&(l=TypeError("The iterator does not provide a '"+i+"' method"),a=1);s=e}else if((t=(d=h.n<0)?l:r.call(n,h))!==o)break}catch(t){s=e,a=1,l=t}finally{u=1}}return{value:t,done:d}}}(r,i,s),!0),l}var o={};function a(){}function l(){}function u(){}t=Object.getPrototypeOf;var c=u.prototype=a.prototype=Object.create([][n]?t(t([][n]())):(S(t={},n,function(){return this}),t));function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,S(e,i,"GeneratorFunction")),e.prototype=Object.create(c),e}return l.prototype=u,S(c,"constructor",u),S(u,"constructor",l),l.displayName="GeneratorFunction",S(u,i,"GeneratorFunction"),S(c),S(c,i,"Generator"),S(c,n,function(){return this}),S(c,"toString",function(){return"[object Generator]"}),(A=function(){return{w:s,m:d}})()}function S(e,t,r,n){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(S=function(e,t,r,n){if(t)i?i(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r;else{var s=function(t,r){S(e,t,function(e){return this._invoke(t,r,e)})};s("next",0),s("throw",1),s("return",2)}})(e,t,r,n)}function T(e,t,r,n,i,s,o){try{var a=e[s](o),l=a.value}catch(e){return void r(e)}a.done?t(l):Promise.resolve(l).then(n,i)}function O(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(e){T(s,n,i,o,a,"next",e)}function a(e){T(s,n,i,o,a,"throw",e)}o(void 0)})}}var I=i.readFile?(0,l.promisify)(i.readFile):O((A()).m(function e(){return A().w(function(e){for(;;)switch(e.n){case 0:throw new R("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},e)})),C="https://oauth2.googleapis.com/token",R=function(e){function t(e,r){var n,i,s;return g(this,t),i=t,s=[e],i=v(i),b(n=function(e,t){if(t&&("object"==c(t)||"function"==typeof t))return t;if(void 0!==t)throw TypeError("Derived constructors may only return object or undefined");var r=e;if(void 0===r)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return r}(this,_()?Reflect.construct(i,s||[],v(this).constructor):i.apply(this,s)),"code",void 0),n.code=r,n}if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&E(t,e),m(t)}(y(Error)),x=new WeakMap,k=new WeakSet;function N(e){return P.apply(this,arguments)}function P(){return(P=O((A()).m(function e(t){return A().w(function(e){for(;;)switch(e.n){case 0:if(!x.get(p(x,this))||t.forceRefresh){e.n=1;break}return e.a(2,x.get(p(x,this)));case 1:return e.p=1,e.n=2,h(x,this,p(k,this,U).call(this,t));case 2:return e.a(2,e.v);case 3:return e.p=3,h(x,this,void 0),e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])}))).apply(this,arguments)}function U(e){return D.apply(this,arguments)}function D(){return(D=O((A()).m(function e(t){var r;return A().w(function(e){for(;;)switch(e.n){case 0:if(!1!==this.isTokenExpiring()||!1!==t.forceRefresh){e.n=1;break}return e.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){e.n=2;break}throw Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){e.n=4;break}return e.n=3,this.getCredentials(this.keyFile);case 3:r=e.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||p(k,this,M).call(this);case 4:return e.a(2,p(k,this,G).call(this))}},e,this)}))).apply(this,arguments)}function M(){if(!this.iss)throw new R("email is required.","MISSING_CREDENTIALS")}function j(){return L.apply(this,arguments)}function L(){return(L=O((A()).m(function e(){var t;return A().w(function(e){for(;;)switch(e.n){case 0:if(this.accessToken){e.n=1;break}throw Error("No token to revoke.");case 1:return t="https://oauth2.googleapis.com/revoke?token="+this.accessToken,e.n=2,this.transporter.request({url:t,retry:!0});case 2:p(k,this,F).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return e.a(2)}},e,this)}))).apply(this,arguments)}function F(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyFile=e.keyFile,this.key=e.key,this.rawToken=void 0,this.iss=e.email||e.iss,this.sub=e.sub,this.additionalClaims=e.additionalClaims,"object"===c(e.scope)?this.scope=e.scope.join(" "):this.scope=e.scope,this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,e.transporter&&(this.transporter=e.transporter)}function G(){return q.apply(this,arguments)}function q(){return(q=O((A()).m(function e(){var t,r,n,i,s,a,l,u,c,d;return A().w(function(e){for(;;)switch(e.n){case 0:return t=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:C,exp:t+3600,iat:t,sub:this.sub},r),i=o.sign({header:{alg:"RS256"},payload:n,secret:this.key}),e.p=1,e.n=2,this.transporter.request({method:"POST",url:C,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:i}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=e.v,this.rawToken=s.data,this.expiresAt=null===s.data.expires_in||void 0===s.data.expires_in?void 0:(t+s.data.expires_in)*1e3,e.a(2,this.rawToken);case 3:throw e.p=3,d=e.v,this.rawToken=void 0,this.tokenExpires=void 0,(u=d.response&&null!=(a=d.response)&&a.data?null==(l=d.response)?void 0:l.data:{}).error&&(c=u.error_description?": ".concat(u.error_description):"",d.message="".concat(u.error).concat(c)),d;case 4:return e.a(2)}},e,this,[[1,3]])}))).apply(this,arguments)}r.GoogleToken=m(function e(t){g(this,e),d(this,k),k.add(this),b(this,"expiresAt",void 0),b(this,"key",void 0),b(this,"keyFile",void 0),b(this,"iss",void 0),b(this,"sub",void 0),b(this,"scope",void 0),b(this,"rawToken",void 0),b(this,"tokenExpires",void 0),b(this,"email",void 0),b(this,"additionalClaims",void 0),b(this,"eagerRefreshThresholdMillis",void 0),b(this,"transporter",{request:function(e){return(0,s.request)(e)}}),d(this,x),x.set(this,void 0),p(k,this,F).call(this,t)},[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var e=new Date().getTime();return!this.rawToken||!this.expiresAt||e>=this.expiresAt}},{key:"isTokenExpiring",value:function(){var e,t=new Date().getTime(),r=null!=(e=this.eagerRefreshThresholdMillis)?e:0;return!this.rawToken||!this.expiresAt||this.expiresAt<=t+r}},{key:"getToken",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"===c(e)&&(t=e,e=void 0),t=Object.assign({forceRefresh:!1},t),e){var r=e;p(k,this,N).call(this,t).then(function(e){return r(null,e)},e);return}return p(k,this,N).call(this,t)}},{key:"getCredentials",value:(n=O((A()).m(function e(t){var r,n,i,s,o;return A().w(function(e){for(;;)switch(e.n){case 0:e.n=".json"===(o=a.extname(t))?1:".der"===o||".crt"===o||".pem"===o?4:".p12"===o||".pfx"===o?6:7;break;case 1:return e.n=2,I(t,"utf8");case 2:if(n=(r=JSON.parse(e.v)).private_key,i=r.client_email,!(!n||!i)){e.n=3;break}throw new R("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return e.a(2,{privateKey:n,clientEmail:i});case 4:return e.n=5,I(t,"utf8");case 5:return s=e.v,e.a(2,{privateKey:s});case 6:throw new R("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new R("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return e.a(2)}},e)})),function(e){return n.apply(this,arguments)})},{key:"revokeToken",value:function(e){return e?void p(k,this,j).call(this).then(function(){return e()},e):p(k,this,j).call(this)}}])},889228,88045,500510,e=>{var t,r,n,i,s,o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I,C,R,x,k,N,P,U,D,M,j,L,F,G,q,$,B,H,V,J,W,K,z,Y,X,Q,Z,ee,et,er,en,ei,es,eo,ea,el,eu,ec,ed,eh,ep,ef,em,eg,ey,e_,eE,ev,eb,ew;let eA,eS,eT,eO;function eI(e,t,r,n,i){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r}function eC(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}let eR=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return eR=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function ex(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let ek=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class eN extends Error{}class eP extends eN{constructor(e,t,r,n){super(`${eP.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t,this.code=t?.code,this.param=t?.param,this.type=t?.type}static makeMessage(e,t,r){let n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new eD({message:r,cause:ek(t)});let i=t?.error;return 400===e?new ej(e,i,r,n):401===e?new eL(e,i,r,n):403===e?new eF(e,i,r,n):404===e?new eG(e,i,r,n):409===e?new eq(e,i,r,n):422===e?new e$(e,i,r,n):429===e?new eB(e,i,r,n):e>=500?new eH(e,i,r,n):new eP(e,i,r,n)}}class eU extends eP{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class eD extends eP{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class eM extends eD{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ej extends eP{}class eL extends eP{}class eF extends eP{}class eG extends eP{}class eq extends eP{}class e$ extends eP{}class eB extends eP{}class eH extends eP{}class eV extends eN{constructor(){super("Could not parse response content as the length limit was reached")}}class eJ extends eN{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class eW extends Error{constructor(e){super(e)}}let eK=/^[a-z][a-z0-9+.-]*:/i,ez=e=>(ez=Array.isArray)(e),eY=ez;function eX(e){return"object"!=typeof e?{}:e??{}}function eQ(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}let eZ=e=>new Promise(t=>setTimeout(t,e)),e0="6.9.1",e1=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",e2=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function e4(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function e6(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return e4({start(){},async pull(e){let{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await t.return?.()}})}function e3(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function e5(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await e[Symbol.asyncIterator]().return?.();let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}let e8=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),e9="RFC3986",e7=e=>String(e),te={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e7},tt=(e,t)=>(tt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),tr=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();function tn(e,t){if(ez(e)){let r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}let ti={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ts=function(e,t){Array.prototype.push.apply(e,ez(t)?t:[t])},to={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,i)=>{if(0===e.length)return e;let s=e;if("symbol"==typeof e?s=Symbol.prototype.toString.call(e):"string"!=typeof e&&(s=String(e)),"iso-8859-1"===r)return escape(s).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let o="";for(let e=0;e<s.length;e+=1024){let t=s.length>=1024?s.slice(e,e+1024):s,r=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);if(45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===i&&(40===n||41===n)){r[r.length]=t.charAt(e);continue}if(n<128){r[r.length]=tr[n];continue}if(n<2048){r[r.length]=tr[192|n>>6]+tr[128|63&n];continue}if(n<55296||n>=57344){r[r.length]=tr[224|n>>12]+tr[128|n>>6&63]+tr[128|63&n];continue}e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=tr[240|n>>18]+tr[128|n>>12&63]+tr[128|n>>6&63]+tr[128|63&n]}o+=r.join("")}return o},encodeValuesOnly:!1,format:e9,formatter:e7,indices:!1,serializeDate:e=>(eS??(eS=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},ta={};function tl(e){let t;return(eT??(eT=(t=new globalThis.TextEncoder).encode.bind(t)))(e)}function tu(e){let t;return(eO??(eO=(t=new globalThis.TextDecoder).decode.bind(t)))(e)}class tc{constructor(){t.set(this,void 0),r.set(this,void 0),eI(this,t,new Uint8Array,"f"),eI(this,r,null,"f")}decode(e){let n;if(null==e)return[];let i=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?tl(e):e;eI(this,t,function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([eC(this,t,"f"),i]),"f");let s=[];for(;null!=(n=function(e,t){for(let r=t??0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(eC(this,t,"f"),eC(this,r,"f")));){if(n.carriage&&null==eC(this,r,"f")){eI(this,r,n.index,"f");continue}if(null!=eC(this,r,"f")&&(n.index!==eC(this,r,"f")+1||n.carriage)){s.push(tu(eC(this,t,"f").subarray(0,eC(this,r,"f")-1))),eI(this,t,eC(this,t,"f").subarray(eC(this,r,"f")),"f"),eI(this,r,null,"f");continue}let e=null!==eC(this,r,"f")?n.preceding-1:n.preceding,i=tu(eC(this,t,"f").subarray(0,e));s.push(i),eI(this,t,eC(this,t,"f").subarray(n.index),"f"),eI(this,r,null,"f")}return s}flush(){return eC(this,t,"f").length?this.decode("\n"):[]}}t=new WeakMap,r=new WeakMap,tc.NEWLINE_CHARS=new Set(["\n","\r"]),tc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let td={off:0,error:200,warn:300,info:400,debug:500},th=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(td,e))return e;ty(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(td))}`)}};function tp(){}function tf(e,t,r){return!t||td[e]>td[r]?tp:t[e].bind(t)}let tm={error:tp,warn:tp,info:tp,debug:tp},tg=new WeakMap;function ty(e){let t=e.logger,r=e.logLevel??"off";if(!t)return tm;let n=tg.get(t);if(n&&n[0]===r)return n[1];let i={error:tf("error",t,r),warn:tf("warn",t,r),info:tf("info",t,r),debug:tf("debug",t,r)};return tg.set(t,[r,i]),i}let t_=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class tE{constructor(e,t,r){this.iterator=e,n.set(this,void 0),this.controller=t,eI(this,n,r,"f")}static fromSSEResponse(e,t,r){let n=!1,i=r?ty(r):console;return new tE(async function*(){if(n)throw new eN("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(let n of tv(e,t))if(!r){if(n.data.startsWith("[DONE]")){r=!0;continue}if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new eP(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw i.error("Could not parse message into JSON:",n.data),i.error("From chunk:",n.raw),e}if(t&&t.error)throw new eP(void 0,t.error,void 0,e.headers);yield t}}r=!0}catch(e){if(ex(e))return;throw e}finally{r||t.abort()}},t,r)}static fromReadableStream(e,t,r){let n=!1;async function*i(){let t=new tc;for await(let r of e3(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new tE(async function*(){if(n)throw new eN("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let e=!1;try{for await(let t of i())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(ex(e))return;throw e}finally{e||t.abort()}},t,r)}[(n=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),i=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new tE(()=>i(e),this.controller,eC(this,n,"f")),new tE(()=>i(t),this.controller,eC(this,n,"f"))]}toReadableStream(){let e,t=this;return e4({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=tl(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*tv(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eN("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eN("Attempted to iterate over a response with no body")}let r=new tw,n=new tc;for await(let t of tb(e3(e.body)))for(let e of n.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of n.flush()){let t=r.decode(e);t&&(yield t)}}async function*tb(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?tl(r):r,i=new Uint8Array(t.length+n.length);for(i.set(t),i.set(n,t.length),t=i;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class tw{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function tA(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{if(t.options.stream)return(ty(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):tE.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let n=r.headers.get("content-type"),i=n?.split(";")[0]?.trim();return i?.includes("application/json")||i?.endsWith("+json")?tS(await r.json(),r):await r.text()})();return ty(e).debug(`[${n}] response parsed`,t_({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}function tS(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class tT extends Promise{constructor(e,t,r=tA){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,i.set(this,void 0),eI(this,i,e,"f")}_thenUnwrap(e){return new tT(eC(this,i,"f"),this.responsePromise,async(t,r)=>tS(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(eC(this,i,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}i=new WeakMap;class tO{constructor(e,t,r,n){s.set(this,void 0),eI(this,s,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new eN("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await eC(this,s,"f").requestAPIList(this.constructor,e)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(s=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class tI extends tT{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await tA(e,t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}class tC extends tO{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class tR extends tO{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...eX(this.options.query),after:t}}:null}}class tx extends tO{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...eX(this.options.query),after:e}}:null}}let tk=()=>{if("u"<typeof File){let{process:e}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof e?.versions?.node&&20>parseInt(e.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function tN(e,t,r){return tk(),new File(e,t??"unknown_file",r)}function tP(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}let tU=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tD=async(e,t)=>tG(e.body)?{...e,body:await tL(e.body,t)}:e,tM=async(e,t)=>({...e,body:await tL(e.body,t)}),tj=new WeakMap,tL=async(e,t)=>{if(!await function(e){let t="function"==typeof e?e:e.fetch,r=tj.get(t);if(r)return r;let n=(async()=>{try{let e="Response"in t?t.Response:(await t("data:,")).constructor,r=new FormData;if(r.toString()===await new e(r).text())return!1;return!0}catch{return!0}})();return tj.set(t,n),n}(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>tq(r,e,t))),r},tF=e=>e instanceof Blob&&"name"in e,tG=e=>{if("object"==typeof e&&null!==e&&(e instanceof Response||tU(e)||tF(e)))return!0;if(Array.isArray(e))return e.some(tG);if(e&&"object"==typeof e){for(let t in e)if(tG(e[t]))return!0}return!1},tq=async(e,t,r)=>{if(void 0!==r){if(null==r)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(r instanceof Response)e.append(t,tN([await r.blob()],tP(r)));else if(tU(r))e.append(t,tN([await new Response(e6(r)).blob()],tP(r)));else if(tF(r))e.append(t,r,tP(r));else if(Array.isArray(r))await Promise.all(r.map(r=>tq(e,t+"[]",r)));else if("object"==typeof r)await Promise.all(Object.entries(r).map(([r,n])=>tq(e,`${t}[${r}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}},t$=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function tB(e,t,r){let n,i;if(tk(),null!=(n=e=await e)&&"object"==typeof n&&"string"==typeof n.name&&"number"==typeof n.lastModified&&t$(n))return e instanceof File?e:tN([await e.arrayBuffer()],e.name);if(null!=(i=e)&&"object"==typeof i&&"string"==typeof i.url&&"function"==typeof i.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),tN(await tH(n),t,r)}let s=await tH(e);if(t||(t=tP(e)),!r?.type){let e=s.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r={...r,type:e})}return tN(s,t,r)}async function tH(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(t$(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(tU(e))for await(let r of e)t.push(...await tH(r));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class tV{constructor(e){this._client=e}}function tJ(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}let tW=Object.freeze(Object.create(null)),tK=((e=tJ)=>function(t,...r){let n;if(1===t.length)return t[0];let i=!1,s=[],o=t.reduce((t,n,o)=>{/[?#]/.test(n)&&(i=!0);let a=r[o],l=(i?encodeURIComponent:e)(""+a);return o!==r.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??tW)??tW)?.toString)&&(l=a+"",s.push({start:t.length+n.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+n+(o===r.length?"":l)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(a));)s.push({start:n.index,length:n[0].length,error:`Value "${n[0]}" can't be safely passed as a path parameter`});if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0,t=s.reduce((t,r)=>{let n=" ".repeat(r.start-e),i="^".repeat(r.length);return e=r.start+r.length,t+n+i},"");throw new eN(`Path parameters result in path with invalid segments:
|
|
14
|
+
${s.map(e=>e.error).join("\n")}
|
|
15
|
+
${o}
|
|
16
|
+
${t}`)}return o})(tJ);class tz extends tV{list(e,t={},r){return this._client.getAPIList(tK`/chat/completions/${e}/messages`,tR,{query:t,...r})}}function tY(e){return void 0!==e&&"function"in e&&void 0!==e.function}function tX(e){return e?.$brand==="auto-parseable-response-format"}function tQ(e){return e?.$brand==="auto-parseable-tool"}function tZ(e,t){let r=e.choices.map(e=>{var r,n;if("length"===e.finish_reason)throw new eV;if("content_filter"===e.finish_reason)throw new eJ;return t1(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>{var r,n;let i;return r=t,n=e,i=r.tools?.find(e=>tY(e)&&e.function?.name===n.function.name),{...n,function:{...n.function,parsed_arguments:tQ(i)?i.$parseRaw(n.function.arguments):i?.function.strict?JSON.parse(n.function.arguments):null}}})??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?(r=t,n=e.message.content,r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(n):JSON.parse(n):null):null}}});return{...e,choices:r}}function t0(e){return!!tX(e.response_format)||(e.tools?.some(e=>tQ(e)||"function"===e.type&&!0===e.function.strict)??!1)}function t1(e){for(let t of e||[])if("function"!==t.type)throw new eN(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}let t2=e=>e?.role==="assistant",t4=e=>e?.role==="tool";class t6{constructor(){o.add(this),this.controller=new AbortController,a.set(this,void 0),l.set(this,()=>{}),u.set(this,()=>{}),c.set(this,void 0),d.set(this,()=>{}),h.set(this,()=>{}),p.set(this,{}),f.set(this,!1),m.set(this,!1),g.set(this,!1),y.set(this,!1),eI(this,a,new Promise((e,t)=>{eI(this,l,e,"f"),eI(this,u,t,"f")}),"f"),eI(this,c,new Promise((e,t)=>{eI(this,d,e,"f"),eI(this,h,t,"f")}),"f"),eC(this,a,"f").catch(()=>{}),eC(this,c,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},eC(this,o,"m",_).bind(this))},0)}_connected(){this.ended||(eC(this,l,"f").call(this),this._emit("connect"))}get ended(){return eC(this,f,"f")}get errored(){return eC(this,m,"f")}get aborted(){return eC(this,g,"f")}abort(){this.controller.abort()}on(e,t){return(eC(this,p,"f")[e]||(eC(this,p,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=eC(this,p,"f")[e];if(!r)return this;let n=r.findIndex(e=>e.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(eC(this,p,"f")[e]||(eC(this,p,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{eI(this,y,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){eI(this,y,!0,"f"),await eC(this,c,"f")}_emit(e,...t){if(eC(this,f,"f"))return;"end"===e&&(eI(this,f,!0,"f"),eC(this,d,"f").call(this));let r=eC(this,p,"f")[e];if(r&&(eC(this,p,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];eC(this,y,"f")||r?.length||Promise.reject(e),eC(this,u,"f").call(this,e),eC(this,h,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];eC(this,y,"f")||r?.length||Promise.reject(e),eC(this,u,"f").call(this,e),eC(this,h,"f").call(this,e),this._emit("end")}}_emitFinal(){}}a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,y=new WeakMap,o=new WeakSet,_=function(e){if(eI(this,m,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eU),e instanceof eU)return eI(this,g,!0,"f"),this._emit("abort",e);if(e instanceof eN)return this._emit("error",e);if(e instanceof Error){let t=new eN(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eN(String(e)))};class t3 extends t6{constructor(){super(...arguments),E.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),t4(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(t2(e)&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new eN("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),eC(this,E,"m",v).call(this)}async finalMessage(){return await this.done(),eC(this,E,"m",b).call(this)}async finalFunctionToolCall(){return await this.done(),eC(this,E,"m",w).call(this)}async finalFunctionToolCallResult(){return await this.done(),eC(this,E,"m",A).call(this)}async totalUsage(){return await this.done(),eC(this,E,"m",S).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=eC(this,E,"m",b).call(this);t&&this._emit("finalMessage",t);let r=eC(this,E,"m",v).call(this);r&&this._emit("finalContent",r);let n=eC(this,E,"m",w).call(this);n&&this._emit("finalFunctionToolCall",n);let i=eC(this,E,"m",A).call(this);null!=i&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",eC(this,E,"m",S).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eC(this,E,"m",T).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(tZ(i,t))}async _runChatCompletion(e,t,r){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:i="auto",stream:s,...o}=t,a="string"!=typeof i&&"function"===i.type&&i?.function?.name,{maxChatCompletions:l=10}=r||{},u=t.tools.map(e=>{if(tQ(e)){if(!e.$callback)throw new eN("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),c={};for(let e of u)"function"===e.type&&(c[e.function.name||e.function.function.name]=e.function);let d="tools"in t?u.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){let t=await this._createChatCompletion(e,{...o,tool_choice:i,tools:d,messages:[...this.messages]},r),s=t.choices[0]?.message;if(!s)throw new eN("missing message in ChatCompletion response");if(!s.tool_calls?.length)break;for(let e of s.tool_calls){let t;if("function"!==e.type)continue;let r=e.id,{name:i,arguments:s}=e.function,o=c[i];if(o){if(a&&a!==i){let e=`Invalid tool_call: ${JSON.stringify(i)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:n,tool_call_id:r,content:e});continue}}else{let e=`Invalid tool_call: ${JSON.stringify(i)}. Available options are: ${Object.keys(c).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:r,content:e});continue}try{t="function"==typeof o.parse?await o.parse(s):s}catch(t){let e=t instanceof Error?t.message:String(t);this._addMessage({role:n,tool_call_id:r,content:e});continue}let l=await o.function(t,this),u=eC(this,E,"m",O).call(this,l);if(this._addMessage({role:n,tool_call_id:r,content:u}),a)return}}}}E=new WeakSet,v=function(){return eC(this,E,"m",b).call(this).content??null},b=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(t2(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new eN("stream ended without producing a ChatCompletionMessage with role=assistant")},w=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t2(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},A=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t4(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},S=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},T=function(e){if(null!=e.n&&e.n>1)throw new eN("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},O=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class t5 extends t3{static runTools(e,t,r){let n=new t5,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,i)),n}_addMessage(e,t=!0){super._addMessage(e,t),t2(e)&&e.content&&this._emit("content",e.content)}}let t8={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,ALL:511};class t9 extends Error{}class t7 extends Error{}let re=e=>(function(e,t=t8.ALL){var r,n;let i,s,o,a,l,u,c,d,h,p;if("string"!=typeof e)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return r=e.trim(),n=t,i=r.length,s=0,o=e=>{throw new t9(`${e} at position ${s}`)},a=e=>{throw new t7(`${e} at position ${s}`)},l=()=>(p(),s>=i&&o("Unexpected end of input"),'"'===r[s])?u():"{"===r[s]?c():"["===r[s]?d():"null"===r.substring(s,s+4)||t8.NULL&n&&i-s<4&&"null".startsWith(r.substring(s))?(s+=4,null):"true"===r.substring(s,s+4)||t8.BOOL&n&&i-s<4&&"true".startsWith(r.substring(s))?(s+=4,!0):"false"===r.substring(s,s+5)||t8.BOOL&n&&i-s<5&&"false".startsWith(r.substring(s))?(s+=5,!1):"Infinity"===r.substring(s,s+8)||t8.INFINITY&n&&i-s<8&&"Infinity".startsWith(r.substring(s))?(s+=8,1/0):"-Infinity"===r.substring(s,s+9)||t8.MINUS_INFINITY&n&&1<i-s&&i-s<9&&"-Infinity".startsWith(r.substring(s))?(s+=9,-1/0):"NaN"===r.substring(s,s+3)||t8.NAN&n&&i-s<3&&"NaN".startsWith(r.substring(s))?(s+=3,0/0):h(),u=()=>{let e=s,t=!1;for(s++;s<i&&('"'!==r[s]||t&&"\\"===r[s-1]);)t="\\"===r[s]&&!t,s++;if('"'==r.charAt(s))try{return JSON.parse(r.substring(e,++s-Number(t)))}catch(e){a(String(e))}else if(t8.STR&n)try{return JSON.parse(r.substring(e,s-Number(t))+'"')}catch(t){return JSON.parse(r.substring(e,r.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{s++,p();let e={};try{for(;"}"!==r[s];){if(p(),s>=i&&t8.OBJ&n)return e;let t=u();p(),s++;try{let r=l();Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}catch(t){if(t8.OBJ&n)return e;throw t}p(),","===r[s]&&s++}}catch(t){if(t8.OBJ&n)return e;o("Expected '}' at end of object")}return s++,e},d=()=>{s++;let e=[];try{for(;"]"!==r[s];)e.push(l()),p(),","===r[s]&&s++}catch(t){if(t8.ARR&n)return e;o("Expected ']' at end of array")}return s++,e},h=()=>{if(0===s){"-"===r&&t8.NUM&n&&o("Not sure what '-' is");try{return JSON.parse(r)}catch(e){if(t8.NUM&n)try{if("."===r[r.length-1])return JSON.parse(r.substring(0,r.lastIndexOf(".")));return JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch(e){}a(String(e))}}let e=s;for("-"===r[s]&&s++;r[s]&&!",]}".includes(r[s]);)s++;s!=i||t8.NUM&n||o("Unterminated number literal");try{return JSON.parse(r.substring(e,s))}catch(t){"-"===r.substring(e,s)&&t8.NUM&n&&o("Not sure what '-' is");try{return JSON.parse(r.substring(e,r.lastIndexOf("e")))}catch(e){a(String(e))}}},p=()=>{for(;s<i&&" \n\r ".includes(r[s]);)s++},l()})(e,t8.ALL^t8.NUM);class rt extends t3{constructor(e){super(),I.add(this),C.set(this,void 0),R.set(this,void 0),x.set(this,void 0),eI(this,C,e,"f"),eI(this,R,[],"f")}get currentChatCompletionSnapshot(){return eC(this,x,"f")}static fromReadableStream(e){let t=new rt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new rt(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eC(this,I,"m",k).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});for await(let e of(this._connected(),i))eC(this,I,"m",P).call(this,e);if(i.controller.signal?.aborted)throw new eU;return this._addChatCompletion(eC(this,I,"m",M).call(this))}async _fromReadableStream(e,t){let r,n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eC(this,I,"m",k).call(this),this._connected();let i=tE.fromReadableStream(e,this.controller);for await(let e of i)r&&r!==e.id&&this._addChatCompletion(eC(this,I,"m",M).call(this)),eC(this,I,"m",P).call(this,e),r=e.id;if(i.controller.signal?.aborted)throw new eU;return this._addChatCompletion(eC(this,I,"m",M).call(this))}[(C=new WeakMap,R=new WeakMap,x=new WeakMap,I=new WeakSet,k=function(){this.ended||eI(this,x,void 0,"f")},N=function(e){let t=eC(this,R,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},eC(this,R,"f")[e.index]=t),t},P=function(e){if(this.ended)return;let t=eC(this,I,"m",L).call(this,e);for(let r of(this._emit("chunk",e,t),e.choices)){let e=t.choices[r.index];null!=r.delta.content&&e.message?.role==="assistant"&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&e.message?.role==="assistant"&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let n=eC(this,I,"m",N).call(this,e);for(let t of(e.finish_reason&&(eC(this,I,"m",D).call(this,e),null!=n.current_tool_call_index&&eC(this,I,"m",U).call(this,e,n.current_tool_call_index)),r.delta.tool_calls??[]))n.current_tool_call_index!==t.index&&(eC(this,I,"m",D).call(this,e),null!=n.current_tool_call_index&&eC(this,I,"m",U).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(let t of r.delta.tool_calls??[]){let r=e.message.tool_calls?.[t.index];r?.type&&(r?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):ri(r?.type))}}},U=function(e,t){if(eC(this,I,"m",N).call(this,e).done_tool_calls.has(t))return;let r=e.message.tool_calls?.[t];if(!r)throw Error("no tool call snapshot");if(!r.type)throw Error("tool call snapshot missing `type`");if("function"===r.type){let e=eC(this,C,"f")?.tools?.find(e=>tY(e)&&e.function.name===r.function.name);this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:tQ(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else ri(r.type)},D=function(e){let t=eC(this,I,"m",N).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let r=eC(this,I,"m",j).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},M=function(){if(this.ended)throw new eN("stream has ended, this shouldn't happen");let e=eC(this,x,"f");if(!e)throw new eN("request ended without sending any chunks");return eI(this,x,void 0,"f"),eI(this,R,[],"f"),function(e,t){var r;let{id:n,choices:i,created:s,model:o,system_fingerprint:a,...l}=e;return r={...l,id:n,choices:i.map(({message:t,finish_reason:r,index:n,logprobs:i,...s})=>{if(!r)throw new eN(`missing finish_reason for choice ${n}`);let{content:o=null,function_call:a,tool_calls:l,...u}=t,c=t.role;if(!c)throw new eN(`missing role for choice ${n}`);if(a){let{arguments:e,name:l}=a;if(null==e)throw new eN(`missing function_call.arguments for choice ${n}`);if(!l)throw new eN(`missing function_call.name for choice ${n}`);return{...s,message:{content:o,function_call:{arguments:e,name:l},role:c,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:i}}return l?{...s,index:n,finish_reason:r,logprobs:i,message:{...u,role:c,content:o,refusal:t.refusal??null,tool_calls:l.map((t,r)=>{let{function:i,type:s,id:o,...a}=t,{arguments:l,name:u,...c}=i||{};if(null==o)throw new eN(`missing choices[${n}].tool_calls[${r}].id
|
|
17
|
+
${rr(e)}`);if(null==s)throw new eN(`missing choices[${n}].tool_calls[${r}].type
|
|
18
|
+
${rr(e)}`);if(null==u)throw new eN(`missing choices[${n}].tool_calls[${r}].function.name
|
|
19
|
+
${rr(e)}`);if(null==l)throw new eN(`missing choices[${n}].tool_calls[${r}].function.arguments
|
|
20
|
+
${rr(e)}`);return{...a,id:o,type:s,function:{...c,name:u,arguments:l}}})}}:{...s,message:{...u,content:o,role:c,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:i}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}},t&&t0(t)?tZ(r,t):{...r,choices:r.choices.map(e=>(t1(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(e,eC(this,C,"f"))},j=function(){let e=eC(this,C,"f")?.response_format;return tX(e)?e:null},L=function(e){var t,r,n,i;let s=eC(this,x,"f"),{choices:o,...a}=e;for(let{delta:o,finish_reason:l,index:u,logprobs:c=null,...d}of(s?Object.assign(s,a):s=eI(this,x,{...a,choices:[]},"f"),e.choices)){let e=s.choices[u];if(e||(e=s.choices[u]={finish_reason:l,index:u,message:{},logprobs:c,...d}),c)if(e.logprobs){let{content:n,refusal:i,...s}=c;rn(s),Object.assign(e.logprobs,s),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),i&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...i))}else e.logprobs=Object.assign({},c);if(l&&(e.finish_reason=l,eC(this,C,"f")&&t0(eC(this,C,"f")))){if("length"===l)throw new eV;if("content_filter"===l)throw new eJ}if(Object.assign(e,d),!o)continue;let{content:a,refusal:h,function_call:p,role:f,tool_calls:m,...g}=o;if(rn(g),Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),a&&(e.message.content=(e.message.content||"")+a,!e.message.refusal&&eC(this,I,"m",j).call(this)&&(e.message.parsed=re(e.message.content))),m)for(let{index:t,id:r,type:n,function:s,...o}of(e.message.tool_calls||(e.message.tool_calls=[]),m)){let a=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(a,o),r&&(a.id=r),n&&(a.type=n),s&&(a.function??(a.function={name:s.name??"",arguments:""})),s?.name&&(a.function.name=s.name),s?.arguments&&(a.function.arguments+=s.arguments,function(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find(e=>tY(e)&&e.function?.name===t.function.name);return tY(r)&&(tQ(r)||r?.function.strict||!1)}(eC(this,C,"f"),a)&&(a.function.parsed_arguments=re(a.function.arguments)))}}return s},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function rr(e){return JSON.stringify(e)}function rn(e){}function ri(e){}class rs extends rt{static fromReadableStream(e){let t=new rs(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new rs(t),i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,i)),n}}class ro extends tV{constructor(){super(...arguments),this.messages=new tz(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(tK`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(tK`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",tR,{query:e,...t})}delete(e,t){return this._client.delete(tK`/chat/completions/${e}`,t)}parse(e,t){for(let t of e.tools??[]){if("function"!==t.type)throw new eN(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new eN(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}return this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>tZ(t,e))}runTools(e,t){return e.stream?rs.runTools(this._client,e,t):t5.runTools(this._client,e,t)}stream(e,t){return rt.createChatCompletion(this._client,e,t)}}ro.Messages=tz;class ra extends tV{constructor(){super(...arguments),this.completions=new ro(this._client)}}ra.Completions=ro;let rl=Symbol("brand.privateNullableHeaders"),ru=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(rl in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():eY(e)?t=e:(r=!0,t=Object.entries(e??{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=eY(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[rl]:!0,values:t,nulls:r}};class rc extends tV{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:ru([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class rd extends tV{create(e,t){return this._client.post("/audio/transcriptions",tM({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class rh extends tV{create(e,t){return this._client.post("/audio/translations",tM({body:e,...t,__metadata:{model:e.model}},this._client))}}class rp extends tV{constructor(){super(...arguments),this.transcriptions=new rd(this._client),this.translations=new rh(this._client),this.speech=new rc(this._client)}}rp.Transcriptions=rd,rp.Translations=rh,rp.Speech=rc;class rf extends tV{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(tK`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",tR,{query:e,...t})}cancel(e,t){return this._client.post(tK`/batches/${e}/cancel`,t)}}class rm extends tV{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tK`/assistants/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(tK`/assistants/${e}`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",tR,{query:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(tK`/assistants/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class rg extends tV{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class ry extends tV{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class r_ extends tV{constructor(){super(...arguments),this.sessions=new rg(this._client),this.transcriptionSessions=new ry(this._client)}}r_.Sessions=rg,r_.TranscriptionSessions=ry;class rE extends tV{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(tK`/chatkit/sessions/${e}/cancel`,{...t,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class rv extends tV{retrieve(e,t){return this._client.get(tK`/chatkit/threads/${e}`,{...t,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",tx,{query:e,...t,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(tK`/chatkit/threads/${e}`,{...t,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(tK`/chatkit/threads/${e}/items`,tx,{query:t,...r,headers:ru([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class rb extends tV{constructor(){super(...arguments),this.sessions=new rE(this._client),this.threads=new rv(this._client)}}rb.Sessions=rE,rb.Threads=rv;class rw extends tV{create(e,t,r){return this._client.post(tK`/threads/${e}/messages`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(tK`/threads/${n}/messages/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...i}=t;return this._client.post(tK`/threads/${n}/messages/${e}`,{body:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(tK`/threads/${e}/messages`,tR,{query:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(tK`/threads/${n}/messages/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class rA extends tV{retrieve(e,t,r){let{thread_id:n,run_id:i,...s}=t;return this._client.get(tK`/threads/${n}/runs/${i}/steps/${e}`,{query:s,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...i}=t;return this._client.getAPIList(tK`/threads/${n}/runs/${e}/steps`,tR,{query:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class rS extends t6{constructor(){super(...arguments),F.add(this),q.set(this,[]),$.set(this,{}),B.set(this,{}),H.set(this,void 0),V.set(this,void 0),J.set(this,void 0),W.set(this,void 0),K.set(this,void 0),z.set(this,void 0),Y.set(this,void 0),X.set(this,void 0),Q.set(this,void 0)}[(q=new WeakMap,$=new WeakMap,B=new WeakMap,H=new WeakMap,V=new WeakMap,J=new WeakMap,W=new WeakMap,K=new WeakMap,z=new WeakMap,Y=new WeakMap,X=new WeakMap,Q=new WeakMap,F=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new G;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=tE.fromReadableStream(e,this.controller);for await(let e of n)eC(this,F,"m",Z).call(this,e);if(n.controller.signal?.aborted)throw new eU;return this._addRun(eC(this,F,"m",ee).call(this))}toReadableStream(){return new tE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let i=new G;return i._run(()=>i._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},o=await e.submitToolOutputs(t,s,{...n,signal:this.controller.signal});for await(let e of(this._connected(),o))eC(this,F,"m",Z).call(this,e);if(o.controller.signal?.aborted)throw new eU;return this._addRun(eC(this,F,"m",ee).call(this))}static createThreadAssistantStream(e,t,r){let n=new G;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let i=new G;return i._run(()=>i._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return eC(this,Y,"f")}currentRun(){return eC(this,X,"f")}currentMessageSnapshot(){return eC(this,H,"f")}currentRunStepSnapshot(){return eC(this,Q,"f")}async finalRunSteps(){return await this.done(),Object.values(eC(this,$,"f"))}async finalMessages(){return await this.done(),Object.values(eC(this,B,"f"))}async finalRun(){if(await this.done(),!eC(this,V,"f"))throw Error("Final run was not received.");return eC(this,V,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let i={...t,stream:!0},s=await e.createAndRun(i,{...r,signal:this.controller.signal});for await(let e of(this._connected(),s))eC(this,F,"m",Z).call(this,e);if(s.controller.signal?.aborted)throw new eU;return this._addRun(eC(this,F,"m",ee).call(this))}async _createAssistantStream(e,t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},o=await e.create(t,s,{...n,signal:this.controller.signal});for await(let e of(this._connected(),o))eC(this,F,"m",Z).call(this,e);if(o.controller.signal?.aborted)throw new eU;return this._addRun(eC(this,F,"m",ee).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null==t||"index"===r||"type"===r){e[r]=n;continue}if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else if(eQ(t)&&eQ(n))t=this.accumulateDelta(t,n);else if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(let e of n){if(!eQ(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let r=e.index;if(null==r)throw console.error(e),Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);let n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`);e[r]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}}G=rS,Z=function(e){if(!this.ended)switch(eI(this,Y,e,"f"),eC(this,F,"m",en).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":eC(this,F,"m",ea).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":eC(this,F,"m",er).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":eC(this,F,"m",et).call(this,e);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier")}},ee=function(){if(this.ended)throw new eN("stream has ended, this shouldn't happen");if(!eC(this,V,"f"))throw Error("Final run has not been received");return eC(this,V,"f")},et=function(e){let[t,r]=eC(this,F,"m",es).call(this,e,eC(this,H,"f"));for(let e of(eI(this,H,t,"f"),eC(this,B,"f")[t.id]=t,r)){let r=t.content[e.index];r?.type=="text"&&this._emit("textCreated",r.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(n&&"text"==n.type)this._emit("textDelta",e,n.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=eC(this,J,"f")){if(eC(this,W,"f"))switch(eC(this,W,"f").type){case"text":this._emit("textDone",eC(this,W,"f").text,eC(this,H,"f"));break;case"image_file":this._emit("imageFileDone",eC(this,W,"f").image_file,eC(this,H,"f"))}eI(this,J,r.index,"f")}eI(this,W,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==eC(this,J,"f")){let t=e.data.content[eC(this,J,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,eC(this,H,"f"));break;case"text":this._emit("textDone",t.text,eC(this,H,"f"))}}eC(this,H,"f")&&this._emit("messageDone",e.data),eI(this,H,void 0,"f")}},er=function(e){let t=eC(this,F,"m",ei).call(this,e);switch(eI(this,Q,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(let e of r.step_details.tool_calls)e.index==eC(this,K,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(eC(this,z,"f")&&this._emit("toolCallDone",eC(this,z,"f")),eI(this,K,e.index,"f"),eI(this,z,t.step_details.tool_calls[e.index],"f"),eC(this,z,"f")&&this._emit("toolCallCreated",eC(this,z,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":eI(this,Q,void 0,"f"),"tool_calls"==e.data.step_details.type&&eC(this,z,"f")&&(this._emit("toolCallDone",eC(this,z,"f")),eI(this,z,void 0,"f")),this._emit("runStepDone",e.data,t)}},en=function(e){eC(this,q,"f").push(e),this._emit("event",e)},ei=function(e){switch(e.event){case"thread.run.step.created":return eC(this,$,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=eC(this,$,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=G.accumulateDelta(t,r.delta);eC(this,$,"f")[e.data.id]=n}return eC(this,$,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":eC(this,$,"f")[e.data.id]=e.data}if(eC(this,$,"f")[e.data.id])return eC(this,$,"f")[e.data.id];throw Error("No snapshot available")},es=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=eC(this,F,"m",eo).call(this,e,r)}else t.content[e.index]=e,r.push(e);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},eo=function(e,t){return G.accumulateDelta(t,e)},ea=function(e){switch(eI(this,X,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":eI(this,V,e.data,"f"),eC(this,z,"f")&&(this._emit("toolCallDone",eC(this,z,"f")),eI(this,z,void 0,"f"))}};class rT extends tV{constructor(){super(...arguments),this.steps=new rA(this._client)}create(e,t,r){let{include:n,...i}=t;return this._client.post(tK`/threads/${e}/runs`,{query:{include:n},body:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(tK`/threads/${n}/runs/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...i}=t;return this._client.post(tK`/threads/${n}/runs/${e}`,{body:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(tK`/threads/${e}/runs`,tR,{query:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(tK`/threads/${n}/runs/${e}/cancel`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return rS.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=ru([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=s.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await eZ(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return rS.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...i}=t;return this._client.post(tK`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return rS.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}rT.Steps=rA;class rO extends tV{constructor(){super(...arguments),this.runs=new rT(this._client),this.messages=new rw(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tK`/threads/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(tK`/threads/${e}`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(tK`/threads/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return rS.createThreadAssistantStream(e,this._client.beta.threads,t)}}rO.Runs=rT,rO.Messages=rw;class rI extends tV{constructor(){super(...arguments),this.realtime=new r_(this._client),this.chatkit=new rb(this._client),this.assistants=new rm(this._client),this.threads=new rO(this._client)}}rI.Realtime=r_,rI.ChatKit=rb,rI.Assistants=rm,rI.Threads=rO;class rC extends tV{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(tK`/containers/${n}/files/${e}/content`,{...r,headers:ru([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class rR extends tV{constructor(){super(...arguments),this.content=new rC(this._client)}create(e,t,r){return this._client.post(tK`/containers/${e}/files`,tM({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(tK`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(tK`/containers/${e}/files`,tR,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(tK`/containers/${n}/files/${e}`,{...r,headers:ru([{Accept:"*/*"},r?.headers])})}}rR.Content=rC;class rx extends tV{constructor(){super(...arguments),this.files=new rR(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(tK`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",tR,{query:e,...t})}delete(e,t){return this._client.delete(tK`/containers/${e}`,{...t,headers:ru([{Accept:"*/*"},t?.headers])})}}rx.Files=rR;class rk extends tV{create(e,t,r){let{include:n,...i}=t;return this._client.post(tK`/conversations/${e}/items`,{query:{include:n},body:i,...r})}retrieve(e,t,r){let{conversation_id:n,...i}=t;return this._client.get(tK`/conversations/${n}/items/${e}`,{query:i,...r})}list(e,t={},r){return this._client.getAPIList(tK`/conversations/${e}/items`,tx,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(tK`/conversations/${n}/items/${e}`,r)}}class rN extends tV{constructor(){super(...arguments),this.items=new rk(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(tK`/conversations/${e}`,t)}update(e,t,r){return this._client.post(tK`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(tK`/conversations/${e}`,t)}}rN.Items=rk;class rP extends tV{retrieve(e,t,r){let{eval_id:n,run_id:i}=t;return this._client.get(tK`/evals/${n}/runs/${i}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...i}=t;return this._client.getAPIList(tK`/evals/${n}/runs/${e}/output_items`,tR,{query:i,...r})}}class rU extends tV{constructor(){super(...arguments),this.outputItems=new rP(this._client)}create(e,t,r){return this._client.post(tK`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(tK`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(tK`/evals/${e}/runs`,tR,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(tK`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(tK`/evals/${n}/runs/${e}`,r)}}rU.OutputItems=rP;class rD extends tV{constructor(){super(...arguments),this.runs=new rU(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(tK`/evals/${e}`,t)}update(e,t,r){return this._client.post(tK`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",tR,{query:e,...t})}delete(e,t){return this._client.delete(tK`/evals/${e}`,t)}}rD.Runs=rU;class rM extends tV{create(e,t){return this._client.post("/files",tM({body:e,...t},this._client))}retrieve(e,t){return this._client.get(tK`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",tR,{query:e,...t})}delete(e,t){return this._client.delete(tK`/files/${e}`,t)}content(e,t){return this._client.get(tK`/files/${e}/content`,{...t,headers:ru([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){let n=new Set(["processed","error","deleted"]),i=Date.now(),s=await this.retrieve(e);for(;!s.status||!n.has(s.status);)if(await eZ(t),s=await this.retrieve(e),Date.now()-i>r)throw new eM({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}}class rj extends tV{}class rL extends tV{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class rF extends tV{constructor(){super(...arguments),this.graders=new rL(this._client)}}rF.Graders=rL;class rG extends tV{create(e,t,r){return this._client.getAPIList(tK`/fine_tuning/checkpoints/${e}/permissions`,tC,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(tK`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(tK`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}}class rq extends tV{constructor(){super(...arguments),this.permissions=new rG(this._client)}}rq.Permissions=rG;class r$ extends tV{list(e,t={},r){return this._client.getAPIList(tK`/fine_tuning/jobs/${e}/checkpoints`,tR,{query:t,...r})}}class rB extends tV{constructor(){super(...arguments),this.checkpoints=new r$(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(tK`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",tR,{query:e,...t})}cancel(e,t){return this._client.post(tK`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(tK`/fine_tuning/jobs/${e}/events`,tR,{query:t,...r})}pause(e,t){return this._client.post(tK`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(tK`/fine_tuning/jobs/${e}/resume`,t)}}rB.Checkpoints=r$;class rH extends tV{constructor(){super(...arguments),this.methods=new rj(this._client),this.jobs=new rB(this._client),this.checkpoints=new rq(this._client),this.alpha=new rF(this._client)}}rH.Methods=rj,rH.Jobs=rB,rH.Checkpoints=rq,rH.Alpha=rF;class rV extends tV{}class rJ extends tV{constructor(){super(...arguments),this.graderModels=new rV(this._client)}}rJ.GraderModels=rV;class rW extends tV{retrieve(e,t){return this._client.get(tK`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",tC,e)}delete(e,t){return this._client.delete(tK`/models/${e}`,t)}}class rK extends tV{accept(e,t,r){return this._client.post(tK`/realtime/calls/${e}/accept`,{body:t,...r,headers:ru([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(tK`/realtime/calls/${e}/hangup`,{...t,headers:ru([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(tK`/realtime/calls/${e}/refer`,{body:t,...r,headers:ru([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(tK`/realtime/calls/${e}/reject`,{body:t,...r,headers:ru([{Accept:"*/*"},r?.headers])})}}class rz extends tV{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class rY extends tV{constructor(){super(...arguments),this.clientSecrets=new rz(this._client),this.calls=new rK(this._client)}}function rX(e,t){let r=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:function(e,t){var r,n;let i=(r=e.tools??[],n=t.name,r.find(e=>"function"===e.type&&e.name===n));return{...t,...t,parsed_arguments:i?.$brand==="auto-parseable-tool"?i.$parseRaw(t.arguments):i?.strict?JSON.parse(t.arguments):null}}(t,e)};if("message"===e.type){let r=e.content.map(e=>{var r,n;return"output_text"===e.type?{...e,parsed:(r=t,n=e.text,r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(n):JSON.parse(n))}:e});return{...e,content:r}}return e}),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||rQ(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let e of n.output)if("message"===e.type){for(let t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed}return null}}),n}function rQ(e){let t=[];for(let r of e.output)if("message"===r.type)for(let e of r.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}rY.ClientSecrets=rz,rY.Calls=rK;class rZ extends t6{constructor(e){super(),el.add(this),eu.set(this,void 0),ec.set(this,void 0),ed.set(this,void 0),eI(this,eu,e,"f")}static createResponse(e,t,r){let n=new rZ(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n,i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),eC(this,el,"m",eh).call(this);let s=null;for await(let i of("response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),s=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected(),n))eC(this,el,"m",ep).call(this,i,s);if(n.controller.signal?.aborted)throw new eU;return eC(this,el,"m",ef).call(this)}[(eu=new WeakMap,ec=new WeakMap,ed=new WeakMap,el=new WeakSet,eh=function(){this.ended||eI(this,ec,void 0,"f")},ep=function(e,t){if(this.ended)return;let r=(e,r)=>{(null==t||r.sequence_number>t)&&this._emit(e,r)},n=eC(this,el,"m",em).call(this,e);switch(r("event",e),e.type){case"response.output_text.delta":{let t=n.output[e.output_index];if(!t)throw new eN(`missing output at index ${e.output_index}`);if("message"===t.type){let n=t.content[e.content_index];if(!n)throw new eN(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new eN(`expected content to be 'output_text', got ${n.type}`);r("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{let t=n.output[e.output_index];if(!t)throw new eN(`missing output at index ${e.output_index}`);"function_call"===t.type&&r("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:r(e.type,e)}},ef=function(){if(this.ended)throw new eN("stream has ended, this shouldn't happen");let e=eC(this,ec,"f");if(!e)throw new eN("request ended without sending any events");eI(this,ec,void 0,"f");let t=function(e,t){var r;return t&&(r=t,tX(r.text?.format))?rX(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}(e,eC(this,eu,"f"));return eI(this,ed,t,"f"),t},em=function(e){let t=eC(this,ec,"f");if(!t){if("response.created"!==e.type)throw new eN(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return eI(this,ec,e.response,"f")}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{let r=t.output[e.output_index];if(!r)throw new eN(`missing output at index ${e.output_index}`);let n=r.type,i=e.part;"message"===n&&"reasoning_text"!==i.type?r.content.push(i):"reasoning"===n&&"reasoning_text"===i.type&&(r.content||(r.content=[]),r.content.push(i));break}case"response.output_text.delta":{let r=t.output[e.output_index];if(!r)throw new eN(`missing output at index ${e.output_index}`);if("message"===r.type){let t=r.content[e.content_index];if(!t)throw new eN(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new eN(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{let r=t.output[e.output_index];if(!r)throw new eN(`missing output at index ${e.output_index}`);"function_call"===r.type&&(r.arguments+=e.delta);break}case"response.reasoning_text.delta":{let r=t.output[e.output_index];if(!r)throw new eN(`missing output at index ${e.output_index}`);if("reasoning"===r.type){let t=r.content?.[e.content_index];if(!t)throw new eN(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new eN(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":eI(this,ec,e.response,"f")}return t},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=eC(this,ed,"f");if(!e)throw new eN("stream ended without producing a ChatCompletion");return e}}class r0 extends tV{list(e,t={},r){return this._client.getAPIList(tK`/responses/${e}/input_items`,tR,{query:t,...r})}}class r1 extends tV{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class r2 extends tV{constructor(){super(...arguments),this.inputItems=new r0(this._client),this.inputTokens=new r1(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&rQ(e),e))}retrieve(e,t={},r){return this._client.get(tK`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&rQ(e),e))}delete(e,t){return this._client.delete(tK`/responses/${e}`,{...t,headers:ru([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>rX(t,e))}stream(e,t){return rZ.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(tK`/responses/${e}/cancel`,t)}}r2.InputItems=r0,r2.InputTokens=r1;class r4 extends tV{create(e,t,r){return this._client.post(tK`/uploads/${e}/parts`,tM({body:t,...r},this._client))}}class r6 extends tV{constructor(){super(...arguments),this.parts=new r4(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(tK`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(tK`/uploads/${e}/complete`,{body:t,...r})}}r6.Parts=r4;let r3=async e=>{let t=await Promise.allSettled(e),r=t.filter(e=>"rejected"===e.status);if(r.length){for(let e of r)console.error(e.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let e of t)"fulfilled"===e.status&&n.push(e.value);return n};class r5 extends tV{create(e,t,r){return this._client.post(tK`/vector_stores/${e}/file_batches`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(tK`/vector_stores/${n}/file_batches/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(tK`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...i}=t;return this._client.getAPIList(tK`/vector_stores/${n}/file_batches/${e}/files`,tR,{query:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=ru([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=s.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await eZ(o);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=Math.min(n?.maxConcurrency??5,t.length),s=this._client,o=t.values(),a=[...r];async function l(e){for(let t of e){let e=await s.files.create({file:t,purpose:"assistants"},n);a.push(e.id)}}let u=Array(i).fill(o).map(l);return await r3(u),await this.createAndPoll(e,{file_ids:a})}}class r8 extends tV{create(e,t,r){return this._client.post(tK`/vector_stores/${e}/files`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(tK`/vector_stores/${n}/files/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...i}=t;return this._client.post(tK`/vector_stores/${n}/files/${e}`,{body:i,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(tK`/vector_stores/${e}/files`,tR,{query:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(tK`/vector_stores/${n}/files/${e}`,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=ru([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),s=i.data;switch(s.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=i.response.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await eZ(o);break;case"failed":case"completed":return s}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(tK`/vector_stores/${n}/files/${e}/content`,tC,{...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class r9 extends tV{constructor(){super(...arguments),this.files=new r8(this._client),this.fileBatches=new r5(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tK`/vector_stores/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(tK`/vector_stores/${e}`,{body:t,...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",tR,{query:e,...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(tK`/vector_stores/${e}`,{...t,headers:ru([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(tK`/vector_stores/${e}/search`,tC,{body:t,method:"post",...r,headers:ru([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}r9.Files=r8,r9.FileBatches=r5;class r7 extends tV{create(e,t){return this._client.post("/videos",tD({body:e,...t},this._client))}retrieve(e,t){return this._client.get(tK`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",tx,{query:e,...t})}delete(e,t){return this._client.delete(tK`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(tK`/videos/${e}/content`,{query:t,...r,headers:ru([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(tK`/videos/${e}/remix`,tD({body:t,...r},this._client))}}class ne extends tV{constructor(){super(...arguments),eg.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if("u"<typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");eC(this,eg,"m",ey).call(this,r);let i=ru([t]).values,s=eC(this,eg,"m",e_).call(this,i,"webhook-signature"),o=eC(this,eg,"m",e_).call(this,i,"webhook-timestamp"),a=eC(this,eg,"m",e_).call(this,i,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new eW("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>n)throw new eW("Webhook timestamp is too old");if(l>u+n)throw new eW("Webhook timestamp is too new");let c=s.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),d=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=a?`${a}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let e of c)try{let t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,new TextEncoder().encode(h)))return}catch{continue}throw new eW("The given webhook signature does not match the expected signature")}}eg=new WeakSet,ey=function(e){if("string"!=typeof e||0===e.length)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},e_=function(e,t){if(!e)throw Error("Headers are required");let r=e.get(t);if(null==r)throw Error(`Missing required header: ${t}`);return r};class nt extends tV{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class nr extends tV{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&ty(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let i=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?i:(ty(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=(e=>{if("u">typeof Buffer){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)}),e)))}}class nn extends tV{createVariation(e,t){return this._client.post("/images/variations",tM({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",tM({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class ni extends tV{create(e,t){return this._client.post("/moderations",{body:e,...t})}}let ns=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;class no{constructor({baseURL:e=ns("OPENAI_BASE_URL"),apiKey:t=ns("OPENAI_API_KEY"),organization:r=ns("OPENAI_ORG_ID")??null,project:n=ns("OPENAI_PROJECT_ID")??null,webhookSecret:i=ns("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(eE.add(this),eb.set(this,void 0),this.completions=new nt(this),this.chat=new ra(this),this.embeddings=new nr(this),this.files=new rM(this),this.images=new nn(this),this.audio=new rp(this),this.moderations=new ni(this),this.models=new rW(this),this.fineTuning=new rH(this),this.graders=new rJ(this),this.vectorStores=new r9(this),this.webhooks=new ne(this),this.beta=new rI(this),this.batches=new rf(this),this.uploads=new r6(this),this.responses=new r2(this),this.realtime=new rY(this),this.conversations=new rN(this),this.evals=new rD(this),this.containers=new rx(this),this.videos=new r7(this),void 0===t)throw new eN("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let o={apiKey:t,organization:r,project:n,webhookSecret:i,...s,baseURL:e||"https://api.openai.com/v1"};o.dangerouslyAllowBrowser,this.baseURL=o.baseURL,this.timeout=o.timeout??ev.DEFAULT_TIMEOUT,this.logger=o.logger??console;let a="warn";this.logLevel=a,this.logLevel=th(o.logLevel,"ClientOptions.logLevel",this)??th(ns("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??a,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),eI(this,eb,e8,"f"),this._options=o,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return ru([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return function(e,t={}){let r,n=e,i=function(e=to){let t;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw TypeError("Encoder has to be a function.");let r=e.charset||to.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=e9;if(void 0!==e.format){if(!tt(te,e.format))throw TypeError("Unknown format option provided.");n=e.format}let i=te[n],s=to.filter;if(("function"==typeof e.filter||ez(e.filter))&&(s=e.filter),t=e.arrayFormat&&e.arrayFormat in ti?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":to.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=void 0===e.allowDots?!0==!!e.encodeDotInKeys||to.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:to.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:to.allowEmptyArrays,arrayFormat:t,charset:r,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:to.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?to.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:to.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:to.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:to.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:to.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:to.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:to.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:to.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):ez(i.filter)&&(r=i.filter);let s=[];if("object"!=typeof n||null===n)return"";let o=ti[i.arrayFormat],a="comma"===o&&i.commaRoundTrip;r||(r=Object.keys(n)),i.sort&&r.sort(i.sort);let l=new WeakMap;for(let e=0;e<r.length;++e){let t=r[e];i.skipNulls&&null===n[t]||ts(s,function e(t,r,n,i,s,o,a,l,u,c,d,h,p,f,m,g,y,_){var E,v;let b,w=t,A=_,S=0,T=!1;for(;void 0!==(A=A.get(ta))&&!T;){let e=A.get(t);if(S+=1,void 0!==e)if(e===S)throw RangeError("Cyclic object value");else T=!0;void 0===A.get(ta)&&(S=0)}if("function"==typeof c?w=c(r,w):w instanceof Date?w=p?.(w):"comma"===n&&ez(w)&&(w=tn(w,function(e){return e instanceof Date?p?.(e):e})),null===w){if(o)return u&&!g?u(r,to.encoder,y,"key",f):r;w=""}if("string"==typeof(E=w)||"number"==typeof E||"boolean"==typeof E||"symbol"==typeof E||"bigint"==typeof E||(v=w)&&"object"==typeof v&&v.constructor&&v.constructor.isBuffer&&v.constructor.isBuffer(v)){if(u){let e=g?r:u(r,to.encoder,y,"key",f);return[m?.(e)+"="+m?.(u(w,to.encoder,y,"value",f))]}return[m?.(r)+"="+m?.(String(w))]}let O=[];if(void 0===w)return O;if("comma"===n&&ez(w))g&&u&&(w=tn(w,u)),b=[{value:w.length>0?w.join(",")||null:void 0}];else if(ez(c))b=c;else{let e=Object.keys(w);b=d?e.sort(d):e}let I=l?String(r).replace(/\./g,"%2E"):String(r),C=i&&ez(w)&&1===w.length?I+"[]":I;if(s&&ez(w)&&0===w.length)return C+"[]";for(let r=0;r<b.length;++r){let E=b[r],v="object"==typeof E&&void 0!==E.value?E.value:w[E];if(a&&null===v)continue;let A=h&&l?E.replace(/\./g,"%2E"):E,T=ez(w)?"function"==typeof n?n(C,A):C:C+(h?"."+A:"["+A+"]");_.set(t,S);let I=new WeakMap;I.set(ta,_),ts(O,e(v,T,n,i,s,o,a,l,"comma"===n&&g&&ez(w)?null:u,c,d,h,p,f,m,g,y,I))}return O}(n[t],t,o,a,i.allowEmptyArrays,i.strictNullHandling,i.skipNulls,i.encodeDotInKeys,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,l))}let u=s.join(i.delimiter),c=!0===i.addQueryPrefix?"?":"";return i.charsetSentinel&&("iso-8859-1"===i.charset?c+="utf8=%26%2310003%3B&":c+="utf8=%E2%9C%93&"),u.length>0?c+u:""}(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${e0}`}defaultIdempotencyKey(){return`stainless-node-retry-${eR()}`}makeStatusError(e,t,r,n){return eP.generate(e,t,r,n)}async _callApiKey(){let e,t=this._options.apiKey;if("function"!=typeof t)return!1;try{e=await t()}catch(e){if(e instanceof eN)throw e;throw new eN(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof e||!e)throw new eN(`Expected 'apiKey' function argument to return a string but it returned ${e}`);return this.apiKey=e,!0}buildURL(e,t,r){let n=!eC(this,eE,"m",ew).call(this)&&r||this.baseURL,i=new URL(eK.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(s)&&(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new tT(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,i=n.maxRetries??this.maxRetries;null==t&&(t=i),await this.prepareOptions(n);let{req:s,url:o,timeout:a}=await this.buildRequest(n,{retryCount:i-t});await this.prepareRequest(s,{url:o,options:n});let l="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),u=void 0===r?"":`, retryOf: ${r}`,c=Date.now();if(ty(this).debug(`[${l}] sending request`,t_({retryOfRequestLogID:r,method:n.method,url:o,options:n,headers:s.headers})),n.signal?.aborted)throw new eU;let d=new AbortController,h=await this.fetchWithTimeout(o,s,a,d).catch(ek),p=Date.now();if(h instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new eU;let i=ex(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return ty(this).info(`[${l}] connection ${i?"timed out":"failed"} - ${e}`),ty(this).debug(`[${l}] connection ${i?"timed out":"failed"} (${e})`,t_({retryOfRequestLogID:r,url:o,durationMs:p-c,message:h.message})),this.retryRequest(n,t,r??l);if(ty(this).info(`[${l}] connection ${i?"timed out":"failed"} - error; no more retries left`),ty(this).debug(`[${l}] connection ${i?"timed out":"failed"} (error; no more retries left)`,t_({retryOfRequestLogID:r,url:o,durationMs:p-c,message:h.message})),i)throw new eM;throw new eD({cause:h})}let f=[...h.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join(""),m=`[${l}${u}${f}] ${s.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-c}ms`;if(!h.ok){let e=await this.shouldRetry(h);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await e5(h.body),ty(this).info(`${m} - ${e}`),ty(this).debug(`[${l}] response error (${e})`,t_({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-c})),this.retryRequest(n,t,r??l,h.headers)}let i=e?"error; no more retries left":"error; not retryable";ty(this).info(`${m} - ${i}`);let s=await h.text().catch(e=>ek(e).message),o=(e=>{try{return JSON.parse(e)}catch(e){return}})(s),a=o?void 0:s;throw ty(this).debug(`[${l}] response error (${i})`,t_({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:a,durationMs:Date.now()-c})),this.makeStatusError(h.status,o,a,h.headers)}return ty(this).info(m),ty(this).debug(`[${l}] response start`,t_({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-c})),{response:h,options:n,controller:d,requestLogID:l,retryOfRequestLogID:r,startTime:c}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){return new tI(this,this.makeRequest(t,null,void 0),e)}async fetchWithTimeout(e,t,r,n){let{signal:i,method:s,...o}=t||{};i&&i.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||"object"==typeof o.body&&null!==o.body&&Symbol.asyncIterator in o.body,u={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...o};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(a)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){let i,s=n?.get("retry-after-ms");if(s){let e=parseFloat(s);Number.isNaN(e)||(i=e)}let o=n?.get("retry-after");if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(i&&0<=i&&i<6e4)){let r=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,r)}return await eZ(i),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:i,query:s,defaultBaseURL:o}=r,a=this.buildURL(i,s,o);"timeout"in r&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eN(`${e} must be an integer`);if(t<0)throw new eN(`${e} must be a positive integer`)})("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:r}),c=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t});return{req:{method:n,headers:c,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:a,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let i={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=ru([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...eA??(eA=(()=>{let e="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e0,"X-Stainless-OS":e2(Deno.build.os),"X-Stainless-Arch":e1(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e0,"X-Stainless-OS":e2(globalThis.process.platform??"unknown"),"X-Stainless-Arch":e1(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=function(){if("u"<typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${n}.${i}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=ru([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:e6(e)}:eC(this,eb,"f").call(this,{body:e,headers:r})}}ev=no,eb=new WeakMap,eE=new WeakSet,ew=function(){return"https://api.openai.com/v1"!==this.baseURL},no.OpenAI=ev,no.DEFAULT_TIMEOUT=6e5,no.OpenAIError=eN,no.APIError=eP,no.APIConnectionError=eD,no.APIConnectionTimeoutError=eM,no.APIUserAbortError=eU,no.NotFoundError=eG,no.ConflictError=eq,no.RateLimitError=eB,no.BadRequestError=ej,no.AuthenticationError=eL,no.InternalServerError=eH,no.PermissionDeniedError=eF,no.UnprocessableEntityError=e$,no.InvalidWebhookSignatureError=eW,no.toFile=tB,no.Completions=nt,no.Chat=ra,no.Embeddings=nr,no.Files=rM,no.Images=nn,no.Audio=rp,no.Moderations=ni,no.Models=rW,no.FineTuning=rH,no.Graders=rJ,no.VectorStores=r9,no.Webhooks=ne,no.Beta=rI,no.Batches=rf,no.Uploads=r6,no.Responses=r2,no.Realtime=rY,no.Conversations=rN,no.Evals=rD,no.Containers=rx,no.Videos=r7,e.s(["f",0,no],88045);let na=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);e.s(["f",0,class extends no{constructor({baseURL:e=ns("OPENAI_BASE_URL"),apiKey:t=ns("AZURE_OPENAI_API_KEY"),apiVersion:r=ns("OPENAI_API_VERSION"),endpoint:n,deployment:i,azureADTokenProvider:s,dangerouslyAllowBrowser:o,...a}={}){if(!r)throw new eN("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if("function"==typeof s&&(o=!0),!s&&!t)throw new eN("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(s&&t)throw new eN("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(a.defaultQuery={...a.defaultQuery,"api-version":r},e){if(n)throw new eN("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new eN("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:s??t,baseURL:e,...a,...void 0!==o?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}async buildRequest(e,t={}){if(na.has(e.path)&&"post"===e.method&&void 0!==e.body){if(!eQ(e.body))throw Error("Expected request body to be an object");let t=this.deploymentName||e.body.model||e.__metadata?.model;void 0===t||this.baseURL.includes("/deployments")||(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return"string"==typeof this._options.apiKey?ru([{"api-key":this.apiKey}]):super.authHeaders(e)}}],500510),e.s([],889228)},97970,(e,t,r)=>{let{EMPTY_BUFFER:n}=e.r(74836),i=Buffer[Symbol.species];function s(e,t,r,n,i){for(let s=0;s<i;s++)r[n+s]=e[s]^t[3&s]}function o(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function a(e){let t;return(a.readOnly=!0,Buffer.isBuffer(e))?e:(e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),a.readOnly=!1),t)}if(t.exports={concat:function(e,t){if(0===e.length)return n;if(1===e.length)return e[0];let r=Buffer.allocUnsafe(t),s=0;for(let t=0;t<e.length;t++){let n=e[t];r.set(n,s),s+=n.length}return s<t?new i(r.buffer,r.byteOffset,s):r},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:a,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,r,n,i,o){o<48?s(t,r,n,i,o):e.mask(t,r,n,i,o)},t.exports.unmask=function(t,r){t.length<32?o(t,r):e.unmask(t,r)}}catch(e){}},74836,(e,t,r)=>{let n=["nodebuffer","arraybuffer","fragments"],i="u">typeof Blob;i&&n.push("blob"),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},170494,(e,t,r)=>{let{kForOnEventAttribute:n,kListener:i}=e.r(74836),s=Symbol("kCode"),o=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),u=Symbol("kReason"),c=Symbol("kTarget"),d=Symbol("kType"),h=Symbol("kWasClean");class p{constructor(e){this[c]=null,this[d]=e}get target(){return this[c]}get type(){return this[d]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[u]=void 0===t.reason?"":t.reason,this[h]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[u]}get wasClean(){return this[h]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[l]}}Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[o]=void 0===t.data?null:t.data}get data(){return this[o]}}function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}Object.defineProperty(g.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:f,ErrorEvent:m,Event:p,EventTarget:{addEventListener(e,t,r={}){let s;for(let s of this.listeners(e))if(!r[n]&&s[i]===t&&!s[n])return;if("message"===e)s=function(e,r){let n=new g("message",{data:r?e:e.toString()});n[c]=this,y(t,this,n)};else if("close"===e)s=function(e,r){let n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[c]=this,y(t,this,n)};else if("error"===e)s=function(e){let r=new m("error",{error:e,message:e.message});r[c]=this,y(t,this,r)};else{if("open"!==e)return;s=function(){let e=new p("open");e[c]=this,y(t,this,e)}}s[n]=!!r[n],s[i]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[i]===t&&!r[n]){this.removeListener(e,r);break}}},MessageEvent:g}},196903,(e,t,r)=>{let{tokenChars:n}=e.r(158739);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,r,s=Object.create(null),o=Object.create(null),a=!1,l=!1,u=!1,c=-1,d=-1,h=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),void 0===t)if(-1===h&&1===n[d])-1===c&&(c=p);else if(0!==p&&(32===d||9===d))-1===h&&-1!==c&&(h=p);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);let r=e.slice(c,h);44===d?(i(s,r,o),o=Object.create(null)):t=r,c=h=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(void 0===r)if(-1===h&&1===n[d])-1===c&&(c=p);else if(32===d||9===d)-1===h&&-1!==c&&(h=p);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p),i(o,e.slice(c,h),!0),44===d&&(i(s,t,o),o=Object.create(null),t=void 0),c=h=-1}else if(61===d&&-1!==c&&-1===h)r=e.slice(c,p),c=h=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(l){if(1!==n[d])throw SyntaxError(`Unexpected character at index ${p}`);-1===c?c=p:a||(a=!0),l=!1}else if(u)if(1===n[d])-1===c&&(c=p);else if(34===d&&-1!==c)u=!1,h=p;else if(92===d)l=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(34===d&&61===e.charCodeAt(p-1))u=!0;else if(-1===h&&1===n[d])-1===c&&(c=p);else if(-1!==c&&(32===d||9===d))-1===h&&(h=p);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);let n=e.slice(c,h);a&&(n=n.replace(/\\/g,""),a=!1),i(o,r,n),44===d&&(i(s,t,o),o=Object.create(null),t=void 0),r=void 0,c=h=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(-1===c||u||32===d||9===d)throw SyntaxError("Unexpected end of input");-1===h&&(h=p);let f=e.slice(c,h);return void 0===t?i(s,f,o):(void 0===r?i(o,f,!0):a?i(o,r,f.replace(/\\/g,"")):i(o,r,f),i(s,t,o)),s}}},362048,(e,t,r)=>{let n=Symbol("kDone"),i=Symbol("kRun");t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}},580295,(e,t,r)=>{let n,i=e.r(406461),s=e.r(97970),o=e.r(362048),{kStatusCode:a}=e.r(74836),l=Buffer[Symbol.species],u=Buffer.from([0,0,255,255]),c=Symbol("permessage-deflate"),d=Symbol("total-length"),h=Symbol("callback"),p=Symbol("buffers"),f=Symbol("error");function m(e){this[p].push(e),this[d]+=e.length}function g(e){(this[d]+=e.length,this[c]._maxPayload<1||this[d]<=this[c]._maxPayload)?this[p].push(e):(this[f]=RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][a]=1009,this.removeListener("data",g),this.reset())}function y(e){(this[c]._inflate=null,this[f])?this[h](this[f]):(e[a]=1007,this[h](e))}t.exports=class{constructor(e){this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._maxPayload=0|this._options.maxPayload,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,n||(n=new o(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[h];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||("number"==typeof e.client_max_window_bits?!(t.clientMaxWindowBits>e.client_max_window_bits):!!e.client_max_window_bits)));if(!r)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:(!0===r.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==r)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=r})}),e}decompress(e,t,r){n.add(n=>{this._decompress(e,t,(e,t)=>{n(),r(e,t)})})}compress(e,t,r){n.add(n=>{this._compress(e,t,(e,t)=>{n(),r(e,t)})})}_decompress(e,t,r){let n=this._isServer?"client":"server";if(!this._inflate){let e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[d]=0,this._inflate[p]=[],this._inflate.on("error",y),this._inflate.on("data",g)}this._inflate[h]=r,this._inflate.write(e),t&&this._inflate.write(u),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,r(e);return}let i=s.concat(this._inflate[p],this._inflate[d]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[d]=0,this._inflate[p]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(e,t,r){let n=this._isServer?"server":"client";if(!this._deflate){let e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[d]=0,this._deflate[p]=[],this._deflate.on("data",m)}this._deflate[h]=r,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=s.concat(this._deflate[p],this._deflate[d]);t&&(e=new l(e.buffer,e.byteOffset,e.length-4)),this._deflate[h]=null,this._deflate[d]=0,this._deflate[p]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},629485,(e,t,r)=>{let{Writable:n}=e.r(688947),i=e.r(580295),{BINARY_TYPES:s,EMPTY_BUFFER:o,kStatusCode:a,kWebSocket:l}=e.r(74836),{concat:u,toArrayBuffer:c,unmask:d}=e.r(97970),{isValidStatusCode:h,isValidUTF8:p}=e.r(158739),f=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||s[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=0|e.maxBufferedChunks,this._maxFragments=0|e.maxFragments,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){return 8===this._opcode&&0==this._state?r():this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks?void r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS")):void(this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r))}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let r=(64&t[0])==64;if(r&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=r}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);r>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*r+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&d(t,this._mask)}if(this._opcode>7)return void this.controlMessage(t,e);if(this._maxFragments>0&&++this._numFragments>this._maxFragments)return void e(this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?u(r,t):"arraybuffer"===this._binaryType?c(u(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)}))}else{let n=u(r,t);if(!this._skipUTF8Validation&&!p(n))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,o),this.end();else{let r=e.readUInt16BE(0);if(!h(r))return void t(this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(n))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}))}createError(e,t,r,n,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[a]=n,s}}},816735,(e,t,r)=>{let n,{Duplex:i}=e.r(688947),{randomFillSync:s}=e.r(254799),{types:{isUint8Array:o}}=e.r(224361),a=e.r(580295),{EMPTY_BUFFER:l,kWebSocket:u,NOOP:c}=e.r(74836),{isBlob:d,isValidStatusCode:h}=e.r(158739),{mask:p,toBuffer:f}=e.r(97970),m=Symbol("kByteLength"),g=Buffer.alloc(4),y=8192;function _(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){let n=e._queue[r],i=n[n.length-1];"function"==typeof i&&i(t)}}function E(e,t,r){_(e,t,r),e.onerror(t)}t.exports=class e{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[u]=void 0}static frame(e,t){let r,i,o=!1,a=2,l=!1;t.mask&&(r=t.maskBuffer||g,t.generateMask?t.generateMask(r):(8192===y&&(void 0===n&&(n=Buffer.alloc(8192)),s(n,0,8192),y=0),r[0]=n[y++],r[1]=n[y++],r[2]=n[y++],r[3]=n[y++]),l=(r[0]|r[1]|r[2]|r[3])==0,a=6),"string"==typeof e?i=(!t.mask||l)&&void 0!==t[m]?t[m]:(e=Buffer.from(e)).length:(i=e.length,o=t.mask&&t.readOnly&&!l);let u=i;i>=65536?(a+=8,u=127):i>125&&(a+=2,u=126);let c=Buffer.allocUnsafe(o?i+a:a);return(c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=u,126===u?c.writeUInt16BE(i,2):127===u&&(c[2]=c[3]=0,c.writeUIntBE(i,4,6)),t.mask)?(c[1]|=128,c[a-4]=r[0],c[a-3]=r[1],c[a-2]=r[2],c[a-1]=r[3],l)?[c,e]:o?(p(e,r,c,a,i),[c]):(p(e,r,e,0,i),[c,e]):[c,e]}close(t,r,n,i){let s;if(void 0===t)s=l;else if("number"==typeof t&&h(t))if(void 0!==r&&r.length){let e=Buffer.byteLength(r);if(e>123)throw RangeError("The message must not be greater than 123 bytes");if((s=Buffer.allocUnsafe(2+e)).writeUInt16BE(t,0),"string"==typeof r)s.write(r,2);else if(o(r))s.set(r,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(s=Buffer.allocUnsafe(2)).writeUInt16BE(t,0);else throw TypeError("First argument must be a valid error code number");let a={[m]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(e.frame(s,a),i)}ping(t,r,n){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):d(t)?(i=t.size,s=!1):(i=(t=f(t)).length,s=f.readOnly),i>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};d(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,n]):this.getBlobData(t,!1,o,n):0!==this._state?this.enqueue([this.dispatch,t,!1,o,n]):this.sendFrame(e.frame(t,o),n)}pong(t,r,n){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):d(t)?(i=t.size,s=!1):(i=(t=f(t)).length,s=f.readOnly),i>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};d(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,n]):this.getBlobData(t,!1,o,n):0!==this._state?this.enqueue([this.dispatch,t,!1,o,n]):this.sendFrame(e.frame(t,o),n)}send(e,t,r){let n,i,s=this._extensions[a.extensionName],o=t.binary?2:1,l=t.compress;"string"==typeof e?(n=Buffer.byteLength(e),i=!1):d(e)?(n=e.size,i=!1):(n=(e=f(e)).length,i=f.readOnly),this._firstFragment?(this._firstFragment=!1,l&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=n>=s._threshold),this._compress=l):(l=!1,o=0),t.fin&&(this._firstFragment=!0);let u={[m]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:l};d(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(t,r,n,i){this._bufferedBytes+=n[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(_,this,e,i);return}this._bufferedBytes-=n[m];let s=f(t);r?this.dispatch(s,r,n,i):(this._state=0,this.sendFrame(e.frame(s,n),i),this.dequeue())}).catch(e=>{process.nextTick(E,this,e,i)})}dispatch(t,r,n,i){if(!r)return void this.sendFrame(e.frame(t,n),i);let s=this._extensions[a.extensionName];this._bufferedBytes+=n[m],this._state=1,s.compress(t,n.fin,(t,r)=>{this._socket.destroyed?_(this,Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=n[m],this._state=0,n.readOnly=!1,this.sendFrame(e.frame(r,n),i),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}},721365,(e,t,r)=>{e.r(835065);let{Duplex:n}=e.r(688947);function i(e){e.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener("error",o),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let r=!0,a=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){let n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(i,a);return}let s=!1;e.once("error",function(e){s=!0,n(e)}),e.once("close",function(){s||n(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,r,n)}):e.send(t,n)},a.on("end",s),a.on("error",o),a}},942977,(e,t,r)=>{let{tokenChars:n}=e.r(158739);t.exports={parse:function(e){let t=new Set,r=-1,i=-1,s=0;for(;s<e.length;s++){let o=e.charCodeAt(s);if(-1===i&&1===n[o])-1===r&&(r=s);else if(0!==s&&(32===o||9===o))-1===i&&-1!==r&&(i=s);else if(44===o){if(-1===r)throw SyntaxError(`Unexpected character at index ${s}`);-1===i&&(i=s);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${s}`)}if(-1===r||-1!==i)throw SyntaxError("Unexpected end of input");let o=e.slice(r,s);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}}},158739,(e,t,r)=>{let{isUtf8:n}=e.r(500874),{hasBlob:i}=e.r(74836);function s(e){let t=e.length,r=0;for(;r<t;)if((128&e[r])==0)r++;else if((224&e[r])==192){if(r+1===t||(192&e[r+1])!=128||(254&e[r])==192)return!1;r+=2}else if((240&e[r])==224){if(r+2>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||224===e[r]&&(224&e[r+1])==128||237===e[r]&&(224&e[r+1])==160)return!1;r+=3}else{if((248&e[r])!=240||r+3>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||(192&e[r+3])!=128||240===e[r]&&(240&e[r+1])==128||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:s,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},n)t.exports.isValidUTF8=function(e){return e.length<24?s(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch(e){}},217198,(e,t,r)=>{let n=e.r(427699),i=e.r(921517),{Duplex:s}=e.r(688947),{createHash:o}=e.r(254799),a=e.r(196903),l=e.r(580295),u=e.r(942977),c=e.r(835065),{CLOSE_TIMEOUT:d,GUID:h,kWebSocket:p}=e.r(74836),f=/^[+/0-9A-Za-z]{22}==$/;function m(e){e._state=2,e.emit("close")}function g(){this.destroy()}function y(e,t,r,n){r=r||i.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r
|
|
21
|
+
`+Object.keys(n).map(e=>`${e}: ${n[e]}`).join("\r\n")+"\r\n\r\n"+r)}function _(e,t,r,n,i,s){if(e.listenerCount("wsClientError")){let n=Error(i);Error.captureStackTrace(n,_),e.emit("wsClientError",n,r,t)}else y(r,n,i,s)}t.exports=class extends n{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let r=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(m,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",g);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void _(this,e,t,405,"Invalid HTTP method");if(void 0===s||"websocket"!==s.toLowerCase())return void _(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!f.test(i))return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==o&&8!==o)return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void y(t,400);let c=e.headers["sec-websocket-protocol"],d=new Set;if(void 0!==c)try{d=u.parse(c)}catch(r){_(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&void 0!==h){let r=new l({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=a.parse(h);e[l.extensionName]&&(r.accept(e[l.extensionName]),p[l.extensionName]=r)}catch(r){_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let s={origin:e.headers[`${8===o?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(s,(s,o,a,l)=>{if(!s)return y(t,o||401,a,l);this.completeUpgrade(p,i,d,e,t,r,n)});if(!this.options.verifyClient(s))return y(t,401)}this.completeUpgrade(p,i,d,e,t,r,n)}completeUpgrade(e,t,r,n,i,s,u){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return y(i,503);let c=o("sha1").update(t+h).digest("base64"),d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),f._protocol=e)}if(e[l.extensionName]){let t=e[l.extensionName].params,r=a.format({[l.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${r}`),f._extensions=e}this.emit("headers",d,n),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",g),f.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(m,this)})),u(f,n)}}},835065,(e,t,r)=>{let n=e.r(427699),i=e.r(524836),s=e.r(921517),o=e.r(504446),a=e.r(755004),{randomBytes:l,createHash:u}=e.r(254799),{Duplex:c,Readable:d}=e.r(688947),{URL:h}=e.r(792509),p=e.r(580295),f=e.r(629485),m=e.r(816735),{isBlob:g}=e.r(158739),{BINARY_TYPES:y,CLOSE_TIMEOUT:_,EMPTY_BUFFER:E,GUID:v,kForOnEventAttribute:b,kListener:w,kStatusCode:A,kWebSocket:S,NOOP:T}=e.r(74836),{EventTarget:{addEventListener:O,removeEventListener:I}}=e.r(170494),{format:C,parse:R}=e.r(196903),{toBuffer:x}=e.r(97970),k=Symbol("kAborted"),N=[8,13],P=["CONNECTING","OPEN","CLOSING","CLOSED"],U=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class D extends n{constructor(e,t,r){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=E,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=D.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=r&&void 0!==r.protocols?Array.isArray(r.protocols)?r.protocols:[r.protocols]:[]:Array.isArray(t)||(t="object"==typeof t&&null!==t?void 0===(r=t).protocols?[]:Array.isArray(r.protocols)?r.protocols:[r.protocols]:[t]),function e(t,r,n,o){let a,c,d,f,m={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:N[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=m.autoPong,t._closeTimeout=m.closeTimeout,!N.includes(m.protocolVersion))throw RangeError(`Unsupported protocol version: ${m.protocolVersion} (supported versions: ${N.join(", ")})`);if(r instanceof h)a=r;else try{a=new h(r)}catch{throw SyntaxError(`Invalid URL: ${r}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),t._url=a.href;let g="wss:"===a.protocol,y="ws+unix:"===a.protocol;if("ws:"===a.protocol||g||y?y&&!a.pathname?c="The URL's pathname is empty":a.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',c){let e=SyntaxError(c);if(0!==t._redirects)return void M(t,e);throw e}let E=g?443:80,b=l(16).toString("base64"),w=g?i.request:s.request,A=new Set;if(m.createConnection=m.createConnection||(g?L:j),m.defaultPort=m.defaultPort||E,m.port=a.port||E,m.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,m.headers={...m.headers,"Sec-WebSocket-Version":m.protocolVersion,"Sec-WebSocket-Key":b,Connection:"Upgrade",Upgrade:"websocket"},m.path=a.pathname+a.search,m.timeout=m.handshakeTimeout,m.perMessageDeflate&&(d=new p({...m.perMessageDeflate,isServer:!1,maxPayload:m.maxPayload}),m.headers["Sec-WebSocket-Extensions"]=C({[p.extensionName]:d.offer()})),n.length){for(let e of n){if("string"!=typeof e||!U.test(e)||A.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");A.add(e)}m.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(m.origin&&(m.protocolVersion<13?m.headers["Sec-WebSocket-Origin"]=m.origin:m.headers.Origin=m.origin),(a.username||a.password)&&(m.auth=`${a.username}:${a.password}`),y){let e=m.path.split(":");m.socketPath=e[0],m.path=e[1]}if(m.followRedirects){if(0===t._redirects){t._originalIpc=y,t._originalSecure=g,t._originalHostOrSocketPath=y?m.socketPath:a.host;let e=o&&o.headers;if(o={...o,headers:{}},e)for(let[t,r]of Object.entries(e))o.headers[t.toLowerCase()]=r}else if(0===t.listenerCount("redirect")){let e=y?!!t._originalIpc&&m.socketPath===t._originalHostOrSocketPath:!t._originalIpc&&a.host===t._originalHostOrSocketPath;e&&(!t._originalSecure||g)||(delete m.headers.authorization,delete m.headers.cookie,e||delete m.headers.host,m.auth=void 0)}m.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(m.auth).toString("base64")),f=t._req=w(m),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=w(m);m.timeout&&f.on("timeout",()=>{F(t,f,"Opening handshake has timed out")}),f.on("error",e=>{null===f||f[k]||(f=t._req=null,M(t,e))}),f.on("response",i=>{let s=i.headers.location,a=i.statusCode;if(s&&m.followRedirects&&a>=300&&a<400){let i;if(++t._redirects>m.maxRedirects)return void F(t,f,"Maximum redirects exceeded");f.abort();try{i=new h(s,r)}catch(e){M(t,SyntaxError(`Invalid URL: ${s}`));return}e(t,i,n,o)}else t.emit("unexpected-response",f,i)||F(t,f,`Unexpected server response: ${i.statusCode}`)}),f.on("upgrade",(e,r,n)=>{let i;if(t.emit("upgrade",e),t.readyState!==D.CONNECTING)return;f=t._req=null;let s=e.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void F(t,r,"Invalid Upgrade header");let o=u("sha1").update(b+v).digest("base64");if(e.headers["sec-websocket-accept"]!==o)return void F(t,r,"Invalid Sec-WebSocket-Accept header");let a=e.headers["sec-websocket-protocol"];if(void 0!==a?A.size?A.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":A.size&&(i="Server sent no subprotocol"),i)return void F(t,r,i);a&&(t._protocol=a);let l=e.headers["sec-websocket-extensions"];if(void 0!==l){let e;if(!d)return void F(t,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{e=R(l)}catch(e){F(t,r,"Invalid Sec-WebSocket-Extensions header");return}let n=Object.keys(e);if(1!==n.length||n[0]!==p.extensionName)return void F(t,r,"Server indicated an extension that was not requested");try{d.accept(e[p.extensionName])}catch(e){F(t,r,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[p.extensionName]=d}t.setSocket(r,n,{allowSynchronousEvents:m.allowSynchronousEvents,generateMask:m.generateMask,maxBufferedChunks:m.maxBufferedChunks,maxFragments:m.maxFragments,maxPayload:m.maxPayload,skipUTF8Validation:m.skipUTF8Validation})}),m.finishRequest?m.finishRequest(f,t):f.end()}(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let n=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new m(e,this._extensions,r.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[S]=this,i[S]=this,e[S]=this,n.on("conclude",q),n.on("drain",$),n.on("error",B),n.on("message",V),n.on("ping",J),n.on("pong",W),i.onerror=z,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",X),e.on("data",Q),e.on("end",Z),e.on("error",ee),this._readyState=D.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING)return void F(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===D.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=D.CLOSING,Y(this)}}pause(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?G(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.ping(e||E,t,r))}pong(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?G(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.pong(e||E,t,r))}resume(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)return void G(this,e,r);let n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(n.compress=!1),this._sender.send(e||E,n,r)}terminate(){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING)return void F(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=D.CLOSING,this._socket.destroy())}}}function M(e,t){e._readyState=D.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function j(e){return e.path=e.socketPath,o.connect(e)}function L(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=o.isIP(e.host)?"":e.host),a.connect(e)}function F(e,t,r){e._readyState=D.CLOSING;let n=Error(r);Error.captureStackTrace(n,F),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(M,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function G(e,t,r){if(t){let r=g(t)?t.size:x(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${P[e.readyState]})`);process.nextTick(r,t)}}function q(e,t){let r=this[S];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[S]&&(r._socket.removeListener("data",Q),process.nextTick(K,r._socket),1005===e?r.close():r.close(e,t))}function $(){let e=this[S];e.isPaused||e._socket.resume()}function B(e){let t=this[S];void 0!==t._socket[S]&&(t._socket.removeListener("data",Q),process.nextTick(K,t._socket),t.close(e[A])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function H(){this[S].emitClose()}function V(e,t){this[S].emit("message",e,t)}function J(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,T),t.emit("ping",e)}function W(e){this[S].emit("pong",e)}function K(e){e.resume()}function z(e){let t=this[S];t.readyState!==D.CLOSED&&(t.readyState===D.OPEN&&(t._readyState=D.CLOSING,Y(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Y(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function X(){let e=this[S];if(this.removeListener("close",X),this.removeListener("data",Q),this.removeListener("end",Z),e._readyState=D.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&0!==this._readableState.length){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",H),e._receiver.on("finish",H))}function Q(e){this[S]._receiver.write(e)||this.pause()}function Z(){let e=this[S];e._readyState=D.CLOSING,e._receiver.end(),this.end()}function ee(){let e=this[S];this.removeListener("error",ee),this.on("error",T),e&&(e._readyState=D.CLOSING,this.destroy())}Object.defineProperty(D,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty(D.prototype,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty(D,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty(D.prototype,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty(D,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty(D.prototype,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty(D,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),Object.defineProperty(D.prototype,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(D.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[w];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[b]:!0})}})}),D.prototype.addEventListener=O,D.prototype.removeEventListener=I,t.exports=D},229236,e=>{e.i(889228);var t=e.i(500510),r=e.i(405898),n=e.i(261829),i=e.i(983598),s=e.i(798003),o=e.i(999617),a=e.i(459398),l=e.i(50377),u=e.i(93716),c=e.i(630166),d=e.i(115851);let h=(0,l.f)("ai:azure");e.s(["f",0,class{client;model;deployment;endpoint;constructor(e){let r=e?.apiKey,n=e?.endpoint,i=e?.deploymentName;if(!r)throw Error("AI_AUTH_ERROR: AZURE_OPENAI_API_KEY is required for Azure OpenAI provider");if(!n)throw Error("AI_AUTH_ERROR: AZURE_OPENAI_ENDPOINT is required for Azure OpenAI provider");if(!i)throw Error("AI_AUTH_ERROR: AZURE_OPENAI_DEPLOYMENT is required for Azure OpenAI provider");this.client=new t.f({apiKey:r,endpoint:n,deployment:i,apiVersion:e?.apiVersion||"2024-02-15-preview"}),this.model=e?.model||i,this.deployment=i,this.endpoint=n,h.info({provider:"Azure OpenAI",model:this.model,deployment:this.deployment,endpoint:n,apiKeyPrefix:r.substring(0,8)+"..."},"Azure AI Provider initialized")}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.f)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.B)(this.extractTag(e,"difficulty_stars")),...(0,o.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.u)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.b)(),p=c?{candidateTags:c}:await (0,a.i)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"Azure OpenAI",endpoint:this.endpoint,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,deployment:this.deployment,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r=await (0,u.V)(r=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let n=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",n),!n)throw Error("Empty response from AI");let i=this.parseResponse(n);return h.box("✅ Parsed & Validated Result",JSON.stringify(i,null,2)),i}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.b)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
|
|
22
|
+
Original Question: "${e}"
|
|
23
|
+
Knowledge Points: ${t.join(", ")}
|
|
24
|
+
`;h.box("🎯 Generate Similar Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.f)(r)}catch(e){throw h.box("❌ Error during similar question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(e,t="zh",n,i,s,a){let l=(0,r.generateReanswerPrompt)(t,e,n,{candidateTags:a},s);h.box("🔄 Reanswer Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,questionLength:e.length,subject:n||"auto",hasImage:!!i}),h.debug({prompt:l},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t=await (0,u.V)(t=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:l},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(t)},"Full API response"),!t||!t.choices||0===t.choices.length)throw h.error({response:JSON.stringify(t)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let r=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"AI raw response"),!r)throw Error("Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",a=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),d=this.extractTag(r,"wrong_answer_text")||"",p=this.extractTag(r,"mistake_analysis")||"",f=(0,c.f)(this.extractTag(r,"mistake_status"),d);return h.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:a,wrongAnswerText:d,mistakeAnalysis:p,mistakeStatus:f,subject:(0,o.G)(this.extractTag(r,"subject")),difficultyStars:(0,o.B)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"Azure OpenAI",model:this.model,deployment:this.deployment,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"Azure OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.r)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"Azure OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.K)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"Azure OpenAI",deployment:this.deployment,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.V)(r=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.t)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"Azure OpenAI",deployment:this.deployment,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.f)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s,o="zh"){let a=(0,r.generateSvgAnimationPrompt)(e,t,i,s,o);h.info({provider:"Azure OpenAI",deployment:this.deployment,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:a},{role:"user",content:r.SVG_ANIMATION_REQUEST[o]}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"Azure OpenAI error"),e instanceof Error){if(e.message===u.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}])},893963,e=>{let t,r,n,i,s;var o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I,C,R,x,k,N,P,U,D,M,j,L,F,G,q,$,B,H,V,J,W,K,z,Y,X,Q,Z,ee,et,er,en,ei,es,eo,ea,el,eu,ec,ed,eh,ep,ef,em,eg,ey,e_,eE,ev,eb,ew,eA,eS,eT,eO,eI,eC,eR,ex,ek,eN,eP,eU,eD,eM,ej,eL,eF,eG,eq,e$,eB,eH,eV,eJ,eW,eK,ez,eY,eX,eQ,eZ,e0,e1,e2,e4,e6,e3,e5,e8,e9,e7,te,tt,tr=e.i(947334),tn=e.i(522734),ti=e.i(924868),ts=e.i(81111),to=e.i(188646);e.i(721365),e.i(196903),e.i(580295),e.i(629485),e.i(816735),e.i(942977);var ta=e.i(835065);e.i(217198),ta.default;var tl=e.i(814747);class tu{}function tc(e,t){return e.replace(/\{([^}]+)\}/g,(e,r)=>{if(Object.prototype.hasOwnProperty.call(t,r)){let e=t[r];return null!=e?String(e):""}throw Error(`Key '${r}' not found in valueMap.`)})}function td(e,t,r){for(let n=0;n<t.length-1;n++){let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))if(Array.isArray(r))e[s]=Array.from({length:r.length},()=>({}));else throw Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[s])){let i=e[s];if(Array.isArray(r))for(let e=0;e<i.length;e++)td(i[e],t.slice(n+1),r[e]);else for(let e of i)td(e,t.slice(n+1),r)}return}if(i.endsWith("[0]")){let s=i.slice(0,-3);s in e||(e[s]=[{}]),td(e[s][0],t.slice(n+1),r);return}e[i]&&"object"==typeof e[i]||(e[i]={}),e=e[i]}let n=t[t.length-1],i=e[n];if(void 0!==i){if(!r||"object"==typeof r&&0===Object.keys(r).length||r===i)return;if("object"==typeof i&&"object"==typeof r&&null!==i&&null!==r)Object.assign(i,r);else throw Error(`Cannot set value for an existing key. Key: ${n}`)}else"_self"!==n||"object"!=typeof r||null===r||Array.isArray(r)?e[n]=r:Object.assign(e,r)}function th(e,t,r){try{if(1===t.length&&"_self"===t[0])return e;for(let n=0;n<t.length;n++){if("object"!=typeof e||null===e)return r;let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))return r;{let i=e[s];if(!Array.isArray(i))return r;return i.map(e=>th(e,t.slice(n+1),r))}}e=e[i]}return e}catch(e){if(e instanceof TypeError)return r;throw e}}function tp(e){if("string"!=typeof e)throw Error("fromImageBytes must be a string");return e}function tf(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["metadata"]);null!=l&&td(o,["metadata"],l);let u=th(e,["done"]);null!=u&&td(o,["done"],u);let c=th(e,["error"]);null!=c&&td(o,["error"],c);let d=th(e,["response"]);return null!=d&&td(o,["response"],(r={},null!=(n=th(t=d,["sdkHttpResponse"]))&&td(r,["sdkHttpResponse"],n),null!=(i=th(t,["parent"]))&&td(r,["parent"],i),null!=(s=th(t,["documentName"]))&&td(r,["documentName"],s),r)),o}(o=eu||(eu={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",o.OUTCOME_OK="OUTCOME_OK",o.OUTCOME_FAILED="OUTCOME_FAILED",o.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(a=ec||(ec={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",a.PYTHON="PYTHON",(l=ed||(ed={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",l.SILENT="SILENT",l.WHEN_IDLE="WHEN_IDLE",l.INTERRUPT="INTERRUPT",(u=eh||(eh={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",u.STRING="STRING",u.NUMBER="NUMBER",u.INTEGER="INTEGER",u.BOOLEAN="BOOLEAN",u.ARRAY="ARRAY",u.OBJECT="OBJECT",u.NULL="NULL",(c=ep||(ep={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",c.MODE_DYNAMIC="MODE_DYNAMIC",(d=ef||(ef={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",d.SIMPLE_SEARCH="SIMPLE_SEARCH",d.ELASTIC_SEARCH="ELASTIC_SEARCH",(h=em||(em={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",h.NO_AUTH="NO_AUTH",h.API_KEY_AUTH="API_KEY_AUTH",h.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",h.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",h.OAUTH="OAUTH",h.OIDC_AUTH="OIDC_AUTH",(p=eg||(eg={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",p.HTTP_IN_QUERY="HTTP_IN_QUERY",p.HTTP_IN_HEADER="HTTP_IN_HEADER",p.HTTP_IN_PATH="HTTP_IN_PATH",p.HTTP_IN_BODY="HTTP_IN_BODY",p.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(f=ey||(ey={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",f.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",f.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",f.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",f.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",f.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",f.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(m=e_||(e_={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",m.LOW="LOW",m.MEDIUM="MEDIUM",m.HIGH="HIGH",m.MINIMAL="MINIMAL",(g=eE||(eE={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",g.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",g.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",g.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",g.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",g.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",g.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",g.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",g.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",g.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",g.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(y=ev||(ev={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",y.SEVERITY="SEVERITY",y.PROBABILITY="PROBABILITY",(_=eb||(eb={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",_.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",_.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",_.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",_.BLOCK_NONE="BLOCK_NONE",_.OFF="OFF",(E=ew||(ew={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",E.STOP="STOP",E.MAX_TOKENS="MAX_TOKENS",E.SAFETY="SAFETY",E.RECITATION="RECITATION",E.LANGUAGE="LANGUAGE",E.OTHER="OTHER",E.BLOCKLIST="BLOCKLIST",E.PROHIBITED_CONTENT="PROHIBITED_CONTENT",E.SPII="SPII",E.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",E.IMAGE_SAFETY="IMAGE_SAFETY",E.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",E.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",E.NO_IMAGE="NO_IMAGE",E.IMAGE_RECITATION="IMAGE_RECITATION",E.IMAGE_OTHER="IMAGE_OTHER",(v=eA||(eA={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",v.NEGLIGIBLE="NEGLIGIBLE",v.LOW="LOW",v.MEDIUM="MEDIUM",v.HIGH="HIGH",(b=eS||(eS={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",b.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",b.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",b.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",b.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(w=eT||(eT={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",w.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",w.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",w.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",w.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(A=eO||(eO={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",A.SAFETY="SAFETY",A.OTHER="OTHER",A.BLOCKLIST="BLOCKLIST",A.PROHIBITED_CONTENT="PROHIBITED_CONTENT",A.IMAGE_SAFETY="IMAGE_SAFETY",A.MODEL_ARMOR="MODEL_ARMOR",A.JAILBREAK="JAILBREAK",(S=eI||(eI={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",S.ON_DEMAND="ON_DEMAND",S.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(T=eC||(eC={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",T.TEXT="TEXT",T.IMAGE="IMAGE",T.AUDIO="AUDIO",(O=eR||(eR={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",O.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",O.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",O.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(I=ex||(ex={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",I.TUNING_MODE_FULL="TUNING_MODE_FULL",I.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(C=ek||(ek={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",C.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",C.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",C.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",C.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",C.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",C.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(R=eN||(eN={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",R.JOB_STATE_QUEUED="JOB_STATE_QUEUED",R.JOB_STATE_PENDING="JOB_STATE_PENDING",R.JOB_STATE_RUNNING="JOB_STATE_RUNNING",R.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",R.JOB_STATE_FAILED="JOB_STATE_FAILED",R.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",R.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",R.JOB_STATE_PAUSED="JOB_STATE_PAUSED",R.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",R.JOB_STATE_UPDATING="JOB_STATE_UPDATING",R.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(x=eP||(eP={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",x.TUNING_TASK_I2V="TUNING_TASK_I2V",x.TUNING_TASK_T2V="TUNING_TASK_T2V",x.TUNING_TASK_R2V="TUNING_TASK_R2V",(k=eU||(eU={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",k.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",k.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",k.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",k.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(N=eD||(eD={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",N.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",N.BALANCED="BALANCED",N.PRIORITIZE_COST="PRIORITIZE_COST",(P=eM||(eM={})).UNSPECIFIED="UNSPECIFIED",P.BLOCKING="BLOCKING",P.NON_BLOCKING="NON_BLOCKING",(U=ej||(ej={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",U.MODE_DYNAMIC="MODE_DYNAMIC",(D=eL||(eL={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",D.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(M=eF||(eF={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",M.AUTO="AUTO",M.ANY="ANY",M.NONE="NONE",M.VALIDATED="VALIDATED",(j=eG||(eG={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",j.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",j.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",j.BLOCK_NONE="BLOCK_NONE",(L=eq||(eq={})).DONT_ALLOW="DONT_ALLOW",L.ALLOW_ADULT="ALLOW_ADULT",L.ALLOW_ALL="ALLOW_ALL",(F=e$||(e$={})).auto="auto",F.en="en",F.ja="ja",F.ko="ko",F.hi="hi",F.zh="zh",F.pt="pt",F.es="es",(G=eB||(eB={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",G.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",G.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",G.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",G.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(q=eH||(eH={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",q.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",q.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",q.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",($=eV||(eV={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",$.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",$.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",$.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(B=eJ||(eJ={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",B.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",B.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",B.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",B.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",B.EDIT_MODE_STYLE="EDIT_MODE_STYLE",B.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",B.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(H=eW||(eW={})).FOREGROUND="FOREGROUND",H.BACKGROUND="BACKGROUND",H.PROMPT="PROMPT",H.SEMANTIC="SEMANTIC",H.INTERACTIVE="INTERACTIVE",(V=eK||(eK={})).ASSET="ASSET",V.STYLE="STYLE",(J=ez||(ez={})).INSERT="INSERT",J.REMOVE="REMOVE",J.REMOVE_STATIC="REMOVE_STATIC",J.OUTPAINT="OUTPAINT",(W=eY||(eY={})).OPTIMIZED="OPTIMIZED",W.LOSSLESS="LOSSLESS",(K=eX||(eX={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",K.PREFERENCE_TUNING="PREFERENCE_TUNING",(z=eQ||(eQ={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",z.STATE_PENDING="STATE_PENDING",z.STATE_ACTIVE="STATE_ACTIVE",z.STATE_FAILED="STATE_FAILED",(Y=eZ||(eZ={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",Y.PROCESSING="PROCESSING",Y.ACTIVE="ACTIVE",Y.FAILED="FAILED",(X=e0||(e0={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",X.UPLOADED="UPLOADED",X.GENERATED="GENERATED",(Q=e1||(e1={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",Q.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",Q.RESPONSE_REJECTED="RESPONSE_REJECTED",Q.NEED_MORE_INPUT="NEED_MORE_INPUT",(Z=e2||(e2={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Z.TEXT="TEXT",Z.IMAGE="IMAGE",Z.VIDEO="VIDEO",Z.AUDIO="AUDIO",Z.DOCUMENT="DOCUMENT",(ee=e4||(e4={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",ee.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",ee.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(et=e6||(e6={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",et.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",et.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(er=e3||(e3={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",er.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",er.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(en=e5||(e5={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",en.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",en.NO_INTERRUPTION="NO_INTERRUPTION",(ei=e8||(e8={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",ei.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",ei.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",(es=e9||(e9={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",es.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",es.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",es.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",es.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",es.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",es.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",es.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",es.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",es.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",es.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",es.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",es.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(eo=e7||(e7={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",eo.QUALITY="QUALITY",eo.DIVERSITY="DIVERSITY",eo.VOCALIZATION="VOCALIZATION",(ea=te||(te={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",ea.PLAY="PLAY",ea.PAUSE="PAUSE",ea.STOP="STOP",ea.RESET_CONTEXT="RESET_CONTEXT";class tm{constructor(e){let t={};for(let r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class tg{get text(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let l="",u=!1,c=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"text"!==t&&"thought"!==t&&"thoughtSignature"!==t&&(null!==r||void 0!==r)&&c.push(t);if("string"==typeof e.text){if("boolean"==typeof e.thought&&e.thought)continue;u=!0,l+=e.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let l="",u=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"inlineData"!==t&&(null!==r||void 0!==r)&&u.push(t);e.inlineData&&"string"==typeof e.inlineData.data&&(l+=atob(e.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let l=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);if((null==l?void 0:l.length)!==0)return l}get executableCode(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.code}get codeExecutionResult(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.output}}class ty{}class t_{}class tE{}class tv{}class tb{}class tw{}class tA{}class tS{}class tT{}class tO{}class tI{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r,n=new tI;if(t){let t,n,i,s,o,a;t={},null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),null!=(a=th(e,["response"]))&&td(t,["response"],function(e){let t={},r=th(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["_self"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["gcsUri"]))&&td(i,["uri"],s),null!=(o=th(t,["bytesBase64Encoded"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["mimeType"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}else{let t,n,i,s,o,a;t={},null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),null!=(a=th(e,["response","generateVideoResponse"]))&&td(t,["response"],function(e){let t={},r=th(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["video"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["uri"]))&&td(i,["uri"],s),null!=(o=th(t,["encodedVideo"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["encoding"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}return Object.assign(n,r),n}}class tC{}class tR{}class tx{}class tk{}class tN{}class tP{}class tU{}class tD{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){var r;let n,i,s,o,a,l,u,c,d,h,p=new tD;return Object.assign(p,(a={},null!=(l=th(e,["name"]))&&td(a,["name"],l),null!=(u=th(e,["metadata"]))&&td(a,["metadata"],u),null!=(c=th(e,["done"]))&&td(a,["done"],c),null!=(d=th(e,["error"]))&&td(a,["error"],d),null!=(h=th(e,["response"]))&&td(a,["response"],(n={},null!=(i=th(r=h,["sdkHttpResponse"]))&&td(n,["sdkHttpResponse"],i),null!=(s=th(r,["parent"]))&&td(n,["parent"],s),null!=(o=th(r,["documentName"]))&&td(n,["documentName"],o),n)),a)),p}}class tM{}class tj{}class tL{}class tF{}class tG{get text(){var e,t,r;let n="",i=!1,s=[];for(let o of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(o))"text"!==e&&"thought"!==e&&null!==t&&s.push(e);if("string"==typeof o.text){if("boolean"==typeof o.thought&&o.thought)continue;i=!0,n+=o.text}}return s.length>0&&console.warn(`there are non-text parts ${s} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),i?n:void 0}get data(){var e,t,r;let n="",i=[];for(let s of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(s))"inlineData"!==e&&null!==t&&i.push(e);s.inlineData&&"string"==typeof s.inlineData.data&&(n+=atob(s.inlineData.data))}return i.length>0&&console.warn(`there are non-data parts ${i} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}}class tq{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class t${_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r=new t$;return Object.assign(r,tf(e)),r}}function tB(e,t){if(!t||"string"!=typeof t)throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else{if(!(t.indexOf("/")>=0))return`publishers/google/models/${t}`;let e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function tH(e,t){let r=tB(e,t);return r?r.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${r}`:r.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${r}`:r:""}function tV(e){return Array.isArray(e)?e.map(e=>tJ(e)):[tJ(e)]}function tJ(e){if("object"==typeof e&&null!==e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function tW(e){let t=tJ(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function tK(e){let t=tJ(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function tz(e){if(null==e)throw Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function tY(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>tz(e)):[tz(e)]}function tX(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function tQ(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function tZ(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function t0(e){if(null==e)throw Error("ContentUnion is required");return tX(e)?e:{role:"user",parts:tY(e)}}function t1(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=t0(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=t0(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>t0(e)):[t0(t)]}function t2(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("contents are required");if(!Array.isArray(e)){if(tQ(e)||tZ(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[t0(e)]}let t=[],r=[],n=tX(e[0]);for(let i of e){let e=tX(i);if(e!=n)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(e)t.push(i);else if(tQ(i)||tZ(i))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else r.push(i)}return n||t.push({role:"user",parts:tY(r)}),t}function t4(e){let t={},r=["items"],n=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let s=e.anyOf;for(let[o,a]of(null!=s&&2==s.length&&("null"===s[0].type?(t.nullable=!0,e=s[1]):"null"===s[1].type&&(t.nullable=!0,e=s[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);let r=e.filter(e=>"null"!==e);if(1===r.length)t.type=Object.values(eh).includes(r[0].toUpperCase())?r[0].toUpperCase():eh.TYPE_UNSPECIFIED;else for(let e of(t.anyOf=[],r))t.anyOf.push({type:Object.values(eh).includes(e.toUpperCase())?e.toUpperCase():eh.TYPE_UNSPECIFIED})}(e.type,t),Object.entries(e)))if(null!=a)if("type"==o){if("null"===a)throw Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(eh).includes(a.toUpperCase())?a.toUpperCase():eh.TYPE_UNSPECIFIED}else if(r.includes(o))t[o]=t4(a);else if(n.includes(o)){let e=[];for(let r of a){if("null"==r.type){t.nullable=!0;continue}e.push(t4(r))}t[o]=e}else if(i.includes(o)){let e={};for(let[t,r]of Object.entries(a))e[t]=t4(r);t[o]=e}else{if("additionalProperties"===o)continue;t[o]=a}return t}function t6(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function t3(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function t5(e){if(e.functionDeclarations)for(let t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=t4(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=t4(t.response));return e}function t8(e){if(null==e)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let r of e)t.push(r);return t}function t9(e,t){if("string"!=typeof t)throw Error("name must be a string");return function(e,t,r,n=1){let i=!t.startsWith(`${r}/`)&&t.split("/").length===n;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${r}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(i)return`projects/${e.getProject()}/locations/${e.getLocation()}/${r}/${t}`;else return t;return i?`${r}/${t}`:t}(e,t,"cachedContents")}function t7(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function re(e){return null!=e&&"object"==typeof e&&"video"in e}function rt(e){return null!=e&&"object"==typeof e&&"uri"in e}function rr(e){var t;let r;if(null!=e&&"object"==typeof e&&"name"in e&&(r=e.name),!rt(e)||void 0!==(r=e.uri)){if(!re(e)||void 0!==(r=null==(t=e.video)?void 0:t.uri)){if("string"==typeof e&&(r=e),void 0===r)throw Error("Could not extract file name from the provided input.");if(r.startsWith("https://")){let e=r.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw Error(`Could not extract file name from URI ${r}`);r=e[0]}else r.startsWith("files/")&&(r=r.split("files/")[1]);return r}}}function rn(e,t){return e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels"}function ri(e){for(let n of["models","tunedModels","publisherModels"]){var t,r;if(t=e,r=n,null!==t&&"object"==typeof t&&r in t)return e[n]}return[]}function rs(e,t){let r;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))r={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))r={format:"bigquery",bigqueryUri:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))r={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");r={inlinedRequests:t}}else r=t;let n=[r.gcsUri,r.bigqueryUri].filter(Boolean).length,i=[r.inlinedRequests,r.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==n)throw Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(n>0||1!==i)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return r}function ro(e){if("object"!=typeof e||null===e)return{};let t=e.inlinedResponses;if("object"!=typeof t||null===t)return e;let r=t.inlinedResponses;if(!Array.isArray(r)||0===r.length)return e;let n=!1;for(let e of r){if("object"!=typeof e||null===e)continue;let t=e.response;if("object"==typeof t&&null!==t&&void 0!==t.embedding){n=!0;break}}return n&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),e}function ra(e,t){if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw Error(`Invalid batch job name: ${t}.`)}function rl(e){if("BATCH_STATE_UNSPECIFIED"===e)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===e)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===e)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===e)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===e)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===e)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===e)return"JOB_STATE_EXPIRED";else return e}function ru(e){let t={},r=th(e,["name"]);null!=r&&td(t,["name"],r);let n=th(e,["metadata","displayName"]);null!=n&&td(t,["displayName"],n);let i=th(e,["metadata","state"]);null!=i&&td(t,["state"],rl(i));let s=th(e,["metadata","createTime"]);null!=s&&td(t,["createTime"],s);let o=th(e,["metadata","endTime"]);null!=o&&td(t,["endTime"],o);let a=th(e,["metadata","updateTime"]);null!=a&&td(t,["updateTime"],a);let l=th(e,["metadata","model"]);null!=l&&td(t,["model"],l);let u=th(e,["metadata","output"]);return null!=u&&td(t,["dest"],function(e){let t={},r=th(e,["responsesFile"]);null!=r&&td(t,["fileName"],r);let n=th(e,["inlinedResponses","inlinedResponses"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["response"]))&&td(r,["response"],function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["content"]);null!=r&&td(t,["content"],r);let n=th(e,["citationMetadata"]);null!=n&&td(t,["citationMetadata"],function(e){let t={},r=th(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["citations"],e)}return t}(n));let i=th(e,["tokenCount"]);null!=i&&td(t,["tokenCount"],i);let s=th(e,["finishReason"]);null!=s&&td(t,["finishReason"],s);let o=th(e,["avgLogprobs"]);null!=o&&td(t,["avgLogprobs"],o);let a=th(e,["groundingMetadata"]);null!=a&&td(t,["groundingMetadata"],a);let l=th(e,["index"]);null!=l&&td(t,["index"],l);let u=th(e,["logprobsResult"]);null!=u&&td(t,["logprobsResult"],u);let c=th(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["safetyRatings"],e)}let d=th(e,["urlContextMetadata"]);return null!=d&&td(t,["urlContextMetadata"],d),t})(e))),td(t,["candidates"],e)}let i=th(e,["modelVersion"]);null!=i&&td(t,["modelVersion"],i);let s=th(e,["promptFeedback"]);null!=s&&td(t,["promptFeedback"],s);let o=th(e,["responseId"]);null!=o&&td(t,["responseId"],o);let a=th(e,["usageMetadata"]);return null!=a&&td(t,["usageMetadata"],a),t}(n)),null!=(i=th(t,["error"]))&&td(r,["error"],i),r})),td(t,["inlinedResponses"],e)}let i=th(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["inlinedEmbedContentResponses"],e)}return t}(ro(u))),t}function rc(e){var t,r;let n,i,s,o,a,l,u,c,d={},h=th(e,["name"]);null!=h&&td(d,["name"],h);let p=th(e,["displayName"]);null!=p&&td(d,["displayName"],p);let f=th(e,["state"]);null!=f&&td(d,["state"],rl(f));let m=th(e,["error"]);null!=m&&td(d,["error"],m);let g=th(e,["createTime"]);null!=g&&td(d,["createTime"],g);let y=th(e,["startTime"]);null!=y&&td(d,["startTime"],y);let _=th(e,["endTime"]);null!=_&&td(d,["endTime"],_);let E=th(e,["updateTime"]);null!=E&&td(d,["updateTime"],E);let v=th(e,["model"]);null!=v&&td(d,["model"],v);let b=th(e,["inputConfig"]);null!=b&&td(d,["src"],(n={},null!=(i=th(r=b,["instancesFormat"]))&&td(n,["format"],i),null!=(s=th(r,["gcsSource","uris"]))&&td(n,["gcsUri"],s),null!=(o=th(r,["bigquerySource","inputUri"]))&&td(n,["bigqueryUri"],o),n));let w=th(e,["outputConfig"]);null!=w&&td(d,["dest"],(t=ro(w),a={},null!=(l=th(t,["predictionsFormat"]))&&td(a,["format"],l),null!=(u=th(t,["gcsDestination","outputUriPrefix"]))&&td(a,["gcsUri"],u),null!=(c=th(t,["bigqueryDestination","outputUri"]))&&td(a,["bigqueryUri"],c),a));let A=th(e,["completionStats"]);return null!=A&&td(d,["completionStats"],A),d}function rd(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}function rh(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["src"]);null!=i&&td(r,["batch","inputConfig"],function(e,t){let r={};if(void 0!==th(t,["format"]))throw Error("format parameter is not supported in Gemini API.");if(void 0!==th(t,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==th(t,["bigqueryUri"]))throw Error("bigqueryUri parameter is not supported in Gemini API.");let n=th(t,["fileName"]);null!=n&&td(r,["fileName"],n);let i=th(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>(function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["request","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rd(e))),td(r,["request","contents"],e)}let s=th(t,["metadata"]);null!=s&&td(r,["metadata"],s);let o=th(t,["config"]);return null!=o&&td(r,["request","generationConfig"],function(e,t,r){var n;let i,s,o,a={},l=th(t,["systemInstruction"]);void 0!==r&&null!=l&&td(r,["systemInstruction"],rd(t0(l)));let u=th(t,["temperature"]);null!=u&&td(a,["temperature"],u);let c=th(t,["topP"]);null!=c&&td(a,["topP"],c);let d=th(t,["topK"]);null!=d&&td(a,["topK"],d);let h=th(t,["candidateCount"]);null!=h&&td(a,["candidateCount"],h);let p=th(t,["maxOutputTokens"]);null!=p&&td(a,["maxOutputTokens"],p);let f=th(t,["stopSequences"]);null!=f&&td(a,["stopSequences"],f);let m=th(t,["responseLogprobs"]);null!=m&&td(a,["responseLogprobs"],m);let g=th(t,["logprobs"]);null!=g&&td(a,["logprobs"],g);let y=th(t,["presencePenalty"]);null!=y&&td(a,["presencePenalty"],y);let _=th(t,["frequencyPenalty"]);null!=_&&td(a,["frequencyPenalty"],_);let E=th(t,["seed"]);null!=E&&td(a,["seed"],E);let v=th(t,["responseMimeType"]);null!=v&&td(a,["responseMimeType"],v);let b=th(t,["responseSchema"]);null!=b&&td(a,["responseSchema"],t4(b));let w=th(t,["responseJsonSchema"]);if(null!=w&&td(a,["responseJsonSchema"],w),void 0!==th(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==th(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let A=th(t,["safetySettings"]);if(void 0!==r&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["category"]);if(null!=r&&td(t,["category"],r),void 0!==th(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=th(e,["threshold"]);return null!=n&&td(t,["threshold"],n),t})(e))),td(r,["safetySettings"],e)}let S=th(t,["tools"]);if(void 0!==r&&null!=S){let e=t8(S);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t5(e)))),td(r,["tools"],e)}let T=th(t,["toolConfig"]);if(void 0!==r&&null!=T&&td(r,["toolConfig"],(i={},null!=(s=th(n=T,["functionCallingConfig"]))&&td(i,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),null!=(o=th(n,["retrievalConfig"]))&&td(i,["retrievalConfig"],o),i)),void 0!==th(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=th(t,["cachedContent"]);void 0!==r&&null!=O&&td(r,["cachedContent"],t9(e,O));let I=th(t,["responseModalities"]);null!=I&&td(a,["responseModalities"],I);let C=th(t,["mediaResolution"]);null!=C&&td(a,["mediaResolution"],C);let R=th(t,["speechConfig"]);if(null!=R&&td(a,["speechConfig"],t6(R)),void 0!==th(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let x=th(t,["thinkingConfig"]);null!=x&&td(a,["thinkingConfig"],x);let k=th(t,["imageConfig"]);null!=k&&td(a,["imageConfig"],function(e){let t={},r=th(e,["aspectRatio"]);null!=r&&td(t,["aspectRatio"],r);let n=th(e,["imageSize"]);if(null!=n&&td(t,["imageSize"],n),void 0!==th(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}(k));let N=th(t,["enableEnhancedCivicAnswers"]);return null!=N&&td(a,["enableEnhancedCivicAnswers"],N),a}(e,o,th(r,["request"],{}))),r})(e,t))),td(r,["requests","requests"],t)}return r}(e,rs(e,i)));let s=th(t,["config"]);return null!=s&&function(e,t){let r=th(e,["displayName"]);if(void 0!==t&&null!=r&&td(t,["batch","displayName"],r),void 0!==th(e,["dest"]))throw Error("dest parameter is not supported in Gemini API.")}(s,r),r}(el=tt||(tt={})).PAGED_ITEM_BATCH_JOBS="batchJobs",el.PAGED_ITEM_MODELS="models",el.PAGED_ITEM_TUNING_JOBS="tuningJobs",el.PAGED_ITEM_FILES="files",el.PAGED_ITEM_CACHED_CONTENTS="cachedContents",el.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",el.PAGED_ITEM_DOCUMENTS="documents";class rp{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let s={config:{}};(s=r&&0!==Object.keys(r).length?"object"==typeof r?Object.assign({},r):r:{config:{}}).config&&(s.config.pageToken=t.nextPageToken),this.paramsInternal=s,this.pageInternalSize=null!=(i=null==(n=s.config)?void 0:n.pageSize)?i:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(!this.hasNextPage())return{value:void 0,done:!0};else await this.nextPage();let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return(null==(e=this.params.config)?void 0:e.pageToken)!==void 0}}class rf extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=rh(this.apiClient,e),r=tc("{model}:batchGenerateContent",t._url),n=t.batch.inputConfig.requests,i=n.requests,s=[];for(let e of i){let t=Object.assign({},e);if(t.systemInstruction){let e=t.systemInstruction;delete t.systemInstruction;let r=t.request;r.systemInstruction=e,t.request=r}s.push(t)}return n.requests=s,delete t.config,delete t._url,delete t._query,{path:r,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){let r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),void 0===r.dest){let t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?r.dest=`${t.slice(0,-6)}/dest`:r.dest=`${t}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let n,i,l,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["model"],tB(s,i)),null!=(l=th(e,["src"]))&&td(n,["inputConfig"],function(e){let t={},r=th(e,["format"]);null!=r&&td(t,["instancesFormat"],r);let n=th(e,["gcsUri"]);null!=n&&td(t,["gcsSource","uris"],n);let i=th(e,["bigqueryUri"]);if(null!=i&&td(t,["bigquerySource","inputUri"],i),void 0!==th(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedRequests"]))throw Error("inlinedRequests parameter is not supported in Vertex AI.");return t}(rs(s,l))),null!=(u=th(e,["config"]))&&(c=th(u,["displayName"]),void 0!==n&&null!=c&&td(n,["displayName"],c),d=th(u,["dest"]),void 0!==n&&null!=d&&td(n,["outputConfig"],function(e){let t={},r=th(e,["format"]);null!=r&&td(t,["predictionsFormat"],r);let n=th(e,["gcsUri"]);null!=n&&td(t,["gcsDestination","outputUriPrefix"],n);let i=th(e,["bigqueryUri"]);if(null!=i&&td(t,["bigqueryDestination","outputUri"],i),void 0!==th(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedResponses"]))throw Error("inlinedResponses parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return t}(function(e){if("string"!=typeof e)return e;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw Error(`Unsupported destination: ${e}`)}(d)))),n);return o=tc("batchPredictionJobs",h._url),a=h._query,delete h._url,delete h._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rc(e))}{let t=rh(this.apiClient,e);return o=tc("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async createEmbeddingsInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g=(n=this.apiClient,d={},null!=(h=th(e,["model"]))&&td(d,["_url","model"],tB(n,h)),null!=(p=th(e,["src"]))&&td(d,["batch","inputConfig"],(i=n,l={},null!=(u=th(s=p,["fileName"]))&&td(l,["file_name"],u),null!=(c=th(s,["inlinedRequests"]))&&td(l,["requests"],function(e,t){let r={},n=th(t,["contents"]);if(null!=n){let t=t1(e,n);Array.isArray(t)&&(t=t.map(e=>e)),td(r,["requests[]","request","content"],t)}let i=th(t,["config"]);return null!=i&&(td(r,["_self"],function(e,t){let r=th(e,["taskType"]);void 0!==t&&null!=r&&td(t,["requests[]","taskType"],r);let n=th(e,["title"]);void 0!==t&&null!=n&&td(t,["requests[]","title"],n);let i=th(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&td(t,["requests[]","outputDimensionality"],i),void 0!==th(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.");return{}}(i,r)),!function(e,t){for(let[r,n]of Object.entries(t)){let t=r.split("."),i=n.split("."),s=new Set,o=-1;for(let e=0;e<t.length;e++)if("*"===t[e]){o=e;break}if(-1!==o&&i.length>o)for(let e=o;e<i.length;e++){let t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||s.add(t)}!function e(t,r,n,i,s){if(i>=r.length||"object"!=typeof t||null===t)return;let o=r[i];if(o.endsWith("[]")){let a=o.slice(0,-2);if(a in t&&Array.isArray(t[a]))for(let o of t[a])e(o,r,n,i+1,s)}else if("*"===o){if("object"==typeof t&&null!==t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith("_")&&!s.has(e)),r={};for(let n of e)r[n]=t[n];for(let[e,s]of Object.entries(r)){let r=[];for(let t of n.slice(i))"*"===t?r.push(e):r.push(t);td(t,r,s)}for(let r of e)delete t[r]}}else o in t&&e(t[o],r,n,i+1,s)}(e,t,i,0,s)}}(r,{"requests[].*":"requests[].request.*"})),r}(i,c)),l)),null!=(f=th(e,["config"]))&&(m=th(f,["displayName"]),void 0!==d&&null!=m&&td(d,["batch","displayName"],m)),d);return o=tc("{model}:asyncBatchEmbedContent",g._url),a=g._query,delete g._url,delete g._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);return a=tc("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rc(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);return a=tc("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async cancel(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);a=tc("batchPredictionJobs/{name}:cancel",o._url),l=o._query,delete o._url,delete o._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}else{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);a=tc("batches/{name}:cancel",s._url),l=s._query,delete s._url,delete s._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal})}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l),u=th(i,["filter"]),void 0!==n&&null!=u&&td(n,["_query","filter"],u)),n);return s=tc("batchPredictionJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rc(e))),td(t,["batchJobs"],e)}return t}(e),r=new tF;return Object.assign(r,t),r})}{let t,r,a=(t={},null!=(r=th(e,["config"]))&&function(e,t){let r=th(e,["pageSize"]);void 0!==t&&null!=r&&td(t,["_query","pageSize"],r);let n=th(e,["pageToken"]);if(void 0!==t&&null!=n&&td(t,["_query","pageToken"],n),void 0!==th(e,["filter"]))throw Error("filter parameter is not supported in Gemini API.")}(r,t),t);return s=tc("batches",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ru(e))),td(t,["batchJobs"],e)}return t}(e),r=new tF;return Object.assign(r,t),r})}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);return a=tc("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),t})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);return a=tc("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),t})}}}function rm(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}class rg extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["model"],tH(s,i)),null!=(o=th(e,["config"]))&&function(e,t){let r=th(e,["ttl"]);void 0!==t&&null!=r&&td(t,["ttl"],r);let n=th(e,["expireTime"]);void 0!==t&&null!=n&&td(t,["expireTime"],n);let i=th(e,["displayName"]);void 0!==t&&null!=i&&td(t,["displayName"],i);let s=th(e,["contents"]);if(void 0!==t&&null!=s){let e=t2(s);Array.isArray(e)&&(e=e.map(e=>e)),td(t,["contents"],e)}let o=th(e,["systemInstruction"]);void 0!==t&&null!=o&&td(t,["systemInstruction"],t0(o));let a=th(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t})(e))),td(t,["tools"],e)}let l=th(e,["toolConfig"]);void 0!==t&&null!=l&&td(t,["toolConfig"],l);let u=th(e,["kmsKeyName"]);void 0!==t&&null!=u&&td(t,["encryption_spec","kmsKeyName"],u)}(o,n),n);return a=tc("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["model"],tH(o,r)),null!=(s=th(e,["config"]))&&function(e,t){var r;let n,i,s,o=th(e,["ttl"]);void 0!==t&&null!=o&&td(t,["ttl"],o);let a=th(e,["expireTime"]);void 0!==t&&null!=a&&td(t,["expireTime"],a);let l=th(e,["displayName"]);void 0!==t&&null!=l&&td(t,["displayName"],l);let u=th(e,["contents"]);if(void 0!==t&&null!=u){let e=t2(u);Array.isArray(e)&&(e=e.map(e=>rm(e))),td(t,["contents"],e)}let c=th(e,["systemInstruction"]);void 0!==t&&null!=c&&td(t,["systemInstruction"],rm(t0(c)));let d=th(e,["tools"]);if(void 0!==t&&null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(e))),td(t,["tools"],e)}let h=th(e,["toolConfig"]);if(void 0!==t&&null!=h&&td(t,["toolConfig"],(n={},null!=(i=th(r=h,["functionCallingConfig"]))&&td(n,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(i)),null!=(s=th(r,["retrievalConfig"]))&&td(n,["retrievalConfig"],s),n)),void 0!==th(e,["kmsKeyName"]))throw Error("kmsKeyName parameter is not supported in Gemini API.")}(s,t),t);return a=tc("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tx;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tx;return Object.assign(i,n),i})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),null!=(o=th(e,["config"]))&&(u=th(o,["ttl"]),void 0!==n&&null!=u&&td(n,["ttl"],u),c=th(o,["expireTime"]),void 0!==n&&null!=c&&td(n,["expireTime"],c)),n);return a=tc("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u,c,d=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),null!=(s=th(e,["config"]))&&(u=th(s,["ttl"]),void 0!==t&&null!=u&&td(t,["ttl"],u),c=th(s,["expireTime"]),void 0!==t&&null!=c&&td(t,["expireTime"],c)),t);return a=tc("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l)),n);return s=tc("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cachedContents"],e)}return t}(e),r=new tk;return Object.assign(r,t),r})}{let t,r,a,l,u=(t={},null!=(r=th(e,["config"]))&&(a=th(r,["pageSize"]),void 0!==t&&null!=a&&td(t,["_query","pageSize"],a),l=th(r,["pageToken"]),void 0!==t&&null!=l&&td(t,["_query","pageToken"],l)),t);return s=tc("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cachedContents"],e)}return t}(e),r=new tk;return Object.assign(r,t),r})}}}function ry(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)0>t.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function r_(e){return this instanceof r_?(this.v=e,this):new r_(e)}function rE(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){i[e]&&(n[e]=function(t){return new Promise(function(r,n){s.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var r;(r=i[e](t)).value instanceof r_?Promise.resolve(r.value.v).then(l,u):c(s[0][2],r)}catch(e){c(s[0][3],e)}}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function rv(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){var s,o,a;s=n,o=i,a=(t=e[r](t)).done,Promise.resolve(t.value).then(function(e){s({value:e,done:a})},o)})}}}function rb(e){if(void 0===e.parts||0===e.parts.length)return!1;for(let t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function rw(e){if(void 0===e||0===e.length)return[];let t=[],r=e.length,n=0;for(;n<r;)if("user"===e[n].role)t.push(e[n]),n++;else{let i=[],s=!0;for(;n<r&&"model"===e[n].role;)i.push(e[n]),s&&!rb(e[n])&&(s=!1),n++;s?t.push(...i):t.pop()}return t}"function"==typeof SuppressedError&&SuppressedError;class rA{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new rS(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class rS{constructor(e,t,r,n={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=r,this.config=n,this.history=i,this.sendPromise=Promise.resolve();if(0!==i.length){for(let e of i)if("user"!==e.role&&"model"!==e.role)throw Error(`Role must be user or model, but got ${e.role}.`)}}async sendMessage(e){var t;await this.sendPromise;let r=t0(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});return this.sendPromise=(async()=>{var e,t,i;let s=await n,o=null==(t=null==(e=s.candidates)?void 0:e[0])?void 0:t.content,a=s.automaticFunctionCallingHistory,l=this.getHistory(!0).length,u=[];null!=a&&(u=null!=(i=a.slice(l))?i:[]),this.recordHistory(r,o?[o]:[],u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;let r=t0(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});this.sendPromise=n.then(()=>void 0).catch(()=>void 0);let i=await n;return this.processStreamResponse(i,r)}getHistory(e=!1){return structuredClone(e?rw(this.history):this.history)}processStreamResponse(e,t){return rE(this,arguments,function*(){let r=[];try{for(var n,i,s,o,a,l,u,c=!0,d=rv(e);!(n=(u=yield r_(d.next())).done);c=!0){if(o=u.value,c=!1,function(e){var t;if(void 0==e.candidates||0===e.candidates.length)return!1;let r=null==(t=e.candidates[0])?void 0:t.content;return void 0!==r&&rb(r)}(o)){let e=null==(l=null==(a=o.candidates)?void 0:a[0])?void 0:l.content;void 0!==e&&r.push(e)}yield yield r_(o)}}catch(e){i={error:e}}finally{try{!c&&!n&&(s=d.return)&&(yield r_(s.call(d)))}finally{if(i)throw i.error}}this.recordHistory(t,r)})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(e=>void 0!==e.role)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...rw(r)):this.history.push(e),this.history.push(...n)}}class rT extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,rT.prototype)}}class rO extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["pageSize"]),void 0!==s&&null!=a&&td(s,["_query","pageSize"],a),l=th(o,["pageToken"]),void 0!==s&&null!=l&&td(s,["_query","pageToken"],l)),s);return n=tc("files",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["files"],e)}return t}(e),r=new tM;return Object.assign(r,t),r})}}async createInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["file"]))&&td(s,["file"],o),s);return n=tc("upload/v1beta/files",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tj;return Object.assign(i,n),i})}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","file"],rr(o)),s);return n=tc("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","file"],rr(o)),s);return n=tc("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tL;return Object.assign(i,n),i})}}}function rI(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}function rC(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}function rR(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rC(e))),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&td(r,["generationConfig"],function(e,t,r){var n;let i,s,o,a={},l=th(t,["systemInstruction"]);void 0!==r&&null!=l&&td(r,["systemInstruction"],rC(t0(l)));let u=th(t,["temperature"]);null!=u&&td(a,["temperature"],u);let c=th(t,["topP"]);null!=c&&td(a,["topP"],c);let d=th(t,["topK"]);null!=d&&td(a,["topK"],d);let h=th(t,["candidateCount"]);null!=h&&td(a,["candidateCount"],h);let p=th(t,["maxOutputTokens"]);null!=p&&td(a,["maxOutputTokens"],p);let f=th(t,["stopSequences"]);null!=f&&td(a,["stopSequences"],f);let m=th(t,["responseLogprobs"]);null!=m&&td(a,["responseLogprobs"],m);let g=th(t,["logprobs"]);null!=g&&td(a,["logprobs"],g);let y=th(t,["presencePenalty"]);null!=y&&td(a,["presencePenalty"],y);let _=th(t,["frequencyPenalty"]);null!=_&&td(a,["frequencyPenalty"],_);let E=th(t,["seed"]);null!=E&&td(a,["seed"],E);let v=th(t,["responseMimeType"]);null!=v&&td(a,["responseMimeType"],v);let b=th(t,["responseSchema"]);null!=b&&td(a,["responseSchema"],t4(b));let w=th(t,["responseJsonSchema"]);if(null!=w&&td(a,["responseJsonSchema"],w),void 0!==th(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==th(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let A=th(t,["safetySettings"]);if(void 0!==r&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["category"]);if(null!=r&&td(t,["category"],r),void 0!==th(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=th(e,["threshold"]);return null!=n&&td(t,["threshold"],n),t})(e))),td(r,["safetySettings"],e)}let S=th(t,["tools"]);if(void 0!==r&&null!=S){let e=t8(S);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t5(e)))),td(r,["tools"],e)}let T=th(t,["toolConfig"]);if(void 0!==r&&null!=T&&td(r,["toolConfig"],(i={},null!=(s=th(n=T,["functionCallingConfig"]))&&td(i,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),null!=(o=th(n,["retrievalConfig"]))&&td(i,["retrievalConfig"],o),i)),void 0!==th(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=th(t,["cachedContent"]);void 0!==r&&null!=O&&td(r,["cachedContent"],t9(e,O));let I=th(t,["responseModalities"]);null!=I&&td(a,["responseModalities"],I);let C=th(t,["mediaResolution"]);null!=C&&td(a,["mediaResolution"],C);let R=th(t,["speechConfig"]);if(null!=R&&td(a,["speechConfig"],t6(R)),void 0!==th(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let x=th(t,["thinkingConfig"]);null!=x&&td(a,["thinkingConfig"],x);let k=th(t,["imageConfig"]);null!=k&&td(a,["imageConfig"],function(e){let t={},r=th(e,["aspectRatio"]);null!=r&&td(t,["aspectRatio"],r);let n=th(e,["imageSize"]);if(null!=n&&td(t,["imageSize"],n),void 0!==th(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}(k));let N=th(t,["enableEnhancedCivicAnswers"]);return null!=N&&td(a,["enableEnhancedCivicAnswers"],N),a}(e,s,r)),r}function rx(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&td(r,["generationConfig"],function(e,t,r){var n;let i,s,o,a,l,u={},c=th(t,["systemInstruction"]);void 0!==r&&null!=c&&td(r,["systemInstruction"],t0(c));let d=th(t,["temperature"]);null!=d&&td(u,["temperature"],d);let h=th(t,["topP"]);null!=h&&td(u,["topP"],h);let p=th(t,["topK"]);null!=p&&td(u,["topK"],p);let f=th(t,["candidateCount"]);null!=f&&td(u,["candidateCount"],f);let m=th(t,["maxOutputTokens"]);null!=m&&td(u,["maxOutputTokens"],m);let g=th(t,["stopSequences"]);null!=g&&td(u,["stopSequences"],g);let y=th(t,["responseLogprobs"]);null!=y&&td(u,["responseLogprobs"],y);let _=th(t,["logprobs"]);null!=_&&td(u,["logprobs"],_);let E=th(t,["presencePenalty"]);null!=E&&td(u,["presencePenalty"],E);let v=th(t,["frequencyPenalty"]);null!=v&&td(u,["frequencyPenalty"],v);let b=th(t,["seed"]);null!=b&&td(u,["seed"],b);let w=th(t,["responseMimeType"]);null!=w&&td(u,["responseMimeType"],w);let A=th(t,["responseSchema"]);null!=A&&td(u,["responseSchema"],t4(A));let S=th(t,["responseJsonSchema"]);null!=S&&td(u,["responseJsonSchema"],S);let T=th(t,["routingConfig"]);null!=T&&td(u,["routingConfig"],T);let O=th(t,["modelSelectionConfig"]);null!=O&&td(u,["modelConfig"],O);let I=th(t,["safetySettings"]);if(void 0!==r&&null!=I){let e=I;Array.isArray(e)&&(e=e.map(e=>e)),td(r,["safetySettings"],e)}let C=th(t,["tools"]);if(void 0!==r&&null!=C){let e=t8(C);Array.isArray(e)&&(e=e.map(e=>rq(t5(e)))),td(r,["tools"],e)}let R=th(t,["toolConfig"]);void 0!==r&&null!=R&&td(r,["toolConfig"],R);let x=th(t,["labels"]);void 0!==r&&null!=x&&td(r,["labels"],x);let k=th(t,["cachedContent"]);void 0!==r&&null!=k&&td(r,["cachedContent"],t9(e,k));let N=th(t,["responseModalities"]);null!=N&&td(u,["responseModalities"],N);let P=th(t,["mediaResolution"]);null!=P&&td(u,["mediaResolution"],P);let U=th(t,["speechConfig"]);null!=U&&td(u,["speechConfig"],t6(U));let D=th(t,["audioTimestamp"]);null!=D&&td(u,["audioTimestamp"],D);let M=th(t,["thinkingConfig"]);null!=M&&td(u,["thinkingConfig"],M);let j=th(t,["imageConfig"]);if(null!=j&&td(u,["imageConfig"],(i={},null!=(s=th(n=j,["aspectRatio"]))&&td(i,["aspectRatio"],s),null!=(o=th(n,["imageSize"]))&&td(i,["imageSize"],o),null!=(a=th(n,["outputMimeType"]))&&td(i,["imageOutputOptions","mimeType"],a),null!=(l=th(n,["outputCompressionQuality"]))&&td(i,["imageOutputOptions","compressionQuality"],l),i)),void 0!==th(t,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return u}(e,s,r)),r}function rk(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["content"]);null!=r&&td(t,["content"],r);let n=th(e,["citationMetadata"]);null!=n&&td(t,["citationMetadata"],function(e){let t={},r=th(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["citations"],e)}return t}(n));let i=th(e,["tokenCount"]);null!=i&&td(t,["tokenCount"],i);let s=th(e,["finishReason"]);null!=s&&td(t,["finishReason"],s);let o=th(e,["avgLogprobs"]);null!=o&&td(t,["avgLogprobs"],o);let a=th(e,["groundingMetadata"]);null!=a&&td(t,["groundingMetadata"],a);let l=th(e,["index"]);null!=l&&td(t,["index"],l);let u=th(e,["logprobsResult"]);null!=u&&td(t,["logprobsResult"],u);let c=th(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["safetyRatings"],e)}let d=th(e,["urlContextMetadata"]);return null!=d&&td(t,["urlContextMetadata"],d),t})(e))),td(t,["candidates"],e)}let i=th(e,["modelVersion"]);null!=i&&td(t,["modelVersion"],i);let s=th(e,["promptFeedback"]);null!=s&&td(t,["promptFeedback"],s);let o=th(e,["responseId"]);null!=o&&td(t,["responseId"],o);let a=th(e,["usageMetadata"]);return null!=a&&td(t,["usageMetadata"],a),t}function rN(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["candidates"],e)}let i=th(e,["createTime"]);null!=i&&td(t,["createTime"],i);let s=th(e,["modelVersion"]);null!=s&&td(t,["modelVersion"],s);let o=th(e,["promptFeedback"]);null!=o&&td(t,["promptFeedback"],o);let a=th(e,["responseId"]);null!=a&&td(t,["responseId"],a);let l=th(e,["usageMetadata"]);return null!=l&&td(t,["usageMetadata"],l),t}function rP(e){let t={},r=th(e,["_self"]);null!=r&&td(t,["image"],rU(r));let n=th(e,["raiFilteredReason"]);null!=n&&td(t,["raiFilteredReason"],n);let i=th(e,["_self"]);null!=i&&td(t,["safetyAttributes"],rG(i));let s=th(e,["prompt"]);return null!=s&&td(t,["enhancedPrompt"],s),t}function rU(e){let t={},r=th(e,["gcsUri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["bytesBase64Encoded"]);null!=n&&td(t,["imageBytes"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rD(e){let t={};if(void 0!==th(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");let r=th(e,["imageBytes"]);null!=r&&td(t,["bytesBase64Encoded"],tp(r));let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}function rM(e){let t={},r=th(e,["gcsUri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["imageBytes"]);null!=n&&td(t,["bytesBase64Encoded"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rj(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["displayName"]);null!=l&&td(o,["displayName"],l);let u=th(e,["description"]);null!=u&&td(o,["description"],u);let c=th(e,["version"]);null!=c&&td(o,["version"],c);let d=th(e,["_self"]);null!=d&&td(o,["tunedModelInfo"],(r={},null!=(n=th(t=d,["baseModel"]))&&td(r,["baseModel"],n),null!=(i=th(t,["createTime"]))&&td(r,["createTime"],i),null!=(s=th(t,["updateTime"]))&&td(r,["updateTime"],s),r));let h=th(e,["inputTokenLimit"]);null!=h&&td(o,["inputTokenLimit"],h);let p=th(e,["outputTokenLimit"]);null!=p&&td(o,["outputTokenLimit"],p);let f=th(e,["supportedGenerationMethods"]);null!=f&&td(o,["supportedActions"],f);let m=th(e,["temperature"]);null!=m&&td(o,["temperature"],m);let g=th(e,["maxTemperature"]);null!=g&&td(o,["maxTemperature"],g);let y=th(e,["topP"]);null!=y&&td(o,["topP"],y);let _=th(e,["topK"]);null!=_&&td(o,["topK"],_);let E=th(e,["thinking"]);return null!=E&&td(o,["thinking"],E),o}function rL(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["displayName"]);null!=l&&td(o,["displayName"],l);let u=th(e,["description"]);null!=u&&td(o,["description"],u);let c=th(e,["versionId"]);null!=c&&td(o,["version"],c);let d=th(e,["deployedModels"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>{let t,r,n;return t={},null!=(r=th(e,["endpoint"]))&&td(t,["name"],r),null!=(n=th(e,["deployedModelId"]))&&td(t,["deployedModelId"],n),t})),td(o,["endpoints"],e)}let h=th(e,["labels"]);null!=h&&td(o,["labels"],h);let p=th(e,["_self"]);null!=p&&td(o,["tunedModelInfo"],(r={},null!=(n=th(t=p,["labels","google-vertex-llm-tuning-base-model-id"]))&&td(r,["baseModel"],n),null!=(i=th(t,["createTime"]))&&td(r,["createTime"],i),null!=(s=th(t,["updateTime"]))&&td(r,["updateTime"],s),r));let f=th(e,["defaultCheckpointId"]);null!=f&&td(o,["defaultCheckpointId"],f);let m=th(e,["checkpoints"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),td(o,["checkpoints"],e)}return o}function rF(e){let t={},r=th(e,["safetyAttributes","categories"]);null!=r&&td(t,["categories"],r);let n=th(e,["safetyAttributes","scores"]);null!=n&&td(t,["scores"],n);let i=th(e,["contentType"]);return null!=i&&td(t,["contentType"],i),t}function rG(e){let t={},r=th(e,["safetyAttributes","categories"]);null!=r&&td(t,["categories"],r);let n=th(e,["safetyAttributes","scores"]);null!=n&&td(t,["scores"],n);let i=th(e,["contentType"]);return null!=i&&td(t,["contentType"],i),t}function rq(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t}function r$(e){let t={},r=th(e,["uri"]);null!=r&&td(t,["uri"],r);let n=th(e,["videoBytes"]);null!=n&&td(t,["encodedVideo"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["encoding"],i),t}function rB(e){let t={},r=th(e,["uri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["videoBytes"]);null!=n&&td(t,["bytesBase64Encoded"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rH(e,t){let r=th(e,["mimeType"]);void 0!==t&&null!=r&&td(t,["mimeType"],r);let n=th(e,["displayName"]);void 0!==t&&null!=n&&td(t,["displayName"],n);let i=th(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["customMetadata"],e)}let s=th(e,["chunkingConfig"]);return void 0!==t&&null!=s&&td(t,["chunkingConfig"],s),{}}let rV="x-goog-api-client";class rJ{constructor(e){var t,r;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});let n={};this.clientOptions.vertexai?(n.apiVersion=null!=(t=this.clientOptions.apiVersion)?t:"v1beta1",n.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(n.apiVersion=null!=(r=this.clientOptions.apiVersion)?r:"v1beta",n.baseUrl="https://generativelanguage.googleapis.com/"),n.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=n,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(n,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&"global"!==this.clientOptions.location?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return null!=(e=this.clientOptions.vertexai)&&e}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw Error("HTTP options are not correctly set.");let t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=new URL(this.getBaseUrl());return e.protocol="http:"==e.protocol?"ws":"wss",e.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,r){let n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),""!==e&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(let[t,r]of Object.entries(e.queryParams))n.searchParams.append(t,String(r));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.unaryApiCall(n,i,e.httpMethod)}patchHttpOptions(e,t){let r=JSON.parse(JSON.stringify(e));for(let[e,n]of Object.entries(t))"object"==typeof n?r[e]=Object.assign(Object.assign({},r[e]),n):void 0!==n&&(r[e]=n);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e),n=this.constructUrl(e.path,t,r);n.searchParams.has("alt")&&"sse"===n.searchParams.get("alt")||n.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.streamApiCall(n,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,r,n){if(t&&t.timeout||n){let r=new AbortController,i=r.signal;if(t.timeout&&(null==t?void 0:t.timeout)>0){let e=setTimeout(()=>r.abort(),t.timeout);e&&"function"==typeof e.unref&&e.unref()}n&&n.addEventListener("abort",()=>{r.abort()}),e.signal=i}return t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let r={};if("string"==typeof e.body&&e.body.length>0)try{let t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");r=t}catch(e){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}e.body=JSON.stringify(function e(t,r){let n=Object.assign({},t);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)){let i=r[t],s=n[t];i&&"object"==typeof i&&!Array.isArray(i)&&s&&"object"==typeof s&&!Array.isArray(s)?n[t]=e(s,i):(s&&i&&typeof s!=typeof i&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${t}". Original type: ${typeof s}, New type: ${typeof i}. Overwriting.`),n[t]=i)}return n}(r,t))}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await rW(e),new tm(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}async streamApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await rW(e),this.processStreamResponse(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}processStreamResponse(e){return rE(this,arguments,function*(){var t;let r=null==(t=null==e?void 0:e.body)?void 0:t.getReader(),n=new TextDecoder("utf-8");if(!r)throw Error("Response body is empty");try{let t="",i="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:o,value:a}=yield r_(r.read());if(o){if(t.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let l=n.decode(a,{stream:!0});try{let e=JSON.parse(l);if("error"in e){let t=JSON.parse(JSON.stringify(e.error)),r=t.status,n=t.code,i=`got status: ${r}. ${JSON.stringify(e)}`;if(n>=400&&n<600)throw new rT({message:i,status:n})}}catch(e){if("ApiError"===e.name)throw e}t+=l;let u=-1,c=0;for(;;){for(let e of(u=-1,c=0,s)){let r=t.indexOf(e);-1!==r&&(-1===u||r<u)&&(u=r,c=e.length)}if(-1===u)break;let r=t.substring(0,u);t=t.substring(u+c);let n=r.trim();if(n.startsWith(i)){let t=n.substring(i.length).trim();try{let r=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield r_(new tm(r))}catch(e){throw Error(`exception parsing stream chunk ${t}. ${e}`)}}}}}finally{r.releaseLock()}})}async apiCall(e,t){return fetch(e,t).catch(e=>{throw Error(`exception ${e} sending request`)})}getDefaultHeaders(){let e={},t="google-genai-sdk/1.34.0 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[rV]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){let r=new Headers;if(e&&e.headers){for(let[t,n]of Object.entries(e.headers))r.append(t,n);e.timeout&&e.timeout>0&&r.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(r,t),r}getFileName(e){var t;let r="";return"string"==typeof e&&(r=null!=(t=(r=e.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?t:""),r}async uploadFile(e,t){var r;let n={};null!=t&&(n.mimeType=t.mimeType,n.name=t.name,n.displayName=t.displayName),n.name&&!n.name.startsWith("files/")&&(n.name=`files/${n.name}`);let i=this.clientOptions.uploader,s=await i.stat(e);n.sizeBytes=String(s.size);let o=null!=(r=null==t?void 0:t.mimeType)?r:s.type;if(void 0===o||""===o)throw Error("Can not determine mimeType. Please provide mimeType in the config.");n.mimeType=o;let a={file:n},l=this.getFileName(e),u=tc("upload/v1beta/files",a._url),c=await this.fetchUploadUrl(u,n.sizeBytes,n.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,c,this)}async uploadFileToFileSearchStore(e,t,r){var n;let i=this.clientOptions.uploader,s=await i.stat(t),o=String(s.size),a=null!=(n=null==r?void 0:r.mimeType)?n:s.type;if(void 0===a||""===a)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=r&&rH(r,c);let d=await this.fetchUploadUrl(l,o,a,u,c,null==r?void 0:r.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){let t=this.clientOptions.downloader;await t.download(e,this)}async fetchUploadUrl(e,t,r,n,i,s){var o;let a={};a=s||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${r}`},n?{"X-Goog-Upload-File-Name":n}:{})};let l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=null==(o=null==l?void 0:l.headers)?void 0:o["x-goog-upload-url"];if(void 0===u)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}}async function rW(e){var t;if(void 0===e)throw Error("response is undefined");if(!e.ok){let r=e.status,n=JSON.stringify((null==(t=e.headers.get("content-type"))?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}});if(r>=400&&r<600)throw new rT({message:n,status:r});throw Error(n)}}function rK(e){for(let r of e){var t;if(null!==(t=r)&&"object"==typeof t&&t instanceof rY||"object"==typeof r&&"inputSchema"in r)return!0}return!1}function rz(e){var t;let r=null!=(t=e[rV])?t:"";e[rV]=(r+" mcp_used/unknown").trimStart()}class rY{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new rY(e,t)}async initialize(){var e,t,r,n;if(this.mcpTools.length>0)return;let i={},s=[];for(let u of this.mcpClients)try{for(var o,a=!0,l=(t=void 0,rv(function(e){return rE(this,arguments,function*(e,t=100){let r,n=0;for(;n<t;){let t=yield r_(e.listTools({cursor:r}));for(let e of t.tools)yield yield r_(e),n++;if(!t.nextCursor)break;r=t.nextCursor}})}(u)));!(e=(o=await l.next()).done);a=!0){n=o.value,a=!1,s.push(n);let e=n.name;if(i[e])throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);i[e]=u}}catch(e){t={error:e}}finally{try{!a&&!e&&(r=l.return)&&await r.call(l)}finally{if(t)throw t.error}}this.mcpTools=s,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){let r=[],n=new Set;for(let i of e){let e=i.name;if(n.has(e))throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);n.add(e);let s=function(e,t={}){let r={name:e.name,description:e.description,parametersJsonSchema:e.inputSchema};return e.outputSchema&&(r.responseJsonSchema=e.outputSchema),t.behavior&&(r.behavior=t.behavior),{functionDeclarations:[r]}}(i,t);s.functionDeclarations&&r.push(...s.functionDeclarations)}return{functionDeclarations:r}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let r of e)if(r.name in this.functionNameToMcpClient){let e,n=this.functionNameToMcpClient[r.name];this.config.timeout&&(e={timeout:this.config.timeout});let i=await n.callTool({name:r.name,arguments:r.args},void 0,e);t.push({functionResponse:{name:r.name,response:i.isError?{error:i}:i}})}return t}}async function rX(e,t,r){let n=new tq;Object.assign(n,r.data instanceof Blob?JSON.parse(await r.data.text()):JSON.parse(r.data)),t(n)}class rQ{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r}async connect(e){var t,r;let n;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),o=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),l=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`,u=()=>{},c=new Promise(e=>{u=e}),d=e.callbacks,h=this.apiClient,p={onopen:function(){u({})},onmessage:e=>{rX(h,d.onmessage,e)},onerror:null!=(t=null==d?void 0:d.onerror)?t:function(e){},onclose:null!=(r=null==d?void 0:d.onclose)?r:function(e){}},f=this.webSocketFactory.create(l,(n={},o.forEach((e,t)=>{n[t]=e}),n),p);f.connect(),await c;let m=tB(this.apiClient,e.model);return f.send(JSON.stringify({setup:{model:m}})),new rZ(f,this.apiClient)}}class rZ{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let t=function(e){let t={},r=th(e,["weightedPrompts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){let t,r;e.musicGenerationConfig||(e.musicGenerationConfig={});let n=(t={},null!=(r=th(e,["musicGenerationConfig"]))&&td(t,["musicGenerationConfig"],r),t);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){this.conn.send(JSON.stringify({playbackControl:e}))}play(){this.sendPlaybackControl(te.PLAY)}pause(){this.sendPlaybackControl(te.PAUSE)}stop(){this.sendPlaybackControl(te.STOP)}resetContext(){this.sendPlaybackControl(te.RESET_CONTEXT)}close(){this.conn.close()}}async function r0(e,t,r){let n=new tG,i=JSON.parse(r.data instanceof Blob?await r.data.text():r.data instanceof ArrayBuffer?new TextDecoder().decode(r.data):r.data);if(e.isVertexAI()){let e,t,r,s,o,a,l,u,c;Object.assign(n,(e={},null!=(t=th(i,["setupComplete"]))&&td(e,["setupComplete"],t),null!=(r=th(i,["serverContent"]))&&td(e,["serverContent"],r),null!=(s=th(i,["toolCall"]))&&td(e,["toolCall"],s),null!=(o=th(i,["toolCallCancellation"]))&&td(e,["toolCallCancellation"],o),null!=(a=th(i,["usageMetadata"]))&&td(e,["usageMetadata"],function(e){let t={},r=th(e,["promptTokenCount"]);null!=r&&td(t,["promptTokenCount"],r);let n=th(e,["cachedContentTokenCount"]);null!=n&&td(t,["cachedContentTokenCount"],n);let i=th(e,["candidatesTokenCount"]);null!=i&&td(t,["responseTokenCount"],i);let s=th(e,["toolUsePromptTokenCount"]);null!=s&&td(t,["toolUsePromptTokenCount"],s);let o=th(e,["thoughtsTokenCount"]);null!=o&&td(t,["thoughtsTokenCount"],o);let a=th(e,["totalTokenCount"]);null!=a&&td(t,["totalTokenCount"],a);let l=th(e,["promptTokensDetails"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["promptTokensDetails"],e)}let u=th(e,["cacheTokensDetails"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cacheTokensDetails"],e)}let c=th(e,["candidatesTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["responseTokensDetails"],e)}let d=th(e,["toolUsePromptTokensDetails"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["toolUsePromptTokensDetails"],e)}let h=th(e,["trafficType"]);return null!=h&&td(t,["trafficType"],h),t}(a)),null!=(l=th(i,["goAway"]))&&td(e,["goAway"],l),null!=(u=th(i,["sessionResumptionUpdate"]))&&td(e,["sessionResumptionUpdate"],u),null!=(c=th(i,["voiceActivityDetectionSignal"]))&&td(e,["voiceActivityDetectionSignal"],c),e))}else Object.assign(n,i);t(n)}class r1{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r,this.music=new rQ(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,r,n,i,s,o,a,l;let u,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),h=this.apiClient.getApiVersion(),p=this.apiClient.getHeaders();e.config&&e.config.tools&&rK(e.config.tools)&&rz(p);let f=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(p);if(this.apiClient.isVertexAI())u=`${d}/ws/google.cloud.aiplatform.${h}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u);else{let e=this.apiClient.getApiKey(),t="BidiGenerateContent",r="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==h&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),t="BidiGenerateContentConstrained",r="access_token"),u=`${d}/ws/google.ai.generativelanguage.${h}.GenerativeService.${t}?${r}=${e}`}let m=()=>{},g=new Promise(e=>{m=e}),y=e.callbacks,_=this.apiClient,E={onopen:function(){var e;null==(e=null==y?void 0:y.onopen)||e.call(y),m({})},onmessage:e=>{r0(_,y.onmessage,e)},onerror:null!=(t=null==y?void 0:y.onerror)?t:function(e){},onclose:null!=(r=null==y?void 0:y.onclose)?r:function(e){}},v=this.webSocketFactory.create(u,(c={},f.forEach((e,t)=>{c[t]=e}),c),E);v.connect(),await g;let b=tB(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&b.startsWith("publishers/")){let e=this.apiClient.getProject(),t=this.apiClient.getLocation();b=`projects/${e}/locations/${t}/`+b}let w={};this.apiClient.isVertexAI()&&(null==(n=e.config)?void 0:n.responseModalities)===void 0&&(void 0===e.config?e.config={responseModalities:[eC.AUDIO]}:e.config.responseModalities=[eC.AUDIO]),(null==(i=e.config)?void 0:i.generationConfig)&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let A=null!=(o=null==(s=e.config)?void 0:s.tools)?o:[],S=[];for(let e of A)this.isCallableTool(e)?S.push(await e.tool()):S.push(e);S.length>0&&(e.config.tools=S);let T={model:b,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI()){let e,t,r;a=this.apiClient,e={},null!=(t=th(T,["model"]))&&td(e,["setup","model"],tB(a,t)),null!=(r=th(T,["config"]))&&td(e,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],function(e){let t={},r=th(e,["modelSelectionConfig"]);null!=r&&td(t,["modelConfig"],r);let n=th(e,["responseJsonSchema"]);null!=n&&td(t,["responseJsonSchema"],n);let i=th(e,["audioTimestamp"]);null!=i&&td(t,["audioTimestamp"],i);let s=th(e,["candidateCount"]);null!=s&&td(t,["candidateCount"],s);let o=th(e,["enableAffectiveDialog"]);null!=o&&td(t,["enableAffectiveDialog"],o);let a=th(e,["frequencyPenalty"]);null!=a&&td(t,["frequencyPenalty"],a);let l=th(e,["logprobs"]);null!=l&&td(t,["logprobs"],l);let u=th(e,["maxOutputTokens"]);null!=u&&td(t,["maxOutputTokens"],u);let c=th(e,["mediaResolution"]);null!=c&&td(t,["mediaResolution"],c);let d=th(e,["presencePenalty"]);null!=d&&td(t,["presencePenalty"],d);let h=th(e,["responseLogprobs"]);null!=h&&td(t,["responseLogprobs"],h);let p=th(e,["responseMimeType"]);null!=p&&td(t,["responseMimeType"],p);let f=th(e,["responseModalities"]);null!=f&&td(t,["responseModalities"],f);let m=th(e,["responseSchema"]);null!=m&&td(t,["responseSchema"],m);let g=th(e,["routingConfig"]);null!=g&&td(t,["routingConfig"],g);let y=th(e,["seed"]);null!=y&&td(t,["seed"],y);let _=th(e,["speechConfig"]);null!=_&&td(t,["speechConfig"],_);let E=th(e,["stopSequences"]);null!=E&&td(t,["stopSequences"],E);let v=th(e,["temperature"]);null!=v&&td(t,["temperature"],v);let b=th(e,["thinkingConfig"]);null!=b&&td(t,["thinkingConfig"],b);let w=th(e,["topK"]);null!=w&&td(t,["topK"],w);let A=th(e,["topP"]);if(null!=A&&td(t,["topP"],A),void 0!==th(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}(r));let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],t0(p));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t8(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t})(t5(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],m);let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);void 0!==t&&null!=v&&td(t,["setup","proactivity"],v);let b=th(e,["explicitVadSignal"]);return void 0!==t&&null!=b&&td(t,["setup","explicitVadSignal"],b),{}}(r,e)),w=e}else{let e,t,r;l=this.apiClient,e={},null!=(t=th(T,["model"]))&&td(e,["setup","model"],tB(l,t)),null!=(r=th(T,["config"]))&&td(e,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],r);let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],function(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],rI(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}(t0(p)));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t8(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t5(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],function(e){let t={},r=th(e,["handle"]);if(null!=r&&td(t,["handle"],r),void 0!==th(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);if(void 0!==t&&null!=v&&td(t,["setup","proactivity"],v),void 0!==th(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(r,e)),w=e}return delete w.config,v.send(JSON.stringify(w)),new r4(v,this.apiClient)}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}}let r2={turnComplete:!0};class r4{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let r=[];try{r=t2(t.turns),e.isVertexAI()||(r=r.map(e=>rC(e)))}catch(e){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:r,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let r=[];if(null==t.functionResponses||0===(r=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses]).length)throw Error("functionResponses is required.");for(let t of r){if("object"!=typeof t||null===t||!("name"in t)||!("response"in t))throw Error(`Could not parse function response, type '${typeof t}'.`);if(!e.isVertexAI()&&!("id"in t))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},r2),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:function(e){let t={},r=th(e,["media"]);if(null!=r){let e=tV(r);Array.isArray(e)&&(e=e.map(e=>e)),td(t,["mediaChunks"],e)}let n=th(e,["audio"]);null!=n&&td(t,["audio"],tK(n));let i=th(e,["audioStreamEnd"]);null!=i&&td(t,["audioStreamEnd"],i);let s=th(e,["video"]);null!=s&&td(t,["video"],tW(s));let o=th(e,["text"]);null!=o&&td(t,["text"],o);let a=th(e,["activityStart"]);null!=a&&td(t,["activityStart"],a);let l=th(e,["activityEnd"]);return null!=l&&td(t,["activityEnd"],l),t}(e)}:{realtimeInput:function(e){let t={},r=th(e,["media"]);if(null!=r){let e=tV(r);Array.isArray(e)&&(e=e.map(e=>rI(e))),td(t,["mediaChunks"],e)}let n=th(e,["audio"]);null!=n&&td(t,["audio"],rI(tK(n)));let i=th(e,["audioStreamEnd"]);null!=i&&td(t,["audioStreamEnd"],i);let s=th(e,["video"]);null!=s&&td(t,["video"],rI(tW(s)));let o=th(e,["text"]);null!=o&&td(t,["text"],o);let a=th(e,["activityStart"]);null!=a&&td(t,["activityStart"],a);let l=th(e,["activityEnd"]);return null!=l&&td(t,["activityEnd"],l),t}(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function r6(e){var t,r,n;if(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.disable)return!0;let i=!1;for(let t of null!=(r=null==e?void 0:e.tools)?r:[])if(r3(t)){i=!0;break}if(!i)return!0;let s=null==(n=null==e?void 0:e.automaticFunctionCalling)?void 0:n.maximumRemoteCalls;return(!(!s||!(s<0)&&Number.isInteger(s))||0==s)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0)}function r3(e){return"callTool"in e&&"function"==typeof e.callTool}function r5(e){var t;let r=[];return(null==(t=null==e?void 0:e.config)?void 0:t.tools)&&e.config.tools.forEach((e,t)=>{r3(e)||e.functionDeclarations&&e.functionDeclarations.length>0&&r.push(t)}),r}function r8(e){var t;return!(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.ignoreCallHistory)}class r9 extends tu{constructor(e){super(),this.apiClient=e,this.generateContent=async e=>{var t,r,n,i,s,o,a,l;let u,c,d=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!(null!=(l=null==(a=null==(o=e.config)?void 0:o.tools)?void 0:a.some(e=>r3(e)))&&l)||r6(e.config))return await this.generateContentInternal(d);let h=r5(e);if(h.length>0){let e=h.map(e=>`tools[${e}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let p=t2(d.contents),f=null!=(n=null==(r=null==(t=d.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,m=0;for(;m<f&&(u=await this.generateContentInternal(d)).functionCalls&&0!==u.functionCalls.length;){let t=u.candidates[0].content,r=[];for(let t of null!=(s=null==(i=e.config)?void 0:i.tools)?s:[])if(r3(t)){let e=await t.callTool(u.functionCalls);r.push(...e)}m++,c={role:"user",parts:r},d.contents=t2(d.contents),d.contents.push(t),d.contents.push(c),r8(d.config)&&(p.push(t),p.push(c))}return r8(d.config)&&(u.automaticFunctionCallingHistory=p),u},this.generateContentStream=async e=>{var t,r,n,i,s;if(this.maybeMoveToResponseJsonSchem(e),r6(e.config)){let t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}let o=r5(e);if(o.length>0){let e=o.map(e=>`tools[${e}]`).join(", ");throw Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let a=null==(n=null==(r=null==(t=null==e?void 0:e.config)?void 0:t.toolConfig)?void 0:r.functionCallingConfig)?void 0:n.streamFunctionCallArguments,l=null==(s=null==(i=null==e?void 0:e.config)?void 0:i.automaticFunctionCalling)?void 0:s.disable;if(a&&!l)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{var t;let r,n=[];if(null==e?void 0:e.generatedImages)for(let i of e.generatedImages)i&&(null==i?void 0:i.safetyAttributes)&&(null==(t=null==i?void 0:i.safetyAttributes)?void 0:t.contentType)==="Positive Prompt"?r=null==i?void 0:i.safetyAttributes:n.push(i);return r?{generatedImages:n,positivePromptSafetyAttributes:r,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:n,sdkHttpResponse:e.sdkHttpResponse}}),this.list=async e=>{var t;let r={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!r.config.queryBase)if(null==(t=r.config)?void 0:t.filter)throw Error("Filtering tuned models list for Vertex AI is not currently supported");else r.config.filter="labels.tune-type:*";return new rp(tt.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(r),r)},this.editImage=async e=>{let t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));let r={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(r)},this.generateVideos=async e=>{var t,r,n,i,s,o;if((e.prompt||e.image||e.video)&&e.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return!this.apiClient.isVertexAI()&&((null==(t=e.video)?void 0:t.uri)&&(null==(r=e.video)?void 0:r.videoBytes)?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:(null==(i=null==(n=e.source)?void 0:n.video)?void 0:i.uri)&&(null==(o=null==(s=e.source)?void 0:s.video)?void 0:o.videoBytes)&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&!e.config.responseJsonSchema&&Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema)}async processParamsMaybeAddMcpUsage(e){var t,r,n;let i=null==(t=e.config)?void 0:t.tools;if(!i)return e;let s=await Promise.all(i.map(async e=>r3(e)?await e.tool():e)),o={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:s})};if(o.config.tools=s,e.config&&e.config.tools&&rK(e.config.tools)){let t=Object.assign({},null!=(n=null==(r=e.config.httpOptions)?void 0:r.headers)?n:{});0===Object.keys(t).length&&(t=this.apiClient.getDefaultHeaders()),rz(t),o.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:t})}return o}async initAfcToolsMap(e){var t,r,n;let i=new Map;for(let s of null!=(r=null==(t=e.config)?void 0:t.tools)?r:[])if(r3(s))for(let e of null!=(n=(await s.tool()).functionDeclarations)?n:[]){if(!e.name)throw Error("Function declaration name is required.");if(i.has(e.name))throw Error(`Duplicate tool declaration name: ${e.name}`);i.set(e.name,s)}return i}async processAfcStream(e){var t,r,n;let i=null!=(n=null==(r=null==(t=e.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,s=!1,o=0;return function(e,t,r){return rE(this,arguments,function*(){for(;o<i;){s&&(o++,s=!1);let m=yield r_(e.processParamsMaybeAddMcpUsage(r)),g=yield r_(e.generateContentStreamInternal(m)),y=[],_=[];try{for(var n,a,l,u,c,d,h,p=!0,f=(a=void 0,rv(g));!(n=(h=yield r_(f.next())).done);p=!0)if(u=h.value,p=!1,yield yield r_(u),u.candidates&&(null==(c=u.candidates[0])?void 0:c.content)){for(let e of(_.push(u.candidates[0].content),null!=(d=u.candidates[0].content.parts)?d:[]))if(o<i&&e.functionCall){if(!e.functionCall.name)throw Error("Function call name was not returned by the model.");if(t.has(e.functionCall.name)){let r=yield r_(t.get(e.functionCall.name).callTool([e.functionCall]));y.push(...r)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, mising tool: ${e.functionCall.name}`)}}}catch(e){a={error:e}}finally{try{!p&&!n&&(l=f.return)&&(yield r_(l.call(f)))}finally{if(a)throw a.error}}if(y.length>0){s=!0;let e=new tg;e.candidates=[{content:{role:"user",parts:y}}],yield yield r_(e);let t=[];t.push(..._),t.push({role:"user",parts:y});let n=t2(r.contents).concat(t);r.contents=n}else break}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rx(this.apiClient,e);return s=tc("{model}:generateContent",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rN(e),r=new tg;return Object.assign(r,t),r})}{let t=rR(this.apiClient,e);return s=tc("{model}:generateContent",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rk(e),r=new tg;return Object.assign(r,t),r})}}async generateContentStreamInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rx(this.apiClient,e);return s=tc("{model}:streamGenerateContent?alt=sse",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(function(e){return rE(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=rv(e);!(t=(s=yield r_(a.next())).done);o=!0){i=s.value,o=!1;let e=rN((yield r_(i.json())));e.sdkHttpResponse={headers:i.headers};let t=new tg;Object.assign(t,e),yield yield r_(t)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield r_(n.call(a)))}finally{if(r)throw r.error}}})})}{let t=rR(this.apiClient,e);return s=tc("{model}:streamGenerateContent?alt=sse",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(function(e){return rE(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=rv(e);!(t=(s=yield r_(a.next())).done);o=!0){i=s.value,o=!1;let e=rk((yield r_(i.json())));e.sdkHttpResponse={headers:i.headers};let t=new tg;Object.assign(t,e),yield yield r_(t)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield r_(n.call(a)))}finally{if(r)throw r.error}}})})}}async embedContent(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=function(e,t){let r,n,i,s,o,a={},l=th(t,["model"]);null!=l&&td(a,["_url","model"],tB(e,l));let u=th(t,["contents"]);if(null!=u){let t=t1(e,u);Array.isArray(t)&&(t=t.map(e=>e)),td(a,["instances[]","content"],t)}let c=th(t,["config"]);return null!=c&&(r=th(c,["taskType"]),void 0!==a&&null!=r&&td(a,["instances[]","task_type"],r),n=th(c,["title"]),void 0!==a&&null!=n&&td(a,["instances[]","title"],n),i=th(c,["outputDimensionality"]),void 0!==a&&null!=i&&td(a,["parameters","outputDimensionality"],i),s=th(c,["mimeType"]),void 0!==a&&null!=s&&td(a,["instances[]","mimeType"],s),o=th(c,["autoTruncate"]),void 0!==a&&null!=o&&td(a,["parameters","autoTruncate"],o)),a}(this.apiClient,e);return s=tc("{model}:predict",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions[]","embeddings"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["values"]))&&td(r,["values"],n),null!=(i=th(e,["statistics"]))&&td(r,["statistics"],(s={},null!=(o=th(t=i,["truncated"]))&&td(s,["truncated"],o),null!=(a=th(t,["token_count"]))&&td(s,["tokenCount"],a),s)),r})),td(t,["embeddings"],e)}let i=th(e,["metadata"]);return null!=i&&td(t,["metadata"],i),t}(e),r=new ty;return Object.assign(r,t),r})}{let t=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let t=t1(e,i);Array.isArray(t)&&(t=t.map(e=>e)),td(r,["requests[]","content"],t)}let s=th(t,["config"]);null!=s&&function(e,t){let r=th(e,["taskType"]);void 0!==t&&null!=r&&td(t,["requests[]","taskType"],r);let n=th(e,["title"]);void 0!==t&&null!=n&&td(t,["requests[]","title"],n);let i=th(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&td(t,["requests[]","outputDimensionality"],i),void 0!==th(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.")}(s,r);let o=th(t,["model"]);return void 0!==o&&td(r,["requests[]","model"],tB(e,o)),r}(this.apiClient,e);return s=tc("{model}:batchEmbedContents",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["embeddings"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["embeddings"],e)}let i=th(e,["metadata"]);return null!=i&&td(t,["metadata"],i),t}(e),r=new ty;return Object.assign(r,t),r})}}async generateImagesInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","model"],tB(s,i)),null!=(o=th(e,["prompt"]))&&td(n,["instances[0]","prompt"],o),null!=(u=th(e,["config"]))&&(c=th(u,["outputGcsUri"]),void 0!==n&&null!=c&&td(n,["parameters","storageUri"],c),d=th(u,["negativePrompt"]),void 0!==n&&null!=d&&td(n,["parameters","negativePrompt"],d),h=th(u,["numberOfImages"]),void 0!==n&&null!=h&&td(n,["parameters","sampleCount"],h),p=th(u,["aspectRatio"]),void 0!==n&&null!=p&&td(n,["parameters","aspectRatio"],p),f=th(u,["guidanceScale"]),void 0!==n&&null!=f&&td(n,["parameters","guidanceScale"],f),m=th(u,["seed"]),void 0!==n&&null!=m&&td(n,["parameters","seed"],m),g=th(u,["safetyFilterLevel"]),void 0!==n&&null!=g&&td(n,["parameters","safetySetting"],g),y=th(u,["personGeneration"]),void 0!==n&&null!=y&&td(n,["parameters","personGeneration"],y),_=th(u,["includeSafetyAttributes"]),void 0!==n&&null!=_&&td(n,["parameters","includeSafetyAttributes"],_),E=th(u,["includeRaiReason"]),void 0!==n&&null!=E&&td(n,["parameters","includeRaiReason"],E),v=th(u,["language"]),void 0!==n&&null!=v&&td(n,["parameters","language"],v),b=th(u,["outputMimeType"]),void 0!==n&&null!=b&&td(n,["parameters","outputOptions","mimeType"],b),w=th(u,["outputCompressionQuality"]),void 0!==n&&null!=w&&td(n,["parameters","outputOptions","compressionQuality"],w),A=th(u,["addWatermark"]),void 0!==n&&null!=A&&td(n,["parameters","addWatermark"],A),S=th(u,["labels"]),void 0!==n&&null!=S&&td(n,["labels"],S),T=th(u,["imageSize"]),void 0!==n&&null!=T&&td(n,["parameters","sampleImageSize"],T),O=th(u,["enhancePrompt"]),void 0!==n&&null!=O&&td(n,["parameters","enhancePrompt"],O)),n);return a=tc("{model}:predict",I._url),l=I._query,delete I._url,delete I._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(I),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}let i=th(e,["positivePromptSafetyAttributes"]);return null!=i&&td(t,["positivePromptSafetyAttributes"],rG(i)),t}(e),r=new t_;return Object.assign(r,t),r})}{let t,r,s,u,c=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","model"],tB(o,r)),null!=(s=th(e,["prompt"]))&&td(t,["instances[0]","prompt"],s),null!=(u=th(e,["config"]))&&function(e,t){if(void 0!==th(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["negativePrompt"]))throw Error("negativePrompt parameter is not supported in Gemini API.");let r=th(e,["numberOfImages"]);void 0!==t&&null!=r&&td(t,["parameters","sampleCount"],r);let n=th(e,["aspectRatio"]);void 0!==t&&null!=n&&td(t,["parameters","aspectRatio"],n);let i=th(e,["guidanceScale"]);if(void 0!==t&&null!=i&&td(t,["parameters","guidanceScale"],i),void 0!==th(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let s=th(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&td(t,["parameters","safetySetting"],s);let o=th(e,["personGeneration"]);void 0!==t&&null!=o&&td(t,["parameters","personGeneration"],o);let a=th(e,["includeSafetyAttributes"]);void 0!==t&&null!=a&&td(t,["parameters","includeSafetyAttributes"],a);let l=th(e,["includeRaiReason"]);void 0!==t&&null!=l&&td(t,["parameters","includeRaiReason"],l);let u=th(e,["language"]);void 0!==t&&null!=u&&td(t,["parameters","language"],u);let c=th(e,["outputMimeType"]);void 0!==t&&null!=c&&td(t,["parameters","outputOptions","mimeType"],c);let d=th(e,["outputCompressionQuality"]);if(void 0!==t&&null!=d&&td(t,["parameters","outputOptions","compressionQuality"],d),void 0!==th(e,["addWatermark"]))throw Error("addWatermark parameter is not supported in Gemini API.");if(void 0!==th(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let h=th(e,["imageSize"]);if(void 0!==t&&null!=h&&td(t,["parameters","sampleImageSize"],h),void 0!==th(e,["enhancePrompt"]))throw Error("enhancePrompt parameter is not supported in Gemini API.")}(u,t),t);return a=tc("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t,r;let n,i,s,o,a,l,u;return n={},null!=(i=th(t=e,["_self"]))&&td(n,["image"],(s={},null!=(o=th(r=i,["bytesBase64Encoded"]))&&td(s,["imageBytes"],tp(o)),null!=(a=th(r,["mimeType"]))&&td(s,["mimeType"],a),s)),null!=(l=th(t,["raiFilteredReason"]))&&td(n,["raiFilteredReason"],l),null!=(u=th(t,["_self"]))&&td(n,["safetyAttributes"],rF(u)),n})),td(t,["generatedImages"],e)}let i=th(e,["positivePromptSafetyAttributes"]);return null!=i&&td(t,["positivePromptSafetyAttributes"],rF(i)),t}(e),r=new t_;return Object.assign(r,t),r})}}async editImageInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g,y,_,E={},v=th(t,["model"]);null!=v&&td(E,["_url","model"],tB(e,v));let b=th(t,["prompt"]);null!=b&&td(E,["instances[0]","prompt"],b);let w=th(t,["referenceImages"]);if(null!=w){let e=w;Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i,s,o,a,l={},u=th(e,["referenceImage"]);null!=u&&td(l,["referenceImage"],rM(u));let c=th(e,["referenceId"]);null!=c&&td(l,["referenceId"],c);let d=th(e,["referenceType"]);null!=d&&td(l,["referenceType"],d);let h=th(e,["maskImageConfig"]);null!=h&&td(l,["maskImageConfig"],(t={},null!=(r=th(h,["maskMode"]))&&td(t,["maskMode"],r),null!=(n=th(h,["segmentationClasses"]))&&td(t,["maskClasses"],n),null!=(i=th(h,["maskDilation"]))&&td(t,["dilation"],i),t));let p=th(e,["controlImageConfig"]);null!=p&&td(l,["controlImageConfig"],(s={},null!=(o=th(p,["controlType"]))&&td(s,["controlType"],o),null!=(a=th(p,["enableControlImageComputation"]))&&td(s,["computeControl"],a),s));let f=th(e,["styleImageConfig"]);null!=f&&td(l,["styleImageConfig"],f);let m=th(e,["subjectImageConfig"]);return null!=m&&td(l,["subjectImageConfig"],m),l})(e))),td(E,["instances[0]","referenceImages"],e)}let A=th(t,["config"]);return null!=A&&(r=th(A,["outputGcsUri"]),void 0!==E&&null!=r&&td(E,["parameters","storageUri"],r),n=th(A,["negativePrompt"]),void 0!==E&&null!=n&&td(E,["parameters","negativePrompt"],n),i=th(A,["numberOfImages"]),void 0!==E&&null!=i&&td(E,["parameters","sampleCount"],i),s=th(A,["aspectRatio"]),void 0!==E&&null!=s&&td(E,["parameters","aspectRatio"],s),o=th(A,["guidanceScale"]),void 0!==E&&null!=o&&td(E,["parameters","guidanceScale"],o),a=th(A,["seed"]),void 0!==E&&null!=a&&td(E,["parameters","seed"],a),l=th(A,["safetyFilterLevel"]),void 0!==E&&null!=l&&td(E,["parameters","safetySetting"],l),u=th(A,["personGeneration"]),void 0!==E&&null!=u&&td(E,["parameters","personGeneration"],u),c=th(A,["includeSafetyAttributes"]),void 0!==E&&null!=c&&td(E,["parameters","includeSafetyAttributes"],c),d=th(A,["includeRaiReason"]),void 0!==E&&null!=d&&td(E,["parameters","includeRaiReason"],d),h=th(A,["language"]),void 0!==E&&null!=h&&td(E,["parameters","language"],h),p=th(A,["outputMimeType"]),void 0!==E&&null!=p&&td(E,["parameters","outputOptions","mimeType"],p),f=th(A,["outputCompressionQuality"]),void 0!==E&&null!=f&&td(E,["parameters","outputOptions","compressionQuality"],f),m=th(A,["addWatermark"]),void 0!==E&&null!=m&&td(E,["parameters","addWatermark"],m),g=th(A,["labels"]),void 0!==E&&null!=g&&td(E,["labels"],g),y=th(A,["editMode"]),void 0!==E&&null!=y&&td(E,["parameters","editMode"],y),_=th(A,["baseSteps"]),void 0!==E&&null!=_&&td(E,["parameters","editConfig","baseSteps"],_)),E}(this.apiClient,e);return n=tc("{model}:predict",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tE;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b,w=(n=this.apiClient,o={},null!=(a=th(e,["model"]))&&td(o,["_url","model"],tB(n,a)),null!=(l=th(e,["image"]))&&td(o,["instances[0]","image"],rM(l)),null!=(u=th(e,["upscaleFactor"]))&&td(o,["parameters","upscaleConfig","upscaleFactor"],u),null!=(c=th(e,["config"]))&&(d=th(c,["outputGcsUri"]),void 0!==o&&null!=d&&td(o,["parameters","storageUri"],d),h=th(c,["safetyFilterLevel"]),void 0!==o&&null!=h&&td(o,["parameters","safetySetting"],h),p=th(c,["personGeneration"]),void 0!==o&&null!=p&&td(o,["parameters","personGeneration"],p),f=th(c,["includeRaiReason"]),void 0!==o&&null!=f&&td(o,["parameters","includeRaiReason"],f),m=th(c,["outputMimeType"]),void 0!==o&&null!=m&&td(o,["parameters","outputOptions","mimeType"],m),g=th(c,["outputCompressionQuality"]),void 0!==o&&null!=g&&td(o,["parameters","outputOptions","compressionQuality"],g),y=th(c,["enhanceInputImage"]),void 0!==o&&null!=y&&td(o,["parameters","upscaleConfig","enhanceInputImage"],y),_=th(c,["imagePreservationFactor"]),void 0!==o&&null!=_&&td(o,["parameters","upscaleConfig","imagePreservationFactor"],_),E=th(c,["labels"]),void 0!==o&&null!=E&&td(o,["labels"],E),v=th(c,["numberOfImages"]),void 0!==o&&null!=v&&td(o,["parameters","sampleCount"],v),b=th(c,["mode"]),void 0!==o&&null!=b&&td(o,["parameters","mode"],b)),o);return i=tc("{model}:predict",w._url),s=w._query,delete w._url,delete w._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(w),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tv;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b=(n=this.apiClient,o={},null!=(a=th(e,["model"]))&&td(o,["_url","model"],tB(n,a)),null!=(l=th(e,["source"]))&&function(e,t){let r=th(e,["prompt"]);void 0!==t&&null!=r&&td(t,["instances[0]","prompt"],r);let n=th(e,["personImage"]);void 0!==t&&null!=n&&td(t,["instances[0]","personImage","image"],rM(n));let i=th(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{let t,r;return t={},null!=(r=th(e,["productImage"]))&&td(t,["image"],rM(r)),t})),td(t,["instances[0]","productImages"],e)}}(l,o),null!=(u=th(e,["config"]))&&(c=th(u,["numberOfImages"]),void 0!==o&&null!=c&&td(o,["parameters","sampleCount"],c),d=th(u,["baseSteps"]),void 0!==o&&null!=d&&td(o,["parameters","baseSteps"],d),h=th(u,["outputGcsUri"]),void 0!==o&&null!=h&&td(o,["parameters","storageUri"],h),p=th(u,["seed"]),void 0!==o&&null!=p&&td(o,["parameters","seed"],p),f=th(u,["safetyFilterLevel"]),void 0!==o&&null!=f&&td(o,["parameters","safetySetting"],f),m=th(u,["personGeneration"]),void 0!==o&&null!=m&&td(o,["parameters","personGeneration"],m),g=th(u,["addWatermark"]),void 0!==o&&null!=g&&td(o,["parameters","addWatermark"],g),y=th(u,["outputMimeType"]),void 0!==o&&null!=y&&td(o,["parameters","outputOptions","mimeType"],y),_=th(u,["outputCompressionQuality"]),void 0!==o&&null!=_&&td(o,["parameters","outputOptions","compressionQuality"],_),E=th(u,["enhancePrompt"]),void 0!==o&&null!=E&&td(o,["parameters","enhancePrompt"],E),v=th(u,["labels"]),void 0!==o&&null!=v&&td(o,["labels"],v)),o);return i=tc("{model}:predict",b._url),s=b._query,delete b._url,delete b._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tb;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let l,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A=(n=this.apiClient,p={},null!=(f=th(e,["model"]))&&td(p,["_url","model"],tB(n,f)),null!=(m=th(e,["source"]))&&(i=m,s=p,c=th(i,["prompt"]),void 0!==s&&null!=c&&td(s,["instances[0]","prompt"],c),d=th(i,["image"]),void 0!==s&&null!=d&&td(s,["instances[0]","image"],rM(d)),h=th(i,["scribbleImage"]),void 0!==s&&null!=h&&td(s,["instances[0]","scribble"],(l={},null!=(u=th(h,["image"]))&&td(l,["image"],rM(u)),l))),null!=(g=th(e,["config"]))&&(y=th(g,["mode"]),void 0!==p&&null!=y&&td(p,["parameters","mode"],y),_=th(g,["maxPredictions"]),void 0!==p&&null!=_&&td(p,["parameters","maxPredictions"],_),E=th(g,["confidenceThreshold"]),void 0!==p&&null!=E&&td(p,["parameters","confidenceThreshold"],E),v=th(g,["maskDilation"]),void 0!==p&&null!=v&&td(p,["parameters","maskDilation"],v),b=th(g,["binaryColorThreshold"]),void 0!==p&&null!=b&&td(p,["parameters","binaryColorThreshold"],b),w=th(g,["labels"]),void 0!==p&&null!=w&&td(p,["labels"],w)),p);return o=tc("{model}:predict",A._url),a=A._query,delete A._url,delete A._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(A),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["_self"]);null!=r&&td(t,["mask"],rU(r));let n=th(e,["labels"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["labels"],e)}return t})(e))),td(t,["generatedMasks"],e)}return t}(e),r=new tw;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","name"],tB(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rL(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rj(e))}}async listInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["config"]))&&(o=th(i,["pageSize"]),void 0!==n&&null!=o&&td(n,["_query","pageSize"],o),u=th(i,["pageToken"]),void 0!==n&&null!=u&&td(n,["_query","pageToken"],u),c=th(i,["filter"]),void 0!==n&&null!=c&&td(n,["_query","filter"],c),d=th(i,["queryBase"]),void 0!==n&&null!=d&&td(n,["_url","models_url"],rn(s,d))),n);return a=tc("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["_self"]);if(null!=i){let e=ri(i);Array.isArray(e)&&(e=e.map(e=>rL(e))),td(t,["models"],e)}return t}(e),r=new tA;return Object.assign(r,t),r})}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=th(e,["config"]))&&(s=th(r,["pageSize"]),void 0!==t&&null!=s&&td(t,["_query","pageSize"],s),u=th(r,["pageToken"]),void 0!==t&&null!=u&&td(t,["_query","pageToken"],u),c=th(r,["filter"]),void 0!==t&&null!=c&&td(t,["_query","filter"],c),d=th(r,["queryBase"]),void 0!==t&&null!=d&&td(t,["_url","models_url"],rn(o,d))),t);return a=tc("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["_self"]);if(null!=i){let e=ri(i);Array.isArray(e)&&(e=e.map(e=>rj(e))),td(t,["models"],e)}return t}(e),r=new tA;return Object.assign(r,t),r})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","model"],tB(s,i)),null!=(o=th(e,["config"]))&&(u=th(o,["displayName"]),void 0!==n&&null!=u&&td(n,["displayName"],u),c=th(o,["description"]),void 0!==n&&null!=c&&td(n,["description"],c),d=th(o,["defaultCheckpointId"]),void 0!==n&&null!=d&&td(n,["defaultCheckpointId"],d)),n);return a=tc("{model}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rL(e))}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),null!=(s=th(e,["config"]))&&(u=th(s,["displayName"]),void 0!==t&&null!=u&&td(t,["displayName"],u),c=th(s,["description"]),void 0!==t&&null!=c&&td(t,["description"],c),d=th(s,["defaultCheckpointId"]),void 0!==t&&null!=d&&td(t,["defaultCheckpointId"],d)),t);return a=tc("{name}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rj(e))}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","name"],tB(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tS;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tS;return Object.assign(i,n),i})}}async countTokens(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&function(e,t){let r=th(e,["systemInstruction"]);void 0!==t&&null!=r&&td(t,["systemInstruction"],t0(r));let n=th(e,["tools"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rq(e))),td(t,["tools"],e)}let i=th(e,["generationConfig"]);void 0!==t&&null!=i&&td(t,["generationConfig"],function(e){let t={},r=th(e,["modelSelectionConfig"]);null!=r&&td(t,["modelConfig"],r);let n=th(e,["responseJsonSchema"]);null!=n&&td(t,["responseJsonSchema"],n);let i=th(e,["audioTimestamp"]);null!=i&&td(t,["audioTimestamp"],i);let s=th(e,["candidateCount"]);null!=s&&td(t,["candidateCount"],s);let o=th(e,["enableAffectiveDialog"]);null!=o&&td(t,["enableAffectiveDialog"],o);let a=th(e,["frequencyPenalty"]);null!=a&&td(t,["frequencyPenalty"],a);let l=th(e,["logprobs"]);null!=l&&td(t,["logprobs"],l);let u=th(e,["maxOutputTokens"]);null!=u&&td(t,["maxOutputTokens"],u);let c=th(e,["mediaResolution"]);null!=c&&td(t,["mediaResolution"],c);let d=th(e,["presencePenalty"]);null!=d&&td(t,["presencePenalty"],d);let h=th(e,["responseLogprobs"]);null!=h&&td(t,["responseLogprobs"],h);let p=th(e,["responseMimeType"]);null!=p&&td(t,["responseMimeType"],p);let f=th(e,["responseModalities"]);null!=f&&td(t,["responseModalities"],f);let m=th(e,["responseSchema"]);null!=m&&td(t,["responseSchema"],m);let g=th(e,["routingConfig"]);null!=g&&td(t,["routingConfig"],g);let y=th(e,["seed"]);null!=y&&td(t,["seed"],y);let _=th(e,["speechConfig"]);null!=_&&td(t,["speechConfig"],_);let E=th(e,["stopSequences"]);null!=E&&td(t,["stopSequences"],E);let v=th(e,["temperature"]);null!=v&&td(t,["temperature"],v);let b=th(e,["thinkingConfig"]);null!=b&&td(t,["thinkingConfig"],b);let w=th(e,["topK"]);null!=w&&td(t,["topK"],w);let A=th(e,["topP"]);if(null!=A&&td(t,["topP"],A),void 0!==th(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}(i))}(s,r),r}(this.apiClient,e);return s=tc("{model}:countTokens",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["totalTokens"]))&&td(t,["totalTokens"],n),t),s=new tT;return Object.assign(s,i),s})}{let t=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rC(e))),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&function(e){if(void 0!==th(e,["systemInstruction"]))throw Error("systemInstruction parameter is not supported in Gemini API.");if(void 0!==th(e,["tools"]))throw Error("tools parameter is not supported in Gemini API.");if(void 0!==th(e,["generationConfig"]))throw Error("generationConfig parameter is not supported in Gemini API.")}(s),r}(this.apiClient,e);return s=tc("{model}:countTokens",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["totalTokens"]))&&td(t,["totalTokens"],n),null!=(i=th(e,["cachedContentTokenCount"]))&&td(t,["cachedContentTokenCount"],i),t),o=new tT;return Object.assign(o,s),o})}}async computeTokens(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}return r}(this.apiClient,e);return n=tc("{model}:computeTokens",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["tokensInfo"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["tokensInfo"],e)}return t}(e),r=new tO;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,r,n,i,s,o,a,l,u,c;let d="",h={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,p,f,m,g,y,_=(s=this.apiClient,u={},null!=(c=th(e,["model"]))&&td(u,["_url","model"],tB(s,c)),null!=(p=th(e,["prompt"]))&&td(u,["instances[0]","prompt"],p),null!=(f=th(e,["image"]))&&td(u,["instances[0]","image"],rM(f)),null!=(m=th(e,["video"]))&&td(u,["instances[0]","video"],rB(m)),null!=(g=th(e,["source"]))&&(a=g,l=u,n=th(a,["prompt"]),void 0!==l&&null!=n&&td(l,["instances[0]","prompt"],n),i=th(a,["image"]),void 0!==l&&null!=i&&td(l,["instances[0]","image"],rM(i)),o=th(a,["video"]),void 0!==l&&null!=o&&td(l,["instances[0]","video"],rB(o))),null!=(y=th(e,["config"]))&&function(e,t){var r;let n,i,s,o=th(e,["numberOfVideos"]);void 0!==t&&null!=o&&td(t,["parameters","sampleCount"],o);let a=th(e,["outputGcsUri"]);void 0!==t&&null!=a&&td(t,["parameters","storageUri"],a);let l=th(e,["fps"]);void 0!==t&&null!=l&&td(t,["parameters","fps"],l);let u=th(e,["durationSeconds"]);void 0!==t&&null!=u&&td(t,["parameters","durationSeconds"],u);let c=th(e,["seed"]);void 0!==t&&null!=c&&td(t,["parameters","seed"],c);let d=th(e,["aspectRatio"]);void 0!==t&&null!=d&&td(t,["parameters","aspectRatio"],d);let h=th(e,["resolution"]);void 0!==t&&null!=h&&td(t,["parameters","resolution"],h);let p=th(e,["personGeneration"]);void 0!==t&&null!=p&&td(t,["parameters","personGeneration"],p);let f=th(e,["pubsubTopic"]);void 0!==t&&null!=f&&td(t,["parameters","pubsubTopic"],f);let m=th(e,["negativePrompt"]);void 0!==t&&null!=m&&td(t,["parameters","negativePrompt"],m);let g=th(e,["enhancePrompt"]);void 0!==t&&null!=g&&td(t,["parameters","enhancePrompt"],g);let y=th(e,["generateAudio"]);void 0!==t&&null!=y&&td(t,["parameters","generateAudio"],y);let _=th(e,["lastFrame"]);void 0!==t&&null!=_&&td(t,["instances[0]","lastFrame"],rM(_));let E=th(e,["referenceImages"]);if(void 0!==t&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["image"]))&&td(r,["image"],rM(n)),null!=(i=th(t,["referenceType"]))&&td(r,["referenceType"],i),r})),td(t,["instances[0]","referenceImages"],e)}let v=th(e,["mask"]);void 0!==t&&null!=v&&td(t,["instances[0]","mask"],(n={},null!=(i=th(r=v,["image"]))&&td(n,["_self"],rM(i)),null!=(s=th(r,["maskMode"]))&&td(n,["maskMode"],s),n));let b=th(e,["compressionQuality"]);void 0!==t&&null!=b&&td(t,["parameters","compressionQuality"],b)}(y,u),u);return d=tc("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=th(e,["name"]))&&td(t,["name"],r),null!=(n=th(e,["metadata"]))&&td(t,["metadata"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),null!=(o=th(e,["response"]))&&td(t,["response"],function(e){let t={},r=th(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["_self"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["gcsUri"]))&&td(i,["uri"],s),null!=(o=th(t,["bytesBase64Encoded"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["mimeType"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tI;return Object.assign(l,a),l})}{let t,r,s,a,l,p,f,m,g,y,_=(o=this.apiClient,a={},null!=(l=th(e,["model"]))&&td(a,["_url","model"],tB(o,l)),null!=(p=th(e,["prompt"]))&&td(a,["instances[0]","prompt"],p),null!=(f=th(e,["image"]))&&td(a,["instances[0]","image"],rD(f)),null!=(m=th(e,["video"]))&&td(a,["instances[0]","video"],r$(m)),null!=(g=th(e,["source"]))&&(u=g,c=a,t=th(u,["prompt"]),void 0!==c&&null!=t&&td(c,["instances[0]","prompt"],t),r=th(u,["image"]),void 0!==c&&null!=r&&td(c,["instances[0]","image"],rD(r)),s=th(u,["video"]),void 0!==c&&null!=s&&td(c,["instances[0]","video"],r$(s))),null!=(y=th(e,["config"]))&&function(e,t){let r=th(e,["numberOfVideos"]);if(void 0!==t&&null!=r&&td(t,["parameters","sampleCount"],r),void 0!==th(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["fps"]))throw Error("fps parameter is not supported in Gemini API.");let n=th(e,["durationSeconds"]);if(void 0!==t&&null!=n&&td(t,["parameters","durationSeconds"],n),void 0!==th(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let i=th(e,["aspectRatio"]);void 0!==t&&null!=i&&td(t,["parameters","aspectRatio"],i);let s=th(e,["resolution"]);void 0!==t&&null!=s&&td(t,["parameters","resolution"],s);let o=th(e,["personGeneration"]);if(void 0!==t&&null!=o&&td(t,["parameters","personGeneration"],o),void 0!==th(e,["pubsubTopic"]))throw Error("pubsubTopic parameter is not supported in Gemini API.");let a=th(e,["negativePrompt"]);void 0!==t&&null!=a&&td(t,["parameters","negativePrompt"],a);let l=th(e,["enhancePrompt"]);if(void 0!==t&&null!=l&&td(t,["parameters","enhancePrompt"],l),void 0!==th(e,["generateAudio"]))throw Error("generateAudio parameter is not supported in Gemini API.");let u=th(e,["lastFrame"]);void 0!==t&&null!=u&&td(t,["instances[0]","lastFrame"],rD(u));let c=th(e,["referenceImages"]);if(void 0!==t&&null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["image"]))&&td(r,["image"],rD(n)),null!=(i=th(t,["referenceType"]))&&td(r,["referenceType"],i),r})),td(t,["instances[0]","referenceImages"],e)}if(void 0!==th(e,["mask"]))throw Error("mask parameter is not supported in Gemini API.");if(void 0!==th(e,["compressionQuality"]))throw Error("compressionQuality parameter is not supported in Gemini API.")}(y,a),a);return d=tc("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=th(e,["name"]))&&td(t,["name"],r),null!=(n=th(e,["metadata"]))&&td(t,["metadata"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),null!=(o=th(e,["response","generateVideoResponse"]))&&td(t,["response"],function(e){let t={},r=th(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["video"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["uri"]))&&td(i,["uri"],s),null!=(o=th(t,["encodedVideo"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["encoding"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tI;return Object.assign(l,a),l})}}}class r7 extends tu{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["operationName"]))&&td(n,["_url","operationName"],i),n);return s=tc("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}{let t,r,a=(t={},null!=(r=th(e,["operationName"]))&&td(t,["_url","operationName"],r),t);return s=tc("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json())}}async fetchPredictVideosOperationInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l=(s={},null!=(o=th(e,["operationName"]))&&td(s,["operationName"],o),null!=(a=th(e,["resourceName"]))&&td(s,["_url","resourceName"],a),s);return n=tc("{resourceName}:fetchPredictOperation",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}throw Error("This method is only supported by the Vertex AI.")}}class ne extends tu{constructor(e){super(),this.apiClient=e}async create(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g,y,_=(n=this.apiClient,d={},null!=(h=th(e,["config"]))&&td(d,["config"],(p=th(h,["expireTime"]),void 0!==d&&null!=p&&td(d,["expireTime"],p),f=th(h,["newSessionExpireTime"]),void 0!==d&&null!=f&&td(d,["newSessionExpireTime"],f),m=th(h,["uses"]),void 0!==d&&null!=m&&td(d,["uses"],m),g=th(h,["liveConnectConstraints"]),void 0!==d&&null!=g&&td(d,["bidiGenerateContentSetup"],(i=n,l={},null!=(u=th(s=g,["model"]))&&td(l,["setup","model"],tB(i,u)),null!=(c=th(s,["config"]))&&td(l,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],r);let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],function(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}(t0(p)));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t8(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t5(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],function(e){let t={},r=th(e,["handle"]);if(null!=r&&td(t,["handle"],r),void 0!==th(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);if(void 0!==t&&null!=v&&td(t,["setup","proactivity"],v),void 0!==th(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(c,l)),l)),y=th(h,["lockAdditionalFields"]),void 0!==d&&null!=y&&td(d,["fieldMask"],y),{})),d);o=tc("auth_tokens",_._url),a=_._query,delete _.config,delete _._url,delete _._query;let E=function(e,t){let r=null,n=e.bidiGenerateContentSetup;if("object"==typeof n&&null!==n&&"setup"in n){let t=n.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,r=t):delete e.bidiGenerateContentSetup}else void 0!==n&&delete e.bidiGenerateContentSetup;let i=e.fieldMask;if(r){let n=function(e){let t=[];for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if("object"==typeof n&&null!=n&&Object.keys(n).length>0){let e=Object.keys(n).map(e=>`${r}.${e}`);t.push(...e)}else t.push(r)}return t.join(",")}(r);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&(null==t?void 0:t.lockAdditionalFields.length)===0)n?e.fieldMask=n:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){let t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],r=[];i.length>0&&(r=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));let s=[];n&&s.push(n),r.length>0&&s.push(...r),s.length>0?e.fieldMask=s.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(_,e.config);return this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(E),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}}class nt extends tu{constructor(e){super(),this.apiClient=e,this.list=async e=>new rp(tt.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),s);return n=tc("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),null!=(a=th(e,["config"]))&&(l=th(a,["force"]),void 0!==s&&null!=l&&td(s,["_query","force"],l)),s);n=tc("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=th(e,["parent"]))&&td(s,["_url","parent"],o),null!=(a=th(e,["config"]))&&(l=th(a,["pageSize"]),void 0!==s&&null!=l&&td(s,["_query","pageSize"],l),u=th(a,["pageToken"]),void 0!==s&&null!=u&&td(s,["_query","pageToken"],u)),s);return n=tc("{parent}/documents",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["documents"],e)}return t}(e),r=new tN;return Object.assign(r,t),r})}}}class nr extends tu{constructor(e,t=new nt(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new rp(tt.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["displayName"]),void 0!==s&&null!=a&&td(s,["displayName"],a)),s);return n=tc("fileSearchStores",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),s);return n=tc("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),null!=(a=th(e,["config"]))&&(l=th(a,["force"]),void 0!==s&&null!=l&&td(s,["_query","force"],l)),s);n=tc("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["pageSize"]),void 0!==s&&null!=a&&td(s,["_query","pageSize"],a),l=th(o,["pageToken"]),void 0!==s&&null!=l&&td(s,["_query","pageToken"],l)),s);return n=tc("fileSearchStores",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["fileSearchStores"],e)}return t}(e),r=new tP;return Object.assign(r,t),r})}}async uploadToFileSearchStoreInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l=(s={},null!=(o=th(e,["fileSearchStoreName"]))&&td(s,["_url","file_search_store_name"],o),null!=(a=th(e,["config"]))&&rH(a,s),s);return n=tc("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tU;return Object.assign(i,n),i})}}async importFile(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["fileSearchStoreName"]))&&td(s,["_url","file_search_store_name"],o),null!=(a=th(e,["fileName"]))&&td(s,["fileName"],a),null!=(l=th(e,["config"]))&&function(e,t){let r=th(e,["customMetadata"]);if(void 0!==t&&null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["customMetadata"],e)}let n=th(e,["chunkingConfig"]);void 0!==t&&null!=n&&td(t,["chunkingConfig"],n)}(l,s),s);return n=tc("{file_search_store_name}:importFile",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h=(o={},null!=(a=th(e,["name"]))&&td(o,["name"],a),null!=(l=th(e,["metadata"]))&&td(o,["metadata"],l),null!=(u=th(e,["done"]))&&td(o,["done"],u),null!=(c=th(e,["error"]))&&td(o,["error"],c),null!=(d=th(e,["response"]))&&td(o,["response"],(r={},null!=(n=th(t=d,["sdkHttpResponse"]))&&td(r,["sdkHttpResponse"],n),null!=(i=th(t,["parent"]))&&td(r,["parent"],i),null!=(s=th(t,["documentName"]))&&td(r,["documentName"],s),r)),o),p=new tD;return Object.assign(p,h),p})}}}let nn=function(){let{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return nn=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function ni(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let ns=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return Error(JSON.stringify(e))}catch(e){}}return Error(e)};class no extends Error{}class na extends no{constructor(e,t,r,n){super(`${na.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.error=t}static makeMessage(e,t,r){let n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){return e&&n?400===e?new nd(e,t,r,n):401===e?new nh(e,t,r,n):403===e?new np(e,t,r,n):404===e?new nf(e,t,r,n):409===e?new nm(e,t,r,n):422===e?new ng(e,t,r,n):429===e?new ny(e,t,r,n):e>=500?new n_(e,t,r,n):new na(e,t,r,n):new nu({message:r,cause:ns(t)})}}class nl extends na{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class nu extends na{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class nc extends nu{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}}class nd extends na{}class nh extends na{}class np extends na{}class nf extends na{}class nm extends na{}class ng extends na{}class ny extends na{}class n_ extends na{}let nE=/^[a-z][a-z0-9+.-]*:/i,nv=e=>(nv=Array.isArray)(e),nb=nv,nw="0.0.1",nA=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",nS=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function nT(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function nO(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nI(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await (null==(r=(t=e[Symbol.asyncIterator]()).return)?void 0:r.call(t));let n=e.getReader(),i=n.cancel();n.releaseLock(),await i}let nC=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),nR=()=>{var e;if("u"<typeof File){let{process:t}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof(null==(e=null==t?void 0:t.versions)?void 0:e.node)&&20>parseInt(t.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function nx(e,t,r){return nR(),new File(e,null!=t?t:"unknown_file",r)}let nk=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function nN(e,t,r){var n;let i,s;if(nR(),null!=(i=e=await e)&&"object"==typeof i&&"string"==typeof i.name&&"number"==typeof i.lastModified&&nk(i))return e instanceof File?e:nx([await e.arrayBuffer()],e.name);if(null!=(s=e)&&"object"==typeof s&&"string"==typeof s.url&&"function"==typeof s.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),nx(await nP(n),t,r)}let o=await nP(e);if(t||(t=("object"==typeof(n=e)&&null!==n&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0),!(null==r?void 0:r.type)){let e=o.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return nx(o,t,r)}async function nP(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nk(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])try{for(var r,n,i,s,o,a,l=!0,u=rv(e);!(r=(a=await u.next()).done);l=!0)s=a.value,l=!1,t.push(...await nP(s))}catch(e){n={error:e}}finally{try{!l&&!r&&(i=u.return)&&await i.call(u)}finally{if(n)throw n.error}}else{let t=null==(o=null==e?void 0:e.constructor)?void 0:o.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class nU{constructor(e){this._client=e}}function nD(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}nU._key=[];let nM=Object.freeze(Object.create(null)),nj=((e=nD)=>function(t,...r){let n;if(1===t.length)return t[0];let i=!1,s=[],o=t.reduce((t,n,o)=>{var a,l,u;/[?#]/.test(n)&&(i=!0);let c=r[o],d=(i?encodeURIComponent:e)(""+c);return o!==r.length&&(null==c||"object"==typeof c&&c.toString===(null==(u=Object.getPrototypeOf(null!=(l=Object.getPrototypeOf(null!=(a=c.hasOwnProperty)?a:nM))?l:nM))?void 0:u.toString))&&(d=c+"",s.push({start:t.length+n.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),t+n+(o===r.length?"":d)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(a));)s.push({start:n.index,length:n[0].length,error:`Value "${n[0]}" can't be safely passed as a path parameter`});if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0,t=s.reduce((t,r)=>{let n=" ".repeat(r.start-e),i="^".repeat(r.length);return e=r.start+r.length,t+n+i},"");throw new no(`Path parameters result in path with invalid segments:
|
|
25
|
+
${s.map(e=>e.error).join("\n")}
|
|
26
|
+
${o}
|
|
27
|
+
${t}`)}return o})(nD);class nL extends nU{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=ry(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new no("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new no("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(nj`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(nj`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(nj`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:s=this._client.apiVersion}=i,o=ry(i,["api_version"]);return this._client.get(nj`/${s}/interactions/${e}`,Object.assign(Object.assign({query:o},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}nL._key=Object.freeze(["interactions"]);class nF extends nL{}function nG(e){let t;return(null!=r?r:r=(t=new globalThis.TextEncoder).encode.bind(t))(e)}function nq(e){let t;return(null!=n?n:n=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class n${constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?nG(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);let n=[];for(;null!=(t=function(e,t){for(let r=null!=t?t:0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(this.buffer,this.carriageReturnIndex));){if(t.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=t.index;continue}if(null!=this.carriageReturnIndex&&(t.index!==this.carriageReturnIndex+1||t.carriage)){n.push(nq(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}let e=null!==this.carriageReturnIndex?t.preceding-1:t.preceding,r=nq(this.buffer.subarray(0,e));n.push(r),this.buffer=this.buffer.subarray(t.index),this.carriageReturnIndex=null}return n}flush(){return this.buffer.length?this.decode("\n"):[]}}n$.NEWLINE_CHARS=new Set(["\n","\r"]),n$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let nB={off:0,error:200,warn:300,info:400,debug:500},nH=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(nB,e))return e;nz(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nB))}`)}};function nV(){}function nJ(e,t,r){return!t||nB[e]>nB[r]?nV:t[e].bind(t)}let nW={error:nV,warn:nV,info:nV,debug:nV},nK=new WeakMap;function nz(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return nW;let i=nK.get(r);if(i&&i[0]===n)return i[1];let s={error:nJ("error",r,n),warn:nJ("warn",r,n),info:nJ("info",r,n),debug:nJ("debug",r,n)};return nK.set(r,[n,s]),s}let nY=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class nX{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?nz(r):console;return new nX(function(){return rE(this,arguments,function*(){var r,s,o,a;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=rv(function(e,t){return rE(this,arguments,function*(){var r,n,i,s;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new no("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new no("Attempted to iterate over a response with no body")}let o=new nQ,a=new n$,l=nO(e.body);try{for(var u,c=!0,d=rv(function(e){return rE(this,arguments,function*(){var t,r,n,i;let s=new Uint8Array;try{for(var o,a=!0,l=rv(e);!(t=(o=yield r_(l.next())).done);a=!0){let e;if(i=o.value,a=!1,null==i)continue;let t=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?nG(i):i,r=new Uint8Array(s.length+t.length);for(r.set(s),r.set(t,s.length),s=r;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(s));)yield yield r_(s.slice(0,e)),s=s.slice(e)}}catch(e){r={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield r_(n.call(l)))}finally{if(r)throw r.error}}s.length>0&&(yield yield r_(s))})}(l));!(r=(u=yield r_(d.next())).done);c=!0)for(let e of(s=u.value,c=!1,a.decode(s))){let t=o.decode(e);t&&(yield yield r_(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield r_(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=o.decode(e);t&&(yield yield r_(t))}})}(e,t));!(r=(u=yield r_(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield r_(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){s={error:e}}finally{try{!c&&!r&&(o=d.return)&&(yield r_(o.call(d)))}finally{if(s)throw s.error}}l=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new nX(function(){return rE(this,arguments,function*(){var r,i,s,o;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=rv(function(){return rE(this,arguments,function*(){var t,r,n,i;let s=new n$,o=nO(e);try{for(var a,l=!0,u=rv(o);!(t=(a=yield r_(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,s.decode(i)))yield yield r_(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield r_(n.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush())yield yield r_(e)})}());!(r=(l=yield r_(c.next())).done);u=!0)o=l.value,u=!1,!a&&o&&(yield yield r_(JSON.parse(o)))}catch(e){i={error:e}}finally{try{!u&&!r&&(s=c.return)&&(yield r_(s.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new nX(()=>n(e),this.controller,this.client),new nX(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nT({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=nG(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class nQ{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function nZ(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{var n;if(t.options.stream)return(nz(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):nX.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),s=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();return(null==s?void 0:s.includes("application/json"))||(null==s?void 0:s.endsWith("+json"))?await r.json():await r.text()})();return nz(e).debug(`[${n}] response parsed`,nY({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}class n0 extends Promise{constructor(e,t,r=nZ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new n0(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let n1=Symbol("brand.privateNullableHeaders"),n2=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(n1 in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nb(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nb(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[n1]:!0,values:t,nulls:r}},n4=e=>{var t,r,n,i,s,o;return void 0!==globalThis.process?null!=(n=null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())?n:void 0:void 0!==globalThis.Deno?null==(o=null==(s=null==(i=globalThis.Deno.env)?void 0:i.get)?void 0:s.call(i,e))?void 0:o.trim():void 0};class n6{constructor(e){var t,r,n,i,s,o,a,{baseURL:l=n4("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=n4("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;let d=Object.assign(Object.assign({apiKey:u,apiVersion:c},ry(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:n6.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;let h="warn";this.logLevel=h,this.logLevel=null!=(s=null!=(i=nH(d.logLevel,"ClientOptions.logLevel",this))?i:nH(n4("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?s:h,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(o=d.maxRetries)?o:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nC,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let t=n2([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return n2([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return n2([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new no(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${nw}`}defaultIdempotencyKey(){return`stainless-node-retry-${nn()}`}makeStatusError(e,t,r,n){return na.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nE.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(s)&&(t=Object.assign(Object.assign({},s),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new n0(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,s;let o=await e,a=null!=(n=o.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(o);let{req:l,url:u,timeout:c}=await this.buildRequest(o,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:o});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,p=Date.now();if(nz(this).debug(`[${d}] sending request`,nY({retryOfRequestLogID:r,method:o.method,url:u,options:o,headers:l.headers})),null==(i=o.signal)?void 0:i.aborted)throw new nl;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(ns),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(s=o.signal)?void 0:s.aborted)throw new nl;let n=ni(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),this.retryRequest(o,t,null!=r?r:d);if(nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),n)throw new nc;throw new nu({cause:m})}let y=`[${d}${h}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-p}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nI(m.body),nz(this).info(`${y} - ${e}`),nz(this).debug(`[${d}] response error (${e})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),this.retryRequest(o,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";nz(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>ns(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=s?void 0:i;throw nz(this).debug(`[${d}] response error (${n})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-p})),this.makeStatusError(m.status,s,a,m.headers)}return nz(this).info(y),nz(this).debug(`[${d}] response start`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),{response:m,options:o,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:p}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:s,method:o}=i,a=ry(i,["signal","method"]);s&&s.addEventListener("abort",()=>n.abort());let l=setTimeout(()=>n.abort(),r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,c=Object.assign(Object.assign(Object.assign({signal:n.signal},u?{duplex:"half"}:{}),{method:"GET"}),a);o&&(c.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let s,o,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(s=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!s){let e=parseFloat(l);s=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){let r=null!=(i=e.maxRetries)?i:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (o=s,new Promise(e=>setTimeout(e,o))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let s=Object.assign({},e),{method:o,path:a,query:l,defaultBaseURL:u}=s,c=this.buildURL(a,l,u);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new no(`${e} must be an integer`);if(t<0)throw new no(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=null!=(r=s.timeout)?r:this.timeout;let{bodyHeaders:d,body:h}=this.buildBody({options:s}),p=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:p},s.signal&&{signal:s.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!=(n=this.fetchOptions)?n:{}),null!=(i=s.fetchOptions)?i:{}),url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=await this.authHeaders(e),a=n2([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),null!=t?t:t=(()=>{var e,t,r,n,i;let s="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(Deno.build.os),"X-Stainless-Arch":nA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:null!=(t=null==(e=Deno.version)?void 0:e.deno)?t:"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(null!=(r=globalThis.process.platform)?r:"unknown"),"X-Stainless-Arch":nA(null!=(n=globalThis.process.arch)?n:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":null!=(i=globalThis.process.version)?i:"unknown"};let o=function(){if("u"<typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${n}.${i}`}}}return null}();return o?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${o.browser}`,"X-Stainless-Runtime-Version":o.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),this._options.defaultHeaders,n,e.headers,o]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){let r;if(!e)return{bodyHeaders:void 0,body:void 0};let n=n2([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"!=typeof e||!(Symbol.asyncIterator in e)&&(!(Symbol.iterator in e)||!("next"in e)||"function"!=typeof e.next))return this.encoder({body:e,headers:n});return{bodyHeaders:void 0,body:(r=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nT({start(){},async pull(e){let{done:t,value:n}=await r.next();t?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=r.return)?void 0:e.call(r))}}))}}}n6.DEFAULT_TIMEOUT=6e4;class n3 extends n6{constructor(){super(...arguments),this.interactions=new nF(this)}}n3.GeminiNextGenAPIClient=n3,n3.GeminiNextGenAPIClientError=no,n3.APIError=na,n3.APIConnectionError=nu,n3.APIConnectionTimeoutError=nc,n3.APIUserAbortError=nl,n3.NotFoundError=nf,n3.ConflictError=nm,n3.RateLimitError=ny,n3.BadRequestError=nd,n3.AuthenticationError=nh,n3.InternalServerError=n_,n3.PermissionDeniedError=np,n3.UnprocessableEntityError=ng,n3.toFile=nN,n3.Interactions=nF;let n5="x-goog-api-key",n8="https://www.googleapis.com/auth/cloud-platform";class n9{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}let t=function(e){let t;if(!e)return{scopes:[n8]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==n8||Array.isArray(t.scopes)&&0>t.scopes.indexOf(n8))throw Error(`Invalid auth scopes. Scopes must include: ${n8}`)}else t.scopes=[n8];return t}(e.googleAuthOptions);this.googleAuth=new tr.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(n5)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(n5,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class n7{async download(e,t){if(e.downloadPath){let r=await ie(e,t);if(r instanceof tm){let t=(0,tn.createWriteStream)(e.downloadPath);ts.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,to.finished)(t)}else try{await (0,ti.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function ie(e,t){var r,n,i;let s=rr(e.file);if(void 0!==s)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(re(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rt(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class it{create(e,t,r){return new ir(e,t,r)}}class ir{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new ta.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ii(e,t){let r,n,i,s={},o=th(e,["sdkHttpResponse"]);null!=o&&td(s,["sdkHttpResponse"],o);let a=th(e,["name"]);null!=a&&td(s,["name"],a);let l=th(e,["state"]);null!=l&&td(s,["state"],t7(l));let u=th(e,["createTime"]);null!=u&&td(s,["createTime"],u);let c=th(e,["tuningTask","startTime"]);null!=c&&td(s,["startTime"],c);let d=th(e,["tuningTask","completeTime"]);null!=d&&td(s,["endTime"],d);let h=th(e,["updateTime"]);null!=h&&td(s,["updateTime"],h);let p=th(e,["description"]);null!=p&&td(s,["description"],p);let f=th(e,["baseModel"]);null!=f&&td(s,["baseModel"],f);let m=th(e,["_self"]);return null!=m&&td(s,["tunedModel"],(r={},null!=(n=th(m,["name"]))&&td(r,["model"],n),null!=(i=th(m,["name"]))&&td(r,["endpoint"],i),r)),s}function is(e,t){let r={},n=th(e,["sdkHttpResponse"]);null!=n&&td(r,["sdkHttpResponse"],n);let i=th(e,["name"]);null!=i&&td(r,["name"],i);let s=th(e,["state"]);null!=s&&td(r,["state"],t7(s));let o=th(e,["createTime"]);null!=o&&td(r,["createTime"],o);let a=th(e,["startTime"]);null!=a&&td(r,["startTime"],a);let l=th(e,["endTime"]);null!=l&&td(r,["endTime"],l);let u=th(e,["updateTime"]);null!=u&&td(r,["updateTime"],u);let c=th(e,["error"]);null!=c&&td(r,["error"],c);let d=th(e,["description"]);null!=d&&td(r,["description"],d);let h=th(e,["baseModel"]);null!=h&&td(r,["baseModel"],h);let p=th(e,["tunedModel"]);null!=p&&td(r,["tunedModel"],p);let f=th(e,["preTunedModel"]);null!=f&&td(r,["preTunedModel"],f);let m=th(e,["supervisedTuningSpec"]);null!=m&&td(r,["supervisedTuningSpec"],m);let g=th(e,["preferenceOptimizationSpec"]);null!=g&&td(r,["preferenceOptimizationSpec"],g);let y=th(e,["tuningDataStats"]);null!=y&&td(r,["tuningDataStats"],y);let _=th(e,["encryptionSpec"]);null!=_&&td(r,["encryptionSpec"],_);let E=th(e,["partnerModelTuningSpec"]);null!=E&&td(r,["partnerModelTuningSpec"],E);let v=th(e,["customBaseModel"]);null!=v&&td(r,["customBaseModel"],v);let b=th(e,["experiment"]);null!=b&&td(r,["experiment"],b);let w=th(e,["labels"]);null!=w&&td(r,["labels"],w);let A=th(e,["outputUri"]);null!=A&&td(r,["outputUri"],A);let S=th(e,["pipelineJob"]);null!=S&&td(r,["pipelineJob"],S);let T=th(e,["serviceAccount"]);null!=T&&td(r,["serviceAccount"],T);let O=th(e,["tunedModelDisplayName"]);null!=O&&td(r,["tunedModelDisplayName"],O);let I=th(e,["veoTuningSpec"]);return null!=I&&td(r,["veoTuningSpec"],I),r}function io(e,t){let r={},n=th(e,["gcsUri"]);null!=n&&td(r,["validationDatasetUri"],n);let i=th(e,["vertexDatasetResource"]);return null!=i&&td(r,["validationDatasetUri"],i),r}class ia extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eN.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ii(e))}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l),u=th(i,["filter"]),void 0!==n&&null!=u&&td(n,["_query","filter"],u)),n);return s=tc("tuningJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>is(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}{let t,r,a,l,u,c=(t={},null!=(r=th(e,["config"]))&&(a=th(r,["pageSize"]),void 0!==t&&null!=a&&td(t,["_query","pageSize"],a),l=th(r,["pageToken"]),void 0!==t&&null!=l&&td(t,["_query","pageToken"],l),u=th(r,["filter"]),void 0!==t&&null!=u&&td(t,["_query","filter"],u)),t);return s=tc("tunedModels",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tunedModels"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ii(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}}async cancel(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}let i=th(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}if(void 0!==th(e,["examples"]))throw Error("examples parameter is not supported in Vertex AI.")}(l,s,e),null!=(u=th(e,["config"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec"],io(r))}else if("PREFERENCE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec"],io(r))}let i=th(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&td(t,["tunedModelDisplayName"],i);let s=th(e,["description"]);void 0!==t&&null!=s&&td(t,["description"],s);let o=th(r,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}let a=th(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}let l=th(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}let u=th(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}if(void 0!==th(e,["batchSize"]))throw Error("batchSize parameter is not supported in Vertex AI.");if(void 0!==th(e,["learningRate"]))throw Error("learningRate parameter is not supported in Vertex AI.");let c=th(e,["labels"]);void 0!==t&&null!=c&&td(t,["labels"],c);let d=th(e,["beta"]);void 0!==t&&null!=d&&td(t,["preferenceOptimizationSpec","hyperParameters","beta"],d)}(u,s,e),s);return n=tc("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}throw Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e){if(void 0!==th(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let t=th(e,["examples"]);if(null!=t){let e=t;Array.isArray(e)&&(e=e.map(e=>e)),td({},["examples","examples"],e)}}(l),null!=(u=th(e,["config"]))&&function(e,t){if(void 0!==th(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let r=th(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=r&&td(t,["displayName"],r),void 0!==th(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let n=th(e,["epochCount"]);void 0!==t&&null!=n&&td(t,["tuningTask","hyperparameters","epochCount"],n);let i=th(e,["learningRateMultiplier"]);if(null!=i&&td({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==th(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==th(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==th(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");let s=th(e,["batchSize"]);void 0!==t&&null!=s&&td(t,["tuningTask","hyperparameters","batchSize"],s);let o=th(e,["learningRate"]);if(void 0!==t&&null!=o&&td(t,["tuningTask","hyperparameters","learningRate"],o),void 0!==th(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==th(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.")}(u,s),s);return n=tc("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),t})}}}let il="x-goog-upload-status";async function iu(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async function ic(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async function id(e,t,r){var n,i;let s=0,o=0,a=new tm(new Response),l="upload";for(s=e.size;o<s;){let u=Math.min(8388608,s-o),c=e.slice(o,o+u);o+u>=s&&(l+=", finalize");let d=0,h=1e3;for(;d<3&&(null==(n=null==(a=await r.request({path:"",body:c,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(o),"Content-Length":String(u)}}}))?void 0:a.headers)||!n[il]);)d++,await ip(h),h*=2;if(o+=u,(null==(i=null==a?void 0:a.headers)?void 0:i[il])!=="active")break;if(s<=o)throw Error("All content has been uploaded, but the upload status is not finalized.")}return a}async function ih(e){return{size:e.size,type:e.type}}function ip(e){return new Promise(t=>setTimeout(t,e))}class im{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await ti.stat(e)).size,t.type=this.inferMimeType(e),t):await ih(e)}async upload(e,t,r){return"string"==typeof e?await this.uploadFileFromPath(e,t,r):iu(e,t,r)}async uploadToFileSearchStore(e,t,r){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r):ic(e,t,r)}inferMimeType(e){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async uploadFileToFileSearchStoreFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async uploadFileFromPathInternal(e,t,r){var n,i;let s,o=0,a=0,l=new tm(new Response),u="upload",c=tl.basename(e);try{if(!(s=await ti.open(e,"r")))throw Error("Failed to open file");for(o=(await s.stat()).size;a<o;){let e=Math.min(8388608,o-a);a+e>=o&&(u+=", finalize");let d=new Uint8Array(e),{bytesRead:h}=await s.read(d,0,e,a);if(h!==e)throw Error(`Failed to read ${e} bytes from file at offset ${a}. bytes actually read: ${h}`);let p=new Blob([d]),f=0,m=1e3;for(;f<3&&(null==(n=null==(l=await r.request({path:"",body:p,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":u,"X-Goog-Upload-Offset":String(a),"Content-Length":String(h),"X-Goog-Upload-File-Name":c}}}))?void 0:l.headers)||!n[il]);)f++,await ip(m),m*=2;if(a+=h,(null==(i=null==l?void 0:l.headers)?void 0:i[il])!=="active")break;if(o<=a)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}finally{s&&await s.close()}}}class ig{get interactions(){if(void 0!==this._interactions)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");let e=this.httpOptions;(null==e?void 0:e.extraBody)&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");let t=new n3({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==e?void 0:e.timeout});return this._interactions=t.interactions,this._interactions}constructor(e){var t,r,n,o,a,l,u;let c,d;if((e.project||e.location)&&e.apiKey)throw Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=null!=(r=null!=(t=e.vertexai)?t:void 0!==(u=iy("GOOGLE_GENAI_USE_VERTEXAI"))&&"true"===u.toLowerCase())&&r;let h=(c=iy("GOOGLE_API_KEY"),d=iy("GEMINI_API_KEY"),c&&d&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),c||d||void 0),p=iy("GOOGLE_CLOUD_PROJECT"),f=iy("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(n=e.apiKey)?n:h,this.project=null!=(o=e.project)?o:p,this.location=null!=(a=e.location)?a:f,e.vertexai&&((null==(l=e.googleAuthOptions)?void 0:l.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(p||f)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&h?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(p||f)&&h&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));let m=function(e,t,r,n){return(null==e?void 0:e.baseUrl)?e.baseUrl:t?null!=s?s:r:null!=i?i:n}(e.httpOptions,e.vertexai,iy("GOOGLE_VERTEX_BASE_URL"),iy("GOOGLE_GEMINI_BASE_URL"));m&&(e.httpOptions?e.httpOptions.baseUrl=m:e.httpOptions={baseUrl:m}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let g=new n9({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new rJ({auth:g,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new im,downloader:new n7}),this.models=new r9(this.apiClient),this.live=new r1(this.apiClient,g,new it),this.batches=new rf(this.apiClient),this.chats=new rA(this.models,this.apiClient),this.caches=new rg(this.apiClient),this.files=new rO(this.apiClient),this.operations=new r7(this.apiClient),this.authTokens=new ne(this.apiClient),this.tunings=new ia(this.apiClient),this.fileSearchStores=new nr(this.apiClient)}}function iy(e){var t,r,n;return null!=(n=null==(r=null==(t=null==process?void 0:process.env)?void 0:t[e])?void 0:r.trim())?n:void 0}var i_=e.i(405898),iE=e.i(261829),iv=e.i(983598),ib=e.i(999617),iw=e.i(798003),iA=e.i(459398),iS=e.i(50377),iT=e.i(93716),iO=e.i(630166),iI=e.i(115851);let iC=(0,iS.f)("ai:gemini");e.s(["f",0,class{ai;modelName;baseUrl;constructor(e){let t=e?.apiKey,r=e?.baseUrl;if(!t)throw Error("AI_AUTH_ERROR: GOOGLE_API_KEY is required for Gemini provider");this.ai=new ig({apiKey:t,httpOptions:r?{baseUrl:r}:void 0}),this.modelName=e?.model||"gemini-2.0-flash",this.baseUrl=r||"https://generativelanguage.googleapis.com",iC.info({provider:"Gemini",model:this.modelName,baseUrl:this.baseUrl,apiKeyPrefix:t.substring(0,8)+"..."},"AI Provider initialized")}async retryOperation(e,t=3){let r;for(let n=1;n<=t;n++)try{return await e()}catch(s){r=s;let e=s instanceof Error?s.message.toLowerCase():String(s);if(!(e.includes("fetch failed")||e.includes("network")||e.includes("connect")||e.includes("503")||e.includes("502")||e.includes("504")||e.includes("overloaded")||e.includes("timeout")||e.includes("etimedout")||e.includes("enotfound")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("unavailable"))||n===t)throw s;let i=1e3*Math.pow(2,n-1);iC.warn({attempt:n,maxRetries:t,error:e,nextRetryDelayMs:i},"Gemini operation failed, retrying..."),await new Promise(e=>setTimeout(e,i))}throw r}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){iC.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),o=this.extractTag(e,"requires_image"),a=this.extractTag(e,"wrong_answer_text")||"",l=this.extractTag(e,"mistake_analysis")||"",u=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw iC.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let c="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(c=i);let d=[];s&&(d=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let h=o?.toLowerCase().trim()==="true",p=(0,iO.f)(u,a),f={questionText:t,answerText:r,analysis:n,wrongAnswerText:a,mistakeAnalysis:l,mistakeStatus:p,subject:c,knowledgePoints:d,requiresImage:h,difficultyStars:(0,ib.B)(this.extractTag(e,"difficulty_stars")),...(0,ib.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},m=(0,ib.u)(f);return m.success?(iC.debug("Validated successfully via XML tags"),m.data):(iC.warn({validationError:m.error.format()},"Schema validation warning"),f)}async analyzeImage(e,t="image/jpeg",r="zh",n,i,s,o){let a=(0,iw.b)(),l=o?{candidateTags:o}:await (0,iA.i)(i,n),u=(0,i_.generateAnalyzePrompt)(r,n,i,{customTemplate:a.prompts?.analyze,...l},s);iC.box("🔍 AI Image Analysis Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,imageSize:`${e.length} bytes`,mimeType:t,model:this.modelName,language:r,grade:n||"all"}),iC.box("📝 Full Prompt",u);try{let r={model:this.modelName,contents:[{text:u},{inlineData:{data:`[...${e.length} bytes base64 data...]`,mimeType:t}}]};iC.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(r,null,2));let n=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:u},{inlineData:{data:e,mimeType:t}}]}));iC.box("📦 Full API Response Metadata",{usageMetadata:n.usageMetadata});let i=n.text||"";if(iC.box("🤖 AI Raw Response",i),!i)throw Error(n.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");let s=this.parseResponse(i);return iC.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw iC.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,r="zh",n="medium",i,s){let o=(0,iw.b)(),a=(0,i_.generateSimilarQuestionPrompt)(r,e,t,n,{customTemplate:o.prompts?.similar,originalFigureSvg:s},i);iC.box("🎯 Generate Similar Question Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:n,language:r}),iC.box("📝 Full Prompt",a);try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:a})),t=e.text||"";if(iC.box("🤖 AI Raw Response",t),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");let r=this.parseResponse(t);return iC.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,iI.f)(r)}catch(e){throw iC.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,o){let{generateReanswerPrompt:a}=await e.A(730249),l=a(r,t,n,{candidateTags:o},s);iC.info({provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),iC.debug({prompt:l},"Full prompt");try{let e;if(i){let t=i.replace(/^data:image\/\w+;base64,/,"");e=[{text:l},{inlineData:{mimeType:"image/jpeg",data:t}}]}else e=l;let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:e})),r=t.text||"";if(iC.debug({rawResponse:r},"AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",o=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),a=this.extractTag(r,"wrong_answer_text")||"",u=this.extractTag(r,"mistake_analysis")||"",c=(0,iO.f)(this.extractTag(r,"mistake_status"),a);return iC.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:o,wrongAnswerText:a,mistakeAnalysis:u,mistakeStatus:c,subject:(0,ib.G)(this.extractTag(r,"subject")),difficultyStars:(0,ib.B)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,r,n){let i=(0,i_.generateGeogebraPrompt)(e,t,r,n);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:i})),t=e.text||"";if(iC.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let s=r.indexOf("{"),o=r.lastIndexOf("}");-1!==s&&-1!==o&&(r=r.substring(s,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,i_.generateMasteryPrompt)(e);iC.info({provider:"Gemini",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),r=e.text||"";if(iC.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");return(0,ib.r)(r)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,i_.generateTagSuggestPrompt)(e);iC.info({provider:"Gemini",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),n=r.text||"";if(iC.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");return(0,ib.K)(n,e.allowedTags)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,r){let n=(0,i_.generateFigurePrompt)(r);iC.info({provider:"Gemini",model:this.modelName,imageSize:e.length},"Figure SVG Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:n},{inlineData:{data:e,mimeType:t}}]})),i=r.text||"";if(iC.debug({rawResponse:i},"Figure SVG AI raw response"),!i)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");return(0,ib.t)(this.extractTag(i,"has_figure"),this.extractTag(i,"figure_svg"))}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,i_.generateLatexFixPrompt)(e);iC.info({provider:"Gemini",model:this.modelName,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:t},{text:"请修复上述内容中的 LaTeX 语法。"}]})),n=r.text||"";if(iC.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");return(0,iv.f)(n,e)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,r,n,i="zh"){let s=(0,i_.generateSvgAnimationPrompt)(e,t,r,n,i);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"SVG Animation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:s},{text:i_.SVG_ANIMATION_REQUEST[i]}]})),t=e.text||"";if(iC.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.z:"Empty response from AI");return(0,iE.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(iC.error({error:e},"Gemini error"),e instanceof Error){if(e.message===iT.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],893963)},592938,e=>{e.i(889228);var t=e.i(88045),t=t,r=e.i(405898),n=e.i(261829),i=e.i(983598),s=e.i(798003),o=e.i(999617),a=e.i(459398),l=e.i(50377),u=e.i(93716),c=e.i(630166),d=e.i(115851);let h=(0,l.f)("ai:openai"),p="gpt-6.1-sol";e.s(["a",0,p,"F",0,class{openai;model;baseURL;apiKey;isLongCat;constructor(e){let r=e?.apiKey,n=e?.baseUrl;if(!r)throw Error("AI_AUTH_ERROR: OPENAI_API_KEY is required for OpenAI provider");this.openai=new t.f({apiKey:r,baseURL:n||void 0,defaultHeaders:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.model=e?.model||p,this.baseURL=n||"https://api.openai.com/v1",this.apiKey=r,this.isLongCat=this.baseURL.includes("longcat.chat"),h.info({provider:"OpenAI",model:this.model,baseURL:this.baseURL,apiKeyPrefix:r.substring(0,8)+"..."},"AI Provider initialized")}adaptMessagesForLongCat(e){return e.map(e=>{if("string"==typeof e.content)return{...e,content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(e=>"image_url"===e.type?{type:"input_image",input_image:{data:[e.image_url.url],type:"url"}}:e);return{...e,content:t}}return e})}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r);if(-1===i)return null;let s=i+r.length,o=e.lastIndexOf(n);return -1===o&&"analysis"===t?(h.warn({tagName:t},"Tag was verified unclosed, treating as truncated and reading to end"),e.substring(s).trim()):-1===o||s>=o?null:e.substring(s,o).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.f)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.B)(this.extractTag(e,"difficulty_stars")),...(0,o.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.u)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.b)(),p=c?{candidateTags:c}:await (0,a.i)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r,n={model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,[...${e.length} bytes base64 data...]`}}]}],max_tokens:8192};if(h.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(n,null,2)),this.isLongCat){let n=this.adaptMessagesForLongCat([{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}]),i=await fetch(`${this.baseURL}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:n,max_tokens:8192})});if(!i.ok){let e=await i.text();throw h.error({status:i.status,body:e},"LongCat API error"),Error(`${i.status} status code (${e})`)}r=await i.json()}else r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let i=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",i),!i)throw Error("Empty response from AI");let s=this.parseResponse(i);return h.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.b)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
|
|
28
|
+
Original Question: "${e}"
|
|
29
|
+
Knowledge Points: ${t.join(", ")}
|
|
30
|
+
`;h.box("🎯 Generate Similar Question Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.f)(r)}catch(e){throw h.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,a){let{generateReanswerPrompt:l}=await e.A(730249),d=l(r,t,n,{candidateTags:a},s);h.info({provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),h.debug({prompt:d},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t={model:this.model,messages:[{role:"system",content:d.substring(0,200)+"..."},{role:"user",content:"string"==typeof e?e:"[包含图片的多模态消息]"}],max_tokens:8192};h.debug({requestParams:t},"Request parameters");let r=await (0,u.V)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:d},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(r)},"Full API response"),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"AI raw response"),!n)throw Error("Empty response from AI");let s=this.extractTag(n,"answer_text")||"",a=this.extractTag(n,"analysis")||"",l=(this.extractTag(n,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),p=this.extractTag(n,"wrong_answer_text")||"",f=this.extractTag(n,"mistake_analysis")||"",m=(0,c.f)(this.extractTag(n,"mistake_status"),p);return h.info("Reanswer parsed successfully"),{answerText:s,analysis:a,knowledgePoints:l,wrongAnswerText:p,mistakeAnalysis:f,mistakeStatus:m,subject:(0,o.G)(this.extractTag(n,"subject")),difficultyStars:(0,o.B)(this.extractTag(n,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.r)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.K)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"OpenAI",model:this.model,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.t)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"OpenAI",model:this.model,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.f)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s,o="zh"){let a=(0,r.generateSvgAnimationPrompt)(e,t,i,s,o);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:a},{role:"user",content:r.SVG_ANIMATION_REQUEST[o]}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"OpenAI error"),e instanceof Error){if(e.message===u.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],592938)}],233405,(e,t,r)=>{t.exports=e.x("child_process",()=>require("child_process"))},924868,(e,t,r)=>{t.exports=e.x("fs/promises",()=>require("fs/promises"))},188646,(e,t,r)=>{t.exports=e.x("node:stream/promises",()=>require("node:stream/promises"))},605365,(e,t,r)=>{t.exports=e.x("process",()=>require("process"))},688947,(e,t,r)=>{t.exports=e.x("stream",()=>require("stream"))},345905,(e,t,r)=>{!function(r){"use strict";var n,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,s=Math.ceil,o=Math.floor,a="[BigNumber Error] ",l=a+"Number primitive has more than 15 significant digits: ",u=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13];function c(e){var t=0|e;return e>0||e===t?t:t-1}function d(e){for(var t,r,n=1,i=e.length,s=e[0]+"";n<i;){for(r=14-(t=e[n++]+"").length;r--;t="0"+t);s+=t}for(i=s.length;48===s.charCodeAt(--i););return s.slice(0,i+1||1)}function h(e,t){var r,n,i=e.c,s=t.c,o=e.s,a=t.s,l=e.e,u=t.e;if(!o||!a)return null;if(r=i&&!i[0],n=s&&!s[0],r||n)return r?n?0:-a:o;if(o!=a)return o;if(r=o<0,n=l==u,!i||!s)return n?0:!i^r?1:-1;if(!n)return l>u^r?1:-1;for(a=(l=i.length)<(u=s.length)?l:u,o=0;o<a;o++)if(i[o]!=s[o])return i[o]>s[o]^r?1:-1;return l==u?0:l>u^r?1:-1}function p(e,t,r,n){if(e<t||e>r||e!==o(e))throw Error(a+(n||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function f(e){var t=e.c.length-1;return c(e.e/14)==t&&e.c[t]%2!=0}function m(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function g(e,t,r){var n,i;if(t<0){for(i=r+".";++t;i+=r);e=i+e}else if(n=e.length,++t>n){for(i=r,t-=n;--t;i+=r);e+=i}else t<n&&(e=e.slice(0,t)+"."+e.slice(t));return e}if((n=function e(t){var r,n,y,_,E,v,b,w,A,S=L.prototype={constructor:L,toString:null,valueOf:null},T=new L(1),O=20,I=4,C=-7,R=21,x=-1e7,k=1e7,N=!1,P=1,U=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",j=!0;function L(e,t){var r,n,s,a,u,c,d,h,f=this;if(!(f instanceof L))return new L(e,t);if(null==t){if(e&&!0===e._isBigNumber){f.s=e.s,!e.c||e.e>k?f.c=f.e=null:e.e<x?f.c=[f.e=0]:(f.e=e.e,f.c=e.c.slice());return}if((c="number"==typeof e)&&0*e==0){if(f.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,u=e;u>=10;u/=10,a++);a>k?f.c=f.e=null:(f.e=a,f.c=[e]);return}h=String(e)}else{if(!i.test(h=String(e)))return A(f,h,c);f.s=45==h.charCodeAt(0)?(h=h.slice(1),-1):1}(a=h.indexOf("."))>-1&&(h=h.replace(".","")),(u=h.search(/e/i))>0?(a<0&&(a=u),a+=+h.slice(u+1),h=h.substring(0,u)):a<0&&(a=h.length)}else{if(p(t,2,M.length,"Base"),10==t&&j)return $(f=new L(e),O+f.e+1,I);if(h=String(e),c="number"==typeof e){if(0*e!=0)return A(f,h,c,t);if(f.s=1/e<0?(h=h.slice(1),-1):1,L.DEBUG&&h.replace(/^0\.0*|\./,"").length>15)throw Error(l+e)}else f.s=45===h.charCodeAt(0)?(h=h.slice(1),-1):1;for(r=M.slice(0,t),a=u=0,d=h.length;u<d;u++)if(0>r.indexOf(n=h.charAt(u))){if("."==n){if(u>a){a=d;continue}}else if(!s&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){s=!0,u=-1,a=0;continue}return A(f,String(e),c,t)}c=!1,(a=(h=w(h,t,10,f.s)).indexOf("."))>-1?h=h.replace(".",""):a=h.length}for(u=0;48===h.charCodeAt(u);u++);for(d=h.length;48===h.charCodeAt(--d););if(h=h.slice(u,++d)){if(d-=u,c&&L.DEBUG&&d>15&&(e>0x1fffffffffffff||e!==o(e)))throw Error(l+f.s*e);if((a=a-u-1)>k)f.c=f.e=null;else if(a<x)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%14,a<0&&(u+=14),u<d){for(u&&f.c.push(+h.slice(0,u)),d-=14;u<d;)f.c.push(+h.slice(u,u+=14));u=14-(h=h.slice(u)).length}else u-=d;for(;u--;h+="0");f.c.push(+h)}}else f.c=[f.e=0]}function F(e,t,r,n){var i,s,o,a,l;if(null==r?r=I:p(r,0,8),!e.c)return e.toString();if(i=e.c[0],o=e.e,null==t)l=d(e.c),l=1==n||2==n&&(o<=C||o>=R)?m(l,o):g(l,o,"0");else if(s=(e=$(new L(e),t,r)).e,a=(l=d(e.c)).length,1==n||2==n&&(t<=s||s<=C)){for(;a<t;l+="0",a++);l=m(l,s)}else if(t-=o+(2===n&&s>o),l=g(l,s,"0"),s+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=s-a)>0)for(s+1==a&&(l+=".");t--;l+="0");return e.s<0&&i?"-"+l:l}function G(e,t){for(var r,n,i=1,s=new L(e[0]);i<e.length;i++)(n=new L(e[i])).s&&(r=h(s,n))!==t&&(0!==r||s.s!==t)||(s=n);return s}function q(e,t,r){for(var n=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,n++);return(r=n+14*r-1)>k?e.c=e.e=null:r<x?e.c=[e.e=0]:(e.e=r,e.c=t),e}function $(e,t,r,n){var i,a,l,c,d,h,p,f=e.c;if(f){e:{for(i=1,c=f[0];c>=10;c/=10,i++);if((a=t-i)<0)a+=14,l=t,p=o((d=f[h=0])/u[i-l-1]%10);else if((h=s((a+1)/14))>=f.length)if(n){for(;f.length<=h;f.push(0));d=p=0,i=1,a%=14,l=a-14+1}else break e;else{for(d=c=f[h],i=1;c>=10;c/=10,i++);a%=14,p=(l=a-14+i)<0?0:o(d/u[i-l-1]%10)}if(n=n||t<0||null!=f[h+1]||(l<0?d:d%u[i-l-1]),n=r<4?(p||n)&&(0==r||r==(e.s<0?3:2)):p>5||5==p&&(4==r||n||6==r&&(a>0?l>0?d/u[i-l]:0:f[h-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=u[(14-t%14)%14],e.e=-t||0):f[0]=e.e=0,e;if(0==a?(f.length=h,c=1,h--):(f.length=h+1,c=u[14-a],f[h]=l>0?o(d/u[i-l]%u[l])*c:0),n)for(;;)if(0==h){for(a=1,l=f[0];l>=10;l/=10,a++);for(l=f[0]+=c,c=1;l>=10;l/=10,c++);a!=c&&(e.e++,1e14==f[0]&&(f[0]=1));break}else{if(f[h]+=c,1e14!=f[h])break;f[h--]=0,c=1}for(a=f.length;0===f[--a];f.pop());}e.e>k?e.c=e.e=null:e.e<x&&(e.c=[e.e=0])}return e}function B(e){var t,r=e.e;return null===r?e.toString():(t=d(e.c),t=r<=C||r>=R?m(t,r):g(t,r,"0"),e.s<0?"-"+t:t)}return L.clone=e,L.ROUND_UP=0,L.ROUND_DOWN=1,L.ROUND_CEIL=2,L.ROUND_FLOOR=3,L.ROUND_HALF_UP=4,L.ROUND_HALF_DOWN=5,L.ROUND_HALF_EVEN=6,L.ROUND_HALF_CEIL=7,L.ROUND_HALF_FLOOR=8,L.EUCLID=9,L.config=L.set=function(e){var t,r;if(null!=e)if("object"==typeof e){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(p(r=e[t],0,1e9,t),O=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(p(r=e[t],0,8,t),I=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(p(r[0],-1e9,0,t),p(r[1],0,1e9,t),C=r[0],R=r[1]):(p(r,-1e9,1e9,t),C=-(R=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)p(r[0],-1e9,-1,t),p(r[1],1,1e9,t),x=r[0],k=r[1];else if(p(r,-1e9,1e9,t),r)x=-(k=r<0?-r:r);else throw Error(a+t+" cannot be zero: "+r);if(e.hasOwnProperty(t="CRYPTO"))if(!!(r=e[t])===r)if(r)if("u">typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=r;else throw N=!r,Error(a+"crypto unavailable");else N=r;else throw Error(a+t+" not true or false: "+r);if(e.hasOwnProperty(t="MODULO_MODE")&&(p(r=e[t],0,9,t),P=r),e.hasOwnProperty(t="POW_PRECISION")&&(p(r=e[t],0,1e9,t),U=r),e.hasOwnProperty(t="FORMAT"))if("object"==typeof(r=e[t]))D=r;else throw Error(a+t+" not an object: "+r);if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(a+t+" invalid: "+r);j="0123456789"==r.slice(0,10),M=r}}else throw Error(a+"Object expected: "+e);return{DECIMAL_PLACES:O,ROUNDING_MODE:I,EXPONENTIAL_AT:[C,R],RANGE:[x,k],CRYPTO:N,MODULO_MODE:P,POW_PRECISION:U,FORMAT:D,ALPHABET:M}},L.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!L.DEBUG)return!0;var t,r,n=e.c,i=e.e,s=e.s;e:if("[object Array]"==({}).toString.call(n)){if((1===s||-1===s)&&i>=-1e9&&i<=1e9&&i===o(i)){if(0===n[0]){if(0===i&&1===n.length)return!0;break e}if((t=(i+1)%14)<1&&(t+=14),String(n[0]).length==t){for(t=0;t<n.length;t++)if((r=n[t])<0||r>=1e14||r!==o(r))break e;if(0!==r)return!0}}}else if(null===n&&null===i&&(null===s||1===s||-1===s))return!0;throw Error(a+"Invalid BigNumber: "+e)},L.maximum=L.max=function(){return G(arguments,-1)},L.minimum=L.min=function(){return G(arguments,1)},r=0x20000000000000*Math.random()&2097151?function(){return o(0x20000000000000*Math.random())}:function(){return(0x40000000*Math.random()|0)*8388608+(8388608*Math.random()|0)},L.random=function(e){var t,n,i,l,c,d=0,h=[],f=new L(T);if(null==e?e=O:p(e,0,1e9),l=s(e/14),N)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(l*=2));d<l;)(c=131072*t[d]+(t[d+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[d]=n[0],t[d+1]=n[1]):(h.push(c%1e14),d+=2);d=l/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(l*=7);d<l;)(c=(31&t[d])*0x1000000000000+0x10000000000*t[d+1]+0x100000000*t[d+2]+0x1000000*t[d+3]+(t[d+4]<<16)+(t[d+5]<<8)+t[d+6])>=9e15?crypto.randomBytes(7).copy(t,d):(h.push(c%1e14),d+=7);d=l/7}else throw N=!1,Error(a+"crypto unavailable");if(!N)for(;d<l;)(c=r())<9e15&&(h[d++]=c%1e14);for(l=h[--d],e%=14,l&&e&&(c=u[14-e],h[d]=o(l/c)*c);0===h[d];h.pop(),d--);if(d<0)h=[i=0];else{for(i=-1;0===h[0];h.splice(0,1),i-=14);for(d=1,c=h[0];c>=10;c/=10,d++);d<14&&(i-=14-d)}return f.e=i,f.c=h,f},L.sum=function(){for(var e=1,t=arguments,r=new L(t[0]);e<t.length;)r=r.plus(t[e++]);return r},w=function(){var e="0123456789";function t(e,t,r,n){for(var i,s,o=[0],a=0,l=e.length;a<l;){for(s=o.length;s--;o[s]*=t);for(o[0]+=n.indexOf(e.charAt(a++)),i=0;i<o.length;i++)o[i]>r-1&&(null==o[i+1]&&(o[i+1]=0),o[i+1]+=o[i]/r|0,o[i]%=r)}return o.reverse()}return function(r,n,i,s,o){var a,l,u,c,h,p,f,m,y=r.indexOf("."),_=O,E=I;for(y>=0&&(c=U,U=0,r=r.replace(".",""),p=(m=new L(n)).pow(r.length-y),U=c,m.c=t(g(d(p.c),p.e,"0"),10,i,e),m.e=m.c.length),u=c=(f=t(r,n,i,o?(a=M,e):(a=e,M))).length;0==f[--c];f.pop());if(!f[0])return a.charAt(0);if(y<0?--u:(p.c=f,p.e=u,p.s=s,f=(p=b(p,m,_,E,i)).c,h=p.r,u=p.e),y=f[l=u+_+1],c=i/2,h=h||l<0||null!=f[l+1],h=E<4?(null!=y||h)&&(0==E||E==(p.s<0?3:2)):y>c||y==c&&(4==E||h||6==E&&1&f[l-1]||E==(p.s<0?8:7)),l<1||!f[0])r=h?g(a.charAt(1),-_,a.charAt(0)):a.charAt(0);else{if(f.length=l,h)for(--i;++f[--l]>i;)f[l]=0,l||(++u,f=[1].concat(f));for(c=f.length;!f[--c];);for(y=0,r="";y<=c;r+=a.charAt(f[y++]));r=g(r,u,a.charAt(0))}return r}}(),b=function(){function e(e,t,r){var n,i,s,o,a=0,l=e.length,u=t%1e7,c=t/1e7|0;for(e=e.slice();l--;)n=c*(s=e[l]%1e7)+(o=e[l]/1e7|0)*u,a=((i=u*s+n%1e7*1e7+a)/r|0)+(n/1e7|0)+c*o,e[l]=i%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var i,s;if(r!=n)s=r>n?1:-1;else for(i=s=0;i<r;i++)if(e[i]!=t[i]){s=e[i]>t[i]?1:-1;break}return s}function r(e,t,r,n){for(var i=0;r--;)e[r]-=i,i=+(e[r]<t[r]),e[r]=i*n+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(n,i,s,a,l){var u,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I=n.s==i.s?1:-1,C=n.c,R=i.c;if(!C||!C[0]||!R||!R[0])return new L(!n.s||!i.s||(C?R&&C[0]==R[0]:!R)?0/0:C&&0==C[0]||!R?0*I:I/0);for(_=(y=new L(I)).c=[],I=s+(d=n.e-i.e)+1,l||(l=1e14,d=c(n.e/14)-c(i.e/14),I=I/14|0),h=0;R[h]==(C[h]||0);h++);if(R[h]>(C[h]||0)&&d--,I<0)_.push(1),p=!0;else{for(A=C.length,T=R.length,h=0,I+=2,(f=o(l/(R[0]+1)))>1&&(R=e(R,f,l),C=e(C,f,l),T=R.length,A=C.length),w=T,v=(E=C.slice(0,T)).length;v<T;E[v++]=0);O=[0].concat(O=R.slice()),S=R[0],R[1]>=l/2&&S++;do{if(f=0,(u=t(R,E,T,v))<0){if(b=E[0],T!=v&&(b=b*l+(E[1]||0)),(f=o(b/S))>1)for(f>=l&&(f=l-1),g=(m=e(R,f,l)).length,v=E.length;1==t(m,E,g,v);)f--,r(m,T<g?O:R,g,l),g=m.length,u=1;else 0==f&&(u=f=1),g=(m=R.slice()).length;if(g<v&&(m=[0].concat(m)),r(E,m,v,l),v=E.length,-1==u)for(;1>t(R,E,T,v);)f++,r(E,T<v?O:R,v,l),v=E.length}else 0===u&&(f++,E=[0]);_[h++]=f,E[0]?E[v++]=C[w]||0:(E=[C[w]],v=1)}while((w++<A||null!=E[0])&&I--)p=null!=E[0],_[0]||_.splice(0,1)}if(1e14==l){for(h=1,I=_[0];I>=10;I/=10,h++);$(y,s+(y.e=h+14*d-1)+1,a,p)}else y.e=d,y.r=+p;return y}}(),n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,_=/^\.([^.]+)$/,E=/^-?(Infinity|NaN)$/,v=/^\s*\+(?=[\w.])|^\s+|\s+$/g,A=function(e,t,r,i){var s,o=r?t:t.replace(v,"");if(E.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!r&&(o=o.replace(n,function(e,t,r){return s="x"==(r=r.toLowerCase())?16:"b"==r?2:8,i&&i!=s?e:t}),i&&(s=i,o=o.replace(y,"$1").replace(_,"0.$1")),t!=o))return new L(o,s);if(L.DEBUG)throw Error(a+"Not a"+(i?" base "+i:"")+" number: "+t);e.s=null}e.c=e.e=null},S.absoluteValue=S.abs=function(){var e=new L(this);return e.s<0&&(e.s=1),e},S.comparedTo=function(e,t){return h(this,new L(e,t))},S.decimalPlaces=S.dp=function(e,t){var r,n,i;if(null!=e)return p(e,0,1e9),null==t?t=I:p(t,0,8),$(new L(this),e+this.e+1,t);if(!(r=this.c))return null;if(n=((i=r.length-1)-c(this.e/14))*14,i=r[i])for(;i%10==0;i/=10,n--);return n<0&&(n=0),n},S.dividedBy=S.div=function(e,t){return b(this,new L(e,t),O,I)},S.dividedToIntegerBy=S.idiv=function(e,t){return b(this,new L(e,t),0,1)},S.exponentiatedBy=S.pow=function(e,t){var r,n,i,l,u,c,d,h,p,m=this;if((e=new L(e)).c&&!e.isInteger())throw Error(a+"Exponent not an integer: "+B(e));if(null!=t&&(t=new L(t)),c=e.e>14,!m.c||!m.c[0]||1==m.c[0]&&!m.e&&1==m.c.length||!e.c||!e.c[0])return p=new L(Math.pow(+B(m),c?e.s*(2-f(e)):+B(e))),t?p.mod(t):p;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new L(0/0);(n=!d&&m.isInteger()&&t.isInteger())&&(m=m.mod(t))}else{if(e.e>9&&(m.e>0||m.e<-1||(0==m.e?m.c[0]>1||c&&m.c[1]>=24e7:m.c[0]<8e13||c&&m.c[0]<=9999975e7)))return l=m.s<0&&f(e)?-0:0,m.e>-1&&(l=1/l),new L(d?1/l:l);U&&(l=s(U/14+2))}for(c?(r=new L(.5),d&&(e.s=1),h=f(e)):h=(i=Math.abs(+B(e)))%2,p=new L(T);;){if(h){if(!(p=p.times(m)).c)break;l?p.c.length>l&&(p.c.length=l):n&&(p=p.mod(t))}if(i){if(0===(i=o(i/2)))break;h=i%2}else if($(e=e.times(r),e.e+1,1),e.e>14)h=f(e);else{if(0==(i=+B(e)))break;h=i%2}m=m.times(m),l?m.c&&m.c.length>l&&(m.c.length=l):n&&(m=m.mod(t))}return n?p:(d&&(p=T.div(p)),t?p.mod(t):l?$(p,U,I,u):p)},S.integerValue=function(e){var t=new L(this);return null==e?e=I:p(e,0,8),$(t,t.e+1,e)},S.isEqualTo=S.eq=function(e,t){return 0===h(this,new L(e,t))},S.isFinite=function(){return!!this.c},S.isGreaterThan=S.gt=function(e,t){return h(this,new L(e,t))>0},S.isGreaterThanOrEqualTo=S.gte=function(e,t){return 1===(t=h(this,new L(e,t)))||0===t},S.isInteger=function(){return!!this.c&&c(this.e/14)>this.c.length-2},S.isLessThan=S.lt=function(e,t){return 0>h(this,new L(e,t))},S.isLessThanOrEqualTo=S.lte=function(e,t){return -1===(t=h(this,new L(e,t)))||0===t},S.isNaN=function(){return!this.s},S.isNegative=function(){return this.s<0},S.isPositive=function(){return this.s>0},S.isZero=function(){return!!this.c&&0==this.c[0]},S.minus=function(e,t){var r,n,i,s,o=this.s;if(t=(e=new L(e,t)).s,!o||!t)return new L(0/0);if(o!=t)return e.s=-t,this.plus(e);var a=this.e/14,l=e.e/14,u=this.c,d=e.c;if(!a||!l){if(!u||!d)return u?(e.s=-t,e):new L(d?this:0/0);if(!u[0]||!d[0])return d[0]?(e.s=-t,e):new L(u[0]?this:3==I?-0:0)}if(a=c(a),l=c(l),u=u.slice(),o=a-l){for((s=o<0)?(o=-o,i=u):(l=a,i=d),i.reverse(),t=o;t--;i.push(0));i.reverse()}else for(n=(s=(o=u.length)<(t=d.length))?o:t,o=t=0;t<n;t++)if(u[t]!=d[t]){s=u[t]<d[t];break}if(s&&(i=u,u=d,d=i,e.s=-e.s),(t=(n=d.length)-(r=u.length))>0)for(;t--;u[r++]=0);for(t=1e14-1;n>o;){if(u[--n]<d[n]){for(r=n;r&&!u[--r];u[r]=t);--u[r],u[n]+=1e14}u[n]-=d[n]}for(;0==u[0];u.splice(0,1),--l);return u[0]?q(e,u,l):(e.s=3==I?-1:1,e.c=[e.e=0],e)},S.modulo=S.mod=function(e,t){var r,n;return(e=new L(e,t),this.c&&e.s&&(!e.c||e.c[0]))?e.c&&(!this.c||this.c[0])?(9==P?(n=e.s,e.s=1,r=b(this,e,0,3),e.s=n,r.s*=n):r=b(this,e,0,P),(e=this.minus(r.times(e))).c[0]||1!=P||(e.s=this.s),e):new L(this):new L(0/0)},S.multipliedBy=S.times=function(e,t){var r,n,i,s,o,a,l,u,d,h,p,f,m,g=this.c,y=(e=new L(e,t)).c;if(!g||!y||!g[0]||!y[0])return this.s&&e.s&&(!g||g[0]||y)&&(!y||y[0]||g)?(e.s*=this.s,g&&y?(e.c=[0],e.e=0):e.c=e.e=null):e.c=e.e=e.s=null,e;for(n=c(this.e/14)+c(e.e/14),e.s*=this.s,(l=g.length)<(h=y.length)&&(m=g,g=y,y=m,i=l,l=h,h=i),i=l+h,m=[];i--;m.push(0));for(i=h;--i>=0;){for(r=0,p=y[i]%1e7,f=y[i]/1e7|0,s=i+(o=l);s>i;)a=f*(u=g[--o]%1e7)+(d=g[o]/1e7|0)*p,r=((u=p*u+a%1e7*1e7+m[s]+r)/1e14|0)+(a/1e7|0)+f*d,m[s--]=u%1e14;m[s]=r}return r?++n:m.splice(0,1),q(e,m,n)},S.negated=function(){var e=new L(this);return e.s=-e.s||null,e},S.plus=function(e,t){var r,n=this.s;if(t=(e=new L(e,t)).s,!n||!t)return new L(0/0);if(n!=t)return e.s=-t,this.minus(e);var i=this.e/14,s=e.e/14,o=this.c,a=e.c;if(!i||!s){if(!o||!a)return new L(n/0);if(!o[0]||!a[0])return a[0]?e:new L(o[0]?this:0*n)}if(i=c(i),s=c(s),o=o.slice(),n=i-s){for(n>0?(s=i,r=a):(n=-n,r=o),r.reverse();n--;r.push(0));r.reverse()}for((n=o.length)-(t=a.length)<0&&(r=a,a=o,o=r,t=n),n=0;t;)n=(o[--t]=o[t]+a[t]+n)/1e14|0,o[t]=1e14===o[t]?0:o[t]%1e14;return n&&(o=[n].concat(o),++s),q(e,o,s)},S.precision=S.sd=function(e,t){var r,n,i;if(null!=e&&!!e!==e)return p(e,1,1e9),null==t?t=I:p(t,0,8),$(new L(this),e,t);if(!(r=this.c))return null;if(n=14*(i=r.length-1)+1,i=r[i]){for(;i%10==0;i/=10,n--);for(i=r[0];i>=10;i/=10,n++);}return e&&this.e+1>n&&(n=this.e+1),n},S.shiftedBy=function(e){return p(e,-0x1fffffffffffff,0x1fffffffffffff),this.times("1e"+e)},S.squareRoot=S.sqrt=function(){var e,t,r,n,i,s=this.c,o=this.s,a=this.e,l=O+4,u=new L("0.5");if(1!==o||!s||!s[0])return new L(!o||o<0&&(!s||s[0])?0/0:s?this:1/0);if(0==(o=Math.sqrt(+B(this)))||1/0==o?(((t=d(s)).length+a)%2==0&&(t+="0"),o=Math.sqrt(+t),a=c((a+1)/2)-(a<0||a%2),r=new L(t=1/0==o?"5e"+a:(t=o.toExponential()).slice(0,t.indexOf("e")+1)+a)):r=new L(o+""),r.c[0]){for((o=(a=r.e)+l)<3&&(o=0);;)if(i=r,r=u.times(i.plus(b(this,i,l,1))),d(i.c).slice(0,o)===(t=d(r.c)).slice(0,o)){if(r.e<a&&--o,"9999"!=(t=t.slice(o-3,o+1))&&(n||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||($(r,r.e+O+2,1),e=!r.times(r).eq(this));break}if(!n&&($(i,i.e+O+2,0),i.times(i).eq(this))){r=i;break}l+=4,o+=4,n=1}}return $(r,r.e+O+1,I,e)},S.toExponential=function(e,t){return null!=e&&(p(e,0,1e9),e++),F(this,e,t,1)},S.toFixed=function(e,t){return null!=e&&(p(e,0,1e9),e=e+this.e+1),F(this,e,t)},S.toFormat=function(e,t,r){var n;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=D;else if("object"!=typeof r)throw Error(a+"Argument not an object: "+r);if(n=this.toFixed(e,t),this.c){var i,s=n.split("."),o=+r.groupSize,l=+r.secondaryGroupSize,u=r.groupSeparator||"",c=s[0],d=s[1],h=this.s<0,p=h?c.slice(1):c,f=p.length;if(l&&(i=o,o=l,l=i,f-=i),o>0&&f>0){for(i=f%o||o,c=p.substr(0,i);i<f;i+=o)c+=u+p.substr(i,o);l>0&&(c+=u+p.slice(i)),h&&(c="-"+c)}n=d?c+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?d.replace(RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):d):c}return(r.prefix||"")+n+(r.suffix||"")},S.toFraction=function(e){var t,r,n,i,s,o,l,c,h,p,f,m,g=this.c;if(null!=e&&(!(l=new L(e)).isInteger()&&(l.c||1!==l.s)||l.lt(T)))throw Error(a+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+B(l));if(!g)return new L(this);for(t=new L(T),h=r=new L(T),n=c=new L(T),m=d(g),s=t.e=m.length-this.e-1,t.c[0]=u[(o=s%14)<0?14+o:o],e=!e||l.comparedTo(t)>0?s>0?t:h:l,o=k,k=1/0,l=new L(m),c.c[0]=0;p=b(l,t,0,1),1!=(i=r.plus(p.times(n))).comparedTo(e);)r=n,n=i,h=c.plus(p.times(i=h)),c=i,t=l.minus(p.times(i=t)),l=i;return i=b(e.minus(r),n,0,1),c=c.plus(i.times(h)),r=r.plus(i.times(n)),c.s=h.s=this.s,s*=2,f=1>b(h,n,s,I).minus(this).abs().comparedTo(b(c,r,s,I).minus(this).abs())?[h,n]:[c,r],k=o,f},S.toNumber=function(){return+B(this)},S.toPrecision=function(e,t){return null!=e&&p(e,1,1e9),F(this,e,t,2)},S.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=C||i>=R?m(d(r.c),i):g(d(r.c),i,"0"):10===e&&j?t=g(d((r=$(new L(r),O+i+1,I)).c),r.e,"0"):(p(e,2,M.length,"Base"),t=w(g(d(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},S.valueOf=S.toJSON=function(){return B(this)},S._isBigNumber=!0,null!=t&&L.set(t),L}()).default=n.BigNumber=n,"function"==typeof define&&define.amd)e.r,void 0!==n&&e.v(n);else t.exports?t.exports=n:(r||(r="u">typeof self&&self?self:window),r.BigNumber=n)}(e.e)},73827,(e,t,r)=>{t.exports={name:"gaxios",version:"7.1.3",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2",rimraf:"^5.0.1"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}},357660,(e,t,r)=>{t.exports={name:"google-auth-library",version:"10.5.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^8.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"echo 'disabled until linkinator is fixed'","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}},301158,(e,t,r)=>{var n=e.r(364349).stringify,i=e.r(767104);t.exports=function(e){return{parse:i(e),stringify:n}},t.exports.parse=i(),t.exports.stringify=n},767104,(e,t,r)=>{var n=null;let i=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,s=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(t){"use strict";var r={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=t){if(!0===t.strict&&(r.strict=!0),!0===t.storeAsString&&(r.storeAsString=!0),r.alwaysParseAsBig=!0===t.alwaysParseAsBig&&t.alwaysParseAsBig,r.useNativeBigInt=!0===t.useNativeBigInt&&t.useNativeBigInt,void 0!==t.constructorAction)if("error"===t.constructorAction||"ignore"===t.constructorAction||"preserve"===t.constructorAction)r.constructorAction=t.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(void 0!==t.protoAction)if("error"===t.protoAction||"ignore"===t.protoAction||"preserve"===t.protoAction)r.protoAction=t.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var o,a,l,u,c={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},d=function(e){throw{name:"SyntaxError",message:e,at:o,text:l}},h=function(e){return e&&e!==a&&d("Expected '"+e+"' instead of '"+a+"'"),a=l.charAt(o),o+=1,a},p=function(){var t,i="";for("-"===a&&(i="-",h("-"));a>="0"&&a<="9";)i+=a,h();if("."===a)for(i+=".";h()&&a>="0"&&a<="9";)i+=a;if("e"===a||"E"===a)for(i+=a,h(),("-"===a||"+"===a)&&(i+=a,h());a>="0"&&a<="9";)i+=a,h();if(isFinite(t=+i))return(null==n&&(n=e.r(345905)),i.length>15)?r.storeAsString?i:r.useNativeBigInt?BigInt(i):new n(i):r.alwaysParseAsBig?r.useNativeBigInt?BigInt(t):new n(t):t;d("Bad number")},f=function(){var e,t,r,n="";if('"'===a)for(var i=o;h();){if('"'===a)return o-1>i&&(n+=l.substring(i,o-1)),h(),n;if("\\"===a){if(o-1>i&&(n+=l.substring(i,o-1)),h(),"u"===a){for(t=0,r=0;t<4&&isFinite(e=parseInt(h(),16));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else if("string"==typeof c[a])n+=c[a];else break;i=o}}d("Bad string")},m=function(){for(;a&&a<=" ";)h()},g=function(){switch(a){case"t":return h("t"),h("r"),h("u"),h("e"),!0;case"f":return h("f"),h("a"),h("l"),h("s"),h("e"),!1;case"n":return h("n"),h("u"),h("l"),h("l"),null}d("Unexpected '"+a+"'")},y=function(){var e=[];if("["===a){if(h("["),m(),"]"===a)return h("]"),e;for(;a;){if(e.push(u()),m(),"]"===a)return h("]"),e;h(","),m()}}d("Bad array")},_=function(){var e,t=Object.create(null);if("{"===a){if(h("{"),m(),"}"===a)return h("}"),t;for(;a;){if(e=f(),m(),h(":"),!0===r.strict&&Object.hasOwnProperty.call(t,e)&&d('Duplicate key "'+e+'"'),!0===i.test(e)?"error"===r.protoAction?d("Object contains forbidden prototype property"):"ignore"===r.protoAction?u():t[e]=u():!0===s.test(e)?"error"===r.constructorAction?d("Object contains forbidden constructor property"):"ignore"===r.constructorAction?u():t[e]=u():t[e]=u(),m(),"}"===a)return h("}"),t;h(","),m()}}d("Bad object")};return u=function(){switch(m(),a){case"{":return _();case"[":return y();case'"':return f();case"-":return p();default:return a>="0"&&a<="9"?p():g()}},function(e,t){var r;return l=e+"",o=0,a=" ",r=u(),m(),a&&d("Syntax error"),"function"==typeof t?function e(r,n){var i,s=r[n];return s&&"object"==typeof s&&Object.keys(s).forEach(function(t){void 0!==(i=e(s,t))?s[t]=i:delete s[t]}),t.call(r,n,s)}({"":r},""):r}}},364349,(e,t,r)=>{var n=e.r(345905),i=t.exports;!function(){"use strict";var e,t,r,s=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return s.lastIndex=0,s.test(e)?'"'+e.replace(s,function(e){var t=o[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}"function"!=typeof i.stringify&&(i.stringify=function(i,s,o){var l;if(e="",t="","number"==typeof o)for(l=0;l<o;l+=1)t+=" ";else"string"==typeof o&&(t=o);if(r=s,s&&"function"!=typeof s&&("object"!=typeof s||"number"!=typeof s.length))throw Error("JSON.stringify");return function i(s,o){var l,u,c,d,h,p=e,f=o[s],m=null!=f&&(f instanceof n||n.isBigNumber(f));switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(s)),"function"==typeof r&&(f=r.call(o,s,f)),typeof f){case"string":if(m)return f;return a(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":case"bigint":return String(f);case"object":if(!f)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(f)){for(d=f.length,l=0;l<d;l+=1)h[l]=i(l,f)||"null";return c=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+p+"]":"["+h.join(",")+"]",e=p,c}if(r&&"object"==typeof r)for(d=r.length,l=0;l<d;l+=1)"string"==typeof r[l]&&(c=i(u=r[l],f))&&h.push(a(u)+(e?": ":":")+c);else Object.keys(f).forEach(function(t){var r=i(t,f);r&&h.push(a(t)+(e?": ":":")+r)});return c=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+p+"}":"{"+h.join(",")+"}",e=p,c}}("",{"":i})})}()},757067,(e,t,r)=>{var n,i=e.r(223469).Buffer,s=e.r(254799),o=e.r(732955),a=e.r(224361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof s.createPublicKey;function d(e){if(!i.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw m(u)}function h(e){if(!i.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw m("key must be a string, a buffer or an object")}function p(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function m(e){var t=[].slice.call(arguments,1);return TypeError(a.format.bind(a,e).apply(null,t))}function g(e){var t;return t=e,i.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!i.isBuffer(e)){if("string"!=typeof e){if(!c||"object"!=typeof e||"secret"!==e.type||"function"!=typeof e.export)throw m(l)}}}(r),t=g(t);var n=s.createHmac("sha"+e,r);return p((n.update(t),n.digest("base64")))}}c&&(u+=" or a KeyObject",l+="or a KeyObject");var _="timingSafeEqual"in s?function(e,t){return e.byteLength===t.byteLength&&s.timingSafeEqual(e,t)}:function(t,r){return n||(n=e.r(922691)),n(t,r)};function E(e){return function(t,r,n){var s=y(e)(t,n);return _(i.from(r),i.from(s))}}function v(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign(r,"base64")))}}function b(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify(n,r,"base64")}}function w(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign({key:r,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function A(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify({key:n,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function S(e){var t=v(e);return function(){var r=t.apply(null,arguments);return o.derToJose(r,"ES"+e)}}function T(e){var t=b(e);return function(r,n,i){return t(r,n=o.joseToDer(n,"ES"+e).toString("base64"),i)}}function O(){return function(){return""}}function I(){return function(e,t){return""===t}}t.exports=function(e){var t=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!t)throw m('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var r=(t[1]||t[3]).toLowerCase(),n=t[2];return{sign:({hs:y,rs:v,ps:w,es:S,none:O})[r](n),verify:({hs:E,rs:b,ps:A,es:T,none:I})[r](n)}}},258184,(e,t,r)=>{var n=e.r(614743),i=e.r(148233);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=n.sign,r.verify=i.verify,r.decode=i.decode,r.isValid=i.isValid,r.createSign=function(e){return new n(e)},r.createVerify=function(e){return new i(e)}},41949,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(688947);function s(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(224361).inherits(s,i),s.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit("data",e)},s.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=s},614743,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361);function u(e,t){return n.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,n,i=e.header,o=e.payload,c=e.secret||e.privateKey,d=e.encoding,h=s(i.alg),p=(t=(t=d)||"utf8",r=u(a(i),"binary"),n=u(a(o),t),l.format("%s.%s",r,n)),f=h.sign(p,c);return l.format("%s.%s",p,f)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new i(e.payload),this.secret.once("close",(function(){!this.payload.writable&&this.readable&&this.sign()}).bind(this)),this.payload.once("close",(function(){!this.secret.writable&&this.readable&&this.sign()}).bind(this))}l.inherits(d,o),d.prototype.sign=function(){try{var e=c({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},576872,(e,t,r)=>{var n=e.r(500874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||n.isBuffer(e)?e.toString():JSON.stringify(e)}},148233,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=n.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function h(e){return u.test(e)&&!!c(e)}function p(e,t,r){if(!t){var n=Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var i=d(e=a(e)),o=e.split(".",2).join(".");return s(t).verify(o,i,r)}function f(e,t){if(t=t||{},!h(e=a(e)))return null;var r,i,s=c(e);if(!s)return null;var o=(r=r||"utf8",i=e.split(".")[1],n.from(i,"base64").toString(r));return("JWT"===s.typ||t.json)&&(o=JSON.parse(o,t.encoding)),{header:s,payload:o,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new i(e.signature),this.secret.once("close",(function(){!this.signature.writable&&this.readable&&this.verify()}).bind(this)),this.signature.once("close",(function(){!this.secret.writable&&this.readable&&this.verify()}).bind(this))}l.inherits(m,o),m.prototype.verify=function(){try{var e=p(this.signature.buffer,this.algorithm,this.key.buffer),t=f(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=f,m.isValid=h,m.verify=p,t.exports=m},223469,(e,t,r)=>{var n=e.r(500874),i=n.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(s(n,r),r.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(e,t,r){if("number"==typeof e)throw TypeError("Argument must not be a number");return i(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},o.allocUnsafe=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return n.SlowBuffer(e)}}];
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=%5Broot-of-the-server%5D__122xu-0xjk0q5._.js.map
|