@madarco/agentbox 0.21.0 → 0.22.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/CHANGELOG.md +109 -0
- package/README.md +32 -0
- package/dist/{_cloud-attach-U3QJO7IF.js → _cloud-attach-YH2SU75S.js} +5 -4
- package/dist/chunk-ALEYDWAO.js +2561 -0
- package/dist/chunk-ALEYDWAO.js.map +1 -0
- package/dist/{chunk-QKL7PCXQ.js → chunk-CDEJ2GQK.js} +836 -488
- package/dist/chunk-CDEJ2GQK.js.map +1 -0
- package/dist/{chunk-PX7G4PSI.js → chunk-GGWVTWJM.js} +65 -34
- package/dist/{chunk-PX7G4PSI.js.map → chunk-GGWVTWJM.js.map} +1 -1
- package/dist/chunk-KBVD2UUQ.js +1654 -0
- package/dist/chunk-KBVD2UUQ.js.map +1 -0
- package/dist/{chunk-IXQTUXWV.js → chunk-O2NDZQHN.js} +50 -52
- package/dist/{chunk-IXQTUXWV.js.map → chunk-O2NDZQHN.js.map} +1 -1
- package/dist/{dist-NWKOEWUJ.js → chunk-O67ZESNL.js} +1059 -109
- package/dist/chunk-O67ZESNL.js.map +1 -0
- package/dist/chunk-VBSRJG53.js +1241 -0
- package/dist/chunk-VBSRJG53.js.map +1 -0
- package/dist/{chunk-6JJIKCMY.js → chunk-W2FLHB54.js} +26 -56
- package/dist/chunk-W2FLHB54.js.map +1 -0
- package/dist/{chunk-YZVFGFYQ.js → chunk-YZXXBHWG.js} +1937 -2975
- package/dist/chunk-YZXXBHWG.js.map +1 -0
- package/dist/{dist-SAS4PIHA.js → dist-EJXUKIR7.js} +41 -36
- package/dist/{dist-UVQJ2BZJ.js → dist-LJHS4PTC.js} +112 -62
- package/dist/dist-LJHS4PTC.js.map +1 -0
- package/dist/dist-QBXEP4VY.js +89 -0
- package/dist/dist-QNV4H6NN.js +80 -0
- package/dist/dist-QNV4H6NN.js.map +1 -0
- package/dist/{dist-FMA5Y25B.js → dist-UR2DB2HT.js} +83 -9
- package/dist/dist-UR2DB2HT.js.map +1 -0
- package/dist/dist-YECTRVGD.js +102 -0
- package/dist/dist-YECTRVGD.js.map +1 -0
- package/dist/index.js +3243 -1448
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-MQHD3M5F-YYVVMTNJ.js → prepared-state-5FIGV4BE-BMUK63FD.js} +2 -2
- package/dist/prepared-state-5FIGV4BE-BMUK63FD.js.map +1 -0
- package/package.json +12 -5
- package/runtime/_shared/agentbox-checkpoint-cleanup +55 -0
- package/runtime/_shared/agentbox-codex-hooks.json +68 -0
- package/runtime/_shared/agentbox-dockerd-start +145 -0
- package/runtime/_shared/agentbox-open +28 -0
- package/runtime/_shared/agentbox-portless-trust +82 -0
- package/runtime/_shared/agentbox-setup-skill.md +317 -0
- package/runtime/_shared/agentbox-vnc-start +102 -0
- package/runtime/_shared/claude-managed-settings.json +116 -0
- package/runtime/_shared/ctl.cjs +27469 -0
- package/runtime/_shared/gh-shim +344 -0
- package/runtime/_shared/git-shim +131 -0
- package/runtime/_shared/linear-shim +181 -0
- package/runtime/_shared/ntn-shim +95 -0
- package/runtime/_shared/opencode-agentbox-plugin.js +76 -0
- package/runtime/docker/Dockerfile.box +30 -17
- package/runtime/docker/packages/ctl/dist/bin.cjs +11871 -10351
- package/runtime/e2b/ctl.cjs +11871 -10351
- package/runtime/e2b/scripts/build-template.sh +31 -15
- package/runtime/hetzner/ctl.cjs +11871 -10351
- package/runtime/hetzner/scripts/install-box.sh +37 -19
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -0
- package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +36 -0
- package/runtime/hub/apps/hub/.next/build-manifest.json +21 -0
- package/runtime/hub/apps/hub/.next/package.json +1 -0
- package/runtime/hub/apps/hub/.next/prerender-manifest.json +36 -0
- package/runtime/hub/apps/hub/.next/required-server-files.json +350 -0
- package/runtime/hub/apps/hub/.next/routes-manifest.json +292 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page.js +14 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route.js +7 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/events/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route.js +7 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/jobs/[id]/logs/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js +7 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js +7 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/server-reference-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page/server-reference-manifest.json +137 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page/server-reference-manifest.json +125 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page/server-reference-manifest.json +89 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +16 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.meta +15 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +14 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +5 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +14 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +5 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +5 -0
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page/build-manifest.json +17 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page/next-font-manifest.json +13 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page.js +13 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +36 -0
- package/runtime/hub/apps/hub/.next/server/chunks/01te_@better-auth_kysely-adapter_dist_0jw_ngm._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/01te_@better-auth_kysely-adapter_dist_0z6cvsk._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/01te_@better-auth_kysely-adapter_dist_210bxd8._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/01te_@better-auth_kysely-adapter_dist_index_mjs_0h-j5xt._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(auth)_api_auth_[___all]_route_actions_1agi0ag.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_boxes_route_actions_1ggp_5o.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_health_route_actions_017gnzg.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_projects_route_actions_04w8ozk.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/09mp_@better-auth_memory-adapter_dist_index_mjs_0ti_30h._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/09xn_next_0tn6frk._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0d-b_next_dist_server_app-render_after-task-async-storage_external_0-exn7p.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0m4a_kysely_dist_095p8vu._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0m4a_kysely_dist_1skbhvx._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0sj1_@opentelemetry_api_build_esm_index_0xy-j06.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_jobs_[id]_logs_route_actions_01aqmf3.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_approvals_route_actions_1vwxs9a.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_boxes_[id]_route_actions_01510xg.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_jobs_[id]_route_actions_0oc630h.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_openapi_json_route_actions_1lunxjz.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_providers_route_actions_1666ry8.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_projects_[id]_route_actions_1beikpx.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/151__@better-auth_core_dist_0ecdp_3._.js +5 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_approvals_[id]_answer_route_actions_1cq4z5x.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_[action]_route_actions_0cib0ju.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_branches_route_actions_15snjix.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_git_[op]_route_actions_116a41w.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_git_route_actions_1a-q-i2.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_services_restart_route_actions_1yvsbmm.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_services_route_actions_1uvv36v.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_jobs_[id]_login-code_route_actions_1825jmw.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_jobs_[id]_logs_route_actions_0msc0_w.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_projects_[id]_branches_route_actions_07i0vrw.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_providers_[id]_credentials_route_actions_1cds5re.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_providers_[id]_prepare_route_actions_079fbng.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[externals]__12m3qoa._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[externals]_pg_15jfwkh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04h15ml._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04jgk9x._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07ednlo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +105 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ig1bot._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ql4fjo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0se1fty._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t7o5ed._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vs8fma._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vxaujy._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w9ud8u._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yhb0gc._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +461 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13jwk_k._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16_uteg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16p2m-g._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19pc87s._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_gu2yk._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ai-945._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +14 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bu2zio._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ctczev._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d6mtlk._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d75vsx._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dn_3i1._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1e4z_-v._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f2sueq._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f9zctr._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1js2jdv._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mttufy._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1nepkp-._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1pp5oib._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q5bqse._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +14 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qwhzmi._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9om6g._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xeczo7._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20503l7._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[turbopack]_runtime.js +903 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_033w048._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +27 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_0pyhcqe._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_1-42ili._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_11__3wi._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_12flzuh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_1rpkqst._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_1wt72m1._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_1x3l5t8._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub__next-internal_server_app_(dashboard)_api_events_route_actions_17s9lxs.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub__next-internal_server_app_(dashboard)_api_v1_docs_route_actions_0d-s_oo.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub__next-internal_server_app_[___path]_route_actions_1hdraye.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +86 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/044u_hub__next-internal_server_app_(dashboard)_projects_[id]_page_actions_15f56np.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0iwlo01._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_client_components_20xzgz2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_client_components_builtin_forbidden_1x5yo9-.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_client_components_builtin_global-error_14poel6.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_client_components_builtin_unauthorized_0vj9qge.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_15jfwkh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_20c820g._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__03-x9xy._.js +19 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0cpdgd0._.js +33 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0j0tjwn._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +33 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1bq2f8q._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1c1x9zr._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1he4k-q._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[turbopack]_runtime.js +903 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_04br1ft._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_09gdzmo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0kpdmm-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ozyjt1._.js +21 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ro6vh6._.js +27 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0tgpglr._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_1laion6._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0_lzzn3._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0b_hsjl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(auth)_signin_page_actions_1vmiwl7.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_approvals_page_actions_1mi0bpn.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_boxes_[id]_page_actions_0k7kgn2.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_page_actions_1t3u0xy.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_settings_page_actions_0ti7gxm.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app__global-error_page_actions_1ofuxm1.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app__not-found_page_actions_1fmdkci.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_[id]_page_tsx_1-j_972._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_components_box-table_tsx_0a9pyn_._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_components_1z1p98f._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_lib_auth_client_ts_1uxjxr_._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/node_modules__pnpm_04qfi10._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/node_modules__pnpm_0kvuy0s._.js +33 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +80 -0
- package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +40 -0
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +21 -0
- package/runtime/hub/apps/hub/.next/server/middleware-manifest.json +6 -0
- package/runtime/hub/apps/hub/.next/server/middleware.js +5 -0
- package/runtime/hub/apps/hub/.next/server/next-font-manifest.js +1 -0
- package/runtime/hub/apps/hub/.next/server/next-font-manifest.json +49 -0
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -0
- package/runtime/hub/apps/hub/.next/server/pages-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/prefetch-hints.json +1 -0
- package/runtime/hub/apps/hub/.next/server/server-reference-manifest.js +1 -0
- package/runtime/hub/apps/hub/.next/server/server-reference-manifest.json +276 -0
- package/runtime/hub/apps/hub/.next/static/TpPTWVdZDxqrPlONtJcR5/_buildManifest.js +11 -0
- package/runtime/hub/apps/hub/.next/static/TpPTWVdZDxqrPlONtJcR5/_clientMiddlewareManifest.js +6 -0
- package/runtime/hub/apps/hub/.next/static/TpPTWVdZDxqrPlONtJcR5/_ssgManifest.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/0cz1d0mv5g_q7.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/0dx4alyqu7cq1.css +3 -0
- package/runtime/hub/apps/hub/.next/static/chunks/0lq354ziiwxxl.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/0ptag81psa0nj.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/11vmjdy3390ik.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/19cwkdx97a5_c.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1svigjdfotduh.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1t3645mc1s54c.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1y49eldffr2-_.js +31 -0
- package/runtime/hub/apps/hub/.next/static/chunks/26ef4lcj-7-li.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/2d5e6t-5j4etp.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/2ozcn3ku69ymf.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/2w65a9zig6ya7.js +4 -0
- package/runtime/hub/apps/hub/.next/static/chunks/2x7nfpuaaba_a.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3-zanu4ioia5i.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3c49t4evjq8hf.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3x8k7so-uoat8.js +2 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3y2c7woqhtx9s.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/turbopack-2x4_cva4cco3h.js +1 -0
- package/runtime/hub/apps/hub/.next/static/media/02263ebadd758ea4-s.29yke99gs9qpn.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/03fc1b4a8d284b5e-s.p.0wiir8udbzjvx.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/1a69062cfe6f77f8-s.0o-3_g79811ob.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/1bcd0e671759a44c-s.2qt3tdwt-y9x_.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/23b7a97ae3b5c134-s.p.226pwps5o-gq_.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/2e95a7d252b9825a-s.15orukf5wyxb5.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/2fe89d53234c61d4-s.1u30mmyq6lnsd.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/57215795b8570f5c-s.2rixgazldzomk.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/59b15b4bcd7b1eb5-s.2vemzm0itqzfy.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/5e05ae5b48faa55e-s.1yd4_i3e35931.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/68757d6cddeff913-s.1i-sca43-qwng.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/6ff74e33ebd7bca3-s.352ti9pm7m6qh.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/7fea77d1d19108bf-s.2y65deuc30pmy.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/90c51ce8fb754fe8-s.02z5rrbg5nt92.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/99e609270109b47d-s.p.40sczeszzbjw1.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/9a4838fcda0d1bca-s.0ngr-xkgqz1kf.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/a7afbb44bec2bb18-s.1qc6dx89jd2qv.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/e15f58668ad64cb8-s.3cvcemwuzoywn.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/e390973e931a41c5-s.0rgnxg2b64rzs.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/e532fa1b9921e1cd-s.3cb5lpr2l6xud.woff2 +0 -0
- package/runtime/hub/apps/hub/.next/static/media/effe91970fc4db64-s.p.0oace-s_gkfks.woff2 +0 -0
- package/runtime/hub/apps/hub/auth-YBXDRLHG.js +75 -0
- package/runtime/hub/apps/hub/auth-config-LJGI76HI.js +21 -0
- package/runtime/hub/apps/hub/chunk-3LAHFDJF.js +287 -0
- package/runtime/hub/apps/hub/chunk-AKLBSCSZ.js +8573 -0
- package/runtime/hub/apps/hub/chunk-EFW34I43.js +7299 -0
- package/runtime/hub/apps/hub/chunk-JDA7BPPN.js +2806 -0
- package/runtime/hub/apps/hub/chunk-LJG4CEGS.js +3341 -0
- package/runtime/hub/apps/hub/chunk-OBKLTPIR.js +41 -0
- package/runtime/hub/apps/hub/chunk-OF242BLD.js +797 -0
- package/runtime/hub/apps/hub/chunk-TZFWAJVB.js +38 -0
- package/runtime/hub/apps/hub/chunk-V5KGFHCF.js +12683 -0
- package/runtime/hub/apps/hub/cloud-poller-SUNA6ZQC-VSKVMYHL.js +10 -0
- package/runtime/hub/apps/hub/dist-BF54UNHK.js +1029 -0
- package/runtime/hub/apps/hub/dist-CM4YAQLI.js +1656 -0
- package/runtime/hub/apps/hub/dist-ELOY2IUE.js +533 -0
- package/runtime/hub/apps/hub/dist-FDBOJ74K.js +1085 -0
- package/runtime/hub/apps/hub/dist-GGM4BUKM.js +2281 -0
- package/runtime/hub/apps/hub/dist-IENF7YOD.js +88 -0
- package/runtime/hub/apps/hub/execa-4DLVNM6E.js +32 -0
- package/runtime/hub/apps/hub/hub-token-EW32VDIU.js +25 -0
- package/runtime/hub/apps/hub/package.json +55 -0
- package/runtime/hub/apps/hub/prepared-state-5FIGV4BE-FIXKBF5A.js +19 -0
- package/runtime/hub/apps/hub/public/logo.svg +5 -0
- package/runtime/hub/apps/hub/server.js +838 -0
- package/runtime/relay/bin.cjs +1738 -482
- package/runtime/vercel/ctl.cjs +11871 -10351
- package/runtime/vercel/scripts/provision.sh +31 -15
- package/dist/chunk-6JJIKCMY.js.map +0 -1
- package/dist/chunk-DBMLOY3T.js +0 -793
- package/dist/chunk-DBMLOY3T.js.map +0 -1
- package/dist/chunk-KTEDFUKM.js +0 -831
- package/dist/chunk-KTEDFUKM.js.map +0 -1
- package/dist/chunk-QKL7PCXQ.js.map +0 -1
- package/dist/chunk-X2DWS4KS.js +0 -820
- package/dist/chunk-X2DWS4KS.js.map +0 -1
- package/dist/chunk-YZVFGFYQ.js.map +0 -1
- package/dist/dist-FMA5Y25B.js.map +0 -1
- package/dist/dist-NWKOEWUJ.js.map +0 -1
- package/dist/dist-U76JL6HI.js +0 -738
- package/dist/dist-U76JL6HI.js.map +0 -1
- package/dist/dist-UVQJ2BZJ.js.map +0 -1
- /package/dist/{_cloud-attach-U3QJO7IF.js.map → _cloud-attach-YH2SU75S.js.map} +0 -0
- /package/dist/{dist-SAS4PIHA.js.map → dist-EJXUKIR7.js.map} +0 -0
- /package/dist/{prepared-state-MQHD3M5F-YYVVMTNJ.js.map → dist-QBXEP4VY.js.map} +0 -0
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
module.exports=[2157,(e,t,r)=>{t.exports=e.x("node:fs",()=>require("node:fs"))},60526,(e,t,r)=>{t.exports=e.x("node:os",()=>require("node:os"))},44733,e=>{"use strict";let t,r,n,i,a,o,s,c,l,d,u;var p,f,h,m,y=e.i(56710),g=e.i(82809),w=e.i(74001),b=e.i(73300),A=e.i(68744),E=e.i(98570),v=e.i(56147),k=e.i(32931),_=e.i(61810),S=e.i(59963),x=e.i(44491),R=e.i(74916),T=e.i(33073),I=e.i(98603),U=e.i(93317),O=e.i(93695);e.i(95533);var P=e.i(75616);function C(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function D(e){if(!e)return[];let t=[],r=0,n=0;for(;n<e.length;){if(","===e[n]){let i=n+1;for(;i<e.length&&" "===e[i];)i++;for(;i<e.length&&"="!==e[i]&&";"!==e[i]&&","!==e[i];)i++;if(i<e.length&&"="===e[i]){let i=e.slice(r,n).trim();for(i&&t.push(i),r=n+1;r<e.length&&" "===e[r];)r++;n=r;continue}}n++}let i=e.slice(r).trim();return i&&t.push(i),t}let L=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,$=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function z(e){return!(e.length<2)&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function N(e){let t=0,r=e.length;for(;t<r;){let r=e.charCodeAt(t);if(32!==r&&9!==r)break;t++}for(;r>t;){let t=e.charCodeAt(r-1);if(32!==t&&9!==t)break;r--}return 0===t&&r===e.length?e:e.slice(t,r)}function j(e){let t=new Map;if(e.length<2)return t;for(let r of e.split(";")){let e=r.indexOf("=");if(-1===e)continue;let n=N(r.slice(0,e)),i=z(N(r.slice(e+1)));L.test(n)&&$.test(i)&&t.set(n,C(i))}return t}var H=e.i(10469),B=e.i(69772);let q=async()=>{let e=(0,H.__getBetterAuthGlobal)();if(!e.context.requestStateAsyncStorage){let t=await (0,B.getAsyncLocalStorage)();e.context.requestStateAsyncStorage=new t}return e.context.requestStateAsyncStorage};async function M(){return void 0!==(await q()).getStore()}async function V(){let e=(await q()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function K(e,t){return(await q()).run(e,t)}function W(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await V();if(!r.has(t)){let n=await e();return r.set(t,n),n}return r.get(t)},async set(e){(await V()).set(t,e)}}}let{get:F,set:J}=W(()=>!1),Z=async()=>{let e=(0,H.__getBetterAuthGlobal)();if(!e.context.endpointContextAsyncStorage){let t=await (0,B.getAsyncLocalStorage)();e.context.endpointContextAsyncStorage=new t}return e.context.endpointContextAsyncStorage};async function G(){let e=(await Z()).getStore();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function Q(e,t){return(await Z()).run(e,t)}var Y=e.i(36004),X=e.i(58461);let ee=/^application\/([a-z0-9.+-]*\+)?json/i;async function et(e,t){let r=e.headers.get("content-type")||"",n=r.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=n.split(";")[0].trim(),r=e.toLowerCase().trim();return t===r||t.includes(r)})){if(!n)throw new X.APIError(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new X.APIError(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(ee.test(n))try{return await e.json()}catch(e){if(e instanceof SyntaxError)throw new X.APIError(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw e}if(n.includes("application/x-www-form-urlencoded")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e.toString()}),r}if(n.includes("multipart/form-data")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e}),r}return n.includes("text/plain")?await e.text():n.includes("application/octet-stream")?await e.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await e.blob():n.includes("application/stream")||e.body instanceof ReadableStream?e.body:await e.text()}}function er(e){return e instanceof X.APIError||e?.name==="APIError"}async function en(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function ei(e){return e instanceof Request||"[object Request]"===Object.prototype.toString.call(e)}let ea=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"]);function eo(e){for(let t of ea)e.delete(t)}function es(e,t){if(t)for(let[r,n]of new Headers(t).entries())"set-cookie"===r.toLowerCase()?e.append(r,n):e.set(r,n)}function ec(e,t){if(e instanceof Response){if(t?.headers){let r=new Headers(t.headers);eo(r),es(e.headers,r)}return e}if(e&&"object"==typeof e&&"_flag"in e&&"json"===e._flag){let r=e.body,n=e.routerResponse;if(n instanceof Response)return n;let i=new Headers;if(es(i,n?.headers),es(i,e.headers),t?.headers){let e=new Headers(t.headers);eo(e),es(i,e)}return i.set("Content-Type","application/json"),new Response(JSON.stringify(r),{...n,headers:i,status:e.status??t?.status??n?.status,statusText:t?.statusText??n?.statusText})}if(er(e))return ec(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,n=new Headers(t?.headers);if(eo(n),e){if("string"==typeof e)r=e,n.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,n.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,n.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,n.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,n.set("Content-Type","application/octet-stream");else if(function(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(e)){let t,i,a;t=new WeakMap,i=new WeakMap,a=0,r=JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("object"==typeof r&&null!==r){if(((e,r)=>{let n=r;for(;n;){if(n===e)return!0;n=t.get(n)}return!1})(r,this))return`[Circular ref-${i.get(r)}]`;t.set(r,this),i.has(r)||i.set(r,a++)}return r}),n.set("Content-Type","application/json")}}else null===e&&(r=JSON.stringify(null)),n.set("content-type","application/json");return new Response(r,{...t,headers:n})}function el(){let e="u">typeof globalThis&&globalThis.crypto;if(e&&"object"==typeof e.subtle&&null!=e.subtle)return e.subtle;throw Error("crypto.subtle must be defined")}let ed={name:"HMAC",hash:"SHA-256"},eu=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await el().importKey("raw",t,ed,!1,["sign","verify"])},ep=async(e,t,r)=>{try{let n=atob(e),i=new Uint8Array(n.length);for(let e=0,t=n.length;e<t;e++)i[e]=n.charCodeAt(e);return await el().verify(ed,r,i,new TextEncoder().encode(t))}catch(e){return!1}},ef=async(e,t)=>{let r=await eu(t);return btoa(String.fromCharCode(...new Uint8Array(await el().sign(ed.name,r,new TextEncoder().encode(e)))))},eh=async(e,t)=>{let r=await ef(e,t);return encodeURIComponent(e=`${e}.${r}`)},em=(e,t)=>{let r=e;if(t)if("secure"===t)r="__Secure-"+e;else{if("host"!==t)return;r="__Host-"+e}return r},ey=(e,t,r={})=>{let n;if(n=r?.prefix==="secure"?`__Secure-${e}=${t}`:r?.prefix==="host"?`__Host-${e}=${t}`:`${e}=${t}`,e.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),e.startsWith("__Host-")&&(r.secure||(r.secure=!0),"/"!==r.path&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&"number"==typeof r.maxAge&&r.maxAge>=0){if(r.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&"host"!==r.prefix&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},eg=(e,t,r)=>ey(e,t=encodeURIComponent(t),r),ew=async(e,t,r,n)=>ey(e,t=await eh(t,r),n);async function eb(e,t={}){let r={body:t.body,query:t.query};if(e.body){let n=await e.body["~standard"].validate(t.body);if(n.issues)return{data:null,error:eA(n.issues,"body")};r.body=n.value}if(e.query){let n=await e.query["~standard"].validate(t.query);if(n.issues)return{data:null,error:eA(n.issues,"query")};r.query=n.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:"Headers is required",issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function eA(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>"object"==typeof e?e.key:e).join("."):t}] ${e.message}`).join("; "),issues:e}}let eE=async(e,{options:t,path:r})=>{let n,i=new Headers,{data:a,error:o}=await eb(t,e);if(o)throw new X.ValidationError(o.message,o.issues);let s="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&ei(e.request)?e.request.headers:null,c=s?.get("cookie"),l=c?function(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let n=e.indexOf("=",r);if(-1===n)break;let i=e.indexOf(";",r);if(-1===i)i=e.length;else if(i<n){r=e.lastIndexOf(";",n-1)+1;continue}let a=e.slice(r,n).trim();if(!t.has(a)){let r=e.slice(n+1,i).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(a,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=i+1}return t}(c):void 0,d={...e,body:a.body,query:a.query,path:e.path||r||"virtual:",context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:"*"===t.method?"GET":t.method),setHeader:(e,t)=>{i.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let r=em(e,t);return r&&l?.get(r)||null},getSignedCookie:async(e,t,r)=>{let n=em(e,r);if(!n)return null;let i=l?.get(n);if(!i)return null;let a=i.lastIndexOf(".");if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return 44===s.length&&s.endsWith("=")?!!await ep(s,o,await eu(t))&&o:null},setCookie:(e,t,r)=>{let n=eg(e,t,r);return i.append("set-cookie",n),n},setSignedCookie:async(e,t,r,n)=>{let a=await ew(e,t,r,n);return i.append("set-cookie",a),a},redirect:e=>(i.set("location",e),new X.APIError("FOUND",void 0,i)),error:(e,t,r)=>new X.APIError(e,t,r),setStatus:e=>{n=e},json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:i,get responseStatus(){return n}};for(let e of t.use||[]){let t=await e({...d,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(d.context,t.response),t.headers&&t.headers.forEach((e,t)=>{d.responseHeaders.set(t,e)})}return d};function ev(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r;if(("GET"===i.method||"HEAD"===i.method)&&i.body)throw new X.BetterCallError("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new X.BetterCallError("Path cannot contain consecutive slashes");let o=async(...e)=>{let t=e[0]||{},{data:r,error:o}=await en(eE(t,{options:i,path:n}));if(o){if(!(o instanceof X.ValidationError))throw o;throw i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new X.APIError(400,{message:o.message,code:"VALIDATION_ERROR"})}let s=await a(r).catch(async e=>{if(er(e)){let r=i.onAPIError;if(r&&await r(e),t.asResponse)return e}throw e}),c=r.responseHeaders,l=r.responseStatus;return t.asResponse?ec(s,{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=n,o}function ek(e,t){let r=async r=>{let n="function"==typeof e?e:t,i=await eE(r,{options:"function"==typeof e?{}:e,path:"/"});if(!n)throw Error("handler must be defined");try{let e=await n(i),t=i.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw er(e)&&Object.defineProperty(e,X.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,get:()=>i.responseHeaders}),e}};return r.options="function"==typeof e?{}:e,r}function e_(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class a extends i{}function o(e){var t;let i=r?.Parent?new a:this;for(let r of(n(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}ev.create=e=>(t,r,n)=>ev(t,{...r,use:[...r?.use||[],...e?.use||[]]},n),ek.create=e=>function(t,r){if("function"==typeof t)return ek({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return ek({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)},Symbol("zod_brand");class eS extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ex extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(h=globalThis).__zod_globalConfig??(h.__zod_globalConfig={});let eR=globalThis.__zod_globalConfig;function eT(e){return e&&Object.assign(eR,e),eR}function eI(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function eU(e,t){return"bigint"==typeof t?t.toString():t}function eO(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function eP(e){return null==e}function eC(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function eD(e,t){let r=e/t,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}let eL=Symbol("evaluating");function e$(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==eL)return void 0===n&&(n=eL,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ez(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function eN(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}function ej(e){return JSON.stringify(e)}function eH(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}let eB="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function eq(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let eM=eO(()=>{if(eR.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function eV(e){if(!1===eq(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==eq(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let eK=new Set(["string","number","symbol"]),eW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function eF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eJ(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function eZ(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function eG(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function eQ(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let eY={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},eX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function e0(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function e1(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function e2(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function e5(e){return"string"==typeof e?e:e?.message}function e6(e,t,r){let n=e.message?e.message:e5(e.inst?._zod.def?.error?.(e))??e5(t?.error?.(e))??e5(r.customError?.(e))??e5(r.localeError?.(e))??"Invalid input",{inst:i,continue:a,input:o,...s}=e;return s.path??(s.path=[]),s.message=n,t?.reportInput&&(s.input=o),s}function e4(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function e8(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function e3(...e){let[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function e9(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function e7(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}e.s(["BIGINT_FORMAT_RANGES",0,eX,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,eY,"aborted",0,e0,"allowsEval",0,eM,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error("Unexpected value in exhaustive check")},"assertNotEqual",0,function(e){return e},"assignProp",0,ez,"base64ToUint8Array",0,e9,"base64urlToUint8Array",0,function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return e9(t+r)},"cached",0,eO,"captureStackTrace",0,eB,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,eC,"clone",0,eJ,"cloneDef",0,function(e){return eN(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,a)=>(t??(t=e()),Reflect.set(t,n,i,a)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})},"defineLazy",0,e$,"esc",0,ej,"escapeRegex",0,eF,"explicitlyAborted",0,e1,"extend",0,function(e,t){if(!eV(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=eN(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return ez(this,"shape",r),r}});return eJ(e,n)},"finalizeIssue",0,e6,"floatSafeRemainder",0,eD,"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,eI,"getLengthableOrigin",0,e8,"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,e4,"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r},"isObject",0,eq,"isPlainObject",0,eV,"issue",0,e3,"joinValues",0,function(e,t="|"){return e.map(e=>eG(e)).join(t)},"jsonStringifyReplacer",0,eU,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=eN(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ez(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return eJ(e,r)},"mergeDefs",0,eN,"normalizeParams",0,eZ,"nullish",0,eP,"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=eN(e._zod.def,{get shape(){let n={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return ez(this,"shape",n),n},checks:[]});return eJ(e,i)},"optionalKeys",0,eQ,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=eN(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(let t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return ez(this,"shape",i),i},checks:[]});return eJ(t,i)},"pick",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=eN(e._zod.def,{get shape(){let e={};for(let n in t){if(!(n in r.shape))throw Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return ez(this,"shape",e),e},checks:[]});return eJ(e,i)},"prefixIssues",0,e2,"primitiveTypes",0,eW,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})},"propertyKeyTypes",0,eK,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let n=eN(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(let t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return ez(this,"shape",i),i}});return eJ(t,n)},"safeExtend",0,function(e,t){if(!eV(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=eN(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return ez(this,"shape",r),r}});return eJ(e,r)},"shallowClone",0,function(e){return eV(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e},"slugify",0,eH,"stringifyPrimitive",0,eG,"uint8ArrayToBase64",0,e7,"uint8ArrayToBase64url",0,function(e){return e7(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"uint8ArrayToHex",0,function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,e5],2721);let te=/^[cC][0-9a-z]{6,}$/,tt=/^[0-9a-z]+$/,tr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tn=/^[0-9a-vA-V]{20}$/,ti=/^[A-Za-z0-9]{27}$/,ta=/^[a-zA-Z0-9_-]{21}$/,to=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ts=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,tc=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tl=tc(4),td=tc(6),tu=tc(7),tp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tf=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;function th(){return RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}let tm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ty=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,tg=e=>{let t=eF(e??":");return RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},tw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,tb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tA=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tE=/^[A-Za-z0-9_-]*$/,tv=/^https?$/,tk=/^\+[1-9]\d{6,14}$/,t_="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",tS=RegExp(`^${t_}$`);function tx(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function tR(e){return RegExp(`^${tx(e)}$`)}function tT(e){let t=tx({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return RegExp(`^${t_}T(?:${n})$`)}let tI=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},tU=/^-?\d+n?$/,tO=/^-?\d+$/,tP=/^-?\d+(?:\.\d+)?$/,tC=/^(?:true|false)$/i,tD=/^null$/i,tL=/^undefined$/i,t$=/^[^A-Z]*$/,tz=/^[^a-z]*$/;function tN(e,t){return RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function tj(e){return RegExp(`^[A-Za-z0-9_-]{${e}}$`)}let tH=tN(22,"=="),tB=tj(22),tq=tN(27,"="),tM=tj(27),tV=tN(43,"="),tK=tj(43),tW=tN(64,""),tF=tj(64),tJ=tN(86,"=="),tZ=tj(86);e.s(["base64",0,tA,"base64url",0,tE,"bigint",0,tU,"boolean",0,tC,"browserEmail",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"cidrv4",0,tw,"cidrv6",0,tb,"cuid",0,te,"cuid2",0,tt,"date",0,tS,"datetime",0,tT,"domain",0,/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,"duration",0,to,"e164",0,tk,"email",0,tp,"emoji",0,th,"extendedDuration",0,/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,"guid",0,ts,"hex",0,/^[0-9a-fA-F]*$/,"hostname",0,/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,"html5Email",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"httpProtocol",0,tv,"idnEmail",0,tf,"integer",0,tO,"ipv4",0,tm,"ipv6",0,ty,"ksuid",0,ti,"lowercase",0,t$,"mac",0,tg,"md5_base64",0,tH,"md5_base64url",0,tB,"md5_hex",0,/^[0-9a-fA-F]{32}$/,"nanoid",0,ta,"null",0,tD,"number",0,tP,"rfc5322Email",0,/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"sha1_base64",0,tq,"sha1_base64url",0,tM,"sha1_hex",0,/^[0-9a-fA-F]{40}$/,"sha256_base64",0,tV,"sha256_base64url",0,tK,"sha256_hex",0,/^[0-9a-fA-F]{64}$/,"sha384_base64",0,tW,"sha384_base64url",0,tF,"sha384_hex",0,/^[0-9a-fA-F]{96}$/,"sha512_base64",0,tJ,"sha512_base64url",0,tZ,"sha512_hex",0,/^[0-9a-fA-F]{128}$/,"string",0,tI,"time",0,tR,"ulid",0,tr,"undefined",0,tL,"unicodeEmail",0,tf,"uppercase",0,tz,"uuid",0,tc,"uuid4",0,tl,"uuid6",0,td,"uuid7",0,tu,"xid",0,tn],10107);let tG=e_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tQ={number:"number",bigint:"bigint",object:"date"},tY=e_("$ZodCheckLessThan",(e,t)=>{tG.init(e,t);let r=tQ[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tX=e_("$ZodCheckGreaterThan",(e,t)=>{tG.init(e,t);let r=tQ[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),t0=e_("$ZodCheckMultipleOf",(e,t)=>{tG.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===eD(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),t1=e_("$ZodCheckNumberFormat",(e,t)=>{tG.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,a]=eY[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=a,r&&(n.pattern=tO)}),e._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?o.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}))}s<i&&o.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),t2=e_("$ZodCheckBigIntFormat",(e,t)=>{tG.init(e,t);let[r,n]=eX[t.format];e._zod.onattach.push(e=>{let i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{let a=i.value;a<r&&i.issues.push({origin:"bigint",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>n&&i.issues.push({origin:"bigint",input:a,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),t5=e_("$ZodCheckMaxSize",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;n.size<=t.maximum||r.issues.push({origin:e4(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),t6=e_("$ZodCheckMinSize",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;n.size>=t.minimum||r.issues.push({origin:e4(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),t4=e_("$ZodCheckSizeEquals",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let n=r.value,i=n.size;if(i===t.size)return;let a=i>t.size;r.issues.push({origin:e4(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),t8=e_("$ZodCheckMaxLength",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;if(n.length<=t.maximum)return;let i=e8(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),t3=e_("$ZodCheckMinLength",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;if(n.length>=t.minimum)return;let i=e8(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),t9=e_("$ZodCheckLengthEquals",(e,t)=>{var r;tG.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!eP(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let n=r.value,i=n.length;if(i===t.length)return;let a=e8(n),o=i>t.length;r.issues.push({origin:a,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),t7=e_("$ZodCheckStringFormat",(e,t)=>{var r,n;tG.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),re=e_("$ZodCheckRegex",(e,t)=>{t7.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),rt=e_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=t$),t7.init(e,t)}),rr=e_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tz),t7.init(e,t)}),rn=e_("$ZodCheckIncludes",(e,t)=>{tG.init(e,t);let r=eF(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),ri=e_("$ZodCheckStartsWith",(e,t)=>{tG.init(e,t);let r=RegExp(`^${eF(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),ra=e_("$ZodCheckEndsWith",(e,t)=>{tG.init(e,t);let r=RegExp(`.*${eF(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});(e,t)=>{tG.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}};let ro=e_("$ZodCheckOverwrite",(e,t)=>{tG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class rs{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}let rc=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,eU,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},rl=e_("$ZodError",rc),rd=e_("$ZodError",rc,{Parent:Error}),ru=e=>(t,r,n,i)=>{let a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new eS;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>e6(e,a,eT())));throw eB(t,i?.callee),t}return o.value},rp=ru(rd),rf=e=>async(t,r,n,i)=>{let a=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>e6(e,a,eT())));throw eB(t,i?.callee),t}return o.value},rh=rf(rd),rm=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new eS;return a.issues.length?{success:!1,error:new(e??rl)(a.issues.map(e=>e6(e,i,eT())))}:{success:!0,data:a.value}},ry=rm(rd),rg=e=>async(t,r,n)=>{let i=n?{...n,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>e6(e,i,eT())))}:{success:!0,data:a.value}},rw=rg(rd),rb={major:4,minor:4,patch:3},rA=e_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=rb;let n=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&n.unshift(e),n))for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,i=e0(e);for(let a of t){if(a._zod.def.when){if(e1(e)||!a._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&r?.async===!1)throw new eS;if(n||o instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(i||(i=e0(e,t)))});else{if(e.issues.length===t)continue;i||(i=e0(e,t))}}return n?n.then(()=>e):e},r=(r,i,a)=>{if(e0(r))return r.aborted=!0,r;let o=t(i,n,a);if(o instanceof Promise){if(!1===a.async)throw new eS;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if("backward"===a.direction){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,a)):r(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(!1===a.async)throw new eS;return o.then(e=>t(e,n,a))}return t(o,n,a)}}e$(e,"~standard",()=>({validate:t=>{try{let r=ry(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return rw(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),rE=e_("$ZodString",(e,t)=>{rA.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??tI(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),rv=e_("$ZodStringFormat",(e,t)=>{t7.init(e,t),rE.init(e,t)}),rk=e_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ts),rv.init(e,t)}),r_=e_("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=tc(e))}else t.pattern??(t.pattern=tc());rv.init(e,t)}),rS=e_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tp),rv.init(e,t)}),rx=e_("$ZodURL",(e,t)=>{rv.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===tv.source&&!/^https?:\/\//i.test(n))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),rR=e_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=th()),rv.init(e,t)}),rT=e_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ta),rv.init(e,t)}),rI=e_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=te),rv.init(e,t)}),rU=e_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=tt),rv.init(e,t)}),rO=e_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=tr),rv.init(e,t)}),rP=e_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=tn),rv.init(e,t)}),rC=e_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ti),rv.init(e,t)}),rD=e_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=tT(t)),rv.init(e,t)}),rL=e_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=tS),rv.init(e,t)}),r$=e_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=tR(t)),rv.init(e,t)}),rz=e_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=to),rv.init(e,t)}),rN=e_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=tm),rv.init(e,t),e._zod.bag.format="ipv4"}),rj=e_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ty),rv.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),rH=((e,t)=>{t.pattern??(t.pattern=tg(t.delimiter)),rv.init(e,t),e._zod.bag.format="mac"},e_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=tw),rv.init(e,t)})),rB=e_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tb),rv.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(2!==n.length)throw Error();let[e,t]=n;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function rq(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let rM=e_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=tA),rv.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{rq(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),rV=e_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=tE),rv.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{!function(e){if(!tE.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return rq(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),rK=e_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=tk),rv.init(e,t)}),rW=e_("$ZodJWT",(e,t)=>{rv.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),rF=((e,t)=>{rv.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}},e_("$ZodNumber",(e,t)=>{rA.init(e,t),e._zod.pattern=e._zod.bag.pattern??tP,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let a="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),r}})),rJ=e_("$ZodNumberFormat",(e,t)=>{t1.init(e,t),rF.init(e,t)}),rZ=e_("$ZodBoolean",(e,t)=>{rA.init(e,t),e._zod.pattern=tC,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),rG=e_("$ZodBigInt",(e,t)=>{rA.init(e,t),e._zod.pattern=tU,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),rQ=((e,t)=>{t2.init(e,t),rG.init(e,t)},e_("$ZodAny",(e,t)=>{rA.init(e,t),e._zod.parse=e=>e})),rY=e_("$ZodUnknown",(e,t)=>{rA.init(e,t),e._zod.parse=e=>e}),rX=e_("$ZodNever",(e,t)=>{rA.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),r0=((e,t)=>{rA.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return void 0===n||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}},e_("$ZodDate",(e,t)=>{rA.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let i=r.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...a?{received:"Invalid Date"}:{},inst:e}),r}}));function r1(e,t,r){e.issues.length&&t.issues.push(...e2(r,e.issues)),t.value[r]=e.value}let r2=e_("$ZodArray",(e,t)=>{rA.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},n);s instanceof Promise?a.push(s.then(t=>r1(t,r,e))):r1(s,r,e)}return a.length?Promise.all(a).then(()=>r):r}});function r5(e,t,r,n,i,a){let o=r in n;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...e2(r,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?o&&(t.value[r]=void 0):t.value[r]=e.value}function r6(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=eQ(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function r4(e,t,r,n,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,d="optional"===c.optin,u="optional"===c.optout;for(let i in t){if("__proto__"===i||s.has(i))continue;if("never"===l){o.push(i);continue}let a=c.run({value:t[i],issues:[]},n);a instanceof Promise?e.push(a.then(e=>r5(e,r,i,t,d,u))):r5(a,r,i,t,d,u)}return(o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length)?Promise.all(e).then(()=>r):r}let r8=e_("$ZodObject",(e,t)=>{let r;rA.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=eO(()=>r6(t));e$(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let n=e[t]._zod;if(n.values)for(let e of(r[t]??(r[t]=new Set),n.values))r[t].add(e)}return r});let a=t.catchall;e._zod.parse=(t,n)=>{r??(r=i.value);let o=t.value;if(!eq(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};let s=[],c=r.shape;for(let e of r.keys){let r=c[e],i="optional"===r._zod.optin,a="optional"===r._zod.optout,l=r._zod.run({value:o[e],issues:[]},n);l instanceof Promise?s.push(l.then(r=>r5(r,t,e,o,i,a))):r5(l,t,e,o,i,a)}return a?r4(s,o,t,n,i.value,e):s.length?Promise.all(s).then(()=>t):t}}),r3=e_("$ZodObjectJIT",(e,t)=>{let r,n;r8.init(e,t);let i=e._zod.parse,a=eO(()=>r6(t)),o=!eR.jitless,s=o&&eM.value,c=t.catchall;e._zod.parse=(l,d)=>{n??(n=a.value);let u=l.value;return eq(u)?o&&s&&d?.async===!1&&!0!==d.jitless?(r||(r=(e=>{let t=new rs(["shape","payload","ctx"]),r=a.value,n=e=>{let t=ej(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),o=0;for(let e of r.keys)i[e]=`key_${o++}`;for(let a of(t.write("const newResult = {};"),r.keys)){let r=i[a],o=ej(a),s=e[a],c=s?._zod?.optin==="optional",l=s?._zod?.optout==="optional";t.write(`const ${r} = ${n(a)};`),c&&l?t.write(`
|
|
2
|
+
if (${r}.issues.length) {
|
|
3
|
+
if (${o} in input) {
|
|
4
|
+
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
5
|
+
...iss,
|
|
6
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
7
|
+
})));
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
if (${r}.value === undefined) {
|
|
12
|
+
if (${o} in input) {
|
|
13
|
+
newResult[${o}] = undefined;
|
|
14
|
+
}
|
|
15
|
+
} else {
|
|
16
|
+
newResult[${o}] = ${r}.value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
`):c?t.write(`
|
|
20
|
+
if (${r}.issues.length) {
|
|
21
|
+
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
22
|
+
...iss,
|
|
23
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
24
|
+
})));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (${r}.value === undefined) {
|
|
28
|
+
if (${o} in input) {
|
|
29
|
+
newResult[${o}] = undefined;
|
|
30
|
+
}
|
|
31
|
+
} else {
|
|
32
|
+
newResult[${o}] = ${r}.value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
`):t.write(`
|
|
36
|
+
const ${r}_present = ${o} in input;
|
|
37
|
+
if (${r}.issues.length) {
|
|
38
|
+
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
39
|
+
...iss,
|
|
40
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
41
|
+
})));
|
|
42
|
+
}
|
|
43
|
+
if (!${r}_present && !${r}.issues.length) {
|
|
44
|
+
payload.issues.push({
|
|
45
|
+
code: "invalid_type",
|
|
46
|
+
expected: "nonoptional",
|
|
47
|
+
input: undefined,
|
|
48
|
+
path: [${o}]
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (${r}_present) {
|
|
53
|
+
if (${r}.value === undefined) {
|
|
54
|
+
newResult[${o}] = undefined;
|
|
55
|
+
} else {
|
|
56
|
+
newResult[${o}] = ${r}.value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
`)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),l=r(l,d),c)?r4([],u,l,d,n,e):l:i(l,d):(l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l)}});function r9(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!e0(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>e6(e,n,eT())))}),t)}let r7=e_("$ZodUnion",(e,t)=>{rA.init(e,t),e$(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),e$(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),e$(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),e$(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>eC(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(0===t.issues.length)return t;o.push(t)}}return a?Promise.all(o).then(t=>r9(t,n,e,i)):r9(o,n,e,i)}});function ne(e,t,r,n){let i=e.filter(e=>0===e.issues.length);return 1===i.length?t.value=i[0].value:0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>e6(e,n,eT())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t}(e,t)=>{r7.init(e,t),t.inclusive=!1;let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);t instanceof Promise?(o.push(t),a=!0):o.push(t)}return a?Promise.all(o).then(t=>ne(t,n,e,i)):ne(o,n,e,i)}},(e,t)=>{t.inclusive=!1,r7.init(e,t);let r=e._zod.parse;e$(e._zod,"propValues",()=>{let e={};for(let r of t.options){let n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(n))for(let n of(e[t]||(e[t]=new Set),r))e[t].add(n)}return e});let n=eO(()=>{let e=t.options,r=new Map;for(let n of e){let e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,a)=>{let o=i.value;if(!eq(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let s=n.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||"backward"===a.direction?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}};let nt=e_("$ZodIntersection",(e,t)=>{rA.init(e,t),e._zod.parse=(e,r)=>{let n=e.value,i=t.left._zod.run({value:n,issues:[]},r),a=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,r])=>nr(e,t,r)):nr(e,i,a)}});function nr(e,t,r){let n,i=new Map;for(let r of t.issues)if("unrecognized_keys"===r.code)for(let e of(n??(n=r),r.keys))i.has(e)||i.set(e,{}),i.get(e).l=!0;else e.issues.push(r);for(let t of r.issues)if("unrecognized_keys"===t.code)for(let e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);let a=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&n&&e.issues.push({...n,keys:a}),e0(e))return e;let o=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(eV(t)&&eV(r)){let n=Object.keys(r),i=Object.keys(t).filter(e=>-1!==n.indexOf(e)),a={...t,...r};for(let n of i){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};a[n]=i.data}return{valid:!0,data:a}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let nn=e_("$ZodTuple",(e,t)=>{rA.init(e,t);let r=t.items;e._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],s=ni(r,"optin"),c=ni(r,"optout");if(!t.rest){if(a.length<s)return n.issues.push({code:"too_small",minimum:s,inclusive:!0,input:a,inst:e,origin:"array"}),n;a.length>r.length&&n.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:a,inst:e,origin:"array"})}let l=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=r.length-1;for(let s of a.slice(r.length)){e++;let r=t.rest._zod.run({value:s,issues:[]},i);r instanceof Promise?o.push(r.then(t=>na(t,n,e))):na(r,n,e)}}return o.length?Promise.all(o).then(()=>no(l,n,r,a,c)):no(l,n,r,a,c)}});function ni(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function na(e,t,r){e.issues.length&&t.issues.push(...e2(r,e.issues)),t.value[r]=e.value}function no(e,t,r,n,i){for(let a=0;a<r.length;a++){let r=e[a],o=a<n.length;if(r.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...e2(a,r.issues))}t.value[a]=r.value}for(let e=t.value.length-1;e>=n.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}let ns=e_("$ZodRecord",(e,t)=>{rA.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!eV(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let a=[],o=t.keyType._zod.values;if(o){let s;r.value={};let c=new Set;for(let s of o)if("string"==typeof s||"number"==typeof s||"symbol"==typeof s){c.add("number"==typeof s?s.toString():s);let o=t.keyType._zod.run({value:s,issues:[]},n);if(o instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>e6(e,n,eT())),input:s,path:[s],inst:e});continue}let l=o.value,d=t.valueType._zod.run({value:i[s],issues:[]},n);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&r.issues.push(...e2(s,e.issues)),r.value[l]=e.value})):(d.issues.length&&r.issues.push(...e2(s,d.issues)),r.value[l]=d.value)}for(let e in i)c.has(e)||(s=s??[]).push(e);s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:s})}else for(let o of(r.value={},Reflect.ownKeys(i))){if("__proto__"===o||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},n);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof o&&tP.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},n);if(e instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?r.value[o]=i[o]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>e6(e,n,eT())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&r.issues.push(...e2(o,e.issues)),r.value[s.value]=e.value})):(c.issues.length&&r.issues.push(...e2(o,c.issues)),r.value[s.value]=c.value)}return a.length?Promise.all(a).then(()=>r):r}});function nc(e,t,r,n,i,a,o){e.issues.length&&(eK.has(typeof n)?r.issues.push(...e2(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:a,issues:e.issues.map(e=>e6(e,o,eT()))})),t.issues.length&&(eK.has(typeof n)?r.issues.push(...e2(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:a,key:n,issues:t.issues.map(e=>e6(e,o,eT()))})),r.value.set(e.value,t.value)}function nl(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}(e,t)=>{rA.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let a=[];for(let[o,s]of(r.value=new Map,i)){let c=t.keyType._zod.run({value:o,issues:[]},n),l=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||l instanceof Promise?a.push(Promise.all([c,l]).then(([t,a])=>{nc(t,a,r,o,i,e,n)})):nc(c,l,r,o,i,e,n)}return a.length?Promise.all(a).then(()=>r):r}},(e,t)=>{rA.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let a=[];for(let e of(r.value=new Set,i)){let i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?a.push(i.then(e=>nl(e,r))):nl(i,r)}return a.length?Promise.all(a).then(()=>r):r}};let nd=e_("$ZodEnum",(e,t)=>{rA.init(e,t);let r=eI(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=RegExp(`^(${r.filter(e=>eK.has(typeof e)).map(e=>"string"==typeof e?eF(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{let a=t.value;return n.has(a)||t.issues.push({code:"invalid_value",values:r,input:a,inst:e}),t}}),nu=((e,t)=>{if(rA.init(e,t),0===t.values.length)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?eF(e):e?eF(e.toString()):String(e)).join("|")})$`),e._zod.parse=(n,i)=>{let a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}},e_("$ZodTransform",(e,t)=>{rA.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new ex(e.constructor.name);let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(r.value=e,r.fallback=!0,r));if(i instanceof Promise)throw new eS;return r.value=i,r.fallback=!0,r}}));function np(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let nf=e_("$ZodOptional",(e,t)=>{rA.init(e,t),e._zod.optin="optional",e._zod.optout="optional",e$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),e$(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eC(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let n=e.value,i=t.innerType._zod.run(e,r);return i instanceof Promise?i.then(e=>np(e,n)):np(i,n)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),nh=e_("$ZodExactOptional",(e,t)=>{nf.init(e,t),e$(e._zod,"values",()=>t.innerType._zod.values),e$(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),nm=e_("$ZodNullable",(e,t)=>{rA.init(e,t),e$(e._zod,"optin",()=>t.innerType._zod.optin),e$(e._zod,"optout",()=>t.innerType._zod.optout),e$(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${eC(e.source)}|null)$`):void 0}),e$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),ny=e_("$ZodDefault",(e,t)=>{rA.init(e,t),e._zod.optin="optional",e$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>ng(e,t)):ng(n,t)}});function ng(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let nw=e_("$ZodPrefault",(e,t)=>{rA.init(e,t),e._zod.optin="optional",e$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),nb=e_("$ZodNonOptional",(e,t)=>{rA.init(e,t),e$(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>nA(t,e)):nA(i,e)}});function nA(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}(e,t)=>{rA.init(e,t),e._zod.parse=(e,r)=>{if("backward"===r.direction)throw new ex("ZodSuccess");let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}};let nE=e_("$ZodCatch",(e,t)=>{rA.init(e,t),e._zod.optin="optional",e$(e._zod,"optout",()=>t.innerType._zod.optout),e$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>e6(e,r,eT()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>e6(e,r,eT()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),nv=((e,t)=>{rA.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)},e_("$ZodPipe",(e,t)=>{rA.init(e,t),e$(e._zod,"values",()=>t.in._zod.values),e$(e._zod,"optin",()=>t.in._zod.optin),e$(e._zod,"optout",()=>t.out._zod.optout),e$(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>nk(e,t.in,r)):nk(n,t.in,r)}let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>nk(e,t.out,r)):nk(n,t.out,r)}}));function nk(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function n_(e,t,r){if(e.issues.length)return e.aborted=!0,e;if("forward"===(r.direction||"forward")){let n=t.transform(e.value,e);return n instanceof Promise?n.then(n=>nS(e,n,t.out,r)):nS(e,n,t.out,r)}{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(n=>nS(e,n,t.in,r)):nS(e,n,t.in,r)}}function nS(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}(e,t)=>{rA.init(e,t),e$(e._zod,"values",()=>t.in._zod.values),e$(e._zod,"optin",()=>t.in._zod.optin),e$(e._zod,"optout",()=>t.out._zod.optout),e$(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("forward"===(r.direction||"forward")){let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>n_(e,t,r)):n_(n,t,r)}{let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>n_(e,t,r)):n_(n,t,r)}}},(e,t)=>{nv.init(e,t)};let nx=e_("$ZodReadonly",(e,t)=>{rA.init(e,t),e$(e._zod,"propValues",()=>t.innerType._zod.propValues),e$(e._zod,"values",()=>t.innerType._zod.values),e$(e._zod,"optin",()=>t.innerType?._zod?.optin),e$(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(nR):nR(n)}});function nR(e){return e.value=Object.freeze(e.value),e}(e,t)=>{rA.init(e,t);let r=[];for(let e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let n=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else if(null===e||eW.has(typeof e))r.push(eF(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>("string"!=typeof r.value?r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source})),r)},(e,t)=>{rA.init(e,t),e$(e._zod,"innerType",()=>(t._cachedInner||(t._cachedInner=t.getter()),t._cachedInner)),e$(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),e$(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),e$(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),e$(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)};let nT=e_("$ZodCustom",(e,t)=>{tG.init(e,t),rA.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>nI(t,r,n,e));nI(i,r,n,e)}});function nI(e,t,r,n){if(!e){let e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(e3(e))}}Symbol("ZodOutput"),Symbol("ZodInput");(m=globalThis).__zod_globalRegistry??(m.__zod_globalRegistry=new class e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});let nU=globalThis.__zod_globalRegistry;function nO(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...eZ(t)})}function nP(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...eZ(t)})}function nC(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...eZ(t)})}function nD(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...eZ(t)})}function nL(e,t){return new tY({check:"less_than",...eZ(t),value:e,inclusive:!1})}function n$(e,t){return new tY({check:"less_than",...eZ(t),value:e,inclusive:!0})}function nz(e,t){return new tX({check:"greater_than",...eZ(t),value:e,inclusive:!1})}function nN(e,t){return new tX({check:"greater_than",...eZ(t),value:e,inclusive:!0})}function nj(e,t){return new t0({check:"multiple_of",...eZ(t),value:e})}function nH(e,t){return new t8({check:"max_length",...eZ(t),maximum:e})}function nB(e,t){return new t3({check:"min_length",...eZ(t),minimum:e})}function nq(e,t){return new t9({check:"length_equals",...eZ(t),length:e})}function nM(e){return new ro({check:"overwrite",tx:e})}e.i(10107);var nV=e.i(2721),nV=nV;function nK(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??nU,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function nW(e,t,r={path:[],schemaPath:[]}){var n;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,n);else{let r=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,r,n)}let a=e._zod.parent;a&&(o.ref||(o.ref=a),nW(a,t,n),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),"input"===t.io&&function e(t,r){let n=r??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let i=t._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return e(i.element,n);if("set"===i.type)return e(i.valueType,n);if("lazy"===i.type)return e(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return e(i.innerType,n);if("intersection"===i.type)return e(i.left,n)||e(i.right,n);if("record"===i.type||"map"===i.type)return e(i.keyType,n)||e(i.valueType,n);if("pipe"===i.type)return!!t._zod.traits.has("$ZodCodec")||e(i.in,n)||e(i.out,n);if("object"===i.type){for(let t in i.shape)if(e(i.shape[t],n))return!0;return!1}if("union"===i.type){for(let t of i.options)if(e(t,n))return!0;return!1}if("tuple"===i.type){for(let t of i.items)if(e(t,n))return!0;if(i.rest&&e(i.rest,n))return!0}return!1}(e)&&(delete o.schema.examples,delete o.schema.default),"input"===t.io&&"_prefault"in o.schema&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function nF(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=n.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let n=t[1],{ref:i,defId:a}=(t=>{let n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(r)return{ref:i(r)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i("__shared")}#/${n}/${a}`}}if(t[1]===r)return{ref:"#"};let i=`#/${n}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}})(t);n.def={...n.schema},a&&(n.defId=a);let o=n.schema;for(let e in o)delete o[e];o.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>
|
|
61
|
+
|
|
62
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let n=r[1];if(t===r[0]){i(r);continue}if(e.external){let n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){i(r);continue}}if(e.metadataRegistry.get(r[0])?.id||n.cycle||n.count>1&&"ref"===e.reused){i(r);continue}}}function nJ(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,a={...i},o=r.ref;if(r.ref=null,o){n(o);let r=e.seen.get(o),s=r.schema;if(s.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in a||delete i[e]);if(s.$ref&&r.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){n(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())n(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let a=e.metadataRegistry.get(t)?.id;void 0!==a&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:nZ(t,"input",e.processors),output:nZ(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let nZ=(e,t,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=nK({...i??{},target:a,io:t,processors:r});return nW(e,o),nF(o,e),nJ(o,e)},nG={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nQ=(e,t,r,n)=>{let i=e._zod.def;nW(i.innerType,t,n),t.seen.get(e).ref=i.innerType},nY=e_("ZodISODateTime",(e,t)=>{rD.init(e,t),ip.init(e,t)}),nX=e_("ZodISODate",(e,t)=>{rL.init(e,t),ip.init(e,t)}),n0=e_("ZodISOTime",(e,t)=>{r$.init(e,t),ip.init(e,t)}),n1=e_("ZodISODuration",(e,t)=>{rz.init(e,t),ip.init(e,t)}),n2=e_("ZodError",(e,t)=>{rl.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>(function(e,t=e=>e.message){let r={_errors:[]},n=(e,i=[])=>{for(let a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(e=>n({issues:e},[...i,...a.path]));else if("invalid_key"===a.code)n({issues:a.issues},[...i,...a.path]);else if("invalid_element"===a.code)n({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(0===e.length)r._errors.push(t(a));else{let n=r,i=0;for(;i<e.length;){let r=e[i];i===e.length-1?(n[r]=n[r]||{_errors:[]},n[r]._errors.push(t(a))):n[r]=n[r]||{_errors:[]},n=n[r],i++}}}};return n(e),r})(e,t)},flatten:{value:t=>(function(e,t=e=>e.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}})(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,eU,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,eU,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),n5=ru(n2),n6=rf(n2),n4=rm(n2),n8=rg(n2),n3=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return ru(n2)(e,t,n)},n9=(e,t,r)=>ru(n2)(e,t,r),n7=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return rf(n2)(e,t,n)},ie=async(e,t,r)=>rf(n2)(e,t,r),it=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return rm(n2)(e,t,n)},ir=(e,t,r)=>rm(n2)(e,t,r),ii=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return rg(n2)(e,t,n)},ia=async(e,t,r)=>rg(n2)(e,t,r),io=new WeakMap;function is(e,t,r){let n=Object.getPrototypeOf(e),i=io.get(n);if(i||(i=new Set,io.set(n,i)),!i.has(t))for(let e in i.add(t),r){let t=r[e];Object.defineProperty(n,e,{configurable:!0,enumerable:!1,get(){let r=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:r}),r},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}let ic=e_("ZodType",(e,t)=>(rA.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:nZ(e,"input"),output:nZ(e,"output")}}),e.toJSONSchema=((e,t={})=>r=>{let n=nK({...r,processors:t});return nW(e,n),nF(n,e),nJ(n,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,r)=>n5(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>n4(e,t,r),e.parseAsync=async(t,r)=>n6(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>n8(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>n3(e,t,r),e.decode=(t,r)=>n9(e,t,r),e.encodeAsync=async(t,r)=>n7(e,t,r),e.decodeAsync=async(t,r)=>ie(e,t,r),e.safeEncode=(t,r)=>it(e,t,r),e.safeDecode=(t,r)=>ir(e,t,r),e.safeEncodeAsync=async(t,r)=>ii(e,t,r),e.safeDecodeAsync=async(t,r)=>ia(e,t,r),is(e,"ZodType",{check(...e){let t=this.def;return this.clone(nV.mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return eJ(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return new aa({type:"custom",check:"custom",fn:e,...eZ(t)})}(e,t))},superRefine(e,t){return this.check(function(e,t){var r;let n,i;return r=t=>(t.addIssue=e=>{"string"==typeof e?t.issues.push(e3(e,t.value,n._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=t.value),e.inst??(e.inst=n),e.continue??(e.continue=!n._zod.def.abort),t.issues.push(e3(e)))},e(t.value,t)),(i=new tG({check:"custom",...eZ(t)}))._zod.check=r,n=i}(e,t))},overwrite(e){return this.check(nM(e))},optional(){return i6(this)},exactOptional(){var e;return e=this,new i4({type:"optional",innerType:e})},nullable(){return i3(this)},nullish(){return i6(i3(this))},nonoptional(e){var t,r;return t=this,r=e,new ae({type:"nonoptional",innerType:t,...nV.normalizeParams(r)})},array(){return iF(this)},or(e){return new iG({type:"union",options:[this,e],...nV.normalizeParams(void 0)})},and(e){var t;return t=this,new iQ({type:"intersection",left:t,right:e})},transform(e){return an(this,new i2({type:"transform",transform:e}))},default(e){var t,r;return t=this,r=e,new i9({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():nV.shallowClone(r)}})},prefault(e){var t,r;return t=this,r=e,new i7({type:"prefault",innerType:t,get defaultValue(){return"function"==typeof r?r():nV.shallowClone(r)}})},catch(e){var t,r;return t=this,new at({type:"catch",innerType:t,catchValue:"function"==typeof(r=e)?r:()=>r})},pipe(e){return an(this,e)},readonly(){var e;return e=this,new ai({type:"readonly",innerType:e})},describe(e){let t=this.clone();return nU.add(t,{description:e}),t},meta(...e){if(0===e.length)return nU.get(this);let t=this.clone();return nU.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>nU.get(e)?.description,configurable:!0}),e)),il=e_("_ZodString",(e,t)=>{rE.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{r.type="string";let{minimum:i,maximum:a,format:o,patterns:s,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof a&&(r.maxLength=a),o&&(r.format=nG[o]??o,""===r.format&&delete r.format,"time"===o&&delete r.format),c&&(r.contentEncoding=c),s&&s.size>0){let e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,r,0);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,is(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new re({check:"string_format",format:"regex",...eZ(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new rn({check:"string_format",format:"includes",...eZ(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new ri({check:"string_format",format:"starts_with",...eZ(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new ra({check:"string_format",format:"ends_with",...eZ(t),suffix:e})}(...e))},min(...e){return this.check(nB(...e))},max(...e){return this.check(nH(...e))},length(...e){return this.check(nq(...e))},nonempty(...e){return this.check(nB(1,...e))},lowercase(e){return this.check(new rt({check:"string_format",format:"lowercase",...eZ(e)}))},uppercase(e){return this.check(new rr({check:"string_format",format:"uppercase",...eZ(e)}))},trim(){return this.check(nM(e=>e.trim()))},normalize(...e){return this.check(function(e){return nM(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(nM(e=>e.toLowerCase()))},toUpperCase(){return this.check(nM(e=>e.toUpperCase()))},slugify(){return this.check(nM(e=>eH(e)))}})}),id=e_("ZodString",(e,t)=>{rE.init(e,t),il.init(e,t),e.email=t=>e.check(nO(ih,t)),e.url=t=>e.check(new ig({type:"string",format:"url",check:"string_format",abort:!1,...eZ(t)})),e.jwt=t=>e.check(new iP({type:"string",format:"jwt",check:"string_format",abort:!1,...eZ(t)})),e.emoji=t=>e.check(new iw({type:"string",format:"emoji",check:"string_format",abort:!1,...eZ(t)})),e.guid=t=>e.check(nP(im,t)),e.uuid=t=>e.check(new iy({type:"string",format:"uuid",check:"string_format",abort:!1,...eZ(t)})),e.uuidv4=t=>e.check(new iy({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...eZ(t)})),e.uuidv6=t=>e.check(new iy({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...eZ(t)})),e.uuidv7=t=>e.check(new iy({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...eZ(t)})),e.nanoid=t=>e.check(new ib({type:"string",format:"nanoid",check:"string_format",abort:!1,...eZ(t)})),e.guid=t=>e.check(nP(im,t)),e.cuid=t=>e.check(new iA({type:"string",format:"cuid",check:"string_format",abort:!1,...eZ(t)})),e.cuid2=t=>e.check(new iE({type:"string",format:"cuid2",check:"string_format",abort:!1,...eZ(t)})),e.ulid=t=>e.check(new iv({type:"string",format:"ulid",check:"string_format",abort:!1,...eZ(t)})),e.base64=t=>e.check(new iI({type:"string",format:"base64",check:"string_format",abort:!1,...eZ(t)})),e.base64url=t=>e.check(new iU({type:"string",format:"base64url",check:"string_format",abort:!1,...eZ(t)})),e.xid=t=>e.check(new ik({type:"string",format:"xid",check:"string_format",abort:!1,...eZ(t)})),e.ksuid=t=>e.check(new i_({type:"string",format:"ksuid",check:"string_format",abort:!1,...eZ(t)})),e.ipv4=t=>e.check(nC(iS,t)),e.ipv6=t=>e.check(nD(ix,t)),e.cidrv4=t=>e.check(new iR({type:"string",format:"cidrv4",check:"string_format",abort:!1,...eZ(t)})),e.cidrv6=t=>e.check(new iT({type:"string",format:"cidrv6",check:"string_format",abort:!1,...eZ(t)})),e.e164=t=>e.check(new iO({type:"string",format:"e164",check:"string_format",abort:!1,...eZ(t)})),e.datetime=t=>e.check(new nY({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...eZ(t)})),e.date=t=>e.check(new nX({type:"string",format:"date",check:"string_format",...eZ(t)})),e.time=t=>e.check(new n0({type:"string",format:"time",check:"string_format",precision:null,...eZ(t)})),e.duration=t=>e.check(new n1({type:"string",format:"duration",check:"string_format",...eZ(t)}))});function iu(e){return new id({type:"string",...eZ(e)})}let ip=e_("ZodStringFormat",(e,t)=>{rv.init(e,t),il.init(e,t)}),ih=e_("ZodEmail",(e,t)=>{rS.init(e,t),ip.init(e,t)}),im=e_("ZodGUID",(e,t)=>{rk.init(e,t),ip.init(e,t)}),iy=e_("ZodUUID",(e,t)=>{r_.init(e,t),ip.init(e,t)}),ig=e_("ZodURL",(e,t)=>{rx.init(e,t),ip.init(e,t)}),iw=e_("ZodEmoji",(e,t)=>{rR.init(e,t),ip.init(e,t)}),ib=e_("ZodNanoID",(e,t)=>{rT.init(e,t),ip.init(e,t)}),iA=e_("ZodCUID",(e,t)=>{rI.init(e,t),ip.init(e,t)}),iE=e_("ZodCUID2",(e,t)=>{rU.init(e,t),ip.init(e,t)}),iv=e_("ZodULID",(e,t)=>{rO.init(e,t),ip.init(e,t)}),ik=e_("ZodXID",(e,t)=>{rP.init(e,t),ip.init(e,t)}),i_=e_("ZodKSUID",(e,t)=>{rC.init(e,t),ip.init(e,t)}),iS=e_("ZodIPv4",(e,t)=>{rN.init(e,t),ip.init(e,t)}),ix=e_("ZodIPv6",(e,t)=>{rj.init(e,t),ip.init(e,t)}),iR=e_("ZodCIDRv4",(e,t)=>{rH.init(e,t),ip.init(e,t)}),iT=e_("ZodCIDRv6",(e,t)=>{rB.init(e,t),ip.init(e,t)}),iI=e_("ZodBase64",(e,t)=>{rM.init(e,t),ip.init(e,t)}),iU=e_("ZodBase64URL",(e,t)=>{rV.init(e,t),ip.init(e,t)}),iO=e_("ZodE164",(e,t)=>{rK.init(e,t),ip.init(e,t)}),iP=e_("ZodJWT",(e,t)=>{rW.init(e,t),ip.init(e,t)}),iC=e_("ZodNumber",(e,t)=>{rF.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let{minimum:i,maximum:a,format:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof o&&o.includes("int")?r.type="integer":r.type="number";let d="number"==typeof l&&l>=(i??-1/0),u="number"==typeof c&&c<=(a??1/0),p="draft-04"===t.target||"openapi-3.0"===t.target;d?p?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),u?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:"number"==typeof a&&(r.maximum=a),"number"==typeof s&&(r.multipleOf=s)})(e,t,r,0),is(e,"ZodNumber",{gt(e,t){return this.check(nz(e,t))},gte(e,t){return this.check(nN(e,t))},min(e,t){return this.check(nN(e,t))},lt(e,t){return this.check(nL(e,t))},lte(e,t){return this.check(n$(e,t))},max(e,t){return this.check(n$(e,t))},int(e){return this.check(i$(e))},safe(e){return this.check(i$(e))},positive(e){return this.check(nz(0,e))},nonnegative(e){return this.check(nN(0,e))},negative(e){return this.check(nL(0,e))},nonpositive(e){return this.check(n$(0,e))},multipleOf(e,t){return this.check(nj(e,t))},step(e,t){return this.check(nj(e,t))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??-1/0,r.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(r.maximum??1/0,r.exclusiveMaximum??1/0)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function iD(e){return new iC({type:"number",checks:[],...eZ(e)})}let iL=e_("ZodNumberFormat",(e,t)=>{rJ.init(e,t),iC.init(e,t)});function i$(e){return new iL({type:"number",check:"number_format",abort:!1,format:"safeint",...eZ(e)})}let iz=e_("ZodBoolean",(e,t)=>{rZ.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.type="boolean"}});function iN(e){return new iz({type:"boolean",...eZ(e)})}let ij=e_("ZodBigInt",(e,t)=>{rG.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")})(0,e,0,0),e.gte=(t,r)=>e.check(nN(t,r)),e.min=(t,r)=>e.check(nN(t,r)),e.gt=(t,r)=>e.check(nz(t,r)),e.gte=(t,r)=>e.check(nN(t,r)),e.min=(t,r)=>e.check(nN(t,r)),e.lt=(t,r)=>e.check(nL(t,r)),e.lte=(t,r)=>e.check(n$(t,r)),e.max=(t,r)=>e.check(n$(t,r)),e.positive=t=>e.check(nz(BigInt(0),t)),e.negative=t=>e.check(nL(BigInt(0),t)),e.nonpositive=t=>e.check(n$(BigInt(0),t)),e.nonnegative=t=>e.check(nN(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(nj(t,r));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),iH=e_("ZodAny",(e,t)=>{rQ.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function iB(){return new iH({type:"any"})}let iq=e_("ZodUnknown",(e,t)=>{rY.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function iM(){return new iq({type:"unknown"})}let iV=e_("ZodNever",(e,t)=>{rX.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.not={}}}),iK=e_("ZodDate",(e,t)=>{r0.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")})(0,e,0,0),e.min=(t,r)=>e.check(nN(t,r)),e.max=(t,r)=>e.check(n$(t,r));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null}),iW=e_("ZodArray",(e,t)=>{r2.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(r.minItems=a),"number"==typeof o&&(r.maxItems=o),r.type="array",r.items=nW(i.element,t,{...n,path:[...n.path,"items"]})})(e,t,r,n),e.element=t.element,is(e,"ZodArray",{min(e,t){return this.check(nB(e,t))},nonempty(e){return this.check(nB(1,e))},max(e,t){return this.check(nH(e,t))},length(e,t){return this.check(nq(e,t))},unwrap(){return this.element}})});function iF(e,t){return new iW({type:"array",element:e,...eZ(t)})}let iJ=e_("ZodObject",(e,t)=>{r3.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object",r.properties={};let a=i.shape;for(let e in a)r.properties[e]=nW(a[e],t,{...n,path:[...n.path,"properties",e]});let o=new Set([...new Set(Object.keys(a))].filter(e=>{let r=i.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));o.size>0&&(r.required=Array.from(o)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=nW(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)})(e,t,r,n),nV.defineLazy(e,"shape",()=>t.shape),is(e,"ZodObject",{keyof(){return i1(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:iM()})},loose(){return this.clone({...this._zod.def,catchall:iM()})},strict(){return this.clone({...this._zod.def,catchall:new iV({type:"never",...eZ(void 0)})})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return nV.extend(this,e)},safeExtend(e){return nV.safeExtend(this,e)},merge(e){return nV.merge(this,e)},pick(e){return nV.pick(this,e)},omit(e){return nV.omit(this,e)},partial(...e){return nV.partial(i5,this,e[0])},required(...e){return nV.required(ae,this,e[0])}})});function iZ(e,t){return new iJ({type:"object",shape:e??{},...nV.normalizeParams(t)})}let iG=e_("ZodUnion",(e,t)=>{r7.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{var i,a,o,s;let c,l,d;return i=e,a=t,o=r,s=n,l=!1===(c=i._zod.def).inclusive,d=c.options.map((e,t)=>nW(e,a,{...s,path:[...s.path,l?"oneOf":"anyOf",t]})),void(l?o.oneOf=d:o.anyOf=d)},e.options=t.options}),iQ=e_("ZodIntersection",(e,t)=>{nt.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o,s;return a=nW((i=e._zod.def).left,t,{...n,path:[...n.path,"allOf",0]}),o=nW(i.right,t,{...n,path:[...n.path,"allOf",1]}),void(r.allOf=[...(s=e=>"allOf"in e&&1===Object.keys(e).length)(a)?a.allOf:[a],...s(o)?o.allOf:[o]])}}),iY=e_("ZodRecord",(e,t)=>{ns.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object";let a=i.keyType,o=a._zod.bag,s=o?.patterns;if("loose"===i.mode&&s&&s.size>0){let e=nW(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});for(let t of(r.patternProperties={},s))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=nW(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=nW(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let c=a._zod.values;if(c){let e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}})(e,t,r,n),e.keyType=t.keyType,e.valueType=t.valueType});function iX(e,t,r){return new iY(t&&t._zod?{type:"record",keyType:e,valueType:t,...nV.normalizeParams(r)}:{type:"record",keyType:iu(),valueType:e,...nV.normalizeParams(t)})}let i0=e_("ZodEnum",(e,t)=>{nd.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;(i=eI(e._zod.def.entries)).every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{let i={};for(let n of e)if(r.has(n))i[n]=t.entries[n];else throw Error(`Key ${n} not found in enum`);return new i0({...t,checks:[],...nV.normalizeParams(n),entries:i})},e.exclude=(e,n)=>{let i={...t.entries};for(let t of e)if(r.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new i0({...t,checks:[],...nV.normalizeParams(n),entries:i})}});function i1(e,t){return new i0({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...nV.normalizeParams(t)})}let i2=e_("ZodTransform",(e,t)=>{nu.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")})(0,e,0,0),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new ex(e.constructor.name);r.addIssue=n=>{"string"==typeof n?r.issues.push(nV.issue(n,r.value,t)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),r.issues.push(nV.issue(n)))};let i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}}),i5=e_("ZodOptional",(e,t)=>{nf.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>nQ(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function i6(e){return new i5({type:"optional",innerType:e})}let i4=e_("ZodExactOptional",(e,t)=>{nh.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>nQ(e,t,r,n),e.unwrap=()=>e._zod.def.innerType}),i8=e_("ZodNullable",(e,t)=>{nm.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=nW((i=e._zod.def).innerType,t,n),o=t.seen.get(e),void("openapi-3.0"===t.target?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}])},e.unwrap=()=>e._zod.def.innerType});function i3(e){return new i8({type:"nullable",innerType:e})}let i9=e_("ZodDefault",(e,t)=>{ny.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;nW((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),i7=e_("ZodPrefault",(e,t)=>{nw.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;nW((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},e.unwrap=()=>e._zod.def.innerType}),ae=e_("ZodNonOptional",(e,t)=>{nb.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;nW((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType},e.unwrap=()=>e._zod.def.innerType}),at=e_("ZodCatch",(e,t)=>{nE.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i,a=e._zod.def;nW(a.innerType,t,n),t.seen.get(e).ref=a.innerType;try{i=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i})(e,t,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),ar=e_("ZodPipe",(e,t)=>{nv.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=(i=e._zod.def).in._zod.traits.has("$ZodTransform"),void(nW(o="input"===t.io?a?i.out:i.in:i.out,t,n),t.seen.get(e).ref=o)},e.in=t.in,e.out=t.out});function an(e,t){return new ar({type:"pipe",in:e,out:t})}let ai=e_("ZodReadonly",(e,t)=>{nx.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;nW((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.readOnly=!0},e.unwrap=()=>e._zod.def.innerType}),aa=e_("ZodCustom",(e,t)=>{nT.init(e,t),ic.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")})(0,e,0,0)}),ao={};function as(e){switch(e.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function ac(e){let t=[];return e.metadata?.openapi?.parameters?t.push(...e.metadata.openapi.parameters):e.query instanceof iJ&&Object.entries(e.query.shape).forEach(([e,r])=>{r instanceof iJ&&t.push({name:e,in:"query",schema:{type:as(r),..."minLength"in r&&r.minLength?{minLength:r.minLength}:{},description:r.description}})}),t}function al(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function ad(e,t){return Object.entries(e).forEach(([e,t])=>{let r=t.options;if(!(!t.path||r.metadata?.SERVER_ONLY)&&("GET"===r.method&&(ao[t.path]={get:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:ac(r),responses:al(r.metadata?.openapi?.responses)}}),"POST"===r.method)){let e=function(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof iJ||e.body instanceof i5)){let t=e.body.shape;if(!t)return;let r={},n=[];return Object.entries(t).forEach(([e,t])=>{t instanceof iJ&&(r[e]={type:as(t),description:t.description},t instanceof i5||n.push(e))}),{required:!(e.body instanceof i5)&&!!e.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}(r);ao[t.path]={post:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:ac(r),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:al(r.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:ao}}let au=((o=function(){}).prototype=Object.create(null),Object.freeze(o.prototype),o);function ap(){return{root:{key:""},static:new au}}function af(e){let[t,...r]=e.split("/");return""===r[r.length-1]?r.slice(0,-1):r}function ah(e,t){let r=new au;for(let[n,i]of t){let t=n<0?e.slice(-(n+1)).join("/"):e[n];if("string"==typeof i)r[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)r[t]=e.groups[t]}}return r}function am(e,t="",r,n){t=t.toUpperCase(),47!==r.charCodeAt(0)&&(r=`/${r}`);let i=af(r=r.replace(/\\:/g,"%3A")),a=e.root,o=0,s=[],c=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.startsWith("**")){a.wildcard||(a.wildcard={key:"**"}),a=a.wildcard,s.push([-(e+1),t.split(":")[1]||"_",2===t.length]);break}if("*"===t||t.includes(":")){if(a.param||(a.param={key:"*"}),a=a.param,"*"===t)s.push([e,`_${o++}`,!0]);else if(t.includes(":",1)){let r=function(e){let t=e.replace(/:(\w+)/g,(e,t)=>`(?<${t}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${t}$`)}(t);c[e]=r,a.hasRegexParam=!0,s.push([e,r,!1])}else s.push([e,t.slice(1),!1]);continue}"\\*"===t?t=i[e]="*":"\\*\\*"===t&&(t=i[e]="**");let r=a.static?.[t];if(r)a=r;else{let e={key:t};a.static||(a.static=new au),a.static[t]=e,a=e}}let l=s.length>0;a.methods||(a.methods=new au),a.methods[t]??=[],a.methods[t].push({data:n||null,paramsRegexp:c,paramsMap:l?s:void 0}),l||(e.static["/"+i.join("/")]=a)}function ay(e){return e instanceof X.APIError||e instanceof Y.APIError||e?.name==="APIError"}let ag=ek(async()=>({})),aw=ek.create({use:[ag,ek(async()=>({}))]}),ab=[ag];function aA(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r,o=async e=>{try{return await Q(e,()=>a(e))}catch(r){var t;throw t=e.responseHeaders,ay(r)&&t&&Object.defineProperty(r,X.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,value:t,writable:!1}),r}};return n?ev(n,{...i,use:[...i?.use||[],...ab]},o):ev({...i,use:[...i?.use||[],...ab]},o)}aA.serverOnly=(e,t)=>aA({...e,metadata:{...e.metadata,SERVER_ONLY:!0}},t);var aE=e.i(89551),av=e.i(12714),ak=e.i(50227),a_=e.i(43651),aS=e.i(80527);async function ax(t,r){let n;if(t.database)n="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,a_.getAuthTables)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await e.A(16432);n=i(r)(t)}return n.transaction||(aS.logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),n.transaction=async e=>e(n)),n}async function aR(t){return ax(t,async t=>{let{createKyselyAdapter:r}=await e.A(19783),{kysely:n,databaseType:i,transaction:a}=await r(t);if(!n)throw new Y.BetterAuthError("Failed to initialize database adapter");let{kyselyAdapter:o}=await e.A(19783);return o(n,{type:i||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:a})(t)})}var aT=e.i(13906),aI=e.i(15272),aU=e.i(97495),aO=e.i(29401);let aP={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};async function aC(e){try{let t=await aO.sql`SHOW search_path`.execute(e),r=t.rows[0]?.search_path??t.rows[0]?.searchPath;if(r)return r.split(",").map(e=>e.trim()).map(e=>e.replace(/^["']|["']$/g,"")).filter(e=>!e.startsWith("$")&&!e.startsWith("\\$"))[0]||"public"}catch{}return"public"}async function aD(e){let t=function(e){let t=(0,a_.getAuthTables)(e),r={};for(let e in t){let n=t[e],i=n.fields,a={};if(Object.entries(i).forEach(([e,r])=>{if(a[r.fieldName||e]=r,r.references){let n=t[r.references.model];n&&(a[r.fieldName||e].references={...r.references,model:n.modelName,field:r.references.field})}}),r[n.modelName]){r[n.modelName].fields={...r[n.modelName].fields,...a},n.disableMigrations&&(r[n.modelName].disableMigrations=!0);continue}r[n.modelName]={fields:a,order:n.order||1/0,disableMigrations:n.disableMigrations}}return r}(e),r=(0,aS.createLogger)(e.logger),{kysely:n,databaseType:i}=await (0,aT.createKyselyAdapter)(e);i||(r.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),i="sqlite"),n||(r.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let a="public";if("postgres"===i){a=await aC(n),r.debug(`PostgreSQL migration: Using schema '${a}' (from search_path)`);try{let e=await aO.sql`
|
|
63
|
+
SELECT schema_name
|
|
64
|
+
FROM information_schema.schemata
|
|
65
|
+
WHERE schema_name = ${a}
|
|
66
|
+
`.execute(n);(e.rows[0]?.schema_name??e.rows[0]?.schemaName)||r.warn(`Schema '${a}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`)}catch(e){r.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}}let o=await n.introspection.getTables(),s=o;if("postgres"===i)try{let e=await aO.sql`
|
|
67
|
+
SELECT table_name
|
|
68
|
+
FROM information_schema.tables
|
|
69
|
+
WHERE table_schema = ${a}
|
|
70
|
+
AND table_type = 'BASE TABLE'
|
|
71
|
+
`.execute(n),t=new Set(e.rows.map(e=>e.table_name??e.tableName));s=o.filter(e=>e.schema===a&&t.has(e.name)),r.debug(`Found ${s.length} table(s) in schema '${a}': ${s.map(e=>e.name).join(", ")||"(none)"}`)}catch(e){r.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${e instanceof Error?e.message:String(e)}`)}let c=[],l=[];for(let[e,n]of Object.entries(t)){if(n.disableMigrations)continue;let t=s.find(t=>t.name===e);if(!t){let t=c.findIndex(t=>t.table===e),r={table:e,fields:n.fields,order:n.order||1/0},i=c.findIndex(e=>(e.order||1/0)>r.order);-1===i?-1===t?c.push(r):c[t].fields={...c[t].fields,...n.fields}:c.splice(i,0,r);continue}let a={};for(let[o,s]of Object.entries(n.fields)){let n=t.columns.find(e=>e.name===o);if(!n){a[o]=s;continue}!function(e,t,r){if("string[]"===t||"number[]"===t)return e.toLowerCase().includes("json");let n=aP[r];return(Array.isArray(t)?n.string.map(e=>e.toLowerCase()):n[t].map(e=>e.toLowerCase())).includes(e.toLowerCase().split("(")[0].trim())}(n.dataType,s.type,i)&&r.warn(`Field ${o} in table ${e} has a different type in the database. Expected ${s.type} but got ${n.dataType}.`)}Object.keys(a).length>0&&l.push({table:e,fields:a,order:n.order||1/0})}let d=[],u=e.advanced?.database?.generateId==="uuid",p=e.advanced?.database?.generateId==="serial";function f(e,t){let r=e.type,n=i||"sqlite",a={string:{sqlite:"text",postgres:"text",mysql:e.unique?"varchar(255)":e.references?"varchar(36)":e.sortable||e.index?"varchar(255)":"text",mssql:e.unique||e.sortable?"varchar(255)":e.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:e.bigint?"bigint":"integer",postgres:e.bigint?"bigint":"integer",mysql:e.bigint?"bigint":"integer",mssql:e.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:aO.sql`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:p?aO.sql`integer GENERATED BY DEFAULT AS IDENTITY`:u?"uuid":"text",mysql:p?"integer":"varchar(36)",mssql:p?"integer":"varchar(36)",sqlite:p?"integer":"text"},foreignKeyId:{postgres:p?"integer":u?"uuid":"text",mysql:p?"integer":"varchar(36)",mssql:p?"integer":"varchar(36)",sqlite:p?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===t||e.references?.field==="id")return"id"===t?a.id[n]:a.foreignKeyId[n];if(Array.isArray(r))return"text";if(!(r in a))throw Error(`Unsupported field type '${String(r)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return a[r][n]}let h=(0,aU.initGetModelName)({schema:(0,a_.getAuthTables)(e),usePlural:!1}),m=(0,aI.initGetFieldName)({schema:(0,a_.getAuthTables)(e),usePlural:!1});function y(e,t){try{return`${h(e)}.${m({model:e,field:t})}`}catch{return`${e}.${t}`}}let g=[];if(l.length)for(let e of l)for(let[t,r]of Object.entries(e.fields)){let a=f(r,t),o=n.schema.alterTable(e.table);if(r.index){let i=`${e.table}_${t}_${r.unique?"uidx":"idx"}`,a=n.schema.createIndex(i).on(e.table).columns([t]);g.push(r.unique?a.unique():a)}let s=o.addColumn(t,a,e=>(e=!1!==r.required?e.notNull():e,r.references&&(e=e.references(y(r.references.model,r.references.field)).onDelete(r.references.onDelete||"cascade")),r.unique&&(e=e.unique()),"date"===r.type&&"function"==typeof r.defaultValue&&("postgres"===i||"mysql"===i||"mssql"===i)&&(e="mysql"===i?e.defaultTo(aO.sql`CURRENT_TIMESTAMP(3)`):e.defaultTo(aO.sql`CURRENT_TIMESTAMP`)),e));d.push(s)}if(c.length)for(let e of c){let t=f({type:p?"number":"string"},"id"),r=n.schema.createTable(e.table).addColumn("id",t,e=>{if(p)return"postgres"===i?e.primaryKey().notNull():"sqlite"===i?e.primaryKey().notNull():"mssql"===i?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull();return u&&"postgres"===i?e.primaryKey().defaultTo(aO.sql`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull()});for(let[t,a]of Object.entries(e.fields)){let o=f(a,t);if(r=r.addColumn(t,o,e=>(e=!1!==a.required?e.notNull():e,a.references&&(e=e.references(y(a.references.model,a.references.field)).onDelete(a.references.onDelete||"cascade")),a.unique&&(e=e.unique()),"date"===a.type&&"function"==typeof a.defaultValue&&("postgres"===i||"mysql"===i||"mssql"===i)&&(e="mysql"===i?e.defaultTo(aO.sql`CURRENT_TIMESTAMP(3)`):e.defaultTo(aO.sql`CURRENT_TIMESTAMP`)),e)),a.index){let r=n.schema.createIndex(`${e.table}_${t}_${a.unique?"uidx":"idx"}`).on(e.table).columns([t]);g.push(a.unique?r.unique():r)}}d.push(r)}for(let e of g)d.push(e);return{toBeCreated:c,toBeAdded:l,runMigrations:async function(){for(let e of d)await e.execute()},compileMigrations:async function(){return d.map(e=>e.compile().sql).join(";\n\n")+";"}}}function aL(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function a$(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function az(e,t){if("string"!=typeof e&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(("string"==typeof t||"boolean"==typeof t)&&(t={separator:t}),2==arguments.length&&!(void 0===t||"object"==typeof t&&null!==t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if("\\"===(t=t||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=function e(t,r=!0){if(Array.isArray(t))return`(?:${t.map(t=>`^${e(t,r)}$`).join("|")})`;let n="",i="",a=".";!0===r?(n="/",i="[/\\\\]",a="[^/\\\\]"):r&&((i=function(e){let t="";for(let r=0;r<e.length;r++)t+=aL(e[r]);return t}(n=r)).length>1?(i=`(?:${i})`,a=`((?!${i}).)`):a=`[^${i}]`);let o=r?`${i}+?`:"",s=r?`${i}*?`:"",c=r?t.split(n):[t],l="";for(let e=0;e<c.length;e++){let t=c[e],n=c[e+1],i="";if(t||!(e>0)){if(r&&(i=e===c.length-1?s:"**"!==n?o:""),r&&"**"===t){i&&(l+=0===e?"":i,l+=`(?:${a}*?${i})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(l+=aL(t[e+1]),e++):"?"===r?l+=a:"*"===r?l+=`${a}*?`:l+=aL(r)}l+=i}}return l}(e,t.separator),n=RegExp(`^${r}$`,t.flags),i=a$.bind(null,n);return i.options=t,i.pattern=e,i.regexp=n,i}var aN=e.i(56958);function aj(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)}function aH(e,t="/api/auth"){try{let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Y.BetterAuthError(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof Y.BetterAuthError)throw t;throw new Y.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}if(function(e){try{return"/"!==(aj(new URL(e).pathname)||"/")}catch{throw new Y.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e))return e;let r=aj(e);return t&&"/"!==t?(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`):r}function aB(e,t){return!!e&&""!==e.trim()&&("proto"===t?"http"===e||"https"===e:"host"===t&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))&&(/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e)))}function aq(e,t,r,n,i){if(e)return aH(e,t);if(!1!==n){let e=aN.env.BETTER_AUTH_URL||aN.env.NEXT_PUBLIC_BETTER_AUTH_URL||aN.env.PUBLIC_BETTER_AUTH_URL||aN.env.NUXT_PUBLIC_BETTER_AUTH_URL||aN.env.NUXT_PUBLIC_AUTH_URL||("/"!==aN.env.BASE_URL?aN.env.BASE_URL:void 0);if(e)return aH(e,t)}let a=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(a&&o&&i&&aB(o,"proto")&&aB(a,"host"))try{return aH(`${o}://${a}`,t)}catch(e){}if(r){let e=aM(r.url);if(!e)throw new Y.BetterAuthError("Could not get origin from request. Please provide a valid base URL.");return aH(e,t)}}function aM(e){try{let t=new URL(e);return"null"===t.origin?null:t.origin}catch{return null}}function aV(e){return"object"==typeof e&&null!==e&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function aK(e){return e instanceof Request||"object"==typeof e&&null!==e&&"[object Request]"===Object.prototype.toString.call(e)&&"string"==typeof e.url&&"object"==typeof e.headers&&null!==e.headers&&"function"==typeof e.headers.get}function aW(e,t){let r=aK(e)?e.headers:e;if(t){let e=r.get("x-forwarded-host");if(e&&aB(e,"host"))return e}let n=r.get("host");if(n&&aB(n,"host"))return n;if(aK(e))try{return new URL(e.url).host}catch{}return null}let aF=(e,t,r)=>{if(e.startsWith("/"))return!!r?.allowRelativePaths&&e.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e);if(t.includes("*")||t.includes("?")){if(t.includes("://"))return az(t)(aM(e)||e);let r=function(e){try{return new URL(e).host}catch{return null}}(e);return!!r&&az(t)(r)}let n=function(e){try{return new URL(e).protocol}catch{return null}}(e);return"http:"!==n&&"https:"!==n&&n?e.startsWith(t):t===aM(e)};function aJ(e){return!!e.database||!!e.secondaryStorage}function aZ(e){return!!e.database}function aG(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}var aQ=e.i(66680);function aY(e,t){return new Promise((r,n)=>{(0,aQ.scrypt)(e.normalize("NFKC"),t,64,{N:16384,r:16,p:1,maxmem:0x4000000},(e,t)=>{e?n(e):r(t)})})}async function aX(e){let t=(0,aQ.randomBytes)(16).toString("hex"),r=await aY(e,t);return`${t}:${r.toString("hex")}`}async function a0(e,t){let[r,n]=e.split(":");if(!r||!n)throw Error("Invalid password hash");return(await aY(t,r)).toString("hex")===n}let a1=async({hash:e,password:t})=>a0(e,t);function a2(e,t=""){if("number"!=typeof e){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function a5(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function a6(e){if("function"!=typeof e||"function"!=typeof e.create)throw TypeError("Hash must wrapped by utils.createHasher");if(a2(e.outputLen),a2(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function a4(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function a8(e,t){a5(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function a3(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function a9(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function a7(e,t){return e<<32-t|e>>>t}class oe{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(a6(e),a5(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),a3(n)}update(e){return a4(this),this.iHash.update(e),this}digestInto(e){a4(this),a8(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let ot=((s=(e,t,r)=>new oe(e,t).update(r).digest()).create=(e,t)=>new oe(e,t),s),or=Uint8Array.of(0),on=Uint8Array.of();class oi{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=a9(this.buffer)}update(e){a4(this),a5(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let t=a9(e);for(;n<=i-a;a+=n)this.process(t,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){a4(this),a8(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;t[a++]=128,a3(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let e=a;e<n;e++)t[e]=0;r.setBigUint64(n-8,BigInt(8*this.length),i),this.process(r,0);let o=a9(e),s=this.outputLen;if(s%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}let oa=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),oo=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),os=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),oc=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),ol=BigInt(0x100000000-1),od=BigInt(32),ou=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),op=new Uint32Array(64);class of extends oi{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:s}=this;return[e,t,r,n,i,a,o,s]}set(e,t,r,n,i,a,o,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|a,this.G=0|o,this.H=0|s}process(e,t){for(let r=0;r<16;r++,t+=4)op[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=op[e-15],r=op[e-2],n=a7(t,7)^a7(t,18)^t>>>3,i=a7(r,17)^a7(r,19)^r>>>10;op[e]=i+op[e-7]+n+op[e-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){var d,u,p,f;let t=l+(a7(o,6)^a7(o,11)^a7(o,25))+((d=o)&s^~d&c)+ou[e]+op[e]|0,h=(a7(r,2)^a7(r,13)^a7(r,22))+((u=r)&(p=n)^u&(f=i)^p&f)|0;l=c,c=s,s=o,o=a+t|0,a=i,i=n,n=r,r=t+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,i,a,o,s,c,l)}roundClean(){a3(op)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),a3(this.buffer)}}class oh extends of{A=0|oa[0];B=0|oa[1];C=0|oa[2];D=0|oa[3];E=0|oa[4];F=0|oa[5];G=0|oa[6];H=0|oa[7];constructor(){super(32)}}let om=function(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){let{h:r,l:o}=function(e,t=!1){return t?{h:Number(e&ol),l:Number(e>>od&ol)}:{h:0|Number(e>>od&ol),l:0|Number(e&ol)}}(e[a],t);[n[a],i[a]]=[r,o]}return[n,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),oy=om[0],og=om[1],ow=new Uint32Array(80),ob=new Uint32Array(80),oA=function(e,t={}){let r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}(()=>new oh,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),oE=new TextEncoder,ov=new TextDecoder;function ok(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function o_(e,t,r){if(t<0||t>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function oS(e){let t=Math.floor(e/0x100000000),r=new Uint8Array(8);return o_(r,t,0),o_(r,e%0x100000000,4),r}function ox(e){let t=new Uint8Array(4);return o_(t,e),t}function oR(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function oT(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:ov.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=ov.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{var r=t;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);let e=atob(r),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function oI(e){let t=e;return("string"==typeof t&&(t=oE.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}e.s(["decode",0,oT,"encode",0,oI],97379);let oU=Symbol();function oO(e,t){if(e)throw TypeError(`${t} can only be called once`)}function oP(e,t,r){try{return oT(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}async function oC(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}let oD=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function oL(e,t){if(parseInt(e.hash.name.slice(4),10)!==t)throw oD(`SHA-${t}`,"algorithm.hash")}function o$(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function oz(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==e.algorithm.name)throw oD("AES-GCM");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw oD(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==e.algorithm.name)throw oD("AES-KW");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw oD(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw oD("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==e.algorithm.name)throw oD("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==e.algorithm.name)throw oD("RSA-OAEP");oL(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}o$(e,r)}function oN(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let oj=(e,...t)=>oN("Key must be ",e,...t),oH=(e,t,...r)=>oN(`Key for the ${e} algorithm must be `,t,...r);class oB extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class oq extends oB{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class oM extends oB{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class oV extends oB{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class oK extends oB{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class oW extends oB{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class oF extends oB{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class oJ extends oB{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class oZ extends oB{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class oG extends oB{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class oQ extends oB{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class oY extends oB{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class oX extends oB{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class o0 extends oB{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class o1 extends oB{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function o2(e){if(!o5(e))throw Error("CryptoKey instance expected")}let o5=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},o6=e=>e?.[Symbol.toStringTag]==="KeyObject",o4=e=>o5(e)||o6(e);function o8(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new oK(`Unsupported JWE Algorithm: ${e}`)}}let o3=e=>crypto.getRandomValues(new Uint8Array(o8(e)>>3));function o9(e,t){let r=e.byteLength<<3;if(r!==t)throw new oF(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function o7(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new oK(`Unsupported JWE Algorithm: ${e}`)}}function se(e,t){if(t.length<<3!==o7(e))throw new oF("Invalid Initialization Vector length")}async function st(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(oj(t,"Uint8Array"));let n=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),macKey:await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]),keySize:n}}async function sr(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function sn(e,t,r,n,i){let{encKey:a,macKey:o,keySize:s}=await st(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),l=ok(i,n,c,oS(i.length<<3));return{ciphertext:c,tag:await sr(o,l,s),iv:n}}async function si(e,t){if(!(e instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,e)),a=new Uint8Array(await crypto.subtle.sign(r,n,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return 0===o}async function sa(e,t,r,n,i,a){let o,s,{encKey:c,macKey:l,keySize:d}=await st(e,t,"decrypt"),u=ok(a,n,r,oS(a.length<<3)),p=await sr(l,u,d);try{o=await si(i,p)}catch{}if(!o)throw new oW;try{s=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!s)throw new oW;return s}async function so(e,t,r,n,i){let a;r instanceof Uint8Array?a=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(oz(r,e,"encrypt"),a=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:n}}async function ss(e,t,r,n,i,a){let o;t instanceof Uint8Array?o=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(oz(t,e,"decrypt"),o=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},o,ok(r,i)))}catch{throw new oW}}let sc="Unsupported JWE Content Encryption Algorithm";async function sl(e,t,r,n,i){if(!o5(r)&&!(r instanceof Uint8Array))throw TypeError(oj(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n)se(e,n);else n=crypto.getRandomValues(new Uint8Array(o7(e)>>3));switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&o9(r,parseInt(e.slice(-3),10)),sn(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&o9(r,parseInt(e.slice(1,4),10)),so(e,t,r,n,i);default:throw new oK(sc)}}async function sd(e,t,r,n,i,a){if(!o5(t)&&!(t instanceof Uint8Array))throw TypeError(oj(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new oF("JWE Initialization Vector missing");if(!i)throw new oF("JWE Authentication Tag missing");switch(se(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&o9(t,parseInt(e.slice(-3),10)),sa(e,t,r,n,i,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&o9(t,parseInt(e.slice(1,4),10)),ss(e,t,r,n,i,a);default:throw new oK(sc)}}function su(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function sp(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(oz(e,t,r),e)}async function sf(e,t,r){let n=await sp(t,e,"wrapKey");su(n,e);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function sh(e,t,r){let n=await sp(t,e,"unwrapKey");su(n,e);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}function sm(e){return ok(ox(e.length),e)}async function sy(e,t,r){let n=t>>3,i=Math.ceil(n/32),a=new Uint8Array(32*i);for(let t=1;t<=i;t++){let n=new Uint8Array(4+e.length+r.length);n.set(ox(t),0),n.set(e,4),n.set(r,4+e.length);let i=await oC("sha256",n);a.set(i,(t-1)*32)}return a.slice(0,n)}async function sg(e,t,r,n,i=new Uint8Array,a=new Uint8Array){var o;oz(e,"ECDH"),oz(t,"ECDH","deriveBits");let s=ok(sm(oR(r)),sm(i),sm(a),ox(n),new Uint8Array);return sy(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,"X25519"===(o=e).algorithm.name?256:Math.ceil(parseInt(o.algorithm.namedCurve.slice(-3),10)/8)<<3)),n,s)}function sw(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===e.algorithm.name}}async function sb(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new oF("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||1!==Math.sign(r))throw new oF("PBES2 Count Input must be a positive integer");let i=ok(oR(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},s=await (n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(oz(n,t,"deriveBits"),n));return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function sA(e,t,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await sb(i,e,n,t);return{encryptedKey:await sf(e.slice(-6),a,r),p2c:n,p2s:oI(i)}}async function sE(e,t,r,n,i){let a=await sb(i,e,n,t);return sh(e.slice(-6),a,r)}function sv(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function sk(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new oK(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function s_(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(oj(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}switch(e){case"HS256":case"HS384":case"HS512":if("HMAC"!==t.algorithm.name)throw oD("HMAC");oL(t.algorithm,parseInt(e.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==t.algorithm.name)throw oD("RSASSA-PKCS1-v1_5");oL(t.algorithm,parseInt(e.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==t.algorithm.name)throw oD("RSA-PSS");oL(t.algorithm,parseInt(e.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==t.algorithm.name)throw oD("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let n;if(n=t.algorithm,n.name!==e)throw oD(e);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==t.algorithm.name)throw oD("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(e);if(t.algorithm.namedCurve!==r)throw oD(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return o$(t,r),t}async function sS(e,t,r){let n=await s_(e,t,"sign");return sv(e,n),new Uint8Array(await crypto.subtle.sign(sk(e,n.algorithm),n,r))}async function sx(e,t,r,n){let i=await s_(e,t,"verify");sv(e,i);let a=sk(e,i.algorithm);try{return await crypto.subtle.verify(a,i,r,n)}catch{return!1}}let sR=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new oK(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function sT(e,t,r){return oz(t,e,"encrypt"),sv(e,t),new Uint8Array(await crypto.subtle.encrypt(sR(e),t,r))}async function sI(e,t,r){return oz(t,e,"decrypt"),sv(e,t),new Uint8Array(await crypto.subtle.decrypt(sR(e),t,r))}function sU(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function sO(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}let sP=e=>sU(e)&&"string"==typeof e.kty,sC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function sD(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new oK(sC)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new oK(sC)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new oK(sC)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new oK(sC)}break;default:throw new oK('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let sL="given KeyObject instance cannot be used for this algorithm",s$=async(e,r,n,i=!1)=>{let a=(t||=new WeakMap).get(e);if(a?.[n])return a[n];let o=await sD({...r,alg:n});return i&&Object.freeze(e),a?a[n]=o:t.set(e,{[n]:o}),o};async function sz(e,r){if(e instanceof Uint8Array||o5(e))return e;if(o6(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,r)=>{let n,i=(t||=new WeakMap).get(e);if(i?.[r])return i[r];let a="public"===e.type,o=!!a;if("x25519"===e.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(sL)}n=e.toCryptoKey(e.asymmetricKeyType,o,a?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError(sL);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==e.asymmetricKeyType.toUpperCase())throw TypeError(sL);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(r){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError(sL)}if(r.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},o,a?["encrypt"]:["decrypt"]);n=e.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},o,[a?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError(sL);let i={ES256:"P-256",ES384:"P-384",ES512:"P-521"};i[r]&&t===i[r]&&(n=e.toCryptoKey({name:"ECDSA",namedCurve:t},o,[a?"verify":"sign"])),r.startsWith("ECDH-ES")&&(n=e.toCryptoKey({name:"ECDH",namedCurve:t},o,a?[]:["deriveBits"]))}if(!n)throw TypeError(sL);return i?i[r]=n:t.set(e,{[r]:n}),n})(e,r)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return s$(e,n,r)}if(sP(e))return e.k?oT(e.k):s$(e,e,r,!0);throw Error("unreachable")}async function sN(e,t,r){let n;if(!sU(e))throw TypeError("JWK must be an object");switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return oT(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new oK('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return sD({...e,alg:t,ext:n});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return sD({...e,ext:n});case"EC":case"OKP":return sD({...e,alg:t,ext:n});default:throw new oK('Unsupported "kty" (Key Type) Parameter value')}}async function sj(e){if(o6(e))if("secret"!==e.type)return e.export({format:"jwk"});else e=e.export();if(e instanceof Uint8Array)return{kty:"oct",k:oI(e)};if(!o5(e))throw TypeError(oj(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...a}=await crypto.subtle.exportKey("jwk",e);return"AKP"===a.kty&&(a.alg=n),a}async function sH(e){return sj(e)}async function sB(e,t,r,n){let i=e.slice(0,7),a=await sl(i,r,t,n,new Uint8Array);return{encryptedKey:a.ciphertext,iv:oI(a.iv),tag:oI(a.tag)}}async function sq(e,t,r,n,i){return sd(e.slice(0,7),t,r,n,i,new Uint8Array)}let sM='Invalid or unsupported "alg" (JWE Algorithm) header value';function sV(e){if(void 0===e)throw new oF("JWE Encrypted Key missing")}async function sK(e,t,r,n,i){switch(e){case"dir":if(void 0!==r)throw new oF("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new oF("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i,a;if(!sU(n.epk))throw new oF('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(o2(t),!sw(t))throw new oK("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await sN(n.epk,e);if(o2(o),void 0!==n.apu){if("string"!=typeof n.apu)throw new oF('JOSE Header "apu" (Agreement PartyUInfo) invalid');i=oP(n.apu,"apu",oF)}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new oF('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=oP(n.apv,"apv",oF)}let s=await sg(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?o8(n.enc):parseInt(e.slice(-5,-2),10),i,a);if("ECDH-ES"===e)return s;return sV(r),sh(e.slice(-6),s,r)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return sV(r),o2(t),sI(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let a;if(sV(r),"number"!=typeof n.p2c)throw new oF('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new oF('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new oF('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return a=oP(n.p2s,"p2s",oF),sE(e,t,r,n.p2c,a)}case"A128KW":case"A192KW":case"A256KW":return sV(r),sh(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(sV(r),"string"!=typeof n.iv)throw new oF('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new oF('JOSE Header "tag" (Authentication Tag) missing or invalid');return sq(e,t,r,oP(n.iv,"iv",oF),oP(n.tag,"tag",oF));default:throw new oK(sM)}}async function sW(e,t,r,n,i={}){let a,o,s;switch(e){case"dir":s=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let c;if(o2(r),!sw(r))throw new oK("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:l,apv:d}=i;c=i.epk?await sz(i.epk,e):(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:u,y:p,crv:f,kty:h}=await sH(c),m=await sg(r,c,"ECDH-ES"===e?t:e,"ECDH-ES"===e?o8(t):parseInt(e.slice(-5,-2),10),l,d);if(o={epk:{x:u,crv:f,kty:h}},"EC"===h&&(o.epk.y=p),l&&(o.apu=oI(l)),d&&(o.apv=oI(d)),"ECDH-ES"===e){s=m;break}s=n||o3(t);let y=e.slice(-6);a=await sf(y,m,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s=n||o3(t),o2(r),a=await sT(e,r,s);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||o3(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await sA(e,r,s,c,l));break}case"A128KW":case"A192KW":case"A256KW":s=n||o3(t),a=await sf(e,r,s);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||o3(t);let{iv:c}=i;({encryptedKey:a,...o}=await sB(e,r,s,c));break}default:throw new oK(sM)}return{cek:s,encryptedKey:a,parameters:o}}function sF(e,t,r,n,i){let a;if(void 0!==i.crit&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let o of(a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,n.crit)){if(!a.has(o))throw new oK(`Extension Header Parameter "${o}" is not recognized`);if(void 0===i[o])throw new e(`Extension Header Parameter "${o}" is missing`);if(a.get(o)&&void 0===n[o])throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}let sJ=e=>e?.[Symbol.toStringTag],sZ=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&t.key_ops?.includes?.(n)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0};function sG(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(sP(t)){if("oct"===t.kty&&"string"==typeof t.k&&sZ(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!o4(t))throw TypeError(oH(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${sJ(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r);break;default:((e,t,r)=>{if(sP(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&sZ(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&sZ(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!o4(t))throw TypeError(oH(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${sJ(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${sJ(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${sJ(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${sJ(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${sJ(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)}}function sQ(e){if(void 0===globalThis[e])throw new oK(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function sY(e){sQ("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],i=t.readable.getReader();for(;;){let{value:e,done:t}=await i.read();if(t)break;n.push(e)}return ok(...n)}async function sX(e,t){sQ("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let i=[],a=0,o=r.readable.getReader();for(;;){let{value:e,done:r}=await o.read();if(r)break;if(i.push(e),a+=e.byteLength,t!==1/0&&a>t)throw new oF("Decompressed plaintext exceeded the configured limit")}return ok(...i)}class s0{#e;#t;#r;#n;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return oO(this.#s,"setKeyManagementParameters"),this.#s=e,this}setProtectedHeader(e){return oO(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return oO(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return oO(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return oO(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return oO(this.#o,"setInitializationVector"),this.#o=e,this}async encrypt(e,t){let r,n,i,a,o,s;if(!this.#t&&!this.#n&&!this.#r)throw new oF("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!sO(this.#t,this.#n,this.#r))throw new oF("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let c={...this.#t,...this.#n,...this.#r};if(sF(oF,new Map,t?.crit,this.#t,c),void 0!==c.zip&&"DEF"!==c.zip)throw new oK('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==c.zip&&!this.#t?.zip)throw new oF('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:l,enc:d}=c;if("string"!=typeof l||!l)throw new oF('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof d||!d)throw new oF('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#a&&("dir"===l||"ECDH-ES"===l))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);sG("dir"===l?d:l,e,"encrypt");{let i,a=await sz(e,l);({cek:n,encryptedKey:r,parameters:i}=await sW(l,d,a,this.#a,this.#s)),i&&(t&&oU in t?this.#n?this.#n={...this.#n,...i}:this.setUnprotectedHeader(i):this.#t?this.#t={...this.#t,...i}:this.setProtectedHeader(i))}if(this.#t?o=oR(a=oI(JSON.stringify(this.#t))):(a="",o=new Uint8Array),this.#i){let e=oR(s=oI(this.#i));i=ok(o,oR("."),e)}else i=o;let u=this.#e;"DEF"===c.zip&&(u=await sY(u).catch(e=>{throw new oF("Failed to compress plaintext",{cause:e})}));let{ciphertext:p,tag:f,iv:h}=await sl(d,u,n,this.#o,i),m={ciphertext:oI(p)};return h&&(m.iv=oI(h)),f&&(m.tag=oI(f)),r&&(m.encrypted_key=oI(r)),s&&(m.aad=s),this.#t&&(m.protected=a),this.#r&&(m.unprotected=this.#r),this.#n&&(m.header=this.#n),m}}class s1{#c;constructor(e){this.#c=new s0(e)}setContentEncryptionKey(e){return this.#c.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#c.setInitializationVector(e),this}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#c.setKeyManagementParameters(e),this}async encrypt(e,t){let r=await this.#c.encrypt(e,t);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}let s2=e=>Math.floor(e.getTime()/1e3),s5=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function s6(e){let t,r=s5.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let n=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*n);break;case"day":case"days":case"d":t=Math.round(86400*n);break;case"week":case"weeks":case"w":t=Math.round(604800*n);break;default:t=Math.round(0x1e187e0*n)}return"-"===r[1]||"ago"===r[4]?-t:t}function s4(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let s8=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;function s3(e,t,r={}){var n,i;let a,o;try{a=JSON.parse(ov.decode(t))}catch{}if(!sU(a))throw new oZ("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||s8(e.typ)!==s8(s)))throw new oq('unexpected "typ" JWT header value',a,"typ","check_failed");let{requiredClaims:c=[],issuer:l,subject:d,audience:u,maxTokenAge:p}=r,f=[...c];for(let e of(void 0!==p&&f.push("iat"),void 0!==u&&f.push("aud"),void 0!==d&&f.push("sub"),void 0!==l&&f.push("iss"),new Set(f.reverse())))if(!(e in a))throw new oq(`missing required "${e}" claim`,a,e,"missing");if(l&&!(Array.isArray(l)?l:[l]).includes(a.iss))throw new oq('unexpected "iss" claim value',a,"iss","check_failed");if(d&&a.sub!==d)throw new oq('unexpected "sub" claim value',a,"sub","check_failed");if(u&&(n=a.aud,i="string"==typeof u?[u]:u,"string"==typeof n?!i.includes(n):!(Array.isArray(n)&&i.some(Set.prototype.has.bind(new Set(n))))))throw new oq('unexpected "aud" claim value',a,"aud","check_failed");switch(typeof r.clockTolerance){case"string":o=s6(r.clockTolerance);break;case"number":o=r.clockTolerance;break;case"undefined":o=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:h}=r,m=s2(h||new Date);if((void 0!==a.iat||p)&&"number"!=typeof a.iat)throw new oq('"iat" claim must be a number',a,"iat","invalid");if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw new oq('"nbf" claim must be a number',a,"nbf","invalid");if(a.nbf>m+o)throw new oq('"nbf" claim timestamp check failed',a,"nbf","check_failed")}if(void 0!==a.exp){if("number"!=typeof a.exp)throw new oq('"exp" claim must be a number',a,"exp","invalid");if(a.exp<=m-o)throw new oM('"exp" claim timestamp check failed',a,"exp","check_failed")}if(p){let e=m-a.iat;if(e-o>("number"==typeof p?p:s6(p)))throw new oM('"iat" claim timestamp check failed (too far in the past)',a,"iat","check_failed");if(e<0-o)throw new oq('"iat" claim timestamp check failed (it should be in the past)',a,"iat","check_failed")}return a}class s9{#l;constructor(e){if(!sU(e))throw TypeError("JWT Claims Set MUST be an object");this.#l=structuredClone(e)}data(){return oE.encode(JSON.stringify(this.#l))}get iss(){return this.#l.iss}set iss(e){this.#l.iss=e}get sub(){return this.#l.sub}set sub(e){this.#l.sub=e}get aud(){return this.#l.aud}set aud(e){this.#l.aud=e}set jti(e){this.#l.jti=e}set nbf(e){"number"==typeof e?this.#l.nbf=s4("setNotBefore",e):e instanceof Date?this.#l.nbf=s4("setNotBefore",s2(e)):this.#l.nbf=s2(new Date)+s6(e)}set exp(e){"number"==typeof e?this.#l.exp=s4("setExpirationTime",e):e instanceof Date?this.#l.exp=s4("setExpirationTime",s2(e)):this.#l.exp=s2(new Date)+s6(e)}set iat(e){void 0===e?this.#l.iat=s2(new Date):e instanceof Date?this.#l.iat=s4("setIssuedAt",s2(e)):"string"==typeof e?this.#l.iat=s4("setIssuedAt",s2(new Date)+s6(e)):this.#l.iat=s4("setIssuedAt",e)}}class s7{#a;#o;#s;#t;#d;#u;#p;#f;constructor(e={}){this.#f=new s9(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return oO(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return oO(this.#s,"setKeyManagementParameters"),this.#s=e,this}setContentEncryptionKey(e){return oO(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return oO(this.#o,"setInitializationVector"),this.#o=e,this}replicateIssuerAsHeader(){return this.#d=!0,this}replicateSubjectAsHeader(){return this.#u=!0,this}replicateAudienceAsHeader(){return this.#p=!0,this}async encrypt(e,t){let r=new s1(this.#f.data());return this.#t&&(this.#d||this.#u||this.#p)&&(this.#t={...this.#t,iss:this.#d?this.#f.iss:void 0,sub:this.#u?this.#f.sub:void 0,aud:this.#p?this.#f.aud:void 0}),r.setProtectedHeader(this.#t),this.#o&&r.setInitializationVector(this.#o),this.#a&&r.setContentEncryptionKey(this.#a),this.#s&&r.setKeyManagementParameters(this.#s),r.encrypt(e,t)}}class ce{#l;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#l=e}setProtectedHeader(e){return oO(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return oO(this.#n,"setUnprotectedHeader"),this.#n=e,this}async sign(e,t){let r,n,i,a;if(!this.#t&&!this.#n)throw new oJ("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!sO(this.#t,this.#n))throw new oJ("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this.#t,...this.#n},s=sF(oJ,new Map([["b64",!0]]),t?.crit,this.#t,o),c=!0;if(s.has("b64")&&"boolean"!=typeof(c=this.#t.b64))throw new oJ('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=o;if("string"!=typeof l||!l)throw new oJ('JWS "alg" (Algorithm) Header Parameter missing or invalid');sG(l,e,"sign"),c?n=oR(r=oI(this.#l)):(n=this.#l,r=""),this.#t?a=oR(i=oI(JSON.stringify(this.#t))):(i="",a=new Uint8Array);let d=ok(a,oR("."),n),u=await sz(e,l),p={signature:oI(await sS(l,u,d)),payload:r};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=i),p}}class ct{#c;constructor(e){this.#c=new ce(e)}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}async sign(e,t){let r=await this.#c.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}class cr{#t;#f;constructor(e={}){this.#f=new s9(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){let r=new ct(this.#f.data());if(r.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new oZ("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var cn=e.i(97379),cn=cn;let ci=(e,t)=>{if("string"!=typeof e||!e)throw new oG(`${t} missing or invalid`)};async function ca(e,t){let r,n;if(sP(e))r=e;else if(o4(e))r=await sH(e);else throw TypeError(oj(e,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(t??="sha256")&&"sha384"!==t&&"sha512"!==t)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(r.kty){case"AKP":ci(r.alg,'"alg" (Algorithm) Parameter'),ci(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":ci(r.crv,'"crv" (Curve) Parameter'),ci(r.x,'"x" (X Coordinate) Parameter'),ci(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":ci(r.crv,'"crv" (Subtype of Key Pair) Parameter'),ci(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":ci(r.e,'"e" (Exponent) Parameter'),ci(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":ci(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new oK('"kty" (Key Type) Parameter missing or unsupported')}let i=oR(JSON.stringify(n));return oI(await oC(t,i))}function co(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(ov.decode(oT(t)));if(!sU(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}function cs(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}async function cc(e,t,r){let n,i,a,o,s,c;if(!sU(e))throw new oF("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new oF("JOSE Header missing");if(void 0!==e.iv&&"string"!=typeof e.iv)throw new oF("JWE Initialization Vector incorrect type");if("string"!=typeof e.ciphertext)throw new oF("JWE Ciphertext missing or incorrect type");if(void 0!==e.tag&&"string"!=typeof e.tag)throw new oF("JWE Authentication Tag incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new oF("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new oF("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new oF("JWE AAD incorrect type");if(void 0!==e.header&&!sU(e.header))throw new oF("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!sU(e.unprotected))throw new oF("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected)try{let t=oT(e.protected);n=JSON.parse(ov.decode(t))}catch{throw new oF("JWE Protected Header is invalid")}if(!sO(n,e.header,e.unprotected))throw new oF("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let l={...n,...e.header,...e.unprotected};if(sF(oF,new Map,r?.crit,n,l),void 0!==l.zip&&"DEF"!==l.zip)throw new oK('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==l.zip&&!n?.zip)throw new oF('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:d,enc:u}=l;if("string"!=typeof d||!d)throw new oF("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new oF("missing JWE Encryption Algorithm (enc) in JWE Header");let p=r&&cs("keyManagementAlgorithms",r.keyManagementAlgorithms),f=r&&cs("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(p&&!p.has(d)||!p&&d.startsWith("PBES2"))throw new oV('"alg" (Algorithm) Header Parameter value not allowed');if(f&&!f.has(u))throw new oV('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==e.encrypted_key&&(i=oP(e.encrypted_key,"encrypted_key",oF));let h=!1;"function"==typeof t&&(t=await t(n,e),h=!0),sG("dir"===d?u:d,t,"decrypt");let m=await sz(t,d);try{a=await sK(d,m,i,l,r)}catch(e){if(e instanceof TypeError||e instanceof oF||e instanceof oK)throw e;a=o3(u)}void 0!==e.iv&&(o=oP(e.iv,"iv",oF)),void 0!==e.tag&&(s=oP(e.tag,"tag",oF));let y=void 0!==e.protected?oR(e.protected):new Uint8Array;c=void 0!==e.aad?ok(y,oR("."),oR(e.aad)):y;let g=oP(e.ciphertext,"ciphertext",oF),w=await sd(u,a,g,o,s,c),b={plaintext:w};if("DEF"===l.zip){let e=r?.maxDecompressedLength??25e4;if(0===e)throw new oK('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");b.plaintext=await sX(w,e).catch(e=>{if(e instanceof oF)throw e;throw new oF("Failed to decompress plaintext",{cause:e})})}return(void 0!==e.protected&&(b.protectedHeader=n),void 0!==e.aad&&(b.additionalAuthenticatedData=oP(e.aad,"aad",oF)),void 0!==e.unprotected&&(b.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(b.unprotectedHeader=e.header),h)?{...b,key:m}:b}async function cl(e,t,r){if(e instanceof Uint8Array&&(e=ov.decode(e)),"string"!=typeof e)throw new oF("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:a,3:o,4:s,length:c}=e.split(".");if(5!==c)throw new oF("Invalid Compact JWE");let l=await cc({ciphertext:o,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}async function cd(e,t,r){let n=await cl(e,t,r),i=s3(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(void 0!==a.iss&&a.iss!==i.iss)throw new oq('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(void 0!==a.sub&&a.sub!==i.sub)throw new oq('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(void 0!==a.aud&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new oq('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:a};return"function"==typeof t?{...o,key:n.key}:o}async function cu(e,t,r){if(!sU(e))throw new oJ("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new oJ('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new oJ("JWS Protected Header incorrect type");if(void 0===e.payload)throw new oJ("JWS Payload missing");if("string"!=typeof e.signature)throw new oJ("JWS Signature missing or incorrect type");if(void 0!==e.header&&!sU(e.header))throw new oJ("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let t=oT(e.protected);n=JSON.parse(ov.decode(t))}catch{throw new oJ("JWS Protected Header is invalid")}if(!sO(n,e.header))throw new oJ("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...e.header},a=sF(oJ,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(a.has("b64")&&"boolean"!=typeof(o=n.b64))throw new oJ('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=i;if("string"!=typeof s||!s)throw new oJ('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&cs("algorithms",r.algorithms);if(c&&!c.has(s))throw new oV('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new oJ("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new oJ("JWS Payload must be a string or an Uint8Array instance");let l=!1;"function"==typeof t&&(t=await t(n,e),l=!0),sG(s,t,"verify");let d=ok(void 0!==e.protected?oR(e.protected):new Uint8Array,oR("."),"string"==typeof e.payload?o?oR(e.payload):oE.encode(e.payload):e.payload),u=oP(e.signature,"signature",oJ),p=await sz(t,s);if(!await sx(s,p,u,d))throw new o1;let f={payload:o?oP(e.payload,"payload",oJ):"string"==typeof e.payload?oE.encode(e.payload):e.payload};return(void 0!==e.protected&&(f.protectedHeader=n),void 0!==e.header&&(f.unprotectedHeader=e.header),l)?{...f,key:p}:f}async function cp(e,t,r){if(e instanceof Uint8Array&&(e=ov.decode(e)),"string"!=typeof e)throw new oJ("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:a,length:o}=e.split(".");if(3!==o)throw new oJ("Invalid Compact JWS");let s=await cu({payload:i,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}async function cf(e,t,r){let n=await cp(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new oZ("JWTs MUST NOT use unencoded payload");let i={payload:s3(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}async function ch(e,t,r=3600){return await new cr(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function cm(e,t){try{return(await cf(e,new TextEncoder().encode(t))).payload}catch{return null}}let cy=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),cg="A256CBC-HS512";function cw(e,t){var r,n,i;return r=new TextEncoder().encode(e),n=new TextEncoder().encode(t),function(e,t,r,n=32){a6(e),a2(n,"length"),a5(t,void 0,"prk");let i=e.outputLen;if(t.length<i)throw Error('"prk" must be at least HashLen octets');if(n>255*i)throw Error("Length must be <= 255*HashLen");let a=Math.ceil(n/i);void 0===r?r=on:a5(r,void 0,"info");let o=new Uint8Array(a*i),s=ot.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)or[0]=e+1,c.update(0===e?on:l).update(r).update(or).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),a3(l,or),o.slice(0,n)}(oA,(i=n,a6(oA),void 0===i&&(i=new Uint8Array(oA.outputLen)),ot(oA,i,r)),cy,64)}function cb(e){if("string"==typeof e)return[{version:0,value:e}];let t=[];for(let[r,n]of e.keys)t.push({version:r,value:n});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function cA(e,t,r,n=3600){let i=cw(function(e){if("string"==typeof e)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}(t),r),a=await ca({kty:"oct",k:cn.encode(i)},"sha256");return await new s7(e).setProtectedHeader({alg:"dir",enc:cg,kid:a}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+n).setJti(crypto.randomUUID()).encrypt(i)}let cE={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[cg,"A256GCM"]};async function cv(e,t,r){if(!e)return null;let n=!1;try{n=void 0!==co(e).kid}catch{return null}try{let n=cb(t),{payload:i}=await cd(e,async e=>{let t=e.kid;if(void 0!==t){for(let e of n){let n=cw(e.value,r);if(t===await ca({kty:"oct",k:cn.encode(n)},"sha256"))return n}throw Error("no matching decryption secret")}return n.length,cw(n[0].value,r)},cE);return i}catch{if(n)return null;let i=cb(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let n=i[t],{payload:a}=await cd(e,cw(n.value,r),cE);return a}catch{continue}return null}}var ck=e.i(33763);function c_(e,t){if(!e||!t)return e;let r=Object.entries(t).filter(([,{returned:e}])=>!1===e).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!r.includes(e)).reduce((e,[t,r])=>({...e,[t]:r}),{})}let cS=new WeakMap;function cx(e,t,r){let n=`${t}:${r}`;cS.has(e)||cS.set(e,new Map);let i=cS.get(e);if(i.has(n))return i.get(n);let a="output"===r?(0,a_.getAuthTables)(e)[t]?.fields??{}:{},o="user"===t||"session"===t||"account"===t?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(s={...s,...r.schema[t].fields});return i.set(n,s),s}function cR(e,t){return c_(t,cx(e,"user","output"))}function cT(e,t){let r=cx(e,"user","output"),n={};for(let e in r){let i=r[e];!1!==i.returned&&(e in t&&void 0!==t[e]?n[e]=t[e]:void 0!==i.defaultValue?n[e]="function"==typeof i.defaultValue?i.defaultValue():i.defaultValue:i.required||(n[e]=null))}return"id"in t&&(n.id=t.id),n}function cI(e,t){return c_(t,cx(e,"session","output"))}function cU(e,t){let r=t.action||"create",n=t.fields,i=Object.create(null);for(let t in n){if(t in e){if(!1===n[t].input){if(void 0!==n[t].defaultValue&&"update"!==r){i[t]=n[t].defaultValue;continue}if(e[t])throw Y.APIError.from("BAD_REQUEST",{...ck.BASE_ERROR_CODES.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(n[t].validator?.input&&void 0!==e[t]){let r=n[t].validator.input["~standard"].validate(e[t]);if(r instanceof Promise)throw Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in r&&r.issues)throw Y.APIError.from("BAD_REQUEST",{...ck.BASE_ERROR_CODES.VALIDATION_ERROR,message:r.issues[0]?.message||"Validation Error"});i[t]=r.value;continue}if(n[t].transform?.input&&void 0!==e[t]){i[t]=n[t].transform?.input(e[t]);continue}i[t]=e[t];continue}if(void 0!==n[t].defaultValue&&"create"===r){if("function"==typeof n[t].defaultValue){i[t]=n[t].defaultValue();continue}i[t]=n[t].defaultValue;continue}if(n[t].required&&"create"===r)throw Y.APIError.from("BAD_REQUEST",{...ck.BASE_ERROR_CODES.MISSING_FIELD,message:`${t} is required`})}return i}function cO(e,t={},r){return cU(t,{fields:cx(e,"user","input"),action:r})}function cP(e,t={},r){let n=cx(e,"user","input"),i=Object.create(null);for(let e of Object.keys(t))n[e]?.input!==!1&&(i[e]=t[e]);return cU(i,{fields:n,action:r})}let cC=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e)),cD=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;var cL=e.i(12680);e.s(["bigint",0,function(e){return new ij({type:"bigint",coerce:!0,...eZ(e)})},"boolean",0,function(e){return new iz({type:"boolean",coerce:!0,...eZ(e)})},"date",0,function(e){return new iK({type:"date",coerce:!0,...eZ(e)})},"number",0,function(e){return new iC({type:"number",coerce:!0,checks:[],...eZ(e)})},"string",0,function(e){return new id({type:"string",coerce:!0,...eZ(e)})}],3099);var c$=e.i(3099),c$=c$;let cz=e=>(t,r,n)=>{let i=function(e,t){let r={};for(let[n,i]of j(t.headers?.get("cookie")||""))n.startsWith(e)&&(r[n]=i);return r}(t,n),a=n.context.logger,o=()=>{let e=function(e,t){let r={};for(let n in e)r[n]={name:n,value:"",attributes:{...t,maxAge:0}};return r}(i,r);for(let e in i)delete i[e];return e};return{chunk(n,s){let c=o();for(let o of function(e,t,r,n){let i=4050-eg(`${t.name}.99`,"",{...t.attributes}).length,a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return r[t.name]=t.value,[t];if(a>100)return n.warn(`${e} cookie is too large to store even after chunking, so the cache was skipped. Reduce the cached data or use a database session.`),[];let o=[];for(let e=0;e<a;e++){let n=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:n,value:s}),r[n]=s}return n.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the 4050 byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}(e,{name:t,value:n,attributes:{...r,...s}},i,a))c[o.name]=o;return Object.values(c)},clean:()=>Object.values(o()),setCookies(e){for(let t of e)n.setCookie(t.name,t.value,t.attributes)}}},cN=cz("Session"),cj=cz("Account");function cH(e,t){let r=e.getCookie(t);if(r)return r;let n=[],i=e.headers?.get("cookie");if(!i)return null;for(let[e,r]of j(i))if(e.startsWith(t+".")){let t=parseInt(e.split(".").at(-1)||"0",10);isNaN(t)||n.push({index:t,value:r})}return n.length>0?(n.sort((e,t)=>e.index-t.index),n.map(e=>e.value).join("")):null}async function cB(e,t){let r=e.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await cA(t,e.context.secretConfig,"better-auth-account",n.maxAge),a=cj(r.name,n,e);a.setCookies(a.chunk(i,n))}async function cq(e){let t=cH(e,e.context.authCookies.accountData.name);if(t){let r=(0,cL.safeJSONParse)(await cv(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}let cM=i6(iZ({disableCookieCache:c$.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:c$.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function cV(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function cK(e,t,r){let n="",i=0,a=0;for(let r of e)for(i=i<<8|r,a+=8;a>=6;)a-=6,n+=t[i>>a&63];if(a>0&&(n+=t[i<<6-a&63]),r){let e=(4-n.length%4)%4;n+="=".repeat(e)}return n}function cW(e,t){let r=new Map;for(let e=0;e<t.length;e++)r.set(t[e],e);let n=[],i=0,a=0;for(let t of e){if("="===t)break;let e=r.get(t);if(void 0===e)throw Error(`Invalid Base64 character: ${t}`);i=i<<6|e,(a+=6)>=8&&(a-=8,n.push(i>>a&255))}return Uint8Array.from(n)}let cF={encode(e,t={}){let r=cV(!1);return cK("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){"string"!=typeof e&&(e=new TextDecoder().decode(e));let t=cV(e.includes("-")||e.includes("_"));return cW(e,t)}},cJ={encode(e,t={}){let r=cV(!0);return cK("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){let t=cV(e.includes("-")||e.includes("_"));return cW(e,t)}},cZ=new Map,cG={decode:(e,t="utf-8")=>(cZ.has(t)||cZ.set(t,new TextDecoder(t)),cZ.get(t).decode(e)),encode:new TextEncoder().encode},cQ=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>el().importKey("raw","string"==typeof t?new TextEncoder().encode(t):t,{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,n)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let i=await el().sign("HMAC",e,"string"==typeof n?new TextEncoder().encode(n):n);return"hex"===t?(e=>{if("string"==typeof e&&(e=new TextEncoder().encode(e)),0===e.byteLength)return"";let t=new Uint8Array(e),r="";for(let e of t)r+=e.toString(16).padStart(2,"0");return r})(i):"base64"===t||"base64url"===t||"base64urlnopad"===t?cJ.encode(i,{padding:"base64urlnopad"!==t}):i},verify:async(e,n,i)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(i=(e=>{if(!e)return"";if("string"==typeof e){if(e.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(e))throw Error("Invalid hexadecimal string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)})(i)),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(i=await cF.decode(i)),el().verify("HMAC",e,"string"==typeof i?new TextEncoder().encode(i):i,"string"==typeof n?new TextEncoder().encode(n):n))};return r};function cY(e){let t="string"==typeof e.baseURL?e.baseURL:void 0,r="object"==typeof e.baseURL&&null!==e.baseURL?e.baseURL.protocol:void 0,n=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:"https"===r||"http"!==r&&(t?t.startsWith("https://"):aN.isProduction))?"__Secure-":"",i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!aV(e.baseURL))throw new Y.BetterAuthError("baseURL is required when crossSubdomainCookies are enabled.");return function(t,r={}){let o=e.advanced?.cookiePrefix||"better-auth",s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${n}${s}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...r,...c}}}}function cX(e){let t=cY(e),r=t("session_token",{maxAge:e.session?.expiresIn||Math.round(function(){let e,t=cD.exec("7d");if(!t||t[4]&&t[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let r=parseFloat(t[2]),n=t[3].toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":e=315576e5*r;break;case"months":case"month":case"mo":e=2592e6*r;break;case"weeks":case"week":case"w":e=6048e5*r;break;case"days":case"day":case"d":e=864e5*r;break;case"hours":case"hour":case"hrs":case"hr":case"h":e=36e5*r;break;case"minutes":case"minute":case"mins":case"min":case"m":e=6e4*r;break;case"seconds":case"second":case"secs":case"sec":case"s":e=1e3*r;break;default:throw TypeError(`Unknown time unit: "${n}"`)}return"-"===t[1]||"ago"===t[4]?-e:e}()/1e3)}),n=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),i=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),a=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function c0(e,t,r){let n;if(!e.context.options.session?.cookieCache?.enabled)return;let i=c_(t.session,e.context.options.session?.additionalFields),a=cR(e.context.options,t.user),o=e.context.options.session?.cookieCache?.version,s="1";if(o){if("string"==typeof o)s=o;else if("function"==typeof o){let e=o(t.session,t.user);s=aG(e)?await e:e}}let c={session:i,user:a,updatedAt:Date.now(),version:s},l={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},d=cC(l.maxAge||60,"sec").getTime(),u=e.context.options.session?.cookieCache?.strategy||"compact";n="jwe"===u?await cA(c,e.context.secretConfig,"better-auth-session",l.maxAge||300):"jwt"===u?await ch(c,e.context.secret,l.maxAge||300):cJ.encode(JSON.stringify({session:c,expiresAt:d,signature:await cQ("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...c,expiresAt:d}))}),{padding:!1});let p=cN(e.context.authCookies.sessionData.name,l,e);if(p.setCookies(p.chunk(n,l)),e.context.options.account?.storeAccountCookie&&!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let n=`${t}=`,i=`${t}.`;for(let e of r)if(("function"==typeof e.getSetCookie?e.getSetCookie():D(e.get("set-cookie")||"")).some(e=>e.startsWith(n)||e.startsWith(i)))return!0;return!1}(e,e.context.authCookies.accountData.name)){let r=await cq(e);if(r)if(aZ(e.context.options)&&r.userId!==t.user.id){c2(e,e.context.authCookies.accountData);let t=cj(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}else await cB(e,r)}}async function c1(e,t,r,n){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!i;let a=e.context.authCookies.sessionToken.attributes,o=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes),await c0(e,t,r),e.context.setNewSession(t)}function c2(e,t){!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let n=`${t}=`,i=`${t}.`;for(let e of r){let t="function"==typeof e.getSetCookie?e.getSetCookie():D(e.get("set-cookie")||"");if(!t.length)continue;let r=t.filter(e=>!e.startsWith(n)&&!e.startsWith(i));if(r.length!==t.length)for(let t of(e.delete("set-cookie"),r))e.append("set-cookie",t)}}(e,t.name),e.setCookie(t.name,"",{...t.attributes,maxAge:0})}function c5(e,t){if(c2(e,e.context.authCookies.sessionToken),c2(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){c2(e,e.context.authCookies.accountData);let t=cj(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),r=t.clean();t.setCookies(r)}"cookie"===e.context.oauthConfig.storeStateStrategy&&c2(e,e.context.createAuthCookie("oauth_state"));let r=cN(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),n=r.clean();r.setCookies(n),t||c2(e,e.context.authCookies.dontRememberToken)}function c6(e,t){return{digest:async r=>{let n=new TextEncoder,i="string"==typeof r?n.encode(r):r,a=await el().digest(e,i);return"hex"===t?Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join(""):"base64"===t||"base64url"===t||"base64urlnopad"===t?t.includes("url")?cJ.encode(a,{padding:"base64urlnopad"!==t}):cF.encode(a):a}}}let c4=async e=>{let t=await c6("SHA-256").digest(new TextEncoder().encode(e));return cJ.encode(new Uint8Array(t),{padding:!1})};async function c8(e,t){return t&&"plain"!==t?"hashed"===t?c4(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function c3(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,n]of Object.entries(t.overrides))if(e.startsWith(r))return n}return t.default}return t}}var c9=e.i(4055),c7=e.i(97454);let le="better_auth.operation_id",lt="better_auth.hook.type",lr="better_auth.context";var ln=e.i(47171),li=e.i(37015);function la(e){return nC(iS,void 0).safeParse(e).success||nD(ix,void 0).safeParse(e).success}function lo(e){return nD(ix,void 0).safeParse(e).success}function ls(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let e=t.substring(7);if(nC(iS,void 0).safeParse(e).success)return e}let r=e.split(":");if(7===r.length&&r[5]?.toLowerCase()==="ffff"){let e=r[6];if(e&&nC(iS,void 0).safeParse(e).success)return e}if(t.includes("::ffff:")||t.includes(":ffff:")){let t=lc(e);if(8===t.length&&"0000"===t[0]&&"0000"===t[1]&&"0000"===t[2]&&"0000"===t[3]&&"0000"===t[4]&&"ffff"===t[5]&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function lc(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=Array(8-r.length-n.length).fill("0000");return[...r.map(e=>e.padStart(4,"0")),...i,...n.map(e=>e.padStart(4,"0"))]}return e.split(":").map(e=>e.padStart(4,"0"))}function ll(e,t={}){if(nC(iS,void 0).safeParse(e).success||!lo(e))return e.toLowerCase();let r=ls(e);if(r)return r.toLowerCase();var n=t.ipv6Subnet??64;let i=lc(e);if(void 0!==n&&n<128){let e=Math.max(0,Math.floor(n));return i.map(t=>{if(e<=0)return"0000";if(e>=16)return e-=16,t;let r=Number.parseInt(t,16)&(65535<<16-e&65535);return e=0,r.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return i.join(":").toLowerCase()}function ld(e){if(nC(iS,void 0).safeParse(e).success)return Uint8Array.from(e.split(".").map(e=>Number(e)));if(!lo(e))return null;let t=ls(e);if(t)return Uint8Array.from(t.split(".").map(e=>Number(e)));let r=lc(e),n=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(r[e]??"0",16);n[2*e]=t>>8&255,n[2*e+1]=255&t}return n}let lu=/^\d+$/;function lp(e){let t=e.lastIndexOf("/"),r=ld(-1===t?e:e.slice(0,t));if(!r)return null;let n=8*r.length;if(-1===t)return{bytes:r,prefix:n};let i=e.slice(t+1);if(!lu.test(i))return null;let a=Number(i);return a<=n?{bytes:r,prefix:a}:null}let lf=["x-forwarded-for"];function lh(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="headers"in e?e.headers:e;for(let e of t.advanced?.ipAddress?.ipAddressHeaders||lf){let n="get"in r?r.get(e):r[e];if("string"==typeof n){let e=function(e,t={}){let r=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===r.length)return null;let n=(t.trustedProxies??[]).map(lp).filter(e=>null!==e);if(n.length>0){for(let e=r.length-1;e>=0;e--){let i=r[e],a=i?ld(i):null;if(!i||!a)break;if(!n.some(e=>(function(e,t){if(e.length!==t.bytes.length)return!1;let r=t.prefix;for(let n=0;n<e.length&&r>0;n++){let i=r>=8?8:r,a=8===i?255:255<<8-i&255;if(((e[n]??0)&a)!=((t.bytes[n]??0)&a))return!1;r-=8}return!0})(a,e)))return ll(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(1!==r.length)return null;let i=r[0];return i&&la(i)?ll(i,{ipv6Subnet:t.ipv6Subnet}):null}(n,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return(0,aN.isTest)()||(0,aN.isDevelopment)()?"127.0.0.1":null}function lm(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let ly=(e,t)=>{let r,n=t.logger,i=t.options,a=i.secondaryStorage,o=new Map,s=!1,c=i.session?.expiresIn||604800,{createWithHooks:l,updateWithHooks:d,updateManyWithHooks:u,deleteWithHooks:p,deleteManyWithHooks:f,consumeOneWithHooks:h}=(r=t.hooks,{createWithHooks:async function(t,n,i){let a=await G().catch(()=>null),o=t;for(let{source:e,hooks:t}of r){let r=t[n]?.create?.before;if(r){let t=await (0,ln.withSpan)(`db create.before ${n}`,{[lt]:"create.before",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:e},()=>r(o,a));if(!1===t)return null;"object"==typeof t&&"data"in t&&(o={...o,...t.data})}}let s=null;for(let{source:t,hooks:c}of((!i||i.executeMainFn)&&(s=await (await (0,c9.getCurrentAdapter)(e)).create({model:n,data:o,forceAllowId:!0})),i?.fn&&(s=await i.fn(s??o)),r)){let e=c[n]?.create?.after;e&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db create.after ${n}`,{[lt]:"create.after",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:t},()=>e(s,a))})}return s},updateWithHooks:async function(t,n,i,a){let o=await G().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,ln.withSpan)(`db update.before ${i}`,{[lt]:"update.before",[c7.ATTR_DB_COLLECTION_NAME]:i,[lr]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await (0,c9.getCurrentAdapter)(e)).update({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db update.after ${i}`,{[lt]:"update.after",[c7.ATTR_DB_COLLECTION_NAME]:i,[lr]:e},()=>r(l,o))})}return l},updateManyWithHooks:async function(t,n,i,a){let o=await G().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,ln.withSpan)(`db updateMany.before ${i}`,{[lt]:"updateMany.before",[c7.ATTR_DB_COLLECTION_NAME]:i,[lr]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await (0,c9.getCurrentAdapter)(e)).updateMany({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db updateMany.after ${i}`,{[lt]:"updateMany.after",[c7.ATTR_DB_COLLECTION_NAME]:i,[lr]:e},()=>r(l,o))})}return l},deleteWithHooks:async function(t,n,i){let a=await G().catch(()=>null),o=null;try{o=(await (await (0,c9.getCurrentAdapter)(e)).findMany({model:n,where:t,limit:1}))[0]||null}catch{}if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.before;if(r&&await (0,ln.withSpan)(`db delete.before ${n}`,{[lt]:"delete.before",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:e},()=>r(o,a))===!1)return null}let s=i?await i.fn(t):null,c=(!i||i.executeMainFn)&&o?await (await (0,c9.getCurrentAdapter)(e)).delete({model:n,where:t}):s;if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.after;r&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db delete.after ${n}`,{[lt]:"delete.after",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:e},()=>r(o,a))})}return c},deleteManyWithHooks:async function(t,n,i){let a=await G().catch(()=>null),o=[];try{o=await (await (0,c9.getCurrentAdapter)(e)).findMany({model:n,where:t})}catch{}for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.before;if(r&&await (0,ln.withSpan)(`db delete.before ${n}`,{[lt]:"delete.before",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:t},()=>r(e,a))===!1)return null}let s=i?await i.fn(t):null,c=!i||i.executeMainFn?await (await (0,c9.getCurrentAdapter)(e)).deleteMany({model:n,where:t}):s;for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.after;r&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db delete.after ${n}`,{[lt]:"delete.after",[c7.ATTR_DB_COLLECTION_NAME]:n,[lr]:t},()=>r(e,a))})}return c},consumeOneWithHooks:async function(t,n,i,a){let o=await G().catch(()=>null),s=r.flatMap(({source:e,hooks:r})=>{let n=r[t]?.delete?.before;return n?[{source:e,fn:n}]:[]}),c=a??null;if(s.length){if(!c)try{c=(await (await (0,c9.getCurrentAdapter)(e)).findMany({model:t,where:n,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:r}of s)if(await (0,ln.withSpan)(`db delete.before ${t}`,{[lt]:"delete.before",[c7.ATTR_DB_COLLECTION_NAME]:t,[lr]:e},()=>r(c,o))===!1)return null}}let l=await i();if(!l)return null;for(let{source:e,hooks:n}of r){let r=n[t]?.delete?.after;r&&await (0,c9.queueAfterTransactionHook)(async()=>{await (0,ln.withSpan)(`db delete.after ${t}`,{[lt]:"delete.after",[c7.ATTR_DB_COLLECTION_NAME]:t,[lr]:e},()=>r(l,o))})}return l}});async function m(e){if(!a)return;let t=await a.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),n=((0,cL.safeJSONParse)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(n.map(async({token:t})=>{let n=await a.get(t);if(!n)return;let i=(0,cL.safeJSONParse)(n);if(!i)return;let o=lm(i.session.expiresAt,r);await a.set(t,JSON.stringify({session:i.session,user:e}),Math.floor(o))}))}async function y(e,t){let r,n=o.get(e)??Promise.resolve(),i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);o.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),o.get(e)===a&&o.delete(e)}}return{createOAuthUser:async(t,r)=>(0,c9.runWithTransaction)(e,async()=>{let e=await l({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);return{user:e,account:await l({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async e=>await l({createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()},"user",void 0),createAccount:async e=>await l({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,n)=>{if(a){let e=await a.get(`active-sessions-${r}`);if(!e)return[];let n=(0,cL.safeJSONParse)(e)||[],i=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:r}of n){if(r<=i||o.has(e))continue;o.add(e);let n=await a.get(e);if(n)try{let e="string"==typeof n?JSON.parse(n):n;if(!e?.session)continue;s.push(cI(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"session",where:[{field:"userId",value:r},...n?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,n,i)=>await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"user",limit:t,offset:r,sortBy:n,where:i}),countTotalUsers:async t=>{let r=await (await (0,c9.getCurrentAdapter)(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{(!a||i.session?.storeSessionInDatabase)&&await f([{field:"userId",value:e}],"session",void 0),await f([{field:"userId",value:e}],"account",void 0),await p([{field:"id",value:e}],"user",void 0)},createSession:async(r,n,o,s)=>{let d,u=await (async()=>{let e=await G().catch(()=>null);return e?.headers||e?.request?.headers})(),p=i.session?.storeSessionInDatabase,{id:f,...h}=o||{};if(a&&!p){let e=t.generateId({model:"session"});d=!1!==e?e:(0,li.generateId)()}let m=function(e){let t=cx(e,"session","input"),r={};for(let e in t)void 0!==t[e].defaultValue&&(r[e]="function"==typeof t[e].defaultValue?t[e].defaultValue():t[e].defaultValue);return r}(i),y={...d?{id:d}:{},ipAddress:u&&lh(u,i)||"",userAgent:u?.get("user-agent")||"",...h,expiresAt:n?cC(86400,"sec"):cC(c,"sec"),userId:r,token:(0,li.generateId)(32),createdAt:new Date,updatedAt:new Date,...m,...s?h:{}};return await l(y,"session",a?{fn:async t=>{let n=await a.get(`active-sessions-${r}`),i=[],o=Date.now();n&&(i=(i=(0,cL.safeJSONParse)(n)||[]).filter(e=>e.expiresAt>o&&e.token!==y.token));let s=[...i,{token:y.token,expiresAt:y.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=lm(s.at(-1)?.expiresAt??y.expiresAt.getTime(),o);c>0&&await a.set(`active-sessions-${r}`,JSON.stringify(s),c);let l=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"user",where:[{field:"id",value:r}]}),d=lm(y.expiresAt,o);return d>0&&await a.set(y.token,JSON.stringify({session:t,user:l}),d),t},executeMainFn:p}:void 0)},findSession:async r=>{if(a){let e=await a.get(r);if(!e&&(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,cL.safeJSONParse)(e);return r?{session:cI(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:cR(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}:null}}let n=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!n)return null;let{user:o,...s}=n;return o?{session:cI(t.options,s),user:cR(t.options,o)}:null},findSessions:async(t,r)=>{if(a){let e=[];for(let n of t){let t=await a.get(n);if(t)try{let n="string"==typeof t?JSON.parse(t):t;if(!n)return[];let i=new Date(n.session.expiresAt);if(r?.onlyActiveSessions&&i<=new Date)continue;let a={session:{...n.session,expiresAt:new Date(n.session.expiresAt)},user:{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)}};e.push(a)}catch{continue}}return e}let n=await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"session",where:[{field:"token",value:t,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!n.length||n.some(e=>!e.user)?[]:n.map(e=>{let{user:t,...r}=e;return{session:r,user:t}})},updateSession:async(e,r)=>await d(r,[{field:"token",value:e}],"session",a?{async fn(r){let n=await a.get(e);if(!n)return null;let i=(0,cL.safeJSONParse)(n);if(!i)return null;let o={...i.session,...r,expiresAt:new Date(r.expiresAt??i.session.expiresAt),createdAt:new Date(i.session.createdAt),updatedAt:new Date(r.updatedAt??i.session.updatedAt)},s=cI(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),d=lm(l,c);if(d>0){await a.set(e,JSON.stringify({session:s,user:i.user}),d);let t=`active-sessions-${s.userId}`,r=await a.get(t),n=(r&&(0,cL.safeJSONParse)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=n.at(-1)?.expiresAt;o&&o>c?await a.set(t,JSON.stringify(n),lm(o,c)):await a.delete(t)}return s},executeMainFn:i.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(a){let r=await a.get(e);if(r){let{session:t}=(0,cL.safeJSONParse)(r)??{};if(!t)return void n.error("Session not found in secondary storage");let i=t.userId,o=await a.get(`active-sessions-${i}`);if(o){let t=(0,cL.safeJSONParse)(o)||[],r=Date.now(),n=t.filter(t=>t.expiresAt>r&&t.token!==e),s=n.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;n.length>0&&s&&s>Date.now()?await a.set(`active-sessions-${i}`,JSON.stringify(n),lm(s,r)):await a.delete(`active-sessions-${i}`)}else n.error("Active sessions list not found in secondary storage")}if(await a.delete(e),!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await p([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await f([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await p([{field:"id",value:e}],"account",void 0)},deleteUserSessions:async e=>{if(a){let r=await a.get(`active-sessions-${e}`),n=r?(0,cL.safeJSONParse)(r):[];if(!n)return;for(let e of n)await a.delete(e.token);if(await a.delete(`active-sessions-${e}`),!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await f([{field:"userId",value:e}],"session",void 0)},deleteSessions:async e=>{if(a){for(let t of e)await a.get(t)&&await a.delete(t);if(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await f([{field:"token",value:e,operator:"in"}],"session",void 0)},findOAuthUser:async(t,r,n)=>{let i=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"account",where:[{value:r,field:"accountId"},{value:n,field:"providerId"}],join:{user:!0}});if(i)if(i.user)return{user:i.user,linkedAccount:i,accounts:[i]};else{let r=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:i,accounts:[i]}:null}{let r=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:null,accounts:await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"account",where:[{value:r.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(t,r)=>{let n=await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!n)return null;let{account:i,...a}=n;return{user:a,accounts:i??[]}},findUserById:async t=>t?await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await l({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await d({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await m(r),r},updateUserByEmail:async(e,t)=>{let r=await d({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await m(r),r},updatePassword:async(e,t)=>{await u({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async t=>await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findAccountByProviderId:async(t,r)=>await (await (0,c9.getCurrentAdapter)(e)).findOne({model:"account",where:[{field:"accountId",value:t},{field:"providerId",value:r}]}),findAccountByUserId:async t=>await (await (0,c9.getCurrentAdapter)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await d(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=c3(e.identifier,i.verification?.storeIdentifier),r=await c8(e.identifier,t);return await l({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",a?{async fn(e){let t=lm(e.expiresAt);return t>0&&await a.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:i.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=c3(t,i.verification?.storeIdentifier),n=await c8(t,r);if(a){let e=await a.get(`verification:${n}`);if(e){let t=(0,cL.safeJSONParse)(e);if(t)return t}if(r&&"plain"!==r){let e=await a.get(`verification:${t}`);if(e){let t=(0,cL.safeJSONParse)(e);if(t)return t}}if(!i.verification?.storeInDatabase)return null}let o=await (0,c9.getCurrentAdapter)(e);async function s(e){return o.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let c=await s(n);return!c.length&&r&&"plain"!==r&&(c=await s(t)),i.verification?.disableCleanup||await f([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await c8(e,c3(e,i.verification?.storeIdentifier));a&&await a.delete(`verification:${t}`),(!a||i.verification?.storeInDatabase)&&await p([{field:"identifier",value:t}],"verification",void 0)},consumeVerificationValue:async t=>{let r=c3(t,i.verification?.storeIdentifier),o=await c8(t,r),c=r&&"plain"!==r?[o,t]:[o],l=e=>{if(!e)return null;let t="string"==typeof e?(0,cL.safeJSONParse)(e):"object"==typeof e?e:null;if(!t)return null;let r=new Date(t.expiresAt);return Number.isFinite(r.getTime())?{...t,expiresAt:r}:null},d=null;if(a&&!i.verification?.storeInDatabase){let e=async e=>a.getAndDelete?l(await a.getAndDelete(e)):(s||(s=!0,n.warn("Secondary storage does not implement `getAndDelete`, so single-use verification values cannot be consumed atomically across processes. Implement `getAndDelete` or use database-backed verification storage to guarantee single use.")),y(e,async()=>{let t=l(await a.get(e));return t?(await a.delete(e),t):null}));for(let t of c){let r=await e(`verification:${t}`);if(r){await Promise.all(c.filter(e=>e!==t).map(e=>a.delete(`verification:${e}`))),d=r;break}}}else{let t=async t=>y(`verification:${t}`,()=>(0,c9.runWithTransaction)(e,async()=>{let r=await (0,c9.getCurrentAdapter)(e),n=[{field:"identifier",value:t}],i=(await r.findMany({model:"verification",where:n,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return i?h("verification",[{field:"id",value:i.id}],async()=>{let e=await r.consumeOne({model:"verification",where:[{field:"id",value:i.id}]});return e?(await r.deleteMany({model:"verification",where:n}),e):null},i):null}));for(let e of c)if(d=await t(e))break;d&&a&&await Promise.all(c.map(e=>a.delete(`verification:${e}`)))}return!d||d.expiresAt<new Date?null:d},reserveVerificationValue:async t=>{let r=cJ.encode(new Uint8Array(await c6("SHA-256").digest(new TextEncoder().encode("reserve:"+t.identifier))),{padding:!1}),n=c3(t.identifier,i.verification?.storeIdentifier),o=await c8(t.identifier,n);if(a&&!i.verification?.storeInDatabase){let e=`verification:${o}`;return!await a.get(e)&&(await a.set(e,JSON.stringify({id:r,identifier:o,value:t.value,expiresAt:t.expiresAt}),lm(t.expiresAt)),!0)}try{await e.create({model:"verification",data:{id:r,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:"verification",where:[{field:"id",value:r}]}))return!1;throw t}if(a){let e=lm(t.expiresAt);e>0&&await a.set(`verification:${o}`,JSON.stringify({id:r,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let r=await c8(e,c3(e,i.verification?.storeIdentifier));if(a){let e=await a.get(`verification:${r}`);if(e){let n=(0,cL.safeJSONParse)(e);if(n){let e={...n,...t},o=e.expiresAt??n.expiresAt,s=lm(o instanceof Date?o:new Date(o));if(s>0&&await a.set(`verification:${r}`,JSON.stringify(e),s),!i.verification?.storeInDatabase)return e}}}return!a||i.verification?.storeInDatabase?await d(t,[{field:"identifier",value:r}],"verification",void 0):t},refreshUserSessions:m}};function lg(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e))}function lw(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,n=".",i){if(!lg(r))return e(t,{},n,i);let a={...r};for(let r of Object.keys(t)){if("__proto__"===r||"constructor"===r)continue;let o=t[r];null!=o&&(i&&i(a,r,o,n)||(Array.isArray(o)&&Array.isArray(a[r])?a[r]=[...o,...a[r]]:lg(o)&&lg(a[r])?a[r]=e(o,a[r],(n?`${n}.`:"")+r.toString(),i):a[r]=o))}return a})(t,r,"",e),{})}let lb=lw();lw((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),lw((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0});let lA=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function lE(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function lv(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function lk(e,t,r){if(0===r)return!0;let n=32===r?0xffffffff:-1<<32-r>>>0;return(e&n)==(t&n)}function l_(e){if("0.0.0.0"===e)return"unspecified";if("255.255.255.255"===e)return"broadcast";let t=lv(e);return lk(t,lv("127.0.0.0"),8)?"loopback":lk(t,lv("10.0.0.0"),8)||lk(t,lv("172.16.0.0"),12)||lk(t,lv("192.168.0.0"),16)?"private":lk(t,lv("169.254.0.0"),16)?"linkLocal":lk(t,lv("100.64.0.0"),10)?"sharedAddressSpace":lk(t,lv("192.0.2.0"),24)||lk(t,lv("198.51.100.0"),24)||lk(t,lv("203.0.113.0"),24)?"documentation":lk(t,lv("198.18.0.0"),15)?"benchmarking":lk(t,lv("224.0.0.0"),4)?"multicast":lk(t,lv("0.0.0.0"),8)||lk(t,lv("192.0.0.0"),24)||lk(t,lv("240.0.0.0"),4)?"reserved":"public"}function lS(e,t,r={}){let n=5*t,i=Number.parseInt(e.slice(n,n+4),16),a=Number.parseInt(e.slice(n+5,n+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return r.xor&&(o=(0xffffffff^o)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${255&o}`}async function lx(e){let t=e.options,r=t.plugins||[],n=[],i=[];for(let a of r)if(a.init){let r,o=a.init(e);if("object"==typeof(r=aG(o)?await o:o)){if(r.options){let{databaseHooks:e,trustedOrigins:o,...s}=r.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),o&&n.push(o),t=lb(t,s)}r.context&&Object.assign(e,r.context)}}if(n.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...n],r=e.filter(Array.isArray).flat(),i=e.filter(e=>"function"==typeof e);i.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(i.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&i.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=ly(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}async function lR(e,t){let r=[];if(aV(e.baseURL)){let t=e.baseURL.allowedHosts,n=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(n&&"https"!==n&&"auto"!==n||r.push(`https://${e}`),("http"===n||"auto"===n||function(e){let t=function(e){var t,r;let n,i=(-1===(n=(r=(t=function(e){if(e.startsWith("[")){let t=e.indexOf("]");return -1===t?e:e.slice(0,t+1)}let t=e.indexOf(":");return -1===t||-1!==e.indexOf(":",t+1)?e:e.slice(0,t)}(e.trim())).length>=2&&t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t).indexOf("%"))?r:r.slice(0,n)).replace(/\.+$/,"").toLowerCase();if(""===i)return{kind:"reserved",literal:"fqdn",canonical:""};if(!la(i))return"localhost"===i||i.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:i}:lA.has(i)?{kind:"cloudMetadata",literal:"fqdn",canonical:i}:{kind:"public",literal:"fqdn",canonical:i};if(lE(i))return{kind:l_(i),literal:"ipv4",canonical:i};let a=ll(i,{ipv6Subnet:128});return lE(a)?{kind:l_(a),literal:"ipv4",canonical:a}:{kind:function(e){if("0000:0000:0000:0000:0000:0000:0000:0000"===e)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===e)return"loopback";let t=Number.parseInt(e.slice(0,2),16),r=Number.parseInt(e.slice(2,4),16);if(255===t)return"multicast";if(254===t&&(192&r)==128)return"linkLocal";if((254&t)==252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2001:0002:0000:"))return"benchmarking";if(e.startsWith("2002:")){let t=lS(e,1);return t&&"public"!==l_(t)?"reserved":"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let t=lS(e,6);return t&&l_(t),"reserved"}if(e.startsWith("0064:ff9b:0001:"))return"reserved";if(e.startsWith("2001:0000:")){let t=lS(e,6,{xor:!0});return t&&l_(t),"reserved"}return e.startsWith("0100:0000:0000:0000:")?"reserved":e.startsWith("3fff:0")?"documentation":e.startsWith("5f00:")?"reserved":"public"}(a),literal:"ipv6",canonical:a}}(e).kind;return"loopback"===t||"localhost"===t}(e))&&r.push(`http://${e}`));if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let n=aq("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);n&&r.push(new URL(n).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let n=await e.trustedOrigins(t);r.push(...n)}let n=aN.env.BETTER_AUTH_TRUSTED_ORIGINS;return n&&r.push(...n.split(",")),r.filter(e=>!!e)}function lT(e){return e.advanced?.trustedProxyHeaders??!0}async function lI(e,t,r){let n,i=e.options.baseURL,a=function(e,t,r,n,i){if(aV(e)){if(r){let n=aW(r,i);if(!n){if(e.fallback)return aH(e.fallback,t);throw new Y.BetterAuthError("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(e.allowedHosts.some(e=>((e,t)=>{if(!e||!t)return!1;let r=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?az(n)(r):r.toLowerCase()===n.toLowerCase()})(n,e)))return aH(`${function(e,t,r){let n;if("http"===t||"https"===t)return t;let i=aK(e)?e.headers:e;if(r){let e=i.get("x-forwarded-proto");if(e&&aB(e,"proto"))return e}if(aK(e))try{let t=new URL(e.url);if("http:"===t.protocol||"https:"===t.protocol)return t.protocol.slice(0,-1)}catch{}let a=aW(e,r);return a&&("localhost"===(n=a.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||n.endsWith(".localhost")||"::1"===n||n.startsWith("127."))?"http":"https"}(r,e.protocol,i)}://${n}`,t);if(e.fallback)return aH(e.fallback,t);throw new Y.BetterAuthError(`Host "${n}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return e.fallback?aH(e.fallback,t):aq(void 0,t,void 0,n,i)}let a=aK(r)?r:void 0;return"string"==typeof e?aq(e,t,a,n,i):aq(void 0,t,a,n,i)}(i,e.options.basePath||"/api/auth",t,void 0,r);if(!a)throw new Y.BetterAuthError("Could not resolve base URL from request. Check your allowedHosts config.");let o=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));o.baseURL=a,o.options={...e.options,baseURL:aM(a)||void 0};let s={...o.options,baseURL:i};return n="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?aK(t)?t:t?new Request(a,{headers:t}):void 0:void 0,o.trustedOrigins=await lR(s,n),o.trustedProviders=await lO(o.options,n),e.options.advanced?.crossSubDomainCookies?.enabled&&(o.authCookies=cX(o.options),o.createAuthCookie=cY(o.options)),o}async function lU(e,t){if(e)for(let r of e){let e="function"==typeof r?await r():r;if(e[t.field??"id"]===t.value)return e}}async function lO(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}async function lP(e,t){let r=(await e.context.internalAdapter.findAccounts(t.userId))?.find(e=>"credential"===e.providerId),n=r?.password;return!!r&&!!n&&await e.context.password.verify({hash:n,password:t.password})}async function lC(e,t){let r=(await t.context.internalAdapter.findAccounts(e))?.find(e=>"credential"===e.providerId),n=r?.password,i=t.body.password;if(!r||!n||!i)throw i&&await t.context.password.hash(i),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD);if(!await t.context.password.verify({hash:n,password:i}))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD);return!0}function lD(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let n=t.replace(/\/+$/,"");return""===n?r:r===n?"/":r.startsWith(n+"/")?r.slice(n.length).replace(/\/+$/,"")||"/":r}function lL(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function l$(e){let t=e.context.skipOriginCheck;if(!0===t)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,n=lD(e.request.url,r);return t.some(e=>{let t=e.replace(/\/+$/,"");return n===t||n.startsWith(`${t}/`)})}catch{}return!1}let lz=(p=function(){},c=!1,function(...e){return c||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),c=!0),p.apply(this,e)}),lN=aw(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await lH(e),l$(e)))return;let{body:t,query:r}=e,n=t?.callbackURL||r?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,r)=>{if(t){if("string"!=typeof t)throw Y.APIError.fromStatus("BAD_REQUEST",{message:`Invalid ${r}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
72
|
+
`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),"origin"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw Y.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}}};n&&s(n,"callbackURL"),i&&s(i,"redirectURL"),a&&s(a,"errorCallbackURL"),o&&s(o,"newUserCallbackURL")}),lj=e=>aw(async t=>{if(!t.request||l$(t))return;let r=e(t),n=(e,r)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:"origin"!==r})){if(t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config
|
|
73
|
+
`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),"origin"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw Y.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};for(let e of Array.isArray(r)?r:[r])n(e,"callbackURL")});async function lH(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let n=r.get("origin")||r.get("referer")||"",i=r.has("cookie");if(e.context.skipCSRFCheck)return;if(lL(e)){e.context.options.advanced?.disableOriginCheck===!0&&lz();return}if(l$(e)||!(t||i))return;if(!n||"null"===n)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN);let a=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!a.some(e=>aF(n,e)))throw e.context.logger.error(`Invalid origin: ${n}`),e.context.logger.info(`If it's a valid URL, please add ${n} to trustedOrigins in your auth config
|
|
74
|
+
`,`Current list of trustedOrigins: ${a}`),Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.INVALID_ORIGIN)}let lB=aw(async e=>{e.request&&await lq(e)});async function lq(e){let t=e.request;if(!t||e.context.skipCSRFCheck||lL(e))return;let r=t.headers;if(r.has("cookie"))return await lH(e);let n=r.get("Sec-Fetch-Site"),i=r.get("Sec-Fetch-Mode"),a=r.get("Sec-Fetch-Dest");if(n&&n.trim()||i&&i.trim()||a&&a.trim()){if("cross-site"===n&&"navigate"===i)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:n,secFetchMode:i,secFetchDest:a}),Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await lH(e,!0)}if(r.get("origin")||r.get("referer"))return await lH(e,!0)}let lM=new Map;function lV(e,t,r){let n=1e3*t.window;return e?r-e.lastRequest>n?{next:{...e,count:1,lastRequest:r},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:lW(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:r},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:r},update:!1,allowed:!0,retryAfter:null}}function lK(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function lW(e,t){return Math.ceil((e+1e3*t-Date.now())/1e3)}let lF=!1;async function lJ(e,t){var r;let n=new URL(t.baseURL).pathname,i=lD(e.url,n),a=t.rateLimit.window,o=t.rateLimit.max,s=lh(e,t.options);if(!s&&t.options.advanced?.ipAddress?.disableIpTracking)return null;s||lF||(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),lF=!0);let c=(r=s??"no-trusted-ip",`${r}|${i}`),l=lY().find(e=>e.pathMatcher(i));for(let e of(l&&(a=l.window,o=l.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(i));if(t){a=t.window,o=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?az(e)(i):e===i);if(r){let n=t.rateLimit.customRules[r],i="function"==typeof n?await n(e,{window:a,max:o}):n;if(i&&(a=i.window,o=i.max),!1===i)return null}}return{key:c,currentWindow:a,currentMax:o}}let lZ=!1;async function lG(e,t){if(!t.rateLimit.enabled)return;let r=await lJ(e,t);if(!r)return;let{key:n,currentWindow:i,currentMax:a}=r,o=function(e,t){let r,n,i,a,o;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let s=e.rateLimit.storage;if("secondary-storage"===s){let r=t=>t??e.options.rateLimit?.window??10;return{get:async t=>{let r=await e.options.secondaryStorage?.get(t);return r?(0,cL.safeJSONParse)(r):null},set:async(n,i,a)=>{await e.options.secondaryStorage?.set?.(n,JSON.stringify(i),r(t.window))},consume:e.options.secondaryStorage?.increment?async(t,n)=>await e.options.secondaryStorage.increment(t,r(n.window))<=n.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:n.window}:void 0}}if("memory"===s){let r=t=>t??e.options.rateLimit?.window??10;return{async get(e){let t=lM.get(e);return t?Date.now()>=t.expiresAt?(lM.delete(e),null):t.data:null},async set(e,n,i){let a=Date.now()+1e3*r(t.window);lM.set(e,{data:n,expiresAt:a})},async consume(e,t){!function(){let e=Date.now();for(let[t,r]of lM)e>=r.expiresAt&&lM.delete(t);if(lM.size<=1e5)return;let t=lM.size-1e5,r=0;for(let e of lM.keys())if(lM.delete(e),++r>=t)break}();let n=Date.now(),i=lM.get(e),a=lV(i&&n<i.expiresAt?i.data:void 0,t,n);return a.allowed&&lM.set(e,{data:{...a.next,key:e},expiresAt:n+1e3*r(t.window)}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return r="rateLimit",n=e.adapter,i=async e=>{let t=(await n.findMany({model:r,where:[{field:"key",value:e}]}))[0];return"bigint"==typeof t?.lastRequest&&(t.lastRequest=Number(t.lastRequest)),t},a=async(e,t)=>{let s=1e3*t.window,c=await i(e),l=Date.now();if(!c)try{return await n.create({model:r,data:{key:e,count:1,lastRequest:l}}),{allowed:!0,retryAfter:null}}catch(r){if(!await i(e))throw r;return a(e,t)}if(l-c.lastRequest>s)return await n.incrementOne({model:r,where:[{field:"key",value:e},{field:"lastRequest",operator:"lte",value:c.lastRequest}],increment:{},set:{count:1,lastRequest:l}})?(o(l),{allowed:!0,retryAfter:null}):a(e,t);let d=l-s;if(await n.incrementOne({model:r,where:[{field:"key",value:e},{field:"lastRequest",operator:"gt",value:d},{field:"count",operator:"lt",value:t.max}],increment:{count:1},set:{lastRequest:l}}))return{allowed:!0,retryAfter:null};let u=await i(e);return!u||l-u.lastRequest>s?a(e,t):{allowed:!1,retryAfter:lW(u.lastRequest,t.window)}},o=t=>{let i=t-1e3*Math.max(e.rateLimit.window,...lY().map(e=>e.window));e.runInBackground(n.deleteMany({model:r,where:[{field:"lastRequest",operator:"lt",value:i}]}).then(()=>void 0).catch(t=>e.logger.error("Error pruning rate limit rows",t)))},{get:i,set:async(t,i,a)=>{try{a?await n.updateMany({model:r,where:[{field:"key",value:t}],update:{count:i.count,lastRequest:i.lastRequest}}):await n.create({model:r,data:{key:t,count:i.count,lastRequest:i.lastRequest}})}catch(t){e.logger.error("Error setting rate limit",t)}},consume:a}}(t,{window:i}),s={window:i,max:a};if(o.consume){let{allowed:e,retryAfter:t}=await o.consume(n,s);return e?void 0:lK(t??i)}return lQ(t,o,n,s)}async function lQ(e,t,r,n){lZ||(e.logger.warn("Rate limiting is best-effort: the configured storage has no atomic `consume`, so concurrent requests may bypass the limit. Provide a storage that implements `consume` for strict enforcement."),lZ=!0);let i=lV(await t.get(r),n,Date.now());if(!i.allowed)return lK(i.retryAfter??n.window);await t.set(r,{...i.next,key:r},i.update)}function lY(){return[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}]}let{get:lX,set:l0}=W(()=>null),l1=()=>aA("/get-session",{method:["GET","POST"],operationId:"getSession",query:cM,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async e=>{let t=e.context.options.session?.deferSessionRefresh,r="POST"===e.method;if(r&&!t)throw Y.APIError.from("METHOD_NOT_ALLOWED",ck.BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let n=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!n)return null;let i=cH(e,e.context.authCookies.sessionData.name),a=null;if(i){let t=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===t){let t=await cv(i,e.context.secretConfig,"better-auth-session");t&&t.session&&t.user?a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}:c2(e,e.context.authCookies.sessionData)}else if("jwt"===t){let t=await cm(i,e.context.secret);t&&t.session&&t.user?a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}:c2(e,e.context.authCookies.sessionData)}else{let t=(0,cL.safeJSONParse)(cG.decode(cJ.decode(i)));t&&(await cQ("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...t.session,expiresAt:t.expiresAt}),t.signature)?a=t:c2(e,e.context.authCookies.sessionData))}}let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(a?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=a.session,r=e.context.options.session?.cookieCache?.version,n="1";if(r){if("string"==typeof r)n=r;else if("function"==typeof r){let e=r(t.session,t.user);n=e instanceof Promise?await e:e}}if((t.version||"1")!==n)c2(e,e.context.authCookies.sessionData);else{let r=new Date(t.session.expiresAt);if(a.expiresAt<Date.now()||r<new Date)c2(e,e.context.authCookies.sessionData);else{let r=e.context.sessionConfig.cookieRefreshCache;if(!1===r){e.context.session=t;let r=cI(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),n=cR(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:r,user:n})}let n=a.expiresAt-Date.now(),i=1e3*r.updateAge,s=await F();if(n<i&&!s){let r={session:{...t.session},user:t.user,updatedAt:Date.now()};await c0(e,r,!1);let n=e.context.authCookies.sessionToken.attributes,i=o?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i});let a=cI(e.context.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),s=cR(e.context.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)});return e.context.session={session:a,user:s},e.json({session:a,user:s})}let c=cI(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=cR(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:c,user:l},e.json({session:c,user:l})}}}let s=await e.context.internalAdapter.findSession(n);if(e.context.session=s,!s||s.session.expiresAt<new Date)return c5(e),s&&(!t||r)&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh){let t=cI(e.context.options,s.session),r=cR(e.context.options,s.user);return e.json({session:t,user:r})}let c=e.context.sessionConfig.expiresIn,l=e.context.sessionConfig.updateAge,d=s.session.expiresAt.valueOf()-1e3*c+1e3*l<=Date.now(),u=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,p=await F(),f=d&&!u&&!p;if(t&&!r){await c0(e,s,!!o);let t=cI(e.context.options,s.session),r=cR(e.context.options,s.user);return e.json({session:t,user:r,needsRefresh:f})}if(f){let t=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:cC(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)throw c5(e),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);let r=e.context.sessionConfig.expiresIn;await c1(e,{session:t,user:s.user},!1,{maxAge:r});let n=cI(e.context.options,t),i=cR(e.context.options,s.user);return e.json({session:n,user:i})}await c0(e,s,!!o);let h=cI(e.context.options,s.session),m=cR(e.context.options,s.user);return e.json({session:h,user:m})}catch(t){if(ay(t))throw t;throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.FAILED_TO_GET_SESSION)}}),l2=async(e,t)=>{if(e.context.session)return e.context.session;let r=await l1()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return r?(r.headers&&r.headers.forEach((t,r)=>{e.context.responseHeaders?"set-cookie"===r.toLowerCase()?e.context.responseHeaders.append(r,t):e.context.responseHeaders.set(r,t):e.context.responseHeaders=new Headers({[r]:t})}),e.context.session=r.response,r.response):(e.context.session=null,null)},l5=async e=>aJ(e.context.options)?(e.context.session=null,l2(e,{disableCookieCache:!0})):l2(e),l6=aw(async e=>{let t=await l2(e);if(!t?.session)throw Y.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),l4=aw(async e=>{let t=await l5(e);if(!t?.session)throw Y.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});aw(async e=>{let t=await l2(e);if(!t?.session&&(e.request||e.headers))throw Y.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});let l8=aw(async e=>{let t=await l2(e);if(!t?.session)throw Y.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.SESSION_NOT_FRESH)}return{session:t}}),l3=aA("/revoke-session",{method:"POST",body:iZ({token:iu().meta({description:"The token to revoke"})}),use:[l4],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),Y.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),l9=aA("/revoke-sessions",{method:"POST",use:[l4],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),Y.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),l7=aA("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[l4],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw Y.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(r.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function de(e,t,r,n){let i=new URLSearchParams({error:r});n&&i.set("error_description",n);let a=t.includes("?")?"&":"?";throw e.redirect(`${t}${a}${i.toString()}`)}function dt(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}var dr=e.i(53082);let dn=(0,dr.createRandomStringGenerator)("a-z","0-9","A-Z","-_");function di(e){if("boolean"!=typeof e)throw TypeError(`boolean expected, not ${e}`)}function da(e){if("number"!=typeof e)throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function ds(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function dc(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function dl(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function dd(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let du=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],dp=e=>e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255,df=du?e=>e:e=>dp(e)>>>0,dh=du?e=>e:e=>{for(let t=0;t<e.length;t++)e[t]=dp(e[t]);return e},dm="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,dy=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function dg(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function dw(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(ds(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!db(t))throw Error("invalid output, must be aligned");return t}function db(e){return e.byteOffset%4==0}function dA(e){return Uint8Array.from(ds(e))}function dE(e=32){da(e);let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}function dv(e,t=dE){let{nonceLength:r}=e;da(r);let n=(e,t,r)=>{let n=function(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];ds(n),t+=n.length}let r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}(e,t);return r.byteLength&&t.byteLength&&r.buffer===t.buffer&&r.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<r.byteOffset+r.byteLength||t.fill(0),n},i=(i,...a)=>({encrypt(o){ds(o);let s=t(r),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>n(s,e,o)):n(s,c,o)},decrypt(t){ds(t);let n=t.subarray(0,r),o=t.subarray(r);return e(i,n,...a).decrypt(o)}});return"blockSize"in e&&(i.blockSize=e.blockSize),"tagLength"in e&&(i.tagLength=e.tagLength),i}let dk=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),d_=dh(dl(dk("expand 16-byte k"))),dS=dh(dl(dk("expand 32-byte k")));function dx(e,t){return e<<t|e>>>32-t}let dR=0x100000000-1,dT=Uint32Array.of();function dI(e,t){return 255&e[t++]|(255&e[t++])<<8}class dU{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){const t=dI(e=dA(ds(e,32,"key")),0),r=dI(e,2),n=dI(e,4),i=dI(e,6),a=dI(e,8),o=dI(e,10),s=dI(e,12),c=dI(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=dI(e,16+2*t)}process(e,t,r=!1){let{h:n,r:i}=this,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],d=i[5],u=i[6],p=i[7],f=i[8],h=i[9],m=dI(e,t+0),y=dI(e,t+2),g=dI(e,t+4),w=dI(e,t+6),b=dI(e,t+8),A=dI(e,t+10),E=dI(e,t+12),v=dI(e,t+14),k=n[0]+(8191&m),_=n[1]+((m>>>13|y<<3)&8191),S=n[2]+((y>>>10|g<<6)&8191),x=n[3]+((g>>>7|w<<9)&8191),R=n[4]+((w>>>4|b<<12)&8191),T=n[5]+(b>>>1&8191),I=n[6]+((b>>>14|A<<2)&8191),U=n[7]+((A>>>11|E<<5)&8191),O=n[8]+((E>>>8|v<<8)&8191),P=n[9]+(v>>>5|2048*!r),C=0,D=0+k*a+5*h*_+5*f*S+5*p*x+5*u*R;C=D>>>13,D&=8191,D+=5*d*T+5*l*I+5*c*U+5*s*O+5*o*P,C+=D>>>13,D&=8191;let L=C+k*o+_*a+5*h*S+5*f*x+5*p*R;C=L>>>13,L&=8191,L+=5*u*T+5*d*I+5*l*U+5*c*O+5*s*P,C+=L>>>13,L&=8191;let $=C+k*s+_*o+S*a+5*h*x+5*f*R;C=$>>>13,$&=8191,$+=5*p*T+5*u*I+5*d*U+5*l*O+5*c*P,C+=$>>>13,$&=8191;let z=C+k*c+_*s+S*o+x*a+5*h*R;C=z>>>13,z&=8191,z+=5*f*T+5*p*I+5*u*U+5*d*O+5*l*P,C+=z>>>13,z&=8191;let N=C+k*l+_*c+S*s+x*o+R*a;C=N>>>13,N&=8191,N+=5*h*T+5*f*I+5*p*U+5*u*O+5*d*P,C+=N>>>13,N&=8191;let j=C+k*d+_*l+S*c+x*s+R*o;C=j>>>13,j&=8191,j+=T*a+5*h*I+5*f*U+5*p*O+5*u*P,C+=j>>>13,j&=8191;let H=C+k*u+_*d+S*l+x*c+R*s;C=H>>>13,H&=8191,H+=T*o+I*a+5*h*U+5*f*O+5*p*P,C+=H>>>13,H&=8191;let B=C+k*p+_*u+S*d+x*l+R*c;C=B>>>13,B&=8191,B+=T*s+I*o+U*a+5*h*O+5*f*P,C+=B>>>13,B&=8191;let q=C+k*f+_*p+S*u+x*d+R*l;C=q>>>13,q&=8191,q+=T*c+I*s+U*o+O*a+5*h*P,C+=q>>>13,q&=8191;let M=C+k*h+_*f+S*p+x*u+R*d;C=M>>>13,M&=8191,M+=T*l+I*c+U*s+O*o+P*a,C+=M>>>13,M&=8191,D=8191&(C=(C=(C<<2)+C|0)+D|0),C>>>=13,L+=C,n[0]=D,n[1]=L,n[2]=$,n[3]=z,n[4]=N,n[5]=j,n[6]=H,n[7]=B,n[8]=q,n[9]=M}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=65535&a;for(let r=1;r<8;r++)a=(e[r]+t[r]|0)+(a>>>16)|0,e[r]=65535&a;dd(r)}update(e){dc(this),ds(e);let{buffer:t,blockLen:r}=this,n=(e=dA(e)).length;for(let i=0;i<n;){let a=Math.min(r-this.pos,n-i);if(a===r){for(;r<=n-i;i+=r)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,dd(this.h,this.r,this.buffer,this.pad)}digestInto(e){dc(this),function(e,t,r=!1){ds(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!db(e))throw Error("invalid output, must be aligned")}(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=r[t]>>>0,e[i++]=r[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let dO=(f=e=>new dU(e),l=()=>[],(d=(e,t)=>f(t,...l(e)).update(e).digest()).outputLen=(u=f(new Uint8Array(32),...l(new Uint8Array(0)))).outputLen,d.blockLen=u.blockLen,d.create=(e,...t)=>f(e,...t),d),dP=function(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:a,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return da(i),da(o),di(a),di(r),(t,s,c,l,d=0)=>{let u,p;if(ds(t,void 0,"key"),ds(s,void 0,"nonce"),ds(c,void 0,"data"),l=dw(c.length,l,!1),da(d),d<0||d>=dR)throw Error("arx: counter overflow");let f=[],h=t.length;if(32===h)f.push(u=dA(t)),p=dS;else if(16===h&&r)(u=new Uint8Array(32)).set(t),u.set(t,16),p=d_,f.push(u);else throw ds(t,32,"arx key"),Error("invalid key size");du&&db(s)||f.push(s=dA(s));let m=dl(u);if(n){if(24!==s.length)throw Error("arx: extended nonce must be 24 bytes");let e=s.subarray(0,16);if(du)n(p,m,dl(e),m);else{let t=dh(Uint32Array.from(p));n(t,m,dl(e),m),dd(t),dh(m)}s=s.subarray(16)}else du||dh(m);let y=16-i;if(y!==s.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let g=dh(dl(s));try{return!function(e,t,r,n,i,a,o,s){let c=i.length,l=new Uint8Array(64),d=dl(l),u=du&&db(i)&&db(a),p=u?dl(i):dT,f=u?dl(a):dT;if(!du){for(let u=0;u<c;o++){if(e(t,r,n,d,o,s),dh(d),o>=dR)throw Error("arx: counter overflow");let p=Math.min(64,c-u);for(let e=0,t;e<p;e++)a[t=u+e]=i[t]^l[e];u+=p}return}for(let h=0;h<c;o++){if(e(t,r,n,d,o,s),o>=dR)throw Error("arx: counter overflow");let m=Math.min(64,c-h);if(u&&64===m){let e=h/4;if(h%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)f[r=e+t]=p[r]^d[t];h+=64;continue}for(let e=0,t;e<m;e++)a[t=h+e]=i[t]^l[e];h+=m}}(e,p,m,g,c,l,d,o),l}finally{dd(...f)}}}(function(e,t,r,n,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],d=t[0],u=t[1],p=t[2],f=t[3],h=t[4],m=t[5],y=t[6],g=t[7],w=r[0],b=r[1],A=r[2],E=o,v=s,k=c,_=l,S=d,x=u,R=p,T=f,I=h,U=m,O=y,P=g,C=i,D=w,L=b,$=A;for(let e=0;e<a;e+=2)I=I+(C=dx(C^(E=E+S|0),16))|0,E=E+(S=dx(S^I,12))|0,I=I+(C=dx(C^E,8))|0,S=dx(S^I,7),U=U+(D=dx(D^(v=v+x|0),16))|0,v=v+(x=dx(x^U,12))|0,U=U+(D=dx(D^v,8))|0,x=dx(x^U,7),O=O+(L=dx(L^(k=k+R|0),16))|0,k=k+(R=dx(R^O,12))|0,O=O+(L=dx(L^k,8))|0,R=dx(R^O,7),P=P+($=dx($^(_=_+T|0),16))|0,_=_+(T=dx(T^P,12))|0,P=P+($=dx($^_,8))|0,T=dx(T^P,7),O=O+($=dx($^(E=E+x|0),16))|0,E=E+(x=dx(x^O,12))|0,O=O+($=dx($^E,8))|0,x=dx(x^O,7),P=P+(C=dx(C^(v=v+R|0),16))|0,v=v+(R=dx(R^P,12))|0,P=P+(C=dx(C^v,8))|0,R=dx(R^P,7),I=I+(D=dx(D^(k=k+T|0),16))|0,k=k+(T=dx(T^I,12))|0,I=I+(D=dx(D^k,8))|0,T=dx(T^I,7),U=U+(L=dx(L^(_=_+S|0),16))|0,_=_+(S=dx(S^U,12))|0,U=U+(L=dx(L^_,8))|0,S=dx(S^U,7);let z=0;n[z++]=o+E|0,n[z++]=s+v|0,n[z++]=c+k|0,n[z++]=l+_|0,n[z++]=d+S|0,n[z++]=u+x|0,n[z++]=p+R|0,n[z++]=f+T|0,n[z++]=h+I|0,n[z++]=m+U|0,n[z++]=y+O|0,n[z++]=g+P|0,n[z++]=i+C|0,n[z++]=w+D|0,n[z++]=b+L|0,n[z++]=A+$|0},{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let i=df(e[0]),a=df(e[1]),o=df(e[2]),s=df(e[3]),c=df(t[0]),l=df(t[1]),d=df(t[2]),u=df(t[3]),p=df(t[4]),f=df(t[5]),h=df(t[6]),m=df(t[7]),y=df(r[0]),g=df(r[1]),w=df(r[2]),b=df(r[3]);for(let e=0;e<20;e+=2)p=p+(y=dx(y^(i=i+c|0),16))|0,i=i+(c=dx(c^p,12))|0,p=p+(y=dx(y^i,8))|0,c=dx(c^p,7),f=f+(g=dx(g^(a=a+l|0),16))|0,a=a+(l=dx(l^f,12))|0,f=f+(g=dx(g^a,8))|0,l=dx(l^f,7),h=h+(w=dx(w^(o=o+d|0),16))|0,o=o+(d=dx(d^h,12))|0,h=h+(w=dx(w^o,8))|0,d=dx(d^h,7),m=m+(b=dx(b^(s=s+u|0),16))|0,s=s+(u=dx(u^m,12))|0,m=m+(b=dx(b^s,8))|0,u=dx(u^m,7),h=h+(b=dx(b^(i=i+l|0),16))|0,i=i+(l=dx(l^h,12))|0,h=h+(b=dx(b^i,8))|0,l=dx(l^h,7),m=m+(y=dx(y^(a=a+d|0),16))|0,a=a+(d=dx(d^m,12))|0,m=m+(y=dx(y^a,8))|0,d=dx(d^m,7),p=p+(g=dx(g^(o=o+u|0),16))|0,o=o+(u=dx(u^p,12))|0,p=p+(g=dx(g^o,8))|0,u=dx(u^p,7),f=f+(w=dx(w^(s=s+c|0),16))|0,s=s+(c=dx(c^f,12))|0,f=f+(w=dx(w^s,8))|0,c=dx(c^f,7);let A=0;n[A++]=i,n[A++]=a,n[A++]=o,n[A++]=s,n[A++]=y,n[A++]=g,n[A++]=w,n[A++]=b,dh(n)},allowShortKeys:!1}),dC=new Uint8Array(16),dD=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(dC.subarray(r))},dL=new Uint8Array(32);function d$(e,t,r,n,i){var a,o;let s,c;void 0!==i&&ds(i,void 0,"AAD");let l=e(t,r,dL),d=(a=n.length,o=i?i.length:0,da(a),da(o),di(!0),(c=new DataView((s=new Uint8Array(16)).buffer,s.byteOffset,s.byteLength)).setBigUint64(0,BigInt(o),!0),c.setBigUint64(8,BigInt(a),!0),s),u=dO.create(l);i&&dD(u,i),dD(u,n),u.update(d);let p=u.digest();return dd(l,d),p}let dz=((e,t)=>{function r(n,...i){ds(n,void 0,"key"),void 0!==e.nonceLength&&ds(i[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let a=e.tagLength;a&&void 0!==i[1]&&ds(i[1],void 0,"AAD");let o=t(n,...i),s=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");ds(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,ds(e),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(ds(e),a&&e.length<a)throw Error('"ciphertext" expected length bigger than tagLength='+a);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16},(e,t,r)=>({encrypt(n,i){let a=n.length;(i=dw(a+16,i,!1)).set(n);let o=i.subarray(0,-16);dP(e,t,o,o,1);let s=d$(dP,e,t,o,r);return i.set(s,a),dd(s),i},decrypt(n,i){i=dw(n.length-16,i,!1);let a=n.subarray(0,-16),o=n.subarray(-16),s=d$(dP,e,t,a,r);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(o,s))throw dd(s),Error("invalid tag");return i.set(n.subarray(0,-16)),dP(e,t,i,i,1),dd(s),i}})),dN="$ba$";async function dj(e,t){let r=await c6("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var i=dv(dz)(new Uint8Array(r)).encrypt(n);if(ds(i),dm)return i.toHex();let a="";for(let e=0;e<i.length;e++)a+=dy[i[e]];return a}async function dH(e,t){let r=await c6("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("hex string expected, got "+typeof e);if(dm)try{return Uint8Array.fromHex(e)}catch(e){if(e instanceof SyntaxError)throw RangeError(e.message);throw e}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){let r=dg(e.charCodeAt(i)),a=dg(e.charCodeAt(i+1));if(void 0===r||void 0===a)throw RangeError('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);n[t]=16*r+a}return n}(t),i=dv(dz)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}let dB=async({key:e,data:t})=>{var r;if("string"==typeof e)return dj(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let i=await dj(n,t);return r=e.currentVersion,`${dN}${r}$${i}`},dq=async({key:e,data:t})=>{if("string"==typeof e)return dH(e,t);let r=function(e){if(!e.startsWith(dN))return null;let t=e.indexOf("$",4);if(-1===t)return null;let r=parseInt(e.slice(4,t),10);return!Number.isInteger(r)||r<0?null:{version:r,ciphertext:e.slice(t+1)}}(t);if(r){let t=e.keys.get(r.version);if(!t)throw Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return dH(t,r.ciphertext)}if(e.legacySecret)return dH(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};function dM(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens)return e.startsWith("$ba$")||e.length%2==0&&/^[0-9a-f]+$/i.test(e)?dq({key:t.secretConfig,data:e}):e;return e}function dV(e,t){return t.options.account?.encryptOAuthTokens&&e?dB({key:t.secretConfig,data:e}):e}async function dK(e,t,r,n=3600,i){return await ch({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...i},e,n)}async function dW(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let r=await dK(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${n}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:r},e.request)}let dF=aA("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:iZ({email:nO(ih,void 0).meta({description:"The email to send the verification email to"}),callbackURL:iu().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await l2(e);if(!r){let r,n=Date.now(),i=await e.context.internalAdapter.findUserByEmail(t);if(!i||i.user.emailVerified)await dK(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await dW(e,i.user)}catch(e){r=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),r)throw r;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.EMAIL_MISMATCH);if(r?.user.emailVerified)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED);return await dW(e,r.user),e.json({status:!0})}),dJ=aA("/verify-email",{method:"GET",operationId:"verifyEmail",query:iZ({token:iu().meta({description:"The token to verify the email"}),callbackURL:iu().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[lj(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){if(e.query.callbackURL.includes("?"))throw e.redirect(`${e.query.callbackURL}&error=${t.code}`);throw e.redirect(`${e.query.callbackURL}?error=${t.code}`)}throw Y.APIError.from("UNAUTHORIZED",t)}let{token:n}=e.query;try{t=await cf(n,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof oM)return r(ck.BASE_ERROR_CODES.TOKEN_EXPIRED);return r(ck.BASE_ERROR_CODES.INVALID_TOKEN)}let i=iZ({email:nO(ih,void 0),updateTo:iu().optional(),requestType:iu().optional()}).parse(t.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return r(ck.BASE_ERROR_CODES.USER_NOT_FOUND);if(i.updateTo){let t=await l2(e);if(t&&t.user.email!==i.email)return r(ck.BASE_ERROR_CODES.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let t=await dK(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),r=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),n=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:n,token:t},e.request?.clone())),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),await c1(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:cR(e.context.options,n)})}default:{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await dK(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},e.request?.clone())),await c1(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:cR(e.context.options,n)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await l2(e);if(t&&t.user.email===i.email)await c1(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);await c1(e,{session:t,user:{...a.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function dZ(e,t){let{userInfo:r,account:n,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=await e.context.internalAdapter.findOAuthUser(r.email.toLowerCase(),n.accountId,n.providerId).catch(t=>{e.context.logger.error("Better auth was unable to query your database.\nError: ",t),de(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,"internal_server_error")}),c=s?.user,l=!c;if(s){let i=s.linkedAccount??s.accounts.find(e=>e.providerId===n.providerId&&e.accountId===n.accountId);if(i){let t=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({idToken:n.idToken,accessToken:await dV(n.accessToken,e.context),refreshToken:await dV(n.refreshToken,e.context),accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope}).filter(([e,t])=>void 0!==t)):{};e.context.options.account?.storeAccountCookie&&await cB(e,{...i,...t}),Object.keys(t).length>0&&await e.context.internalAdapter.updateAccount(i.id,t),r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||!1!==t.trustProviderByName&&e.context.trustedProviders.includes(n.providerId),o=i?.requireLocalEmailVerified??!0;if(!a&&!r.emailVerified||o&&!s.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0)return(0,aN.isDevelopment)()&&e.context.logger.warn(`User already exist but account isn't linked to ${n.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:n.providerId,accountId:r.id.toString(),userId:s.user.id,accessToken:await dV(n.accessToken,e.context),refreshToken:await dV(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope})}catch(t){return e.context.logger.error("Unable to link account",t),{error:"unable to link account",data:null}}r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0}),c=await dG(e,s.user.id,r)??c}if(o){let{id:t,email:n,emailVerified:i,name:a,image:o,...l}=r,d=cP(e.context.options,l,"update");c=await e.context.internalAdapter.updateUser(s.user.id,{name:a,image:o,...d,email:r.email.toLowerCase(),emailVerified:r.email.toLowerCase()===s.user.email&&s.user.emailVerified||r.emailVerified})}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:t,email:a,emailVerified:o,name:s,image:l,...d}=r,u=cP(e.context.options,d,"create"),p={accessToken:await dV(n.accessToken,e.context),refreshToken:await dV(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope,providerId:n.providerId,accountId:r.id.toString()},{user:f,account:h}=await e.context.internalAdapter.createOAuthUser({name:s,image:l,...u,email:r.email.toLowerCase(),emailVerified:r.emailVerified},p);if(c=f,e.context.options.account?.storeAccountCookie&&await cB(e,h),!r.emailVerified&&c&&e.context.options.emailVerification?.sendOnSignUp&&e.context.options.emailVerification?.sendVerificationEmail){let t=await dK(e.context.secret,c.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${encodeURIComponent(i||"/")}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:c,url:r,token:t},e.request))}}catch(t){if(e.context.logger.error(t),ay(t))return{error:t.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!c)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(c.id);return d?{data:{session:d,user:c},error:null,isRegister:l}:{error:"unable to create session",data:null,isRegister:!1}}async function dG(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{id:n,email:i,emailVerified:a,name:o,image:s,...c}=r,l=cP(e.context.options,c,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:s,...l})}catch(t){e.context.logger.warn("Could not update user info on account link",t);return}}var dQ=Y,c$=c$;let dY=new iJ({type:"object",shape:{callbackURL:iu(),codeVerifier:iu(),errorURL:iu().optional(),newUserURL:iu().optional(),expiresAt:iD(),oauthState:iu().optional(),link:iZ({email:iu(),userId:c$.string()}).optional(),requestSignUp:iN().optional()},catchall:iM(),...nV.normalizeParams(void 0)});Object.keys(dY.shape);var dX=class extends dQ.BetterAuthError{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function d0(e,t,r){let n=dn(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let i={...t,oauthState:n},a=await dB({key:e.context.secretConfig,data:JSON.stringify(i)}),o=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:n,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(i.name,n,e.context.secret,i.attributes);let a=new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:n}),identifier:n,expiresAt:a}))throw new dX("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:t.codeVerifier}}async function d1(e,t,r){let n;if(!t)throw new dX("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let i=e.context.createAuthCookie(r?.cookieName??"oauth_state"),a=e.getCookie(i.name);if(!a)throw new dX("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await dq({key:e.context.secretConfig,data:a});n=dY.parse(JSON.parse(t))}catch(e){throw new dX("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!n.oauthState||n.oauthState!==t)throw new dX("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});c2(e,i)}else{let i=await e.context.internalAdapter.findVerificationValue(t);if(!i)throw new dX("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(n=dY.parse(JSON.parse(i.value))).oauthState&&n.oauthState!==t)throw new dX("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});let a=e.context.createAuthCookie(r?.cookieName??"state"),o=await e.getSignedCookie(a.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new dX("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});c2(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(t)}if(n.expiresAt<Date.now())throw new dX("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:n.expiresAt},errorURL:n.errorURL});return n}async function d2(e,t,r){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.CALLBACK_URL_REQUIRED);let i=dn(128),a={...r||{},callbackURL:n,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp};await l0(a);try{return d0(e,a)}catch(t){throw e.context.logger.error("Failed to create verification",t),new Y.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function d5(e){let t,r=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await d1(e,r)}catch(i){e.context.logger.error("Failed to parse state",i);let t="internal_server_error",r=n;i instanceof dX&&(t="state_security_mismatch"===i.code?"state_mismatch":i.code,r=i.errorURL??n),de(e,r,t)}return t.errorURL||(t.errorURL=n),t&&await l0(t),t}function d6(e){let t=e=>new Date(new Date().getTime()+1e3*e);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:e?.scope?"string"==typeof e.scope?e.scope.split(" "):e.scope:[],idToken:e.id_token,raw:e}}function d4(e){let t=Array.isArray(e)?e[0]:e;return"string"==typeof t&&t.length>0?t:void 0}async function d8(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return cJ.encode(new Uint8Array(r),{padding:!1})}async function d3({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:d,responseType:u,display:p,loginHint:f,hd:h,responseMode:m,additionalParams:y,scopeJoiner:g}){let w=new URL((t="function"==typeof t?await t():t).authorizationEndpoint||r);w.searchParams.set("response_type",u||"code");let b=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;if(w.searchParams.set("client_id",b),w.searchParams.set("state",n),a&&w.searchParams.set("scope",a.join(g||" ")),w.searchParams.set("redirect_uri",t.redirectURI||s),c&&w.searchParams.set("duration",c),p&&w.searchParams.set("display",p),f&&w.searchParams.set("login_hint",f),l&&w.searchParams.set("prompt",l),h&&w.searchParams.set("hd",h),d&&w.searchParams.set("access_type",d),m&&w.searchParams.set("response_mode",m),i){let e=await d8(i);w.searchParams.set("code_challenge_method","S256"),w.searchParams.set("code_challenge",e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});w.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}return y&&Object.entries(y).forEach(([e,t])=>{w.searchParams.set(e,t)}),w}var d9=Object.defineProperty,d7=Object.defineProperties,ue=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertySymbols,ur=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ui=(e,t,r)=>t in e?d9(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ua=(e,t)=>{for(var r in t||(t={}))ur.call(t,r)&&ui(e,r,t[r]);if(ut)for(var r of ut(t))un.call(t,r)&&ui(e,r,t[r]);return e},uo=(e,t)=>d7(e,ue(t)),us=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},uc=async(e,t)=>{var r,n,i,a,o,s;let c=t||{},l={onRequest:[null==t?void 0:t.onRequest],onResponse:[null==t?void 0:t.onResponse],onSuccess:[null==t?void 0:t.onSuccess],onError:[null==t?void 0:t.onError],onRetry:[null==t?void 0:t.onRetry]};if(!t||!(null==t?void 0:t.plugins))return{url:e,options:c,hooks:l};for(let d of(null==t?void 0:t.plugins)||[]){if(d.init){let n=await (null==(r=d.init)?void 0:r.call(d,e.toString(),t));c=n.options||c,e=n.url}l.onRequest.push(null==(n=d.hooks)?void 0:n.onRequest),l.onResponse.push(null==(i=d.hooks)?void 0:i.onResponse),l.onSuccess.push(null==(a=d.hooks)?void 0:a.onSuccess),l.onError.push(null==(o=d.hooks)?void 0:o.onError),l.onRetry.push(null==(s=d.hooks)?void 0:s.onRetry)}return{url:e,options:c,hooks:l}},ul=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},ud=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}},uu=async e=>{let t={},r=async e=>"function"==typeof e?await e():e;if(null==e?void 0:e.auth){if("Bearer"===e.auth.type){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if("Basic"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!i)return t;t.authorization=`Basic ${btoa(`${n}:${i}`)}`}else if("Custom"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!i)return t;t.authorization=`${null!=n?n:""} ${i}`}}return t},up=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function uf(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}function uh(e){try{return JSON.parse(e)}catch(t){return e}}async function um(e){let t=new Headers(function(...e){let t={};for(let r of e)if(r)if(r instanceof Headers)r.forEach((e,r)=>{t[r]=e});else for(let[e,n]of Array.isArray(r)?r:Object.entries(r))null!=n&&(t[e]=n);return t}(null==e?void 0:e.headers,await uu(e)));if(!t.has("content-type")){let r=uf(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var uy=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function ug(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new uy(r.issues);return r.value}var uw=["get","post","put","patch","delete"],ub=async(e,t)=>{var r,n,i,a,o,s,c,l;let d,{hooks:u,url:p,options:f}=await uc(e,t),h=function(e){if(null==e?void 0:e.customFetchImpl)return e.customFetchImpl;if("u">typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch;throw Error("No fetch implementation found")}(f),m=new AbortController,y=null!=(r=f.signal)?r:m.signal,g=function(e,t){let{baseURL:r,params:n,query:i}=t||{query:{},params:{},baseURL:""},a=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let t=e.toString().split("@")[1].split("/")[0];uw.includes(t)&&(e=e.replace(`@${t}/`,"/"))}a.endsWith("/")||(a+="/");let[o,s]=e.replace(a,"").split("?"),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){let r;if(null!=t){if("string"==typeof t)r=t;else if(Array.isArray(t)){for(let r of t)c.append(e,r);continue}else r=JSON.stringify(t);c.set(e,r)}}let l=new Map;if(n)if(Array.isArray(n))for(let[e,t]of o.split("/").filter(e=>e.startsWith(":")).entries()){let r=n[e];l.set(t,String(r))}else for(let[e,t]of Object.entries(n))l.set(`:${e}`,String(t));o=(o=o.split("/").map(e=>(function(e,t){let r,n=e;for(let[e,r]of t)n=n.replace(e,r);if("."===(r=n)||".."===r)throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(n)})(e,l)).join("/")).replace(/^\/+/,"");let d=c.toString();return(d=d.length>0?`?${d}`.replace(/\+/g,"%20"):"",a.startsWith("http"))?new URL(`${o}${d}`,a):`${a}${o}${d}`}(p,f),w=await um(f),b=function(e,t){let r,{body:n}=e;return n?uf(n)&&"string"!=typeof n?"application/x-www-form-urlencoded"===((r=t.get("content-type"))?r.split(";")[0].trim().toLowerCase():null)?new URLSearchParams(n).toString():JSON.stringify(n):n:null}(f,w),A=function(e,t){var r;if(null==t?void 0:t.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=null==(r=e.split("@")[1])?void 0:r.split("/")[0];return uw.includes(n)?n.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}return(null==t?void 0:t.body)?"POST":"GET"}(p,f),E=uo(ua({},f),{url:g,headers:w,body:b,method:A,signal:y});for(let e of u.onRequest)if(e){let t=await e(E);"object"==typeof t&&null!==t&&Object.assign(E,t)}("pipeTo"in E&&"function"==typeof E.pipeTo||"function"==typeof(null==(n=null==t?void 0:t.body)?void 0:n.pipe))&&!("duplex"in E)&&(E.duplex="half");let{clearTimeout:v}=(!(null==f?void 0:f.signal)&&(null==f?void 0:f.timeout)&&(d=setTimeout(()=>null==m?void 0:m.abort(),null==f?void 0:f.timeout)),{abortTimeout:d,clearTimeout:()=>{d&&clearTimeout(d)}}),k=await h(E.url,E);v();let _={response:k,request:E};for(let e of u.onResponse)if(e){let r=await e(uo(ua({},_),{response:(null==(i=null==t?void 0:t.hookOptions)?void 0:i.cloneResponse)?k.clone():k}));r instanceof Response?k=r:"object"==typeof r&&null!==r&&(k=r.response)}if(k.ok){if("HEAD"===E.method)return{data:"",error:null};let e=function(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";return up.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}(k),r={data:null,response:k,request:E};if("json"===e||"text"===e){let e=await k.text(),t=null!=(a=E.jsonParser)?a:uh;r.data=await t(e)}else r.data=await k[e]();for(let e of((null==E?void 0:E.output)&&E.output&&!E.disableValidation&&(r.data=await ug(E.output,r.data)),u.onSuccess))e&&await e(uo(ua({},r),{response:(null==(o=null==t?void 0:t.hookOptions)?void 0:o.cloneResponse)?k.clone():k}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let S=null!=(s=null==t?void 0:t.jsonParser)?s:uh,x=await k.text(),R=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(x),T=R?await S(x):null,I={response:k,responseText:x,request:E,error:uo(ua({},T),{status:k.status,statusText:k.statusText})};for(let e of u.onError)e&&await e(uo(ua({},I),{response:(null==(c=null==t?void 0:t.hookOptions)?void 0:c.cloneResponse)?k.clone():k}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new ul({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new ul(e);case"exponential":return new ud(e);default:throw Error("Invalid retry strategy")}}(t.retry),n=null!=(l=t.retryAttempt)?l:0;if(await r.shouldAttemptRetry(n,k)){for(let e of u.onRetry)e&&await e(_);let i=r.getDelay(n);return await new Promise(e=>setTimeout(e,i)),await ub(e,uo(ua({},t),{retryAttempt:n+1}))}}if(null==t?void 0:t.throw)throw new us(k.status,k.statusText,R?T:x);return{data:null,error:uo(ua({},T),{status:k.status,statusText:k.statusText})}};let uA=new Set([301,302,303,307,308]),uE={redirect:"manual"};async function uv(e,t){let r=!1,n=await ub(e,{...t,...uE,onError(e){var t;("opaqueredirect"===(t=e.response).type||uA.has(t.status))&&(r=!0)}});if(r)throw new Y.BetterAuthError(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`);return n}async function uk({refreshToken:e,options:t,tokenEndpoint:r,authentication:n,extraParams:i}){let{body:a,headers:o}=await function({refreshToken:e,options:t,authentication:r,extraParams:n,resource:i}){let a=new URLSearchParams,o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(a.set("grant_type","refresh_token"),a.set("refresh_token",e),"basic"===r){let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;e?o.authorization="Basic "+cF.encode(`${e}:${t.clientSecret??""}`):o.authorization="Basic "+cF.encode(`:${t.clientSecret??""}`)}else{let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;a.set("client_id",e),t.clientSecret&&a.set("client_secret",t.clientSecret)}if(i)if("string"==typeof i)a.append("resource",i);else for(let e of i)a.append("resource",e);if(n)for(let[e,t]of Object.entries(n))a.set(e,t);return{body:a,headers:o}}({refreshToken:e,options:t,authentication:n,extraParams:i}),{data:s,error:c}=await uv(r,{method:"POST",body:a,headers:o});if(c)throw c;let l={accessToken:s.access_token,refreshToken:s.refresh_token,tokenType:s.token_type,scopes:s.scope?.split(" "),idToken:s.id_token};return s.expires_in&&(l.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*s.expires_in)),s.refresh_token_expires_in&&(l.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*s.refresh_token_expires_in)),l}function u_(e){return sU(e)}class uS{#h;#m=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(u_)}(e))throw new oQ("JSON Web Key Set malformed");this.#h=structuredClone(e)}jwks(){return this.#h}async getKey(e,t){let{alg:r,kid:n}={...e,...t?.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new oK('Unsupported "alg" value for a JSON Web Key Set')}}(r),a=this.#h.keys.filter(e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&("string"==typeof e.alg||"AKP"===i)&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:o,length:s}=a;if(0===s)throw new oY;if(1!==s){let e=new oX,t=this.#m;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await ux(t,e,r)}catch{}},e}return ux(this.#m,o,r)}}async function ux(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){let e=await sN({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new oQ("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function uR(e){let t=new uS(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(r="jose/v6.2.3");let uT=Symbol();async function uI(e,t,r,n=fetch){let i=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{if("TimeoutError"===e.name)throw new o0;throw e});if(200!==i.status)throw new oB("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new oB("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let uU=Symbol();class uO{#y;#g;#w;#b;#A;#E;#v;#k;#_;#S;constructor(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");this.#y=new URL(e.href),this.#g="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this.#w="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this.#b="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,this.#v=new Headers(t?.headers),r&&!this.#v.has("User-Agent")&&this.#v.set("User-Agent",r),this.#v.has("accept")||(this.#v.set("accept","application/json"),this.#v.append("accept","application/jwk-set+json")),this.#k=t?.[uT],t?.[uU]!==void 0&&(this.#S=t?.[uU],function(e,t){return!("object"!=typeof e||null===e||!("uat"in e)||"number"!=typeof e.uat||Date.now()-e.uat>=t)&&"jwks"in e&&!!sU(e.jwks)&&!!Array.isArray(e.jwks.keys)&&!!Array.prototype.every.call(e.jwks.keys,sU)}(t?.[uU],this.#b)&&(this.#A=this.#S.uat,this.#_=uR(this.#S.jwks)))}pendingFetch(){return!!this.#E}coolingDown(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#w}fresh(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#b}jwks(){return this.#_?.jwks()}async getKey(e,t){this.#_&&this.fresh()||await this.reload();try{return await this.#_(e,t)}catch(r){if(r instanceof oY&&!1===this.coolingDown())return await this.reload(),this.#_(e,t);throw r}}async reload(){this.#E&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#E=void 0),this.#E||=uI(this.#y.href,this.#v,AbortSignal.timeout(this.#g),this.#k).then(e=>{this.#_=uR(e),this.#S&&(this.#S.uat=Date.now(),this.#S.jwks=e),this.#A=Date.now(),this.#E=void 0}).catch(e=>{throw this.#E=void 0,e}),await this.#E}}async function uP({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){return uC({code:e,codeVerifier:t,redirectURI:r,options:n="function"==typeof n?await n():n,authentication:i,deviceId:a,headers:o,additionalParams:s,resource:c})}function uC({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){let l=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),n.clientKey&&l.set("client_key",n.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",n.redirectURI||r),c)if("string"==typeof c)l.append("resource",c);else for(let e of c)l.append("resource",e);if("basic"===i){let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;d.authorization=`Basic ${cF.encode(`${e}:${n.clientSecret??""}`)}`}else{let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;l.set("client_id",e),n.clientSecret&&l.set("client_secret",n.clientSecret)}for(let[e,t]of Object.entries(s))l.has(e)||l.append(e,t);return{body:l,headers:d}}async function uD({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:i,authentication:a,deviceId:o,headers:s,additionalParams:c={},resource:l}){let{body:d,headers:u}=await uP({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:a,deviceId:o,headers:s,additionalParams:c,resource:l}),{data:p,error:f}=await uv(i,{method:"POST",body:d,headers:u});if(f)throw f;return d6(p)}function uL(e){let t,r;if("string"!=typeof e)throw new oZ("JWTs must use Compact JWS serialization, JWT must be a string");let{1:n,length:i}=e.split(".");if(5===i)throw new oZ("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new oZ("Invalid JWT");if(!n)throw new oZ("JWTs must contain a payload");try{t=oT(n)}catch{throw new oZ("Failed to base64url decode the payload")}try{r=JSON.parse(ov.decode(t))}catch{throw new oZ("Failed to parse the decoded payload as JSON")}if(!sU(r))throw new oZ("Invalid JWT Claims Set");return r}async function u$(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function uz(e,t){return"string"==typeof e&&(e===t||e===await u$(t))}let uN=async e=>{let{data:t}=await ub("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new Y.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await sN(r,r.alg)},uj=async(e,t,r)=>{let n=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await ub(n);if(!t?.keys)throw new Y.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await sN(r,r.alg)}catch(e){throw aS.logger.error("Failed to fetch Cognito public key:",e),e}};async function uH(e,t){let r=d4(t.clientId);if(!r||!t.clientSecret)return null;let n=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await ub("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:`${r}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return!0===o&&s&&n.includes(s)&&c?c:null}let uB=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),uq=async({token:e,audience:t,nonce:r})=>{try{let{kid:n,alg:i}=co(e);if(!n||!i)return null;let{payload:a}=await cf(e,await uV(n),{algorithms:[i],issuer:["https://accounts.google.com","accounts.google.com"],audience:t,maxTokenAge:"1h"});if(r&&a.nonce!==r)return null;return a}catch{return null}},uM=(e,t)=>!e||"string"==typeof t&&!!t&&("*"===e||t===e),uV=async e=>{let{data:t}=await ub("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new Y.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await sN(r,r.alg)},uK="9188040d-6c67-4c5b-b112-36a304b66dad",uW=async(e,t,r)=>{let{data:n}=await ub(`${r}/${t}/discovery/v2.0/keys`);if(!n?.keys)throw new Y.APIError("BAD_REQUEST",{message:"Keys not found"});let i=n.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await sN(i,i.alg)},uF=["RS256","HS256"],uJ=async(e,t)=>{let{data:r}=await ub(t);if(!r?.keys)throw new Y.APIError("BAD_REQUEST",{message:"Keys not found"});let n=r.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await sN(n,n.alg)},uZ="https://backboard.railway.com/oauth/token",uG={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:t,scopes:r,redirectURI:n}){if(!d4(e.clientId)||!e.clientSecret)throw aS.logger.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let i=e.disableDefaultScope?[]:["email","name"];return e.scope&&i.push(...e.scope),r&&i.push(...r),await d3({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:i,state:t,redirectURI:n,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=co(t);if(!n||!i)return!1;let{payload:a}=await cf(t,await uN(n),{algorithms:[i],issuer:"https://appleid.apple.com",audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(e=>{void 0!==a[e]&&(a[e]=!!a[e])}),r&&!await uz(a.nonce,r))return!1;return!!a}catch{return!1}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=uL(t.idToken);if(!n)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():n.name||"";let i="boolean"==typeof n.email_verified?n.email_verified:"true"===n.email_verified,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{id:n.sub,name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw aS.logger.error("Client Id and Secret are required for Atlassian"),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new Y.BetterAuthError("codeVerifier is required for Atlassian");let a=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,additionalParams:{audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:r}=await ub("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...n},data:r}}catch(e){return aS.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw aS.logger.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new Y.BetterAuthError("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,n=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!d4(e.clientId))throw aS.logger.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw aS.logger.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new Y.BetterAuthError("CLIENT_SECRET_REQUIRED");let o=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&o.push(...e.scope),n&&o.push(...n);let s=await d3({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt}),c=s.searchParams.get("scope");if(c){s.searchParams.delete("scope");let e=encodeURIComponent(c),t=s.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>uD({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=co(t);if(!n||!i)return!1;let a=await uj(n,e.region,e.userPoolId),o=`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,{payload:s}=await cf(t,a,{algorithms:[i],issuer:o,audience:e.clientId,maxTokenAge:"1h"});if(r&&s.nonce!==r)return!1;return!0}catch(e){return aS.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=uL(t.idToken);if(!r)return null;let n=r.name||r.given_name||r.username||"",i={...r,name:n},a=await e.mapProfileToUser?.(i);return{user:{id:r.sub,name:i.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:i}}catch(e){aS.logger.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await ub(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:r.email_verified,...t},data:r}}}catch(e){aS.logger.error("Failed to fetch user info from Cognito:",e)}return null},options:e}},discord:e=>{let t="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identify","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=i.includes("bot")&&void 0!==e.permissions?`&permissions=${e.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}${a}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(null===r.avatar)r.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===r.discriminator?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5}.png`;else{let e=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${e}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n,loginHint:i}){if(!d4(e.clientId)||!e.clientSecret)throw aS.logger.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let a=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d3({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:a,state:t,redirectURI:n,loginHint:i,additionalParams:e.configId?{config_id:e.configId}:{}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>uD({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);if(3===t.split(".").length)try{var n;let i,a,{payload:o}=await cf(t,(n=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),i=new uO(n,void 0),a=async(e,t)=>i.getKey(e,t),Object.defineProperties(a,{coolingDown:{get:()=>i.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>i.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>i.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>i.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>i.jwks(),enumerable:!0,configurable:!1,writable:!1}}),a),{algorithms:["RS256"],audience:e.clientId,issuer:"https://www.facebook.com"});if(r&&o.nonce!==r)return!1;return!!o}catch{return!1}return await uH(t,e)!==null},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&3===t.idToken.split(".").length){let r=uL(t.idToken),n={id:r.sub,name:r.name,email:r.email,picture:{data:{url:r.picture,height:100,width:100,is_silhouette:!1}}},i=await e.mapProfileToUser?.({...n,email_verified:!1});return{user:{...n,emailVerified:!1,...i},data:r}}let r=t.accessToken;if(!r)return null;let n=await uH(r,e);if(!n)return null;let{data:i,error:a}=await ub("https://graph.facebook.com/me?fields="+["id","name","email","picture",...e?.fields||[]].join(","),{auth:{type:"Bearer",token:r}});if(a||i.id!==n)return null;let o=await e.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw aS.logger.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new Y.BetterAuthError("codeVerifier is required for Figma");let a=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d3({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await ub("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return aS.logger.error("Failed to fetch user from Figma"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...n},data:r}}catch(e){return aS.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},github:e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:r,loginHint:n,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),d3({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:o,state:t,codeVerifier:i,redirectURI:a,loginHint:n,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>{let{body:a,headers:o}=uC({code:r,codeVerifier:n,redirectURI:i,options:e}),{data:s,error:c}=await ub(t,{method:"POST",body:a,headers:o});return c?(aS.logger.error("GitHub OAuth token exchange failed:",c),null):"error"in s?(aS.logger.error("GitHub OAuth token exchange failed:",s),null):d6(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i}=await ub("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&i&&(r.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===r.email)?.verified??!1,o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:a,...o},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";for(;r.endsWith("/");)r=r.slice(0,-1);let n=`${r}/${t}/oauth2/v2.0/authorize`,i=`${r}/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(t){if(!d4(e.clientId))throw aS.logger.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),d3({id:"microsoft",options:e,authorizationEndpoint:n,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:n})=>uD({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:i}),async verifyIdToken(n,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(n,i);try{let{kid:a,alg:o}=co(n);if(!a||!o)return!1;let s=await uW(a,t,r),c={algorithms:[o],audience:e.clientId,maxTokenAge:"1h"};"common"!==t&&"organizations"!==t&&"consumers"!==t&&(c.issuer=`${r}/${t}/v2.0`);let{payload:l}=await cf(n,s,c);if(i&&l.nonce!==i)return!1;let d=l.tid;if("string"!=typeof d||l.iss!==`${r}/${d}/v2.0`||"organizations"===t&&d===uK||"consumers"===t&&d!==uK)return!1;return!0}catch(e){return aS.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=uL(t.idToken),n=e.profilePhotoSize||48;await ub(`https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(t){if(!e.disableProfilePhoto&&t.response.ok)try{let e=await t.response.clone().arrayBuffer();r.picture=`data:image/jpeg;base64, ${cF.encode(e)}`}catch(e){aS.logger.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let i=await e.mapProfileToUser?.(r),a=void 0!==r.email_verified?r.email_verified:!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:a,...i},data:r}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),uk({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:i})},options:e}},google:e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a,display:o}){if(!d4(e.clientId)||!e.clientSecret)throw aS.logger.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new Y.BetterAuthError("codeVerifier is required for Google");let s=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await d3({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:s,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>uD({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=await uq({token:t,audience:e.clientId,nonce:r});return!!n&&uM(e.hd,n.hd)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=uL(t.idToken);if(!uM(e.hd,r.hd))return aS.logger.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=new URL("https://slack.com/openid/connect/authorize");return a.searchParams.set("scope",i.join(" ")),a.searchParams.set("response_type","code"),a.searchParams.set("client_id",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r["https://slack.com/user_id"],name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...i},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d3({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return aS.logger.error("No idToken found in token"),null;let n=uL(r),i=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:n.email_verified,...i},data:n}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),d3({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,authentication:"basic",redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i,error:a}=await ub("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(r.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.email||r.data.username||null,image:r.data.profile_image_url,emailVerified:o,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:r,codeVerifier:n,redirectURI:i})=>{let a=e.disableDefaultScope?[]:["account_info.read"];e.scope&&a.push(...e.scope),r&&a.push(...r);let o={};return e.accessType&&(o.token_access_type=e.accessType),await d3({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>await uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...i},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",createAuthorizationURL({state:t,scopes:r,redirectURI:n,codeVerifier:i}){let a=e.disableDefaultScope?[]:["user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"kick",redirectURI:n,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:a,codeVerifier:i,state:t})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:n})=>uD({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=r.data[0],a=await e.mapProfileToUser?.(i);return{user:{id:i.user_id,name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
75
|
+
query {
|
|
76
|
+
viewer {
|
|
77
|
+
id
|
|
78
|
+
name
|
|
79
|
+
email
|
|
80
|
+
avatarUrl
|
|
81
|
+
active
|
|
82
|
+
createdAt
|
|
83
|
+
updatedAt
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
`})});if(n||!r?.data?.viewer)return null;let i=r.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{id:r.data.viewer.id,name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:r,redirectURI:n,loginHint:i})=>{let a=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d3({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:a,state:t,loginHint:i,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>await uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...i},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:n,userinfoEndpoint:i}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:uB(`${t}/oauth/authorize`),tokenEndpoint:uB(`${t}/oauth/token`),userinfoEndpoint:uB(`${t}/api/v4/user`)}),a="gitlab";return{id:a,name:"Gitlab",createAuthorizationURL:async({state:t,scopes:n,codeVerifier:i,loginHint:o,redirectURI:s})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),n&&c.push(...n),await d3({id:a,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:i,loginHint:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>uD({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub(i,{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||"active"!==r.state||r.locked)return null;let a=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/";return{id:"tiktok",name:"TikTok",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user.info.profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${i.join(",")}&response_type=code&client_key=${e.clientKey}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:e.redirectURI||n,options:{clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"post",extraParams:{client_key:e.clientKey}}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return n?null:{user:{email:r.data.user.email||r.data.user.username,id:r.data.user.open_id,name:r.data.user.display_name||r.data.user.username||"",image:r.data.user.avatar_large_url,emailVerified:!1},data:r}},options:e}},reddit:e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identity"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d3({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),{data:i,error:a}=await ub("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${cF.encode(`${e.clientId}:${e.clientSecret}`)}`},body:n.toString()});if(a)throw a;return d6(i)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:"https://www.reddit.com/api/v1/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;let i=await e.mapProfileToUser?.(r),a=i?.email||`${r.id}@reddit.invalid`;return{user:{id:r.id,name:r.name,image:r.icon_img?.split("?")[0],...i,email:a,emailVerified:i?.emailVerified??!1},data:r}},options:e}),roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"select_account consent"}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.nickname||r.preferred_username||"",image:r.picture,email:r.preferred_username||null,emailVerified:!1,...i},data:{...r}}},options:e}},salesforce:e=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!e.clientId||!e.clientSecret)throw aS.logger.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new Y.BetterAuthError("codeVerifier is required for Salesforce");let o=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&o.push(...e.scope),n&&o.push(...n),d3({id:"salesforce",options:e,authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:e.redirectURI||a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>uD({code:t,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await ub(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return aS.logger.error("Failed to fetch user info from Salesforce"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.user_id,name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...n},data:r}}catch(e){return aS.logger.error("Failed to fetch user info from Salesforce:",e),null}},options:e}},vk:e=>{let t="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["email","phone"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i,deviceId:a})=>uD({code:r,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:n,error:i}=await ub("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(i)return null;let a=await e.mapProfileToUser?.(n);return n.user.email||a?.email?{user:{id:n.user.user_id,first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...a},data:n}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:n})=>{let i=new URLSearchParams({response_type:"code",redirect_uri:t.redirectURI?t.redirectURI:r,client_id:t.clientId,state:e});if(t.pkce){let e=await d8(n);i.set("code_challenge_method","S256"),i.set("code_challenge",e)}let a=new URL("https://zoom.us/oauth/authorize");return a.search=i.toString(),a},validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:n})=>uD({code:e,redirectURI:t.redirectURI||r,codeVerifier:n,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>uk({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:r,error:n}=await ub("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(n)return null;let i=await t.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...i},data:{...r}}}}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=(e.disableDefaultScope,[]);return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n,additionalParams:{owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(n||!r)return null;let i=r.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name||"",email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d3({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r),a=r.kakao_account||{},o=a.profile||{};return{user:{id:String(r.id),name:o.nickname||a.name||"",email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["profile","email"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d3({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>uD({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r||"00"!==r.resultcode)return null;let i=await e.mapProfileToUser?.(r),a=r.response||{};return{user:{id:a.id,name:a.name||a.nickname||"",email:a.email,image:a.profile_image,emailVerified:!1,...i},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),await d3({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:o,state:t,codeVerifier:n,redirectURI:i,loginHint:a})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=new URLSearchParams;n.set("id_token",t),n.set("client_id",e.clientId),r&&n.set("nonce",r);let{data:i,error:a}=await ub("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n});return!a&&!!i&&i.aud===e.clientId&&(!i.nonce||i.nonce===r)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=uL(t.idToken)}catch{}if(!r){let{data:e}=await ub("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let n=await e.mapProfileToUser?.(r),i=r.sub||r.userId,a=r.name||r.displayName||"",o=r.picture||r.pictureUrl||void 0;return{user:{id:i,name:a,email:r.email,image:o,emailVerified:!1,...n},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,n=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a,loginHint:o}){if(!e.clientId||!e.clientSecret)throw aS.logger.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new Y.BetterAuthError("codeVerifier is required for Paybin");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),n&&s.push(...n),await d3({id:"paybin",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>uD({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=uL(t.idToken),n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...n},data:r}},options:e}},paypal:e=>{let t="sandbox"===(e.environment||"sandbox"),r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",n=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",a=t?"https://www.sandbox.paypal.com":"https://www.paypal.com",o=t?"https://api.sandbox.paypal.com/v1/oauth2/certs":"https://api.paypal.com/v1/oauth2/certs";return{id:"paypal",name:"PayPal",async createAuthorizationURL({state:t,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw aS.logger.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new Y.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");return await d3({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let i=cF.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await ub(n,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r}).toString()});if(!e.data)throw new Y.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN");let a=e.data;return{accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?new Date(Date.now()+1e3*a.expires_in):void 0,idToken:a.id_token}}catch(e){throw aS.logger.error("PayPal token exchange failed:",e),new Y.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=cF.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await ub(n,{method:"POST",headers:{Authorization:`Basic ${r}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t}).toString()});if(!e.data)throw new Y.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN");let i=e.data;return{accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:i.expires_in?new Date(Date.now()+1e3*i.expires_in):void 0}}catch(e){throw aS.logger.error("PayPal token refresh failed:",e),new Y.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=co(t);if(!i||!uF.includes(i))return!1;let s="HS256"===i?new TextEncoder().encode(e.clientSecret):n?await uJ(n,o):void 0;if(!s)return!1;let{payload:c}=await cf(t,s,{algorithms:[i],issuer:a,audience:e.clientId,maxTokenAge:"1h"});if(r&&c.nonce!==r)return!1;return!0}catch(e){return aS.logger.error("Failed to verify PayPal ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return aS.logger.error("Access token is required to fetch PayPal user info"),null;try{let r=await ub(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return aS.logger.error("Failed to fetch user info from PayPal"),null;let n=r.data;if(t.idToken){let e;try{e=uL(t.idToken).sub}catch(e){return aS.logger.error("Failed to decode PayPal ID token:",e),null}let r=n.sub??n.user_id;if(!e||r!==e)return aS.logger.error("PayPal user info subject does not match ID token subject"),null}let a=await e.mapProfileToUser?.(n);return{user:{id:n.user_id,name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:n}}catch(e){return aS.logger.error("Failed to fetch user info from PayPal:",e),null}},options:e}},polar:e=>{let t="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>uD({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>uk({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d3({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>uD({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:uZ,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>uk({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:uZ,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}),vercel:e=>({id:"vercel",name:"Vercel",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a;if(!n)throw new Y.BetterAuthError("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(a=[],e.scope&&a.push(...e.scope),r&&a.push(...r)),d3({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>uD({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await ub("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}),wechat:e=>({id:"wechat",name:"WeChat",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&i.push(...e.scope),r&&i.push(...r);let a=new URL("https://open.weixin.qq.com/connect/qrconnect");return a.searchParams.set("scope",i.join(",")),a.searchParams.set("response_type","code"),a.searchParams.set("appid",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a.searchParams.set("lang",e.lang||"cn"),a.hash="wechat_redirect",a},validateAuthorizationCode:async({code:t})=>{let{data:r,error:n}=await ub("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:r,error:n}=await ub("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:e.clientId,grant_type:"refresh_token",refresh_token:t}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let{data:n,error:i}=await ub("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!n||n.errcode)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.unionid||n.openid||r,name:n.nickname,email:n.email||`${n.unionid||n.openid||r}@wechat.invalid`,image:n.headimgurl,emailVerified:!1,...a},data:n}},options:e})},uQ=i1(Object.keys(uG)).or(iu()),uY=aA("/list-accounts",{method:"GET",use:[l6],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(t=>{let{scope:r,...n}=function(e,t){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=c_(t,cx(e,"account","output"));return c}(e.context.options,t);return{...n,scopes:r?.split(",")||[]}}))}),uX=aA("/link-social",{method:"POST",requireHeaders:!0,body:iZ({callbackURL:iu().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:uQ,idToken:iZ({token:iu(),nonce:iu().optional(),accessToken:iu().optional(),refreshToken:iu().optional(),scopes:iF(iu()).optional()}).optional(),requestSignUp:iN().optional(),scopes:iF(iu()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:iu().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:iN().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),additionalData:iX(iu(),iB()).optional()}),use:[l6],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=await lU(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:i}=e.body.idToken;if(!await r.verifyIdToken(n,i))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_TOKEN);let a=await r.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let o=String(a.user.id);if(!a.user.email)throw e.context.logger.error(dt(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);if((await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>e.providerId===r.id&&e.accountId===o))return e.json({url:"",status:!0,redirect:!1});if(!e.context.trustedProviders.includes(r.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw Y.APIError.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw Y.APIError.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:r.id,accountId:o,accessToken:e.body.idToken.accessToken,idToken:n,refreshToken:e.body.idToken.refreshToken,scope:e.body.idToken.scopes?.join(",")})}catch(e){throw Y.APIError.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await dG(e,t.user.id,a.user),e.json({url:"",status:!0,redirect:!1})}let n=await d2(e,{userId:t.user.id,email:t.user.email},e.body.additionalData),i=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),u0=aA("/unlink-account",{method:"POST",body:iZ({providerId:iu(),accountId:iu().optional()}),use:[l8],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{providerId:t,accountId:r}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===n.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=n.find(e=>r?e.accountId===r&&e.providerId===t:e.providerId===t);if(!i)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})});async function u1(e,t){let r=await l2(e,{disableCookieCache:aJ(e.context.options)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let n=r?.user?.id||t;if(!n)throw Y.APIError.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return n}function u2(e,t,{resolvedUserId:r,providerId:n,accountId:i}){return(!aZ(e.context.options)||t.userId===r)&&(!n||n===t.providerId)&&(!i||t.accountId===i)}async function u5(e,{resolvedUserId:t,providerId:r,accountId:n,account:i}){let a=await lU(e.context.socialProviders,{value:r});if(!a)throw Y.APIError.from("BAD_REQUEST",{message:`Provider ${r} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});let o=i;if(!o){let i=await cq(e);o=i&&u2(e,i,{resolvedUserId:t,providerId:r,accountId:n})?i:(await e.context.internalAdapter.findAccounts(t)).find(e=>n?e.accountId===n&&e.providerId===r:e.providerId===r)}if(!o)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);try{let t=null,r=o.accessTokenExpiresAt&&new Date(o.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(o.refreshToken&&r&&a.refreshAccessToken){let r=await dM(o.refreshToken,e.context);t=await a.refreshAccessToken(r);let n={accessToken:await dV(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await dV(t.refreshToken,e.context):o.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??o.refreshTokenExpiresAt,idToken:t?.idToken||o.idToken},i=null;o.id&&(i=await e.context.internalAdapter.updateAccount(o.id,n)),e.context.options.account?.storeAccountCookie&&await cB(e,{...o,...i??n})}let n=t?.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:o.accessTokenExpiresAt?"string"==typeof o.accessTokenExpiresAt?new Date(o.accessTokenExpiresAt):o.accessTokenExpiresAt:void 0;return{accessToken:t?.accessToken??await dM(o.accessToken??"",e.context),accessTokenExpiresAt:n,scopes:o.scope?.split(",")??[],idToken:t?.idToken??o.idToken??void 0}}catch(e){throw Y.APIError.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let u6=aA("/get-access-token",{method:"POST",body:iZ({providerId:iu().meta({description:"The provider ID for the OAuth provider"}),accountId:iu().meta({description:"The account ID associated with the refresh token"}).optional(),userId:iu().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{providerId:t,accountId:r,userId:n}=e.body||{},i=await u5(e,{resolvedUserId:await u1(e,n),providerId:t,accountId:r});return e.json(i)}),u4=aA("/refresh-token",{method:"POST",body:iZ({providerId:iu().meta({description:"The provider ID for the OAuth provider"}),accountId:iu().meta({description:"The account ID associated with the refresh token"}).optional(),userId:iu().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let t,{providerId:r,accountId:n,userId:i}=e.body,a=await u1(e,i),o=await lU(e.context.socialProviders,{value:r});if(!o)throw Y.APIError.from("BAD_REQUEST",{message:`Provider ${r} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!o.refreshAccessToken)throw Y.APIError.from("BAD_REQUEST",{message:`Provider ${r} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let s=await cq(e),c=!!s&&u2(e,s,{resolvedUserId:a,providerId:r,accountId:n});if(!(t=c?s:(await e.context.internalAdapter.findAccounts(a)).find(e=>n?e.accountId===n&&e.providerId===r:e.providerId===r)))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);let l=t.refreshToken??void 0;if(!l)throw Y.APIError.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let r=await dM(l,e.context),n=await o.refreshAccessToken(r),i=n.refreshToken?await dV(n.refreshToken,e.context):l,a=n.refreshTokenExpiresAt??t.refreshTokenExpiresAt;if(t.id){let r={...t||{},accessToken:await dV(n.accessToken,e.context),refreshToken:i,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:a,scope:n.scopes?.join(",")||t.scope,idToken:n.idToken||t.idToken};await e.context.internalAdapter.updateAccount(t.id,r)}return c&&e.context.options.account?.storeAccountCookie&&await cB(e,{...s,accessToken:await dV(n.accessToken,e.context),refreshToken:i,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:a,scope:n.scopes?.join(",")||s.scope,idToken:n.idToken||s.idToken}),e.json({accessToken:n.accessToken,refreshToken:n.refreshToken??r,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:a,scope:n.scopes?.join(",")||t.scope,idToken:n.idToken||t.idToken,providerId:t.providerId,accountId:t.accountId})}catch(e){throw Y.APIError.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),u8=aA("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},email:{type:"string"},image:{type:"string"},emailVerified:{type:"boolean"}},required:["id","emailVerified"]},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data"],additionalProperties:!1}}}}}}},query:i6(iZ({accountId:iu().meta({description:"The provider given account id for which to get the account info"}).optional(),providerId:iu().meta({description:"The provider ID to disambiguate provider-issued account IDs"}).optional(),userId:iu().meta({description:"The user ID associated with the account"}).optional()}))},async e=>{let t,{accountId:r,providerId:n,userId:i}=e.query||{},a=await u1(e,i);if(r){let i=(await e.context.internalAdapter.findAccounts(a)).filter(e=>e.accountId===r&&(!n||e.providerId===n));if(i.length>1)throw Y.APIError.from("BAD_REQUEST",{message:"Multiple accounts share this account ID. Pass a providerId to disambiguate.",code:"AMBIGUOUS_ACCOUNT"});t=i[0]}else if(e.context.options.account?.storeAccountCookie){let r=await cq(e);r&&u2(e,r,{resolvedUserId:a,providerId:n})&&(t=r)}if(!t||!u2(e,t,{resolvedUserId:a}))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);let o=await lU(e.context.socialProviders,{value:t.providerId});if(!o)throw Y.APIError.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let s=await u5(e,{resolvedUserId:a,providerId:t.providerId,accountId:t.accountId,account:t});if(!s.accessToken)throw Y.APIError.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let c=await o.getUserInfo({...s,accessToken:s.accessToken});return e.json(c)}),u3={scope:"server"},u9=iZ({code:iu().optional(),error:iu().optional(),device_id:iu().optional(),error_description:iu().optional(),state:iu().optional(),user:iu().optional()}),u7=aA("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:u9.optional(),query:u9.optional(),metadata:{...u3,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,n,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?u9.parse(e.body):{},r=e.query?u9.parse(e.query):{},n=u9.parse({...t,...r}),i=new URLSearchParams;for(let[e,t]of Object.entries(n))null!=t&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if("GET"===e.method)t=u9.parse(e.query);else if("POST"===e.method)t=u9.parse(e.body);else throw Error("Unsupported method")}catch(t){e.context.logger.error("INVALID_CALLBACK_REQUEST",t),de(e,a,"invalid_callback_request")}let{code:o,error:s,error_description:c,device_id:l,user:d}=t,{codeVerifier:u,callbackURL:p,link:f,errorURL:h,newUserURL:m,requestSignUp:y}=await d5(e),g=h??a;s&&de(e,g,s,c),o||(e.context.logger.warn("Code not found"),de(e,g,"no_code"));let w=await lU(e.context.socialProviders,{value:e.params.id});w||(e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),de(e,g,"oauth_provider_not_found"));try{r=await w.validateAuthorizationCode({code:o,codeVerifier:u,deviceId:l,redirectURI:`${e.context.baseURL}/callback/${w.id}`})}catch(t){e.context.logger.error("",t),de(e,g,"invalid_code")}r||de(e,g,"invalid_code");let b=d?(0,cL.safeJSONParse)(d):null,A=await w.getUserInfo({...r,user:b??void 0}).then(e=>e?.user);A&&void 0!==A.id&&null!==A.id&&""!==A.id||(e.context.logger.error("Unable to get user info"),de(e,g,"unable_to_get_user_info"));let E=String(A.id);if(p||(e.context.logger.error("No callback URL found"),de(e,g,"no_callback_url")),f){let t;(e.context.trustedProviders.includes(w.id)||A.emailVerified)&&e.context.options.account?.accountLinking?.enabled!==!1||(e.context.logger.error("Unable to link account - untrusted provider"),de(e,g,"unable_to_link_account")),A.email?.toLowerCase()!==f.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0&&de(e,g,"email_doesn't_match");let n=await e.context.internalAdapter.findAccountByProviderId(E,w.id);if(n){n.userId.toString()!==f.userId.toString()&&de(e,g,"account_already_linked_to_different_user");let t=Object.fromEntries(Object.entries({accessToken:await dV(r.accessToken,e.context),refreshToken:await dV(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scopes?.join(",")}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(n.id,t)}else await e.context.internalAdapter.createAccount({userId:f.userId,providerId:w.id,accountId:E,...r,accessToken:await dV(r.accessToken,e.context),refreshToken:await dV(r.refreshToken,e.context),scope:r.scopes?.join(",")})||de(e,g,"unable_to_link_account");await dG(e,f.userId,A);try{t=p.toString()}catch{t=p}throw e.redirect(t)}A.email||(e.context.logger.error(dt(w.id)),de(e,g,"email_not_found"));let v={providerId:w.id,accountId:E,...r,scope:r.scopes?.join(",")};try{n=await dZ(e,{userInfo:{...A,id:E,email:A.email,name:A.name||""},account:v,callbackURL:p,disableSignUp:w.disableImplicitSignUp&&!y||w.options?.disableSignUp,overrideUserInfo:w.options?.overrideUserInfoOnSignIn})}catch(t){throw ay(t)&&t.body?.code&&de(e,g,t.body.code,t.body.message),t}n.error&&(e.context.logger.error(n.error.split(" ").join("_")),de(e,g,n.error.split(" ").join("_")));let{session:k,user:_}=n.data;await c1(e,{session:k,user:_});try{i=(n.isRegister&&m||p).toString()}catch{i=n.isRegister&&m||p}throw e.redirect(i)});function pe(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&")}let pt=aA("/error",{method:"GET",metadata:{...u3,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",n=t.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",a=n?pe(n):null,o=new URLSearchParams;o.set("error",i),n&&o.set("error_description",n);let s=e.context.options,c=s.onAPIError?.errorURL;return c?new Response(null,{status:302,headers:{Location:`${c}${c.includes("?")?"&":"?"}${o.toString()}`}}):aN.isProduction&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let n=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
87
|
+
<html lang="en">
|
|
88
|
+
<head>
|
|
89
|
+
<meta charset="UTF-8" />
|
|
90
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
91
|
+
<title>Error</title>
|
|
92
|
+
<style>
|
|
93
|
+
* {
|
|
94
|
+
box-sizing: border-box;
|
|
95
|
+
}
|
|
96
|
+
body {
|
|
97
|
+
font-family: ${n?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
|
|
98
|
+
background: ${n?.colors?.background||"var(--background)"};
|
|
99
|
+
color: var(--foreground);
|
|
100
|
+
margin: 0;
|
|
101
|
+
}
|
|
102
|
+
:root,
|
|
103
|
+
:host {
|
|
104
|
+
--spacing: 0.25rem;
|
|
105
|
+
--container-md: 28rem;
|
|
106
|
+
--text-sm: ${n?.size?.textSm||"0.875rem"};
|
|
107
|
+
--text-sm--line-height: calc(1.25 / 0.875);
|
|
108
|
+
--text-2xl: ${n?.size?.text2xl||"1.5rem"};
|
|
109
|
+
--text-2xl--line-height: calc(2 / 1.5);
|
|
110
|
+
--text-4xl: ${n?.size?.text4xl||"2.25rem"};
|
|
111
|
+
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
112
|
+
--text-6xl: ${n?.size?.text6xl||"3rem"};
|
|
113
|
+
--text-6xl--line-height: 1;
|
|
114
|
+
--font-weight-medium: 500;
|
|
115
|
+
--font-weight-semibold: 600;
|
|
116
|
+
--font-weight-bold: 700;
|
|
117
|
+
--default-transition-duration: 150ms;
|
|
118
|
+
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
119
|
+
--radius: ${n?.size?.radiusSm||"0.625rem"};
|
|
120
|
+
--default-mono-font-family: ${n?.font?.monoFamily||"var(--font-geist-mono)"};
|
|
121
|
+
--primary: ${n?.colors?.primary||"black"};
|
|
122
|
+
--primary-foreground: ${n?.colors?.primaryForeground||"white"};
|
|
123
|
+
--background: ${n?.colors?.background||"white"};
|
|
124
|
+
--foreground: ${n?.colors?.foreground||"oklch(0.271 0 0)"};
|
|
125
|
+
--border: ${n?.colors?.border||"oklch(0.89 0 0)"};
|
|
126
|
+
--destructive: ${n?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
|
|
127
|
+
--muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.545 0 0)"};
|
|
128
|
+
--corner-border: ${n?.colors?.cornerBorder||"#404040"};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
button, .btn {
|
|
132
|
+
cursor: pointer;
|
|
133
|
+
background: none;
|
|
134
|
+
border: none;
|
|
135
|
+
color: inherit;
|
|
136
|
+
font: inherit;
|
|
137
|
+
transition: all var(--default-transition-duration)
|
|
138
|
+
var(--default-transition-timing-function);
|
|
139
|
+
}
|
|
140
|
+
button:hover, .btn:hover {
|
|
141
|
+
opacity: 0.8;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
@media (prefers-color-scheme: dark) {
|
|
145
|
+
:root,
|
|
146
|
+
:host {
|
|
147
|
+
--primary: ${n?.colors?.primary||"white"};
|
|
148
|
+
--primary-foreground: ${n?.colors?.primaryForeground||"black"};
|
|
149
|
+
--background: ${n?.colors?.background||"oklch(0.15 0 0)"};
|
|
150
|
+
--foreground: ${n?.colors?.foreground||"oklch(0.98 0 0)"};
|
|
151
|
+
--border: ${n?.colors?.border||"oklch(0.27 0 0)"};
|
|
152
|
+
--destructive: ${n?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
|
|
153
|
+
--muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.65 0 0)"};
|
|
154
|
+
--corner-border: ${n?.colors?.cornerBorder||"#a0a0a0"};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
@media (max-width: 640px) {
|
|
158
|
+
:root, :host {
|
|
159
|
+
--text-6xl: 2.5rem;
|
|
160
|
+
--text-2xl: 1.25rem;
|
|
161
|
+
--text-sm: 0.8125rem;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
@media (max-width: 480px) {
|
|
165
|
+
:root, :host {
|
|
166
|
+
--text-6xl: 2rem;
|
|
167
|
+
--text-2xl: 1.125rem;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
</style>
|
|
171
|
+
</head>
|
|
172
|
+
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
173
|
+
<div
|
|
174
|
+
style="
|
|
175
|
+
display: flex;
|
|
176
|
+
flex-direction: column;
|
|
177
|
+
align-items: center;
|
|
178
|
+
justify-content: center;
|
|
179
|
+
gap: 1.5rem;
|
|
180
|
+
position: relative;
|
|
181
|
+
width: 100%;
|
|
182
|
+
min-height: 100vh;
|
|
183
|
+
padding: 1rem;
|
|
184
|
+
"
|
|
185
|
+
>
|
|
186
|
+
${n?.disableBackgroundGrid?"":`
|
|
187
|
+
<div
|
|
188
|
+
style="
|
|
189
|
+
position: absolute;
|
|
190
|
+
inset: 0;
|
|
191
|
+
background-image: linear-gradient(to right, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
|
|
192
|
+
linear-gradient(to bottom, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
|
|
193
|
+
background-size: 40px 40px;
|
|
194
|
+
opacity: 0.6;
|
|
195
|
+
pointer-events: none;
|
|
196
|
+
width: 100vw;
|
|
197
|
+
height: 100vh;
|
|
198
|
+
"
|
|
199
|
+
></div>
|
|
200
|
+
<div
|
|
201
|
+
style="
|
|
202
|
+
position: absolute;
|
|
203
|
+
inset: 0;
|
|
204
|
+
display: flex;
|
|
205
|
+
align-items: center;
|
|
206
|
+
justify-content: center;
|
|
207
|
+
background: ${n?.colors?.background||"var(--background)"};
|
|
208
|
+
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
209
|
+
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
210
|
+
pointer-events: none;
|
|
211
|
+
"
|
|
212
|
+
></div>
|
|
213
|
+
`}
|
|
214
|
+
|
|
215
|
+
<div
|
|
216
|
+
style="
|
|
217
|
+
position: relative;
|
|
218
|
+
z-index: 10;
|
|
219
|
+
border: 2px solid var(--border);
|
|
220
|
+
background: ${n?.colors?.cardBackground||"var(--background)"};
|
|
221
|
+
padding: 1.5rem;
|
|
222
|
+
max-width: 42rem;
|
|
223
|
+
width: 100%;
|
|
224
|
+
"
|
|
225
|
+
>
|
|
226
|
+
${n?.disableCornerDecorations?"":`
|
|
227
|
+
<!-- Corner decorations -->
|
|
228
|
+
<div
|
|
229
|
+
style="
|
|
230
|
+
position: absolute;
|
|
231
|
+
top: -2px;
|
|
232
|
+
left: -2px;
|
|
233
|
+
width: 2rem;
|
|
234
|
+
height: 2rem;
|
|
235
|
+
border-top: 4px solid var(--corner-border);
|
|
236
|
+
border-left: 4px solid var(--corner-border);
|
|
237
|
+
"
|
|
238
|
+
></div>
|
|
239
|
+
<div
|
|
240
|
+
style="
|
|
241
|
+
position: absolute;
|
|
242
|
+
top: -2px;
|
|
243
|
+
right: -2px;
|
|
244
|
+
width: 2rem;
|
|
245
|
+
height: 2rem;
|
|
246
|
+
border-top: 4px solid var(--corner-border);
|
|
247
|
+
border-right: 4px solid var(--corner-border);
|
|
248
|
+
"
|
|
249
|
+
></div>
|
|
250
|
+
|
|
251
|
+
<div
|
|
252
|
+
style="
|
|
253
|
+
position: absolute;
|
|
254
|
+
bottom: -2px;
|
|
255
|
+
left: -2px;
|
|
256
|
+
width: 2rem;
|
|
257
|
+
height: 2rem;
|
|
258
|
+
border-bottom: 4px solid var(--corner-border);
|
|
259
|
+
border-left: 4px solid var(--corner-border);
|
|
260
|
+
"
|
|
261
|
+
></div>
|
|
262
|
+
<div
|
|
263
|
+
style="
|
|
264
|
+
position: absolute;
|
|
265
|
+
bottom: -2px;
|
|
266
|
+
right: -2px;
|
|
267
|
+
width: 2rem;
|
|
268
|
+
height: 2rem;
|
|
269
|
+
border-bottom: 4px solid var(--corner-border);
|
|
270
|
+
border-right: 4px solid var(--corner-border);
|
|
271
|
+
"
|
|
272
|
+
></div>`}
|
|
273
|
+
|
|
274
|
+
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
275
|
+
<div style="margin-bottom: 1.5rem;">
|
|
276
|
+
<div
|
|
277
|
+
style="
|
|
278
|
+
display: inline-block;
|
|
279
|
+
border: 2px solid ${n?.disableTitleBorder?"transparent":n?.colors?.titleBorder||"var(--destructive)"};
|
|
280
|
+
padding: 0.375rem 1rem;
|
|
281
|
+
"
|
|
282
|
+
>
|
|
283
|
+
<h1
|
|
284
|
+
style="
|
|
285
|
+
font-size: var(--text-6xl);
|
|
286
|
+
font-weight: var(--font-weight-semibold);
|
|
287
|
+
color: ${n?.colors?.titleColor||"var(--foreground)"};
|
|
288
|
+
letter-spacing: -0.02em;
|
|
289
|
+
margin: 0;
|
|
290
|
+
"
|
|
291
|
+
>
|
|
292
|
+
ERROR
|
|
293
|
+
</h1>
|
|
294
|
+
</div>
|
|
295
|
+
<div
|
|
296
|
+
style="
|
|
297
|
+
height: 2px;
|
|
298
|
+
background-color: var(--border);
|
|
299
|
+
width: calc(100% + 3rem);
|
|
300
|
+
margin-left: -1.5rem;
|
|
301
|
+
margin-top: 1.5rem;
|
|
302
|
+
"
|
|
303
|
+
></div>
|
|
304
|
+
</div>
|
|
305
|
+
|
|
306
|
+
<h2
|
|
307
|
+
style="
|
|
308
|
+
font-size: var(--text-2xl);
|
|
309
|
+
font-weight: var(--font-weight-semibold);
|
|
310
|
+
color: var(--foreground);
|
|
311
|
+
margin: 0 0 1rem;
|
|
312
|
+
"
|
|
313
|
+
>
|
|
314
|
+
Something went wrong
|
|
315
|
+
</h2>
|
|
316
|
+
|
|
317
|
+
<div
|
|
318
|
+
style="
|
|
319
|
+
display: inline-flex;
|
|
320
|
+
align-items: center;
|
|
321
|
+
gap: 0.5rem;
|
|
322
|
+
border: 2px solid var(--border);
|
|
323
|
+
background-color: var(--muted);
|
|
324
|
+
padding: 0.375rem 0.75rem;
|
|
325
|
+
margin: 0 0 1rem;
|
|
326
|
+
flex-wrap: wrap;
|
|
327
|
+
justify-content: center;
|
|
328
|
+
"
|
|
329
|
+
>
|
|
330
|
+
<span
|
|
331
|
+
style="
|
|
332
|
+
font-size: 0.75rem;
|
|
333
|
+
color: var(--muted-foreground);
|
|
334
|
+
font-weight: var(--font-weight-semibold);
|
|
335
|
+
"
|
|
336
|
+
>
|
|
337
|
+
CODE:
|
|
338
|
+
</span>
|
|
339
|
+
<span
|
|
340
|
+
style="
|
|
341
|
+
font-size: var(--text-sm);
|
|
342
|
+
font-family: var(--default-mono-font-family, monospace);
|
|
343
|
+
color: var(--foreground);
|
|
344
|
+
word-break: break-all;
|
|
345
|
+
"
|
|
346
|
+
>
|
|
347
|
+
${pe(t)}
|
|
348
|
+
</span>
|
|
349
|
+
</div>
|
|
350
|
+
|
|
351
|
+
<p
|
|
352
|
+
style="
|
|
353
|
+
color: var(--muted-foreground);
|
|
354
|
+
max-width: 28rem;
|
|
355
|
+
margin: 0 auto;
|
|
356
|
+
font-size: var(--text-sm);
|
|
357
|
+
line-height: 1.5;
|
|
358
|
+
text-wrap: pretty;
|
|
359
|
+
"
|
|
360
|
+
>
|
|
361
|
+
${!r?`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:r}
|
|
362
|
+
</p>
|
|
363
|
+
</div>
|
|
364
|
+
|
|
365
|
+
<div
|
|
366
|
+
style="
|
|
367
|
+
display: flex;
|
|
368
|
+
gap: 0.75rem;
|
|
369
|
+
margin-top: 1.5rem;
|
|
370
|
+
justify-content: center;
|
|
371
|
+
flex-wrap: wrap;
|
|
372
|
+
"
|
|
373
|
+
>
|
|
374
|
+
<a
|
|
375
|
+
href="/"
|
|
376
|
+
style="
|
|
377
|
+
text-decoration: none;
|
|
378
|
+
"
|
|
379
|
+
>
|
|
380
|
+
<div
|
|
381
|
+
style="
|
|
382
|
+
border: 2px solid var(--border);
|
|
383
|
+
background: var(--primary);
|
|
384
|
+
color: var(--primary-foreground);
|
|
385
|
+
padding: 0.5rem 1rem;
|
|
386
|
+
border-radius: 0;
|
|
387
|
+
white-space: nowrap;
|
|
388
|
+
"
|
|
389
|
+
class="btn"
|
|
390
|
+
>
|
|
391
|
+
Go Home
|
|
392
|
+
</div>
|
|
393
|
+
</a>
|
|
394
|
+
<a
|
|
395
|
+
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
|
|
396
|
+
target="_blank"
|
|
397
|
+
rel="noopener noreferrer"
|
|
398
|
+
style="
|
|
399
|
+
text-decoration: none;
|
|
400
|
+
"
|
|
401
|
+
>
|
|
402
|
+
<div
|
|
403
|
+
style="
|
|
404
|
+
border: 2px solid var(--border);
|
|
405
|
+
background: transparent;
|
|
406
|
+
color: var(--foreground);
|
|
407
|
+
padding: 0.5rem 1rem;
|
|
408
|
+
border-radius: 0;
|
|
409
|
+
white-space: nowrap;
|
|
410
|
+
"
|
|
411
|
+
class="btn"
|
|
412
|
+
>
|
|
413
|
+
Ask AI
|
|
414
|
+
</div>
|
|
415
|
+
</a>
|
|
416
|
+
</div>
|
|
417
|
+
</div>
|
|
418
|
+
</div>
|
|
419
|
+
</body>
|
|
420
|
+
</html>`})(e.context.options,i,a),{headers:{"Content-Type":"text/html"}})}),pr=aA("/ok",{method:"GET",metadata:{...u3,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0}));function pn(e,t,r){let n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href}let pi=aA("/request-password-reset",{method:"POST",body:iZ({email:nO(ih,void 0).meta({description:"The email address of the user to send a password reset email to"}),redirectTo:iu().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[lj(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),Y.APIError.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return(0,li.generateId)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=cC(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),a=(0,li.generateId)(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:s,token:a},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),pa=aA("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:iZ({callbackURL:iu().meta({description:"The URL to redirect the user to reset their password"})}),use:[lj(e=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let n,{token:i}=e.params,{callbackURL:a}=e.query;if(!i||!a)throw e.redirect(pn(e.context,a,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);if(!o||o.expiresAt<new Date)throw e.redirect(pn(e.context,a,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:i},n=new URL(a,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href))}),po=aA("/reset-password",{method:"POST",operationId:"resetPassword",query:iZ({token:iu().optional()}).optional(),body:iZ({newPassword:iu().meta({description:"The new password to set"}),token:iu().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_TOKEN);let{newPassword:r}=e.body,n=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<n)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);if(r.length>i)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=`reset-password:${t}`,o=await e.context.internalAdapter.consumeVerificationValue(a);if(!o)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_TOKEN);let s=o.value,c=await e.context.password.hash(r);if((await e.context.internalAdapter.findAccounts(s)).find(e=>"credential"===e.providerId)?await e.context.internalAdapter.updatePassword(s,c):await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:c,accountId:s}),e.context.options.emailAndPassword?.onPasswordReset){let t=await e.context.internalAdapter.findUserById(s);t&&await e.context.options.emailAndPassword.onPasswordReset({user:t},e.request)}return e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(s),e.json({status:!0})}),ps=aA("/verify-password",{method:"POST",body:iZ({password:iu().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[l4]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await lP(e,{password:t,userId:r.user.id}))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD);return e.json({status:!0})}),pc=iZ({callbackURL:iu().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:iu().optional(),errorCallbackURL:iu().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:uQ,disableRedirect:iN().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:i6(iZ({token:iu().meta({description:"ID token from the provider"}),nonce:iu().meta({description:"Nonce used to generate the token"}).optional(),accessToken:iu().meta({description:"Access token from the provider"}).optional(),refreshToken:iu().meta({description:"Refresh token from the provider"}).optional(),expiresAt:iD().meta({description:"Expiry date of the token"}).optional(),user:iZ({name:iZ({firstName:iu().optional(),lastName:iu().optional()}).optional(),email:iu().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:iF(iu()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:iN().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:iu().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalData:iX(iu(),iB()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),pl=aA("/sign-out",{method:"POST",operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}return c5(e),e.json({success:!0})}),pd=iZ({name:iu(),email:nO(ih,void 0),password:iu().nonempty(),image:iu().optional(),callbackURL:iu().optional(),rememberMe:iN().optional()}).and(iX(iu(),iB())),pu=iX(iu().meta({description:"Field name must be a string"}),iB()),pp=iX(iu().meta({description:"Field name must be a string"}),iB()),pf=aA("/change-password",{method:"POST",operationId:"changePassword",body:iZ({newPassword:iu().meta({description:"The new password to set"}),currentPassword:iu().meta({description:"The current password is required"}),revokeOtherSessions:iN().meta({description:"Must be a boolean value"}).optional()}),use:[l4],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,i=e.context.session,a=e.context.password.config.minPasswordLength;if(t.length<a)throw e.context.logger.warn("Password is too short"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.warn("Password is too long"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!s||!s.password)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:r}))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD);await e.context.internalAdapter.updateAccount(s.id,{password:c});let l=null;if(n){await e.context.internalAdapter.deleteUserSessions(i.user.id);let t=await e.context.internalAdapter.createSession(i.user.id);if(!t)throw Y.APIError.from("INTERNAL_SERVER_ERROR",ck.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);await c1(e,{session:t,user:i.user}),l=t.token}return e.json({token:l,user:cR(e.context.options,i.user)})}),ph=aA.serverOnly({method:"POST",body:iZ({newPassword:iu().meta({description:"The new password to set is required"})}),use:[l4]},async e=>{let{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.warn("Password is too short"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.warn("Password is too long"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(e=>"credential"===e.providerId&&e.password),o=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:o}),e.json({status:!0});throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_ALREADY_SET)}),pm=aA("/delete-user",{method:"POST",use:[l4],body:iZ({callbackURL:iu().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:iu().meta({description:"The password of the user is required to delete the user"}).optional(),token:iu().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),Y.APIError.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){let r=(await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!r||!r.password)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD)}if(e.body.token)return await py({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=dn(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let n=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:r},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),c5(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),py=aA("/delete-user/callback",{method:"GET",query:iZ({token:iu().meta({description:"The token to verify the deletion request"}),callbackURL:iu().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[lj(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),Y.APIError.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await l2(e,{disableCookieCache:aJ(e.context.options)});if(!t)throw Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!r||r.value!==t.user.id)throw Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.INVALID_TOKEN);let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),c5(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),pg=aA("/change-email",{method:"POST",body:iZ({newEmail:nO(ih,void 0).meta({description:"The new email address to set must be a valid email address"}),callbackURL:iu().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[l4],metadata:{openapi:{operationId:"changeEmail",responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),Y.APIError.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,n=e.context.options.emailVerification?.sendVerificationEmail,i=n&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!i&&!n)throw e.context.logger.error("Verification email isn't enabled."),Y.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await dK(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t}),await c1(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),n){let r=await dK(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:i,token:r},e.request))}return e.json({status:!0})}if(i){let r=await dK(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:n,token:r},e.request)),e.json({status:!0})}if(!n)throw e.context.logger.error("Verification email isn't enabled."),Y.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let a=await dK(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),pw=lw((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),pb=new WeakMap;function pA(e,t){let r=e.options;return r?.operationId??r?.metadata?.openapi?.operationId??t??e.path??"/:virtual"}function pE(e,t){t&&t.forEach((t,r)=>{e.responseHeaders?"set-cookie"===r.toLowerCase()?e.responseHeaders.append(r,t):e.responseHeaders.set(r,t):e.responseHeaders=new Headers({[r]:t})})}function pv(e){let t=e[X.kAPIErrorHeaderSymbol],r=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!r)return null;let n=new Headers;return t?.forEach((e,t)=>{n.append(t,e)}),r?.forEach((e,t)=>{"set-cookie"===t.toLowerCase()?n.append(t,e):n.set(t,e)}),n}async function pk(e,t,r,n){let i={};for(let a of t){let t=!1;try{t=a.matcher(e)}catch(r){let t=pb.get(a.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${t} hook matcher execution:`,r),new Y.APIError("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!t)continue;let o=pb.get(a.handler)??"unknown",s=r.path??"/:virtual",c=await (0,ln.withSpan)(`hook before ${s} ${o}`,{[lt]:"before",[c7.ATTR_HTTP_ROUTE]:s,[lr]:o,[le]:n},()=>a.handler({...e,returnHeaders:!0})).catch(t=>{throw ay(t)&&(0,aS.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),t});pE(e.context,c?.headers);let l=c?.response;if(l&&"object"==typeof l){if("context"in l&&"object"==typeof l.context){let{headers:e,...t}=l.context;e instanceof Headers&&(i.headers?e.forEach((e,t)=>{i.headers?.set(t,e)}):i.headers=e),i=pw(t,i);continue}return l}}return{context:i}}async function p_(e,t,r,n){for(let i of t){if(!i.matcher(e))continue;let t=pb.get(i.handler)??"unknown",a=r.path??"/:virtual",o=await (0,ln.withSpan)(`hook after ${a} ${t}`,{[lt]:"after",[c7.ATTR_HTTP_ROUTE]:a,[lr]:t,[le]:n},()=>i.handler(e)).catch(t=>{if(ay(t))return(0,aS.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),{response:t,headers:pv(t)};throw t});pE(e.context,o.headers),void 0!==o.response&&(e.context.returned=o.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}async function pS(e,t){let r=t.operationId??pA(e),n=e.path??"/:virtual",i=e.options?.method,a=Array.isArray(i)?i[0]:i,o=t.method??t.request?.method??a??"?",s=t.asResponse??aK(t.request),c={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return(0,ln.withSpan)(`${o} ${n}`,{[c7.ATTR_HTTP_ROUTE]:n,[le]:r},async()=>Q(c,async()=>{var i;let a,o,l,d,u,p,f,{beforeHooks:h,afterHooks:m}=(a=(i=c.context).options.plugins||[],o=[],l=[],(d=i.options.hooks?.before)&&(pb.set(d,"user"),o.push({matcher:()=>!0,handler:d})),(u=i.options.hooks?.after)&&(pb.set(u,"user"),l.push({matcher:()=>!0,handler:u})),p=a.flatMap(e=>(e.hooks?.before??[]).map(t=>(pb.set(t.handler,`plugin:${e.id}`),t))),f=a.flatMap(e=>(e.hooks?.after??[]).map(t=>(pb.set(t.handler,`plugin:${e.id}`),t))),p.length&&o.push(...p),f.length&&l.push(...f),{beforeHooks:o,afterHooks:l}),y=await pk(c,h,e,r);if("context"in y&&y.context&&"object"==typeof y.context){let{headers:e,...t}=y.context;if(e){c.headers||(c.headers=new Headers);let t=c.headers;e.forEach((e,r)=>{t.set(r,e)})}c=pw(t,c)}else if(y){let e=c.context.responseHeaders;return s?ec(y,{headers:e}):t.returnHeaders?{headers:e,response:y}:y}c.asResponse=!1,c.returnHeaders=!0,c.returnStatus=!0;let g=await Q(c,()=>(0,ln.withSpan)(`handler ${n}`,{[c7.ATTR_HTTP_ROUTE]:n,[le]:r},()=>e(c))).catch(e=>{if(ay(e))return{response:e,status:e.statusCode,headers:pv(e)};throw e});if(g instanceof Response)return g;c.context.returned=g.response,c.context.responseHeaders=g.headers??void 0;let w=await p_(c,m,e,r);if(void 0!==w.response&&(g.response=w.response),g.headers=w.headers??g.headers,ay(g.response)&&(0,aS.shouldPublishLog)(c.context.logger.level,"debug")&&(g.response.stack=g.response.errorStack),ay(g.response)&&!s)throw g.headers&&Object.defineProperty(g.response,X.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,writable:!1,value:g.headers}),g.response;return s?ec(g.response,{headers:g.headers??void 0,status:g.status}):t.returnHeaders?t.returnStatus?{headers:g.headers,response:g.response,status:g.status}:{headers:g.headers,response:g.response}:t.returnStatus?{response:g.response,status:g.status}:g.response}))}async function px(e,t){if(e.baseURL)return e;let r=function(e){if(aK(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has("host")||t.has("x-forwarded-host"))return t}(t),n=e.options.baseURL,i=aV(n)&&!!n.fallback;if(void 0===r&&!i)throw new Y.APIError("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await lI(e,r,lT(e.options))}catch(e){if(e instanceof Y.BetterAuthError)throw new Y.APIError("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}function pR(e,t){let r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},n=t.plugins?.map(t=>t.middlewares?.map(r=>{let n=async n=>{let i=await e;return(0,ln.withSpan)(`middleware ${r.path} ${t.id}`,{[lt]:"middleware",[c7.ATTR_HTTP_ROUTE]:r.path,[lr]:`plugin:${t.id}`},()=>r.middleware({...n,context:{...i,...n.context}}))};return n.options=r.middleware.options,{path:r.path,middleware:n}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=async e=>{let r=pA(i,n),a=async()=>{let n=await t,a=aV(n.options.baseURL)?await px(n,e):n;return pS(i,{...e,context:a,operationId:r,asResponse:e?.asResponse??aK(e?.request)})};return await M()?a():K(new WeakMap,a)},r[n].path=i.path,r[n].options=i.options;return r}({signInSocial:aA("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:pc,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=await lU(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),Y.APIError.from("NOT_FOUND",ck.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:n}=e.body.idToken;if(!await t.verifyIdToken(r,n))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_TOKEN);let i=await t.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user});if(!i||!i?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);if(!i.user.email)throw e.context.logger.error(dt(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);let a=await dZ(e,{userInfo:{...i.user,email:i.user.email,id:String(i.user.id),name:i.user.name||"",image:i.user.image,emailVerified:i.user.emailVerified||!1},account:{providerId:t.id,accountId:String(i.user.id),accessToken:e.body.idToken.accessToken},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(a.error)throw Y.APIError.from("UNAUTHORIZED",{message:a.error,code:"OAUTH_LINK_ERROR"});return await c1(e,a.data),e.json({redirect:!1,token:a.data.session.token,url:void 0,user:cR(e.context.options,a.data.user)})}let{codeVerifier:r,state:n}=await d2(e,void 0,e.body.additionalData),i=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:u7,getSession:l1(),signOut:pl,signUpEmail:aA("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[lB],body:pd,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>(0,c9.runWithTransaction)(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw Y.APIError.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:n,email:i,password:a,image:o,callbackURL:s,rememberMe:c,...l}=r;if(!nO(ih,void 0).safeParse(i).success)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_EMAIL);if(!a||"string"!=typeof a)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_PASSWORD);let d=e.context.password.config.minPasswordLength;if(a.length<d)throw e.context.logger.warn("Password is too short"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let u=e.context.password.config.maxPasswordLength;if(a.length>u)throw e.context.logger.warn("Password is too long"),Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let p=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,f=!1===e.context.options.emailAndPassword.autoSignIn||p,h=cO(e.context.options,l,"create"),m=i.toLowerCase(),y=await e.context.internalAdapter.findUserByEmail(m);if(y?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${i}`),p){let t;await e.context.password.hash(a),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:y.user},e.request?.clone()));let r=new Date,i=e.context.generateId({model:"user"})||(0,li.generateId)(),s={name:n,email:m,emailVerified:!1,image:o??null,createdAt:r,updatedAt:r},c=e.context.options.emailAndPassword?.customSyntheticUser;if(c){let r=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of r)e in h&&(n[e]=h[e]);let a=c({coreFields:s,additionalFields:n,id:i});t=cT(e.context.options,a)}else t=cT(e.context.options,{...s,...h,id:i});return e.json({token:null,user:cR(e.context.options,t)})}throw Y.APIError.from("UNPROCESSABLE_ENTITY",ck.BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let g=await e.context.password.hash(a);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:n,image:o,...h,emailVerified:!1})))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}catch(t){if((0,aN.isDevelopment)()&&e.context.logger.error("Failed to create user",t),ay(t))throw t;throw e.context.logger?.error("Failed to create user",t),Y.APIError.from("UNPROCESSABLE_ENTITY",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}if(!t)throw Y.APIError.from("UNPROCESSABLE_ENTITY",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:g}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await dK(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),i=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${i}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:n},e.request?.clone()))}if(f)return e.json({token:null,user:cR(e.context.options,t)});let w=await e.context.internalAdapter.createSession(t.id,!1===c);if(!w)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await c1(e,{session:w,user:t},!1===c),e.json({token:w.token,user:cR(e.context.options,t)})})),signInEmail:aA("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[lB],cloneRequest:!0,body:iZ({email:iu().meta({description:"Email of the user"}),password:iu().meta({description:"Password of the user"}),callbackURL:iu().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:iN().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),Y.APIError.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!nO(ih,void 0).safeParse(t).success)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.INVALID_EMAIL);let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let i=n.accounts.find(e=>"credential"===e.providerId);if(!i)throw await e.context.password.hash(r),e.context.logger.warn("Credential account not found"),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let a=i?.password;if(!a)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.warn("Invalid password"),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await dK(e.context.secret,n.user.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:i,token:t},e.request?.clone()))}throw Y.APIError.from("FORBIDDEN",ck.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED)}let o=await e.context.internalAdapter.createSession(n.user.id,!1===e.body.rememberMe);if(!o)throw e.context.logger.error("Failed to create session"),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await c1(e,{session:o,user:n.user},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:o.token,url:e.body.callbackURL,user:cR(e.context.options,n.user)})}),resetPassword:po,verifyPassword:ps,verifyEmail:dJ,sendVerificationEmail:dF,changeEmail:pg,changePassword:pf,setPassword:ph,updateSession:aA("/update-session",{method:"POST",operationId:"updateSession",body:pu,use:[l6],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{var t;let r=e.body;if("object"!=typeof r||Array.isArray(r))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,i=(t=e.context.options,cU(r,{fields:cx(t,"session","input"),action:"update"}));if(0===Object.keys(i).length)throw Y.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(n.session.token,{...i,updatedAt:new Date});if(!a&&aJ(e.context.options))throw c5(e),Y.APIError.from("UNAUTHORIZED",ck.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);let o=a??{...n.session,...i,updatedAt:new Date};return await c1(e,{session:o,user:n.user}),e.json({session:cI(e.context.options,o)})}),updateUser:aA("/update-user",{method:"POST",operationId:"updateUser",body:pp,use:[l6],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);if(t.email)throw Y.APIError.from("BAD_REQUEST",ck.BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:n,...i}=t,a=e.context.session,o=cO(e.context.options,i,"update");if(void 0===n&&void 0===r&&0===Object.keys(o).length)throw Y.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:r,image:n,...o})??{...a.user,...void 0!==r&&{name:r},...void 0!==n&&{image:n},...o};return await c1(e,{session:a.session,user:s}),e.json({status:!0})}),deleteUser:pm,requestPasswordReset:pi,requestPasswordResetCallback:pa,listSessions:aA("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[l8],requireHeaders:!0,metadata:{openapi:{operationId:"listUserSessions",description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>cI(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),revokeSession:l3,revokeSessions:l9,revokeOtherSessions:l7,linkSocialAccount:uX,listUserAccounts:uY,deleteUserCallback:py,unlinkAccount:u0,refreshToken:u4,getAccessToken:u6,accountInfo:u8,...r,ok:pr,error:pt},e),middlewares:n}}var pT=e.i(2157),pI=e.i(60526);async function pU(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let r=e.socialProviders?.[t];if(!r)return{};let n="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!n.mapProfileToUser,disableDefaultScope:!!n.disableDefaultScope,disableIdTokenSignIn:!!n.disableIdTokenSignIn,disableImplicitSignUp:n.disableImplicitSignUp,disableSignUp:n.disableSignUp,getUserInfo:!!n.getUserInfo,overrideUserInfoOnSignIn:!!n.overrideUserInfoOnSignIn,prompt:n.prompt,verifyIdToken:!!n.verifyIdToken,scope:n.scope,refreshAccessToken:!!n.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function pO(e){let t=await c6("SHA-256").digest(e);return cF.encode(t)}async function pP(){if(n)return n;try{let e=process.cwd();if(!e)return;let t=await av.default.readFile(ak.default.join(e,"package.json"),"utf-8");return n=JSON.parse(t)}catch{}}async function pC(e){if(n)return n.dependencies?.[e]||n.devDependencies?.[e]||n.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=ak.default.join(t,"node_modules",e,"package.json"),n=await av.default.readFile(r,"utf-8");return JSON.parse(n).version||await pD(e)||void 0}catch{}return pD(e)}async function pD(e){let t=await pP();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function pL(){return(await pP())?.name}async function p$(){try{let e,t,r=pI.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":t("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":t("NETLIFY","NETLIFY_URL")?"netlify":t("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":t("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":t("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":t("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":t("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":t("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":t("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":t("DYNO","HEROKU_APP_NAME")?"heroku":t("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":t("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:pI.default.platform(),systemRelease:pI.default.release(),systemArchitecture:pI.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:pI.default.totalmem(),isWSL:await pH(),isDocker:await pj(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function pz(){try{return pT.default.statSync("/.dockerenv"),!0}catch{return!1}}async function pN(){try{return pT.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function pj(){return void 0===i&&(i=await pz()||await pN()),i}async function pH(){try{return!1}catch{return!1}}let pB=null;async function pq(e){if(pB)return pB;let t=await pL();return t?pB=await pO(e?e+t:t):e?pB=await pO(e):pB=(0,dr.createRandomStringGenerator)("a-z","A-Z","0-9")(32)}async function pM(){for(let[e,t]of Object.entries({pg:"postgresql",mysql:"mysql",mariadb:"mariadb",sqlite3:"sqlite","better-sqlite3":"sqlite","@prisma/client":"prisma",mongoose:"mongodb",mongodb:"mongodb","drizzle-orm":"drizzle"})){let r=await pC(e);if(r)return{name:t,version:r}}}async function pV(){for(let[e,t]of Object.entries({next:"next",nuxt:"nuxt","react-router":"react-router",astro:"astro","@sveltejs/kit":"sveltekit","solid-start":"solid-start","tanstack-start":"tanstack-start",hono:"hono",express:"express",elysia:"elysia",expo:"expo"})){let r=await pC(e);if(r)return{name:t,version:r}}}let pK=async function(){};async function pW(e,t){let r,n=e.telemetry?.debug||(0,aN.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY_DEBUG",!1),i=aN.ENV.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!i&&!t?.customTrack)return{publish:pK};let a=async e=>{t?.customTrack?await t.customTrack(e).catch(aS.logger.error):i&&(n?aS.logger.info("telemetry event",JSON.stringify(e,null,2)):await ub(i,{method:"POST",body:e}).catch(aS.logger.error))},o=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,aN.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,aN.isTest)())},s=await o();return s&&(r=await pq("string"==typeof e.baseURL?e.baseURL:void 0),a({type:"init",payload:{config:await pU(e,t),runtime:"u">typeof Deno?{name:"deno",version:Deno?.version?.deno??null}:"u">typeof Bun?{name:"bun",version:Bun?.version??null}:"u">typeof process&&process?.versions?.node?{name:"node",version:process.versions.node??null}:{name:"edge",version:null},database:await pM(),framework:await pV(),environment:"production"===(0,aN.getEnvVar)("NODE_ENV")?"production":"false"!==aN.env.CI&&("BUILD_ID"in aN.env||"BUILD_NUMBER"in aN.env||"CI"in aN.env||"CI_APP_ID"in aN.env||"CI_BUILD_ID"in aN.env||"CI_BUILD_NUMBER"in aN.env||"CI_NAME"in aN.env||"CONTINUOUS_INTEGRATION"in aN.env||"RUN_ID"in aN.env)?"ci":(0,aN.isTest)()?"test":"development",systemInfo:await p$(),packageManager:function(){let e=aN.env.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),n=t.substring(0,r);return{name:"npminstall"===n?"cnpm":n,version:t.substring(r+1)}}()},anonymousId:r})),{publish:async t=>{s&&(r||(r=await pq("string"==typeof e.baseURL?e.baseURL:void 0)),await a({type:t.type,payload:t.payload,anonymousId:r}))}}}async function pF(e,t,r){let n,i,a,o,s=aJ(t);s||(t=lb(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=lb(t,{account:{storeAccountCookie:!0}}));let c=t.plugins||[],l=(m=t,m.advanced?.crossSubDomainCookies?.enabled,[]),d=(0,aS.createLogger)(t.logger),u=aV(t.baseURL);if(aV(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new Y.BetterAuthError('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let p=u?void 0:aq("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);p||u||d.warn("[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&d.error(`[better-auth] Misconfiguration detected.
|
|
421
|
+
You are using the memory DB with generateId: false.
|
|
422
|
+
This will cause no id to be generated for any model.
|
|
423
|
+
Most of the features of Better Auth will not work correctly.`);let f=t.secrets??((y=aN.env.BETTER_AUTH_SECRETS)?y.split(",").map(e=>{let t=(e=e.trim()).indexOf(":");if(-1===t)throw new Y.BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let r=parseInt(e.slice(0,t),10);if(!Number.isInteger(r)||r<0)throw new Y.BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let n=e.slice(t+1).trim();if(!n)throw new Y.BetterAuthError(`Empty secret value for version ${r} in BETTER_AUTH_SECRETS.`);return{version:r,value:n}}):null),h=t.secret||aN.env.BETTER_AUTH_SECRET||aN.env.AUTH_SECRET||"";if(f)!function(e,t){var r;let n;if(0===e.length)throw new Y.BetterAuthError("`secrets` array must contain at least one entry.");let i=new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new Y.BetterAuthError(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new Y.BetterAuthError(`Empty secret value for version ${e} in \`secrets\`.`);if(i.has(e))throw new Y.BetterAuthError(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);i.add(e)}let a=e[0];a.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${a.version}) should be at least 32 characters long for adequate security.`),120>(0===(n=new Set(r=a.value).size)?0:Math.log2(Math.pow(n,r.length)))&&t.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(f,d),n=f[0].value,i=function(e,t){let r=new Map;for(let t of e)r.set(parseInt(String(t.version),10),t.value);return{keys:r,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&"better-auth-secret-12345678901234567890"!==t?t:void 0}}(f,h);else{var m,y,g=n=h||"better-auth-secret-12345678901234567890";let e="better-auth-secret-12345678901234567890"===g;if(!(0,aN.isTest)()){let t;if(e&&aN.isProduction)throw new Y.BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!g)throw new Y.BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");g.length<32&&d.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),120>(0===(t=new Set(g).size)?0:Math.log2(Math.pow(t,g.length)))&&d.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}i=n}!function(e,t){let r=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,n]of Object.entries(e.endpoints))if(n&&"path"in n&&"string"==typeof n.path){let i=n.path,a=[];n.options&&"method"in n.options&&(Array.isArray(n.options.method)?a=n.options.method:"string"==typeof n.options.method&&(a=[n.options.method])),0===a.length&&(a=["*"]),r.has(i)||r.set(i,[]),r.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let n=[];for(let[e,t]of r.entries())if(t.length>1){let r=new Map,i=!1;for(let e of t)for(let n of e.methods)r.has(n)||r.set(n,[]),r.get(n).push(e.pluginId),r.get(n).length>1&&(i=!0),"*"===n&&t.length>1?i=!0:"*"!==n&&r.has("*")&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,n]of r.entries())(n.length>1||"*"===e&&t.length>1||"*"!==e&&r.has("*"))&&a.push(e);n.push({path:e,plugins:i,conflictingMethods:a})}}if(n.length>0){let e=n.map(e=>` - "${e.path}" [${e.conflictingMethods.join(", ")}] used by plugins: ${e.plugins.join(", ")}`).join("\n");t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
424
|
+
${e}
|
|
425
|
+
|
|
426
|
+
To resolve this, you can:
|
|
427
|
+
1. Use only one of the conflicting plugins
|
|
428
|
+
2. Configure the plugins to use different paths (if supported)
|
|
429
|
+
3. Ensure plugins use different HTTP methods for the same path
|
|
430
|
+
`)}}(t={...t,secret:n,baseURL:u?t.baseURL:p?new URL(p).origin:"",basePath:t.basePath||"/api/auth",plugins:c.concat(l)},d);let w=t.advanced?.ipAddress?.trustedProxies;if(w&&w.length>0){let e=w.filter(e=>null===lp(e));e.length>0&&d.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let b=cX(t),A=(0,a_.getAuthTables)(t),E=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let r="function"==typeof t?await t():t;if(null==r||!1===r.enabled)return null;r.clientId||d.warn(`Social provider ${e} is missing clientId or clientSecret`);let n=uG[e](r);return n.disableImplicitSignUp=r.disableImplicitSignUp,n}))).filter(e=>null!==e),v=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let n=t?.advanced?.database?.generateId;return"function"==typeof n?n({model:e,size:r}):"uuid"===n?crypto.randomUUID():"serial"!==n&&!1!==n&&(0,li.generateId)(r)},{publish:k}=await pW(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),_=new Set(t.plugins.map(e=>e.id)),S=await lR(t),x=await lO(t),R={appName:t.appName||"Better Auth",baseURL:p||"",version:(0,H.getBetterAuthVersion)(),socialProviders:E,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:A,trustedOrigins:S,trustedProviders:x,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>aF(e,r,t))},sessionConfig:{updateAge:t.session?.updateAge!==void 0?t.session.updateAge:86400,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(a=t.session?.cookieCache?.refreshCache,o=t.session?.cookieCache?.maxAge||300,s&&a?(d.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==a&&void 0!==a&&(!0===a?{enabled:!0,updateAge:Math.floor(.2*o)}:{enabled:!0,updateAge:void 0!==a.updateAge?a.updateAge:Math.floor(.2*o)}))},secret:n,secretConfig:i,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??aN.isProduction,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:b,logger:d,generateId:v,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||aX,verify:t.emailAndPassword?.password?.verify||a1,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:lC},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:ly(e,{options:t,logger:d,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:v}),createAuthCookie:cY(t),async runMigrations(){throw new Y.BetterAuthError("runMigrations will be set by the specific init implementation")},publishTelemetry:k,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,aN.isTest)(),runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{d.error("Failed to run background task:",e)})):await e}catch(e){d.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>_.has(e)},T=lx(R);return aG(T)&&await T,R}let pJ=async e=>{let t=await aR(e),r=await pF(t,e,e=>(0,aT.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new Y.BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await aD(e);await t()},r};async function pZ(){if("vercel"===(0,aE.hubProfile)()){let{Pool:t}=await e.A(6194),r=process.env.POSTGRES_URL;if(!r)throw Error("POSTGRES_URL is required for the vercel hub auth store");return new t({connectionString:r})}let{DatabaseSync:t}=await Promise.resolve().then(()=>e.x("node:sqlite",()=>require("node:sqlite"),!0));return await (0,av.mkdir)((0,ak.dirname)(aE.AUTH_DB_PATH),{recursive:!0}),new t(aE.AUTH_DB_PATH)}async function pG(){let t;return((e,t)=>{let r=t(e),{api:n}=pR(r,e);return{handler:async t=>{let n,i=await r,a=i.options.basePath||"/api/auth";if(aV(e.baseURL))n=await lI(i,t,lT(i.options));else{n=Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i));let e=i.options;if(!i.options.baseURL){let r=aq(void 0,a,t,void 0,i.options.advanced?.trustedProxyHeaders);if(!r)throw new Y.BetterAuthError("Could not get base URL from request. Please provide a valid base URL.");n.baseURL=r,n.options={...i.options,baseURL:aM(r)||void 0},e=n.options}n.trustedOrigins=await lR(e,t),n.trustedProviders=await lO(e,t)}let{handler:o}=((e,t)=>{let{api:r,middlewares:n}=pR(e,t),i=new URL(e.baseURL).pathname;return((e,t)=>{if(!t?.openapi?.disabled){let r={path:"/api/reference",...t?.openapi};e.openapi=ev(r.path,{method:"GET"},async t=>{let n,i;return new Response((n=await ad(e),i=r.scalar,`<!doctype html>
|
|
431
|
+
<html>
|
|
432
|
+
<head>
|
|
433
|
+
<title>Scalar API Reference</title>
|
|
434
|
+
<meta charset="utf-8" />
|
|
435
|
+
<meta
|
|
436
|
+
name="viewport"
|
|
437
|
+
content="width=device-width, initial-scale=1" />
|
|
438
|
+
</head>
|
|
439
|
+
<body>
|
|
440
|
+
<script
|
|
441
|
+
id="api-reference"
|
|
442
|
+
type="application/json">
|
|
443
|
+
${JSON.stringify(n)}
|
|
444
|
+
</script>
|
|
445
|
+
<script>
|
|
446
|
+
var configuration = {
|
|
447
|
+
favicon: ${i?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(i.logo)}`:void 0} ,
|
|
448
|
+
theme: ${i?.theme||"saturn"},
|
|
449
|
+
metaData: {
|
|
450
|
+
title: ${i?.title||"Open API Reference"},
|
|
451
|
+
description: ${i?.description||"Better Call Open API"},
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
document.getElementById('api-reference').dataset.configuration =
|
|
455
|
+
JSON.stringify(configuration)
|
|
456
|
+
</script>
|
|
457
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
458
|
+
</body>
|
|
459
|
+
</html>`),{headers:{"Content-Type":"text/html"}})})}let r=ap(),n=ap();for(let t of Object.values(e))if(!(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY))for(let e of Array.isArray(t.options?.method)?t.options.method:[t.options?.method])am(r,e,t.path,t);if(t?.routerMiddleware?.length)for(let{path:e,middleware:r}of t.routerMiddleware)am(n,"*",e,r);let i=t?.basePath&&"/"!==t.basePath?t.basePath.replace(/\/+$/,""):"",a=async e=>{let a,o=new URL(e.url),s=o.pathname;if(i){if(!s.startsWith(`${i}/`))return new Response(null,{status:404,statusText:"Not Found"});a=s.slice(i.length)}else a=s;if(0===a.length||/\/{2,}/.test(a))return new Response(null,{status:404,statusText:"Not Found"});let c=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=e.static[r];if(n&&n.methods){let e=n.methods[t]||n.methods[""];if(void 0!==e)return e[0]}let i=af(r),a=function e(t,r,n,i,a){if(a===i.length){if(r.methods){let e=r.methods[n]||r.methods[""];if(e)return e}if(r.param&&r.param.methods){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}return}let o=i[a];if(r.static){let s=r.static[o];if(s){let r=e(t,s,n,i,a+1);if(r)return r}}if(r.param){let s=e(t,r.param,n,i,a+1);if(s){if(r.param.hasRegexParam){let e=s.find(e=>e.paramsRegexp[a]?.test(o))||s.find(e=>!e.paramsRegexp[a]);return e?[e]:void 0}return s}}if(r.wildcard&&r.wildcard.methods)return r.wildcard.methods[n]||r.wildcard.methods[""]}(e,e.root,t,i,0)?.[0];if(void 0!==a)return{data:a.data,params:a.paramsMap?ah(i,a.paramsMap):void 0}}(r,e.method,a);if(a.endsWith("/")!==c?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:"Not Found"});let l={};o.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let d=c.data;try{let r=d.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:a,method:e.method,headers:e.headers,params:c.params?JSON.parse(JSON.stringify(c.params)):{},request:e,body:d.options.disableBody?void 0:await et(d.options.cloneRequest?e.clone():e,r),query:l,_flag:"router",asResponse:!0,context:t?.routerContext},o=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=af(r);return(function e(t,r,n,i,a,o=[]){let s=i[a];if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];e&&o.push(...e)}if(r.param&&(e(t,r.param,n,i,a+1,o),a===i.length&&r.param.methods)){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;t?.[t?.length-1]?.[2]&&o.push(...e)}}let c=r.static?.[s];if(c&&e(t,c,n,i,a+1,o),a===i.length&&r.methods){let e=r.methods[n]||r.methods[""];e&&o.push(...e)}return o})(e,e.root,t,n,0).map(e=>({data:e.data,params:e.paramsMap?ah(n,e.paramsMap):void 0}))}(n,"*",a);if(o?.length)for(let{data:e,params:t}of o){let r=await e({...i,params:t,asResponse:!1});if(r instanceof Response)return r}return await d(i)}catch(r){if(t?.onError)try{let n=await t.onError(r,e);if(n instanceof Response)return ec(n)}catch(e){if(er(e))return ec(e);throw e}if(t?.throwError)throw r;if(er(r))return ec(r);return console.error("# SERVER_ERROR: ",r),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async e=>{let r=await t?.onRequest?.(e);if(r instanceof Response)return r;let n=ei(r)?r:e,i=await a(n),o=await t?.onResponse?.(i,n);return o instanceof Response?o:i},endpoints:e}})(r,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:"/**",middleware:lN},...n],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],n=lD(t.url,i);if(r.includes(n))return new Response("Not Found",{status:404});let a=t,o=await lG(a,e);if(o)return o;for(let t of e.options.plugins||[])if(t.onRequest){let r=await (0,ln.withSpan)(`onRequest ${t.id}`,{[lt]:"onRequest",[lr]:`plugin:${t.id}`},()=>t.onRequest(a,e));if(r&&"response"in r)return r.response;r&&"request"in r&&(a=r.request)}return a},async onResponse(t,r){for(let r of e.options.plugins||[])if(r.onResponse){let n=await (0,ln.withSpan)(`onResponse ${r.id}`,{[lt]:"onResponse",[lr]:`plugin:${r.id}`,[c7.ATTR_HTTP_RESPONSE_STATUS_CODE]:t.status},()=>r.onResponse(t,e));if(n)return n.response}return t},onError(r){if(ay(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError)return void t.onAPIError.onError(r,e);let n=t.logger?.level,i="error"===n||"warn"===n||"debug"===n?aS.logger:void 0;if(t.logger?.disabled!==!0){if(r&&"object"==typeof r&&"message"in r&&"string"==typeof r.message&&(r.message.includes("no column")||r.message.includes("column")||r.message.includes("relation")||r.message.includes("table")||r.message.includes("does not exist")))return void e.logger?.error(r.message);ay(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),i?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(n,e);return(0,c9.runWithAdapter)(n.adapter,()=>o(t))},api:n,options:e,$context:r,$ERROR_CODES:{...e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),...ck.BASE_ERROR_CODES}}})({database:await pZ(),secret:process.env.BETTER_AUTH_SECRET,baseURL:process.env.BETTER_AUTH_URL,emailAndPassword:{enabled:!0},session:{cookieCache:{enabled:!0,maxAge:300}},advanced:{defaultCookieAttributes:{httpOnly:!0,sameSite:"lax",secure:(0,aE.cookieSecure)()}},trustedOrigins:e=>{let t=e?.headers.get("origin");return t?[t]:[]},plugins:[(t=!1,{id:"next-cookies",version:"1.6.23",hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:aw(async r=>{let n;if(t||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let n=r.findIndex(e=>e.id===t);-1===n||r.slice(n+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${t}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(r.context,"next-cookies"),t=!0),"_flag"in r&&"router"===r._flag)return;try{let{headers:t}=await e.A(19741);n=await t()}catch{return}let i="1"===n.get("RSC"),a=!!n.get("next-action");i&&!a&&await J(!0)})}],after:[{matcher:e=>!0,handler:aw(async t=>{let r=t.context.responseHeaders;if((!("_flag"in t)||"router"!==t._flag)&&r instanceof Headers){let t,n,i=r?.get("set-cookie");if(!i)return;let a=(n=new Map,D(i).forEach(e=>{let[t,...r]=e.split(";").map(e=>e.trim()),[i,...a]=(t||"").split("="),o=z(a.join("="));if(!i)return;let s={value:C(o)};r.forEach(e=>{let[t,...r]=e.split("="),n=r.join("="),i=t.trim().toLowerCase();switch(i){case"max-age":s["max-age"]=n?parseInt(n.trim(),10):void 0;break;case"expires":s.expires=n?new Date(n.trim()):void 0;break;case"domain":s.domain=n?n.trim():void 0;break;case"path":s.path=n?n.trim():void 0;break;case"secure":s.secure=!0;break;case"httponly":s.httponly=!0;break;case"samesite":s.samesite=n?n.trim().toLowerCase():void 0;break;case"partitioned":s.partitioned=!0;break;default:s[i]=!n||n.trim()}}),n.set(i,s)}),n);try{let{cookies:r}=await e.A(19741);t=await r()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}a.forEach((e,r)=>{if(r)try{t.set(r,e.value,{maxAge:e["max-age"],expires:e.expires,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httponly,sameSite:e.samesite,partitioned:e.partitioned})}catch{}});return}})}]}})]},pJ)}async function pQ(e){var t;let r;if("password"!==(0,aE.authMode)())return new Response("auth disabled",{status:404});let{GET:n,POST:i}=(t=await (a??=pG()),{GET:r=async e=>"handler"in t?t.handler(e):t(e),POST:r,PATCH:r,PUT:r,DELETE:r});return"POST"===e.method?i(e):n(e)}e.s(["GET",0,pQ,"POST",0,pQ,"dynamic",0,"force-dynamic","runtime",0,"nodejs"],82924);var pY=e.i(82924);let pX=new y.AppRouteRouteModule({definition:{kind:g.RouteKind.APP_ROUTE,page:"/(auth)/api/auth/[...all]/route",pathname:"/api/auth/[...all]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/apps/hub/app/(auth)/api/auth/[...all]/route.ts",nextConfigOutput:"standalone",userland:pY,...{}}),{workAsyncStorage:p0,workUnitAsyncStorage:p1,serverHooks:p2}=pX;async function p5(e,t,r){r.requestMeta&&(0,b.setRequestMeta)(e,r.requestMeta),pX.isDev&&(0,b.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let n="/(auth)/api/auth/[...all]/route";n=n.replace(/\/index$/,"")||"/";let i=await pX.prepare(e,t,{srcPage:n,multiZoneDraftMode:!1});if(!i)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:a,deploymentId:o,params:s,nextConfig:c,parsedUrl:l,isDraftMode:d,prerenderManifest:u,routerServerContext:p,isOnDemandRevalidate:f,revalidateOnlyGenerated:h,resolvedPathname:m,clientReferenceManifest:y,serverActionsManifest:w}=i,C=(0,v.normalizeAppPath)(n),D=!!(u.dynamicRoutes[C]||u.routes[m]),L=async()=>((null==p?void 0:p.render404)?await p.render404(e,t,l,!1):t.end("This page could not be found"),null);if(D&&!d){let e=!!u.routes[m],t=u.dynamicRoutes[C];if(t&&!1===t.fallback&&!e){if(c.adapterPath)return await L();throw new O.NoFallbackError}}let $=null;!D||pX.isDev||d||($="/index"===($=m)?"/":$);let z=!0===pX.isDev||!D,N=D&&!z;w&&y&&(0,E.setManifestsSingleton)({page:n,clientReferenceManifest:y,serverActionsManifest:w});let j=e.method||"GET",H=(0,A.getTracer)(),B=H.getActiveScopeSpan(),q=!!(null==p?void 0:p.isWrappedByNextServer),M=!!(0,b.getRequestMeta)(e,"minimalMode"),V=(0,b.getRequestMeta)(e,"incrementalCache")||await pX.getIncrementalCache(e,c,u,M);null==V||V.resetRequestCache(),globalThis.__incrementalCache=V;let K={params:s,previewProps:u.preview,renderOpts:{experimental:{authInterrupts:!!c.experimental.authInterrupts},cacheComponents:!!c.cacheComponents,supportsDynamicResponse:z,incrementalCache:V,cacheLifeProfiles:c.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,n,i)=>pX.onRequestError(e,t,n,i,p)},sharedContext:{buildId:a,deploymentId:o}},W=new k.NodeNextRequest(e),F=new k.NodeNextResponse(t),J=_.NextRequestAdapter.fromNodeNextRequest(W,(0,_.signalFromNodeResponse)(t));try{let i,a=async e=>pX.handle(J,K).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=H.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==S.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${j} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),i&&i!==e&&(i.setAttribute("http.route",a),i.updateName(t))}else e.updateName(`${j} ${n}`)}),o=async i=>{var o,s;let l=async({previousCacheEntry:o})=>{try{if(!M&&f&&h&&!o)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await a(i);e.fetchMetrics=K.renderOpts.fetchMetrics;let s=K.renderOpts.pendingWaitUntil;s&&r.waitUntil&&(r.waitUntil(s),s=void 0);let c=K.renderOpts.collectedTags;if(!D)return await (0,R.sendResponse)(W,F,n,K.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,T.toNodeOutgoingHttpHeaders)(n.headers);c&&(t[U.NEXT_CACHE_TAGS_HEADER]=c),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==K.renderOpts.collectedRevalidate&&!(K.renderOpts.collectedRevalidate>=U.INFINITE_CACHE)&&K.renderOpts.collectedRevalidate,i=void 0===K.renderOpts.collectedExpire||K.renderOpts.collectedExpire>=U.INFINITE_CACHE?void 0:K.renderOpts.collectedExpire;return{value:{kind:P.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:i}}}}catch(t){throw(null==o?void 0:o.isStale)&&await pX.onRequestError(e,t,{routerKind:"App Router",routePath:n,routeType:"route",revalidateReason:(0,x.getRevalidateReason)({isStaticGeneration:N,isOnDemandRevalidate:f})},!1,p),t}},m=await pX.handleResponse({req:e,nextConfig:c,cacheKey:$,routeKind:g.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:u,isRoutePPREnabled:!1,isOnDemandRevalidate:f,revalidateOnlyGenerated:h,responseGenerator:l,waitUntil:r.waitUntil,isMinimalMode:M});if(!D)return null;if((null==m||null==(o=m.value)?void 0:o.kind)!==P.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==m||null==(s=m.value)?void 0:s.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});M||t.setHeader("x-nextjs-cache",f?"REVALIDATED":m.isMiss?"MISS":m.isStale?"STALE":"HIT"),d&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let y=(0,T.fromNodeOutgoingHttpHeaders)(m.value.headers);return M&&D||y.delete(U.NEXT_CACHE_TAGS_HEADER),!m.cacheControl||t.getHeader("Cache-Control")||y.get("Cache-Control")||y.set("Cache-Control",(0,I.getCacheControlHeader)(m.cacheControl)),await (0,R.sendResponse)(W,F,new Response(m.value.body,{headers:y,status:m.value.status||200})),null};q&&B?await o(B):(i=H.getActiveScopeSpan(),await H.withPropagatedContext(e.headers,()=>H.trace(S.BaseServerSpan.handleRequest,{spanName:`${j} ${n}`,kind:A.SpanKind.SERVER,attributes:{"http.method":j,"http.target":e.url}},o),void 0,!q))}catch(t){if(t instanceof O.NoFallbackError||await pX.onRequestError(e,t,{routerKind:"App Router",routePath:C,routeType:"route",revalidateReason:(0,x.getRevalidateReason)({isStaticGeneration:N,isOnDemandRevalidate:f})},!1,p),D)throw t;return await (0,R.sendResponse)(W,F,new Response(null,{status:500})),null}}e.s(["handler",0,p5,"patchFetch",0,function(){return(0,w.patchFetch)({workAsyncStorage:p0,workUnitAsyncStorage:p1})},"routeModule",0,pX,"serverHooks",0,p2,"workAsyncStorage",0,p0,"workUnitAsyncStorage",0,p1],44733)}];
|
|
460
|
+
|
|
461
|
+
//# sourceMappingURL=%5Broot-of-the-server%5D__1-9g0ae._.js.map
|