constella 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -0
- package/.next/app-path-routes-manifest.json +53 -0
- package/.next/build-manifest.json +20 -0
- package/.next/diagnostics/build-diagnostics.json +6 -0
- package/.next/diagnostics/framework.json +1 -0
- package/.next/export-marker.json +6 -0
- package/.next/images-manifest.json +68 -0
- package/.next/next-minimal-server.js.nft.json +1 -0
- package/.next/next-server.js.nft.json +1 -0
- package/.next/package.json +1 -0
- package/.next/prerender-manifest.json +36 -0
- package/.next/react-loadable-manifest.json +14 -0
- package/.next/required-server-files.js +343 -0
- package/.next/required-server-files.json +343 -0
- package/.next/routes-manifest.json +362 -0
- package/.next/server/app/(app)/activity/page.js +2 -0
- package/.next/server/app/(app)/activity/page.js.nft.json +1 -0
- package/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/agents/[handle]/page.js +18 -0
- package/.next/server/app/(app)/agents/[handle]/page.js.nft.json +1 -0
- package/.next/server/app/(app)/agents/[handle]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/code/page.js +2 -0
- package/.next/server/app/(app)/code/page.js.nft.json +1 -0
- package/.next/server/app/(app)/code/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/config/page.js +2 -0
- package/.next/server/app/(app)/config/page.js.nft.json +1 -0
- package/.next/server/app/(app)/config/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/costs/page.js +2 -0
- package/.next/server/app/(app)/costs/page.js.nft.json +1 -0
- package/.next/server/app/(app)/costs/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/cron/page.js +2 -0
- package/.next/server/app/(app)/cron/page.js.nft.json +1 -0
- package/.next/server/app/(app)/cron/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/dashboard/page.js +2 -0
- package/.next/server/app/(app)/dashboard/page.js.nft.json +1 -0
- package/.next/server/app/(app)/dashboard/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/docs/[id]/page.js +2 -0
- package/.next/server/app/(app)/docs/[id]/page.js.nft.json +1 -0
- package/.next/server/app/(app)/docs/[id]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/docs/page.js +2 -0
- package/.next/server/app/(app)/docs/page.js.nft.json +1 -0
- package/.next/server/app/(app)/docs/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/github/page.js +2 -0
- package/.next/server/app/(app)/github/page.js.nft.json +1 -0
- package/.next/server/app/(app)/github/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/goals/page.js +2 -0
- package/.next/server/app/(app)/goals/page.js.nft.json +1 -0
- package/.next/server/app/(app)/goals/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/inbox/page.js +2 -0
- package/.next/server/app/(app)/inbox/page.js.nft.json +1 -0
- package/.next/server/app/(app)/inbox/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/knowledge/page.js +3 -0
- package/.next/server/app/(app)/knowledge/page.js.nft.json +1 -0
- package/.next/server/app/(app)/knowledge/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/models/page.js +2 -0
- package/.next/server/app/(app)/models/page.js.nft.json +1 -0
- package/.next/server/app/(app)/models/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/notifications/page.js +2 -0
- package/.next/server/app/(app)/notifications/page.js.nft.json +1 -0
- package/.next/server/app/(app)/notifications/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/org/page.js +2 -0
- package/.next/server/app/(app)/org/page.js.nft.json +1 -0
- package/.next/server/app/(app)/org/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/organizations/page.js +2 -0
- package/.next/server/app/(app)/organizations/page.js.nft.json +1 -0
- package/.next/server/app/(app)/organizations/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/page.js +3 -0
- package/.next/server/app/(app)/page.js.nft.json +1 -0
- package/.next/server/app/(app)/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/planner/page.js +2 -0
- package/.next/server/app/(app)/planner/page.js.nft.json +1 -0
- package/.next/server/app/(app)/planner/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/plugins/page.js +2 -0
- package/.next/server/app/(app)/plugins/page.js.nft.json +1 -0
- package/.next/server/app/(app)/plugins/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/pm/page.js +2 -0
- package/.next/server/app/(app)/pm/page.js.nft.json +1 -0
- package/.next/server/app/(app)/pm/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/prepare-deploy/page.js +19 -0
- package/.next/server/app/(app)/prepare-deploy/page.js.nft.json +1 -0
- package/.next/server/app/(app)/prepare-deploy/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/profile/page.js +2 -0
- package/.next/server/app/(app)/profile/page.js.nft.json +1 -0
- package/.next/server/app/(app)/profile/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/pulse/page.js +2 -0
- package/.next/server/app/(app)/pulse/page.js.nft.json +1 -0
- package/.next/server/app/(app)/pulse/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/reports/[id]/page.js +3 -0
- package/.next/server/app/(app)/reports/[id]/page.js.nft.json +1 -0
- package/.next/server/app/(app)/reports/[id]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/reports/page.js +5 -0
- package/.next/server/app/(app)/reports/page.js.nft.json +1 -0
- package/.next/server/app/(app)/reports/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/routines/page.js +2 -0
- package/.next/server/app/(app)/routines/page.js.nft.json +1 -0
- package/.next/server/app/(app)/routines/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/search/page.js +2 -0
- package/.next/server/app/(app)/search/page.js.nft.json +1 -0
- package/.next/server/app/(app)/search/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/security/page.js +2 -0
- package/.next/server/app/(app)/security/page.js.nft.json +1 -0
- package/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/skills/page.js +18 -0
- package/.next/server/app/(app)/skills/page.js.nft.json +1 -0
- package/.next/server/app/(app)/skills/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/tasks/page.js +2 -0
- package/.next/server/app/(app)/tasks/page.js.nft.json +1 -0
- package/.next/server/app/(app)/tasks/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/test-dev/page.js +2 -0
- package/.next/server/app/(app)/test-dev/page.js.nft.json +1 -0
- package/.next/server/app/(app)/test-dev/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(app)/update/page.js +2 -0
- package/.next/server/app/(app)/update/page.js.nft.json +1 -0
- package/.next/server/app/(app)/update/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(auth)/login/page.js +2 -0
- package/.next/server/app/(auth)/login/page.js.nft.json +1 -0
- package/.next/server/app/(auth)/login/page_client-reference-manifest.js +1 -0
- package/.next/server/app/(auth)/onboarding/page.js +18 -0
- package/.next/server/app/(auth)/onboarding/page.js.nft.json +1 -0
- package/.next/server/app/(auth)/onboarding/page_client-reference-manifest.js +1 -0
- package/.next/server/app/_global-error/page.js +32 -0
- package/.next/server/app/_global-error/page.js.nft.json +1 -0
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -0
- package/.next/server/app/_global-error.html +1 -0
- package/.next/server/app/_global-error.meta +16 -0
- package/.next/server/app/_global-error.rsc +15 -0
- package/.next/server/app/_global-error.segments/_full.segment.rsc +15 -0
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +5 -0
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +5 -0
- package/.next/server/app/_global-error.segments/_head.segment.rsc +5 -0
- package/.next/server/app/_global-error.segments/_index.segment.rsc +6 -0
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
- package/.next/server/app/_not-found/page.js +2 -0
- package/.next/server/app/_not-found/page.js.nft.json +1 -0
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
- package/.next/server/app/api/auth/[...all]/route.js +1 -0
- package/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -0
- package/.next/server/app/api/auth/[...all]/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/cron/tick/route.js +52 -0
- package/.next/server/app/api/cron/tick/route.js.nft.json +1 -0
- package/.next/server/app/api/cron/tick/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/dev-login/route.js +1 -0
- package/.next/server/app/api/dev-login/route.js.nft.json +1 -0
- package/.next/server/app/api/dev-login/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/locks/acquire/route.js +1 -0
- package/.next/server/app/api/locks/acquire/route.js.nft.json +1 -0
- package/.next/server/app/api/locks/acquire/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/models/progress/route.js +1 -0
- package/.next/server/app/api/models/progress/route.js.nft.json +1 -0
- package/.next/server/app/api/models/progress/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/passkey/authenticate/options/route.js +1 -0
- package/.next/server/app/api/passkey/authenticate/options/route.js.nft.json +1 -0
- package/.next/server/app/api/passkey/authenticate/options/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/passkey/authenticate/verify/route.js +1 -0
- package/.next/server/app/api/passkey/authenticate/verify/route.js.nft.json +1 -0
- package/.next/server/app/api/passkey/authenticate/verify/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/passkey/register/options/route.js +1 -0
- package/.next/server/app/api/passkey/register/options/route.js.nft.json +1 -0
- package/.next/server/app/api/passkey/register/options/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/passkey/register/verify/route.js +1 -0
- package/.next/server/app/api/passkey/register/verify/route.js.nft.json +1 -0
- package/.next/server/app/api/passkey/register/verify/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/stream/route.js +4 -0
- package/.next/server/app/api/stream/route.js.nft.json +1 -0
- package/.next/server/app/api/stream/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/sync/file/route.js +2 -0
- package/.next/server/app/api/sync/file/route.js.nft.json +1 -0
- package/.next/server/app/api/sync/file/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/telegram/poll/route.js +15 -0
- package/.next/server/app/api/telegram/poll/route.js.nft.json +1 -0
- package/.next/server/app/api/telegram/poll/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/upload/route.js +1 -0
- package/.next/server/app/api/upload/route.js.nft.json +1 -0
- package/.next/server/app/api/upload/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/v1/[[...path]]/route.js +1 -0
- package/.next/server/app/api/v1/[[...path]]/route.js.nft.json +1 -0
- package/.next/server/app/api/v1/[[...path]]/route_client-reference-manifest.js +1 -0
- package/.next/server/app-paths-manifest.json +53 -0
- package/.next/server/chunks/1003.js +1 -0
- package/.next/server/chunks/127.js +26 -0
- package/.next/server/chunks/1388.js +1 -0
- package/.next/server/chunks/1408.js +21 -0
- package/.next/server/chunks/1572.js +1 -0
- package/.next/server/chunks/1591.js +24 -0
- package/.next/server/chunks/1619.js +188 -0
- package/.next/server/chunks/162.js +1 -0
- package/.next/server/chunks/1881.js +1 -0
- package/.next/server/chunks/1968.js +1 -0
- package/.next/server/chunks/2297.js +348 -0
- package/.next/server/chunks/2341.js +1 -0
- package/.next/server/chunks/2517.js +1 -0
- package/.next/server/chunks/2549.js +1 -0
- package/.next/server/chunks/259.js +14 -0
- package/.next/server/chunks/2599.js +1 -0
- package/.next/server/chunks/260.js +1 -0
- package/.next/server/chunks/2867.js +147 -0
- package/.next/server/chunks/3018.js +1 -0
- package/.next/server/chunks/3050.js +18 -0
- package/.next/server/chunks/3085.js +12 -0
- package/.next/server/chunks/3131.js +1 -0
- package/.next/server/chunks/3242.js +1 -0
- package/.next/server/chunks/3266.js +15 -0
- package/.next/server/chunks/3524.js +1 -0
- package/.next/server/chunks/3527.js +479 -0
- package/.next/server/chunks/3533.js +869 -0
- package/.next/server/chunks/3550.js +1 -0
- package/.next/server/chunks/3609.js +2 -0
- package/.next/server/chunks/3667.js +462 -0
- package/.next/server/chunks/3760.js +4 -0
- package/.next/server/chunks/4679.js +1 -0
- package/.next/server/chunks/4804.js +1 -0
- package/.next/server/chunks/4832.js +2 -0
- package/.next/server/chunks/4853.js +1 -0
- package/.next/server/chunks/4979.js +67 -0
- package/.next/server/chunks/5060.js +1 -0
- package/.next/server/chunks/5278.js +1 -0
- package/.next/server/chunks/5614.js +1 -0
- package/.next/server/chunks/5818.js +1 -0
- package/.next/server/chunks/6479.js +1 -0
- package/.next/server/chunks/6658.js +1 -0
- package/.next/server/chunks/6706.js +1 -0
- package/.next/server/chunks/6719.js +1 -0
- package/.next/server/chunks/678.js +1 -0
- package/.next/server/chunks/683.js +1 -0
- package/.next/server/chunks/6862.js +1 -0
- package/.next/server/chunks/6882.js +1 -0
- package/.next/server/chunks/7037.js +1 -0
- package/.next/server/chunks/7107.js +741 -0
- package/.next/server/chunks/73.js +17 -0
- package/.next/server/chunks/7327.js +1 -0
- package/.next/server/chunks/7514.js +1 -0
- package/.next/server/chunks/7622.js +1 -0
- package/.next/server/chunks/7778.js +1 -0
- package/.next/server/chunks/7912.js +1 -0
- package/.next/server/chunks/7949.js +1 -0
- package/.next/server/chunks/7971.js +1 -0
- package/.next/server/chunks/7989.js +1 -0
- package/.next/server/chunks/842.js +22 -0
- package/.next/server/chunks/8762.js +15 -0
- package/.next/server/chunks/8823.js +77 -0
- package/.next/server/chunks/9146.js +4 -0
- package/.next/server/chunks/9676.js +1 -0
- package/.next/server/chunks/9783.js +22 -0
- package/.next/server/chunks/9969.js +3 -0
- package/.next/server/functions-config-manifest.json +18 -0
- package/.next/server/instrumentation.js +1 -0
- package/.next/server/instrumentation.js.nft.json +1 -0
- package/.next/server/interception-route-rewrite-manifest.js +1 -0
- package/.next/server/middleware-build-manifest.js +1 -0
- package/.next/server/middleware-manifest.json +6 -0
- package/.next/server/middleware-react-loadable-manifest.js +1 -0
- package/.next/server/middleware.js +18 -0
- package/.next/server/middleware.js.nft.json +1 -0
- package/.next/server/next-font-manifest.js +1 -0
- package/.next/server/next-font-manifest.json +1 -0
- package/.next/server/pages/500.html +1 -0
- package/.next/server/pages-manifest.json +3 -0
- package/.next/server/prefetch-hints.json +1 -0
- package/.next/server/server-reference-manifest.js +1 -0
- package/.next/server/server-reference-manifest.json +1 -0
- package/.next/server/webpack-runtime.js +1 -0
- package/.next/static/chunks/1858-339516f78a4b00da.js +1 -0
- package/.next/static/chunks/2320-fc8b39380e69d465.js +2 -0
- package/.next/static/chunks/23550918-ff694f70f4b0648c.js +1 -0
- package/.next/static/chunks/3219-ebb3c23be38c838d.js +1 -0
- package/.next/static/chunks/4263-adecb5b466380b6e.js +1 -0
- package/.next/static/chunks/5479-0cceab68cd0ca9c7.js +1 -0
- package/.next/static/chunks/5701-665b927b06158b76.js +1 -0
- package/.next/static/chunks/5920.6451a68b63918988.js +1 -0
- package/.next/static/chunks/6575-5c9139720bb0f5bf.js +4 -0
- package/.next/static/chunks/6834-4759af1ce7d95fb6.js +32 -0
- package/.next/static/chunks/7509.721cd47a931c5518.js +1 -0
- package/.next/static/chunks/8264-1ca011989ee2b231.js +1 -0
- package/.next/static/chunks/9219-4a39a98b5502d9d1.js +1 -0
- package/.next/static/chunks/9690-53d5222618cbeddb.js +1 -0
- package/.next/static/chunks/app/(app)/activity/page-3973534281ecea81.js +1 -0
- package/.next/static/chunks/app/(app)/agents/[handle]/page-83662a175c098282.js +1 -0
- package/.next/static/chunks/app/(app)/code/page-33979545192cd137.js +1 -0
- package/.next/static/chunks/app/(app)/config/page-9933aed1ca8a85c1.js +1 -0
- package/.next/static/chunks/app/(app)/costs/page-131c4dc580efcc19.js +1 -0
- package/.next/static/chunks/app/(app)/cron/page-53ea1aff998a87ca.js +1 -0
- package/.next/static/chunks/app/(app)/dashboard/page-deed83aaa9d0d447.js +1 -0
- package/.next/static/chunks/app/(app)/docs/[id]/page-38c993d73c0eab4f.js +1 -0
- package/.next/static/chunks/app/(app)/docs/page-bf463b55d0554e86.js +1 -0
- package/.next/static/chunks/app/(app)/error-988cd28480809861.js +1 -0
- package/.next/static/chunks/app/(app)/github/page-62678b4e82dfecb6.js +1 -0
- package/.next/static/chunks/app/(app)/goals/page-4adb426fe1c96106.js +1 -0
- package/.next/static/chunks/app/(app)/inbox/page-e347dc55ab467310.js +1 -0
- package/.next/static/chunks/app/(app)/knowledge/page-65393a045b4349be.js +1 -0
- package/.next/static/chunks/app/(app)/layout-7f65675705b011d8.js +1 -0
- package/.next/static/chunks/app/(app)/models/page-e01f1dd7e49a2951.js +1 -0
- package/.next/static/chunks/app/(app)/notifications/page-56548ac87aef00da.js +1 -0
- package/.next/static/chunks/app/(app)/org/page-699e6a6dc0db7d81.js +1 -0
- package/.next/static/chunks/app/(app)/organizations/page-36051a380a7e8eb7.js +1 -0
- package/.next/static/chunks/app/(app)/page-7d1011a566f81520.js +1 -0
- package/.next/static/chunks/app/(app)/planner/page-dab7ced94083373a.js +1 -0
- package/.next/static/chunks/app/(app)/plugins/page-5b5a1f53389be42e.js +1 -0
- package/.next/static/chunks/app/(app)/pm/page-0de5c08c0b227bb0.js +1 -0
- package/.next/static/chunks/app/(app)/prepare-deploy/page-e426038552df8d41.js +1 -0
- package/.next/static/chunks/app/(app)/profile/page-608dfcaf8aae0a69.js +1 -0
- package/.next/static/chunks/app/(app)/pulse/page-309ccaca91de1faa.js +1 -0
- package/.next/static/chunks/app/(app)/reports/[id]/page-53ea1aff998a87ca.js +1 -0
- package/.next/static/chunks/app/(app)/reports/page-68cdc6dcfa472d86.js +1 -0
- package/.next/static/chunks/app/(app)/routines/page-bcc55550b197a9fa.js +1 -0
- package/.next/static/chunks/app/(app)/search/page-5c5f67558d0dbf0d.js +1 -0
- package/.next/static/chunks/app/(app)/security/page-a7d41e36aa366b45.js +1 -0
- package/.next/static/chunks/app/(app)/skills/page-c5b21e89593b8336.js +1 -0
- package/.next/static/chunks/app/(app)/tasks/page-08ae079e3e54d2ce.js +1 -0
- package/.next/static/chunks/app/(app)/test-dev/page-633f82dfd9c3ce23.js +1 -0
- package/.next/static/chunks/app/(app)/update/page-4be019054351bfac.js +1 -0
- package/.next/static/chunks/app/(auth)/login/page-6e85d3377062acae.js +1 -0
- package/.next/static/chunks/app/(auth)/onboarding/page-ebb10c175abf3b85.js +1 -0
- package/.next/static/chunks/app/_global-error/page-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/_not-found/page-dc38b02aebeab535.js +1 -0
- package/.next/static/chunks/app/api/auth/[...all]/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/cron/tick/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/dev-login/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/locks/acquire/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/models/progress/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/passkey/authenticate/options/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/passkey/authenticate/verify/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/passkey/register/options/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/passkey/register/verify/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/stream/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/sync/file/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/telegram/poll/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/upload/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/api/v1/[[...path]]/route-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/app/error-09899a13c38b6e89.js +1 -0
- package/.next/static/chunks/app/global-error-b8050d4d886f448c.js +1 -0
- package/.next/static/chunks/app/layout-ab9deed1e7e2e9df.js +1 -0
- package/.next/static/chunks/framework-4b2c6b6043dd203f.js +1 -0
- package/.next/static/chunks/main-722e16032e7764d1.js +5 -0
- package/.next/static/chunks/main-app-761880af2b6f1962.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-23fe50a6bf589c97.js +1 -0
- package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
- package/.next/static/chunks/webpack-222e3894b78c67db.js +1 -0
- package/.next/static/css/0a9b5805594444e3.css +1 -0
- package/.next/static/yztMvBwyrWWkSqP6jfXoa/_buildManifest.js +1 -0
- package/.next/static/yztMvBwyrWWkSqP6jfXoa/_ssgManifest.js +1 -0
- package/.next/trace-build +1 -0
- package/.next/types/app/(app)/activity/page.ts +87 -0
- package/.next/types/app/(app)/agents/[handle]/page.ts +87 -0
- package/.next/types/app/(app)/code/page.ts +87 -0
- package/.next/types/app/(app)/config/page.ts +87 -0
- package/.next/types/app/(app)/costs/page.ts +87 -0
- package/.next/types/app/(app)/cron/page.ts +87 -0
- package/.next/types/app/(app)/dashboard/page.ts +87 -0
- package/.next/types/app/(app)/docs/[id]/page.ts +87 -0
- package/.next/types/app/(app)/docs/page.ts +87 -0
- package/.next/types/app/(app)/github/page.ts +87 -0
- package/.next/types/app/(app)/goals/page.ts +87 -0
- package/.next/types/app/(app)/inbox/page.ts +87 -0
- package/.next/types/app/(app)/knowledge/page.ts +87 -0
- package/.next/types/app/(app)/models/page.ts +87 -0
- package/.next/types/app/(app)/notifications/page.ts +87 -0
- package/.next/types/app/(app)/org/page.ts +87 -0
- package/.next/types/app/(app)/organizations/page.ts +87 -0
- package/.next/types/app/(app)/page.ts +87 -0
- package/.next/types/app/(app)/planner/page.ts +87 -0
- package/.next/types/app/(app)/plugins/page.ts +87 -0
- package/.next/types/app/(app)/pm/page.ts +87 -0
- package/.next/types/app/(app)/prepare-deploy/page.ts +87 -0
- package/.next/types/app/(app)/profile/page.ts +87 -0
- package/.next/types/app/(app)/pulse/page.ts +87 -0
- package/.next/types/app/(app)/reports/[id]/page.ts +87 -0
- package/.next/types/app/(app)/reports/page.ts +87 -0
- package/.next/types/app/(app)/routines/page.ts +87 -0
- package/.next/types/app/(app)/search/page.ts +87 -0
- package/.next/types/app/(app)/security/page.ts +87 -0
- package/.next/types/app/(app)/skills/page.ts +87 -0
- package/.next/types/app/(app)/tasks/page.ts +87 -0
- package/.next/types/app/(app)/test-dev/page.ts +87 -0
- package/.next/types/app/(app)/update/page.ts +87 -0
- package/.next/types/app/(auth)/login/page.ts +87 -0
- package/.next/types/app/(auth)/onboarding/page.ts +87 -0
- package/.next/types/app/api/auth/[...all]/route.ts +351 -0
- package/.next/types/app/api/cron/tick/route.ts +351 -0
- package/.next/types/app/api/dev-login/route.ts +351 -0
- package/.next/types/app/api/locks/acquire/route.ts +351 -0
- package/.next/types/app/api/models/progress/route.ts +351 -0
- package/.next/types/app/api/passkey/authenticate/options/route.ts +351 -0
- package/.next/types/app/api/passkey/authenticate/verify/route.ts +351 -0
- package/.next/types/app/api/passkey/register/options/route.ts +351 -0
- package/.next/types/app/api/passkey/register/verify/route.ts +351 -0
- package/.next/types/app/api/stream/route.ts +351 -0
- package/.next/types/app/api/sync/file/route.ts +351 -0
- package/.next/types/app/api/telegram/poll/route.ts +351 -0
- package/.next/types/app/api/upload/route.ts +351 -0
- package/.next/types/app/api/v1/[[...path]]/route.ts +351 -0
- package/.next/types/cache-life.d.ts +145 -0
- package/.next/types/link.d.ts +210 -0
- package/.next/types/package.json +1 -0
- package/.next/types/routes.d.ts +120 -0
- package/.next/types/validator.ts +511 -0
- package/CHANGELOG.md +312 -0
- package/LICENSE +21 -0
- package/README.md +382 -0
- package/README.pt-BR.md +391 -0
- package/bin/constella.mjs +329 -0
- package/bin/guard-hook.mjs +44 -0
- package/bin/lock-hook.mjs +49 -0
- package/bin/worker.mjs +142 -0
- package/docs/assets/arch-orbit.svg +56 -0
- package/docs/assets/blackhole.svg +37 -0
- package/docs/assets/divider-orbit.svg +23 -0
- package/docs/assets/hero-constella.svg +72 -0
- package/docs/en/AGENTS.md +279 -0
- package/docs/en/AI_ARCHITECTURE.md +373 -0
- package/docs/en/ARCHITECTURE.md +334 -0
- package/docs/en/AUTH_MODE.md +247 -0
- package/docs/en/CHAT_COMMANDS.md +305 -0
- package/docs/en/CONFIGURATION.md +340 -0
- package/docs/en/DEPLOY.md +331 -0
- package/docs/en/DM.md +297 -0
- package/docs/en/FAQ.md +258 -0
- package/docs/en/GITHUB.md +341 -0
- package/docs/en/GOALS_SPECS_ISSUES.md +303 -0
- package/docs/en/INBOX.md +340 -0
- package/docs/en/INSTALLATION.md +329 -0
- package/docs/en/KB_AGENT.md +305 -0
- package/docs/en/KB_RAG.md +356 -0
- package/docs/en/MCP.md +313 -0
- package/docs/en/MEMORY_RAG.md +289 -0
- package/docs/en/MODELS.md +341 -0
- package/docs/en/ONBOARDING.md +327 -0
- package/docs/en/PLUGINS.md +290 -0
- package/docs/en/PORTABLE_MODE.md +387 -0
- package/docs/en/PO_AGENT.md +379 -0
- package/docs/en/PREPARE_DEPLOY.md +308 -0
- package/docs/en/PROJECT_STACKS.md +258 -0
- package/docs/en/PUBLIC_API.md +315 -0
- package/docs/en/PUBLISHING.md +343 -0
- package/docs/en/README.md +95 -0
- package/docs/en/SECURITY.md +280 -0
- package/docs/en/SKILLS.md +349 -0
- package/docs/en/START_MODE.md +340 -0
- package/docs/en/SYNCED_BLOCKS.md +320 -0
- package/docs/en/TEAM_ROOM.md +285 -0
- package/docs/en/TELEGRAM.md +294 -0
- package/docs/en/TEST_DEV.md +321 -0
- package/docs/en/TROUBLESHOOTING.md +294 -0
- package/docs/en/UPDATE.md +301 -0
- package/docs/en/VPS_MODE.md +334 -0
- package/docs/en/WORKFLOW.md +321 -0
- package/docs/pt/AGENTS.md +279 -0
- package/docs/pt/AI_ARCHITECTURE.md +373 -0
- package/docs/pt/ARCHITECTURE.md +334 -0
- package/docs/pt/AUTH_MODE.md +247 -0
- package/docs/pt/CHAT_COMMANDS.md +307 -0
- package/docs/pt/CONFIGURATION.md +340 -0
- package/docs/pt/DEPLOY.md +331 -0
- package/docs/pt/DM.md +297 -0
- package/docs/pt/FAQ.md +258 -0
- package/docs/pt/GITHUB.md +341 -0
- package/docs/pt/GOALS_SPECS_ISSUES.md +303 -0
- package/docs/pt/INBOX.md +340 -0
- package/docs/pt/INSTALLATION.md +329 -0
- package/docs/pt/KB_AGENT.md +305 -0
- package/docs/pt/KB_RAG.md +356 -0
- package/docs/pt/MCP.md +313 -0
- package/docs/pt/MEMORY_RAG.md +289 -0
- package/docs/pt/MODELS.md +341 -0
- package/docs/pt/ONBOARDING.md +327 -0
- package/docs/pt/PLUGINS.md +290 -0
- package/docs/pt/PORTABLE_MODE.md +387 -0
- package/docs/pt/PO_AGENT.md +379 -0
- package/docs/pt/PREPARE_DEPLOY.md +308 -0
- package/docs/pt/PROJECT_STACKS.md +258 -0
- package/docs/pt/PUBLIC_API.md +315 -0
- package/docs/pt/PUBLISHING.md +343 -0
- package/docs/pt/README.md +95 -0
- package/docs/pt/SECURITY.md +280 -0
- package/docs/pt/SKILLS.md +349 -0
- package/docs/pt/START_MODE.md +340 -0
- package/docs/pt/SYNCED_BLOCKS.md +320 -0
- package/docs/pt/TEAM_ROOM.md +285 -0
- package/docs/pt/TELEGRAM.md +294 -0
- package/docs/pt/TEST_DEV.md +321 -0
- package/docs/pt/TROUBLESHOOTING.md +294 -0
- package/docs/pt/UPDATE.md +301 -0
- package/docs/pt/VPS_MODE.md +334 -0
- package/docs/pt/WORKFLOW.md +321 -0
- package/drizzle/0000_regular_nightshade.sql +644 -0
- package/drizzle/0001_mixed_zombie.sql +106 -0
- package/drizzle/meta/0000_snapshot.json +4650 -0
- package/drizzle/meta/0001_snapshot.json +5418 -0
- package/drizzle/meta/_journal.json +20 -0
- package/drizzle.config.mjs +16 -0
- package/next.config.mjs +18 -0
- package/package.json +130 -0
- package/scripts/clean-repo.mjs +20 -0
- package/scripts/dev-all.mjs +46 -0
- package/scripts/i18n-parity.mjs +57 -0
- package/scripts/mcp-server.mjs +100 -0
- package/scripts/postbuild.mjs +11 -0
- package/scripts/publish-public.mjs +116 -0
- package/scripts/start-all.mjs +45 -0
- package/scripts/trim-next.mjs +23 -0
- package/scripts/vps-install.sh +39 -0
- package/skills/CONTRIBUTING.md +122 -0
- package/skills/COVERAGE.md +129 -0
- package/skills/INDEX.json +3443 -0
- package/skills/README.md +57 -0
- package/skills/design/animation-motion/SKILL.md +60 -0
- package/skills/design/color-and-typography/SKILL.md +60 -0
- package/skills/design/css-techniques/SKILL.md +58 -0
- package/skills/design/design-systems/SKILL.md +60 -0
- package/skills/design/gradients/SKILL.md +59 -0
- package/skills/design/graphic-design-basics/SKILL.md +55 -0
- package/skills/design/microinteractions/SKILL.md +58 -0
- package/skills/design/responsive-layout/SKILL.md +59 -0
- package/skills/design/ui-ux-principles/SKILL.md +58 -0
- package/skills/engineering/architecture/api-design-rest-graphql/SKILL.md +67 -0
- package/skills/engineering/architecture/caching-strategies/SKILL.md +59 -0
- package/skills/engineering/architecture/data-modeling/SKILL.md +64 -0
- package/skills/engineering/architecture/message-queues-async/SKILL.md +58 -0
- package/skills/engineering/architecture/scalability-reliability/SKILL.md +62 -0
- package/skills/engineering/architecture/software-architecture-patterns/SKILL.md +56 -0
- package/skills/engineering/architecture/system-design-fundamentals/SKILL.md +56 -0
- package/skills/engineering/backend/auth-and-authorization/SKILL.md +62 -0
- package/skills/engineering/backend/backend-fundamentals/SKILL.md +65 -0
- package/skills/engineering/backend/observability-logging/SKILL.md +60 -0
- package/skills/engineering/frontend/accessibility-wcag/SKILL.md +57 -0
- package/skills/engineering/frontend/frontend-architecture/SKILL.md +65 -0
- package/skills/engineering/frontend/rendering-strategies-ssr-csr/SKILL.md +60 -0
- package/skills/engineering/frontend/state-management/SKILL.md +69 -0
- package/skills/engineering/performance/backend-performance/SKILL.md +69 -0
- package/skills/engineering/performance/database-query-optimization/SKILL.md +64 -0
- package/skills/engineering/performance/profiling-and-benchmarking/SKILL.md +60 -0
- package/skills/engineering/performance/web-performance-core-vitals/SKILL.md +72 -0
- package/skills/engineering/practices/clean-code/SKILL.md +61 -0
- package/skills/engineering/practices/code-optimization/SKILL.md +60 -0
- package/skills/engineering/practices/code-review-practices/SKILL.md +58 -0
- package/skills/engineering/practices/git-workflow/SKILL.md +62 -0
- package/skills/engineering/practices/refactoring/SKILL.md +58 -0
- package/skills/engineering/security/appsec-fundamentals/SKILL.md +70 -0
- package/skills/engineering/security/dependency-supply-chain/SKILL.md +77 -0
- package/skills/engineering/security/owasp-asvs/SKILL.md +54 -0
- package/skills/engineering/security/owasp-top-10/SKILL.md +63 -0
- package/skills/engineering/security/secrets-management/SKILL.md +58 -0
- package/skills/engineering/security/secure-auth-sessions/SKILL.md +56 -0
- package/skills/engineering/testing/tdd-and-coverage/SKILL.md +62 -0
- package/skills/engineering/testing/testing-strategy-pyramid/SKILL.md +56 -0
- package/skills/engineering/testing/unit-integration-e2e/SKILL.md +75 -0
- package/skills/languages/c/SKILL.md +74 -0
- package/skills/languages/clojure/SKILL.md +73 -0
- package/skills/languages/cpp/SKILL.md +75 -0
- package/skills/languages/csharp/SKILL.md +75 -0
- package/skills/languages/dart/SKILL.md +82 -0
- package/skills/languages/elixir/SKILL.md +74 -0
- package/skills/languages/erlang/SKILL.md +76 -0
- package/skills/languages/go/SKILL.md +83 -0
- package/skills/languages/haskell/SKILL.md +70 -0
- package/skills/languages/java/SKILL.md +71 -0
- package/skills/languages/javascript/SKILL.md +62 -0
- package/skills/languages/kotlin/SKILL.md +68 -0
- package/skills/languages/lua/SKILL.md +79 -0
- package/skills/languages/objectivec/SKILL.md +83 -0
- package/skills/languages/php/SKILL.md +74 -0
- package/skills/languages/python/SKILL.md +68 -0
- package/skills/languages/r/SKILL.md +70 -0
- package/skills/languages/ruby/SKILL.md +67 -0
- package/skills/languages/rust/SKILL.md +72 -0
- package/skills/languages/scala/SKILL.md +73 -0
- package/skills/languages/swift/SKILL.md +73 -0
- package/skills/languages/typescript/SKILL.md +69 -0
- package/skills/meta/authoring-agent-skills/SKILL.md +73 -0
- package/skills/meta/progressive-disclosure/SKILL.md +65 -0
- package/skills/meta/skill-frontmatter-spec/SKILL.md +65 -0
- package/skills/process/adr-technical-decisions/SKILL.md +59 -0
- package/skills/process/app-planning/SKILL.md +63 -0
- package/skills/process/architecture-before-code/SKILL.md +52 -0
- package/skills/process/breaking-work-into-sprints/SKILL.md +53 -0
- package/skills/process/idea-to-product/SKILL.md +50 -0
- package/skills/process/mocks-and-screen-flows/SKILL.md +52 -0
- package/skills/process/prioritization-moscow-rice/SKILL.md +64 -0
- package/skills/process/problem-framing/SKILL.md +51 -0
- package/skills/process/product-discovery/SKILL.md +53 -0
- package/skills/process/readme-generation/SKILL.md +90 -0
- package/skills/process/requirements-to-specs/SKILL.md +53 -0
- package/skills/process/research-official-docs/SKILL.md +58 -0
- package/skills/process/review-code-perf-security/SKILL.md +65 -0
- package/skills/process/security-by-design/SKILL.md +68 -0
- package/skills/process/specs-to-issues/SKILL.md +53 -0
- package/skills/process/testing-before-done/SKILL.md +61 -0
- package/skills/process/validating-ux-navigation/SKILL.md +63 -0
- package/skills/references/ai-attachments-ui/SKILL.md +66 -0
- package/skills/references/ai-in-browser-webllm/SKILL.md +74 -0
- package/skills/references/ai-tool-ui-patterns/SKILL.md +63 -0
- package/skills/references/component-patterns-gallery/SKILL.md +62 -0
- package/skills/references/gradient-resources/SKILL.md +66 -0
- package/skills/references/react-component-libraries/SKILL.md +61 -0
- package/skills/references/saas-landing-patterns/SKILL.md +67 -0
- package/skills/references/shadcn-tailwind-theming/SKILL.md +74 -0
- package/skills/references/vercel-ai-sdk-elements/SKILL.md +66 -0
- package/skills/references/web-animation-codrops/SKILL.md +68 -0
- package/skills/stacks/aiml/jupyter/SKILL.md +68 -0
- package/skills/stacks/aiml/keras/SKILL.md +77 -0
- package/skills/stacks/aiml/numpy/SKILL.md +69 -0
- package/skills/stacks/aiml/pandas/SKILL.md +72 -0
- package/skills/stacks/aiml/pytorch/SKILL.md +77 -0
- package/skills/stacks/aiml/scikit-learn/SKILL.md +74 -0
- package/skills/stacks/aiml/tensorflow/SKILL.md +79 -0
- package/skills/stacks/auth/auth0/SKILL.md +63 -0
- package/skills/stacks/auth/authjs/SKILL.md +69 -0
- package/skills/stacks/auth/clerk/SKILL.md +72 -0
- package/skills/stacks/auth/keycloak/SKILL.md +63 -0
- package/skills/stacks/auth/lucia/SKILL.md +56 -0
- package/skills/stacks/auth/passport/SKILL.md +70 -0
- package/skills/stacks/auth/supabase-auth/SKILL.md +66 -0
- package/skills/stacks/baas/amplify/SKILL.md +71 -0
- package/skills/stacks/baas/appwrite/SKILL.md +79 -0
- package/skills/stacks/baas/firebase/SKILL.md +73 -0
- package/skills/stacks/baas/heroku/SKILL.md +71 -0
- package/skills/stacks/backend/actix/SKILL.md +77 -0
- package/skills/stacks/backend/adonisjs/SKILL.md +65 -0
- package/skills/stacks/backend/aspnet-core/SKILL.md +75 -0
- package/skills/stacks/backend/codeigniter/SKILL.md +76 -0
- package/skills/stacks/backend/django/SKILL.md +62 -0
- package/skills/stacks/backend/express/SKILL.md +65 -0
- package/skills/stacks/backend/fastapi/SKILL.md +64 -0
- package/skills/stacks/backend/fastify/SKILL.md +64 -0
- package/skills/stacks/backend/fiber/SKILL.md +68 -0
- package/skills/stacks/backend/flask/SKILL.md +71 -0
- package/skills/stacks/backend/gin/SKILL.md +68 -0
- package/skills/stacks/backend/graphql/SKILL.md +70 -0
- package/skills/stacks/backend/hono/SKILL.md +64 -0
- package/skills/stacks/backend/koa/SKILL.md +63 -0
- package/skills/stacks/backend/laravel/SKILL.md +73 -0
- package/skills/stacks/backend/nestjs/SKILL.md +70 -0
- package/skills/stacks/backend/nginx/SKILL.md +77 -0
- package/skills/stacks/backend/phoenix/SKILL.md +68 -0
- package/skills/stacks/backend/rails/SKILL.md +67 -0
- package/skills/stacks/backend/spring/SKILL.md +70 -0
- package/skills/stacks/backend/spring-boot/SKILL.md +70 -0
- package/skills/stacks/backend/symfony/SKILL.md +77 -0
- package/skills/stacks/container/containerd/SKILL.md +75 -0
- package/skills/stacks/container/docker/SKILL.md +90 -0
- package/skills/stacks/container/podman/SKILL.md +93 -0
- package/skills/stacks/database/cassandra/SKILL.md +74 -0
- package/skills/stacks/database/cockroachdb/SKILL.md +69 -0
- package/skills/stacks/database/dynamodb/SKILL.md +62 -0
- package/skills/stacks/database/mariadb/SKILL.md +71 -0
- package/skills/stacks/database/mongodb/SKILL.md +71 -0
- package/skills/stacks/database/mysql/SKILL.md +72 -0
- package/skills/stacks/database/neon/SKILL.md +68 -0
- package/skills/stacks/database/planetscale/SKILL.md +70 -0
- package/skills/stacks/database/postgresql/SKILL.md +81 -0
- package/skills/stacks/database/redis/SKILL.md +78 -0
- package/skills/stacks/database/sqlite/SKILL.md +70 -0
- package/skills/stacks/database/supabase/SKILL.md +79 -0
- package/skills/stacks/dataviz/chart-js/SKILL.md +72 -0
- package/skills/stacks/dataviz/d3/SKILL.md +77 -0
- package/skills/stacks/dataviz/grafana/SKILL.md +69 -0
- package/skills/stacks/dataviz/plotly/SKILL.md +71 -0
- package/skills/stacks/frontend/alpine/SKILL.md +75 -0
- package/skills/stacks/frontend/angular/SKILL.md +75 -0
- package/skills/stacks/frontend/backbone/SKILL.md +82 -0
- package/skills/stacks/frontend/ember/SKILL.md +85 -0
- package/skills/stacks/frontend/htmx/SKILL.md +73 -0
- package/skills/stacks/frontend/lit/SKILL.md +76 -0
- package/skills/stacks/frontend/preact/SKILL.md +74 -0
- package/skills/stacks/frontend/qwik/SKILL.md +65 -0
- package/skills/stacks/frontend/react/SKILL.md +77 -0
- package/skills/stacks/frontend/solidjs/SKILL.md +75 -0
- package/skills/stacks/frontend/svelte/SKILL.md +70 -0
- package/skills/stacks/frontend/vue/SKILL.md +69 -0
- package/skills/stacks/infra/ansible/SKILL.md +76 -0
- package/skills/stacks/infra/aws/SKILL.md +66 -0
- package/skills/stacks/infra/azure/SKILL.md +72 -0
- package/skills/stacks/infra/circleci/SKILL.md +78 -0
- package/skills/stacks/infra/cloudflare/SKILL.md +65 -0
- package/skills/stacks/infra/fly-io/SKILL.md +63 -0
- package/skills/stacks/infra/gcp/SKILL.md +66 -0
- package/skills/stacks/infra/jenkins/SKILL.md +73 -0
- package/skills/stacks/infra/kubernetes/SKILL.md +64 -0
- package/skills/stacks/infra/netlify/SKILL.md +60 -0
- package/skills/stacks/infra/railway/SKILL.md +63 -0
- package/skills/stacks/infra/tailscale/SKILL.md +65 -0
- package/skills/stacks/infra/terraform/SKILL.md +75 -0
- package/skills/stacks/infra/vagrant/SKILL.md +70 -0
- package/skills/stacks/infra/vercel/SKILL.md +60 -0
- package/skills/stacks/meta/astro/SKILL.md +64 -0
- package/skills/stacks/meta/docusaurus/SKILL.md +71 -0
- package/skills/stacks/meta/eleventy/SKILL.md +69 -0
- package/skills/stacks/meta/gatsby/SKILL.md +63 -0
- package/skills/stacks/meta/hugo/SKILL.md +73 -0
- package/skills/stacks/meta/jekyll/SKILL.md +70 -0
- package/skills/stacks/meta/nextjs/SKILL.md +62 -0
- package/skills/stacks/meta/nuxt/SKILL.md +66 -0
- package/skills/stacks/meta/remix/SKILL.md +67 -0
- package/skills/stacks/meta/sveltekit/SKILL.md +70 -0
- package/skills/stacks/meta/vite/SKILL.md +63 -0
- package/skills/stacks/mobile/android/SKILL.md +77 -0
- package/skills/stacks/mobile/flutter/SKILL.md +77 -0
- package/skills/stacks/mobile/ionic/SKILL.md +72 -0
- package/skills/stacks/mobile/nativescript/SKILL.md +71 -0
- package/skills/stacks/mobile/react-native/SKILL.md +75 -0
- package/skills/stacks/mobile/xamarin/SKILL.md +73 -0
- package/skills/stacks/orm/diesel/SKILL.md +72 -0
- package/skills/stacks/orm/django-orm/SKILL.md +58 -0
- package/skills/stacks/orm/drizzle/SKILL.md +67 -0
- package/skills/stacks/orm/gorm/SKILL.md +73 -0
- package/skills/stacks/orm/knex/SKILL.md +64 -0
- package/skills/stacks/orm/mongoose/SKILL.md +64 -0
- package/skills/stacks/orm/prisma/SKILL.md +64 -0
- package/skills/stacks/orm/sequelize/SKILL.md +65 -0
- package/skills/stacks/orm/sqlalchemy/SKILL.md +71 -0
- package/skills/stacks/orm/typeorm/SKILL.md +70 -0
- package/skills/stacks/queue/bullmq/SKILL.md +69 -0
- package/skills/stacks/queue/celery/SKILL.md +68 -0
- package/skills/stacks/queue/kafka/SKILL.md +66 -0
- package/skills/stacks/queue/nats/SKILL.md +66 -0
- package/skills/stacks/queue/rabbitmq/SKILL.md +64 -0
- package/skills/stacks/queue/redis/SKILL.md +66 -0
- package/skills/stacks/runtime/beam/SKILL.md +72 -0
- package/skills/stacks/runtime/bun/SKILL.md +80 -0
- package/skills/stacks/runtime/deno/SKILL.md +74 -0
- package/skills/stacks/runtime/dotnet/SKILL.md +64 -0
- package/skills/stacks/runtime/jvm/SKILL.md +66 -0
- package/skills/stacks/runtime/node/SKILL.md +70 -0
- package/skills/stacks/runtime/pypy/SKILL.md +69 -0
- package/skills/stacks/runtime/python3/SKILL.md +70 -0
- package/skills/stacks/styling/bootstrap/SKILL.md +74 -0
- package/skills/stacks/styling/bulma/SKILL.md +80 -0
- package/skills/stacks/styling/chakra-ui/SKILL.md +61 -0
- package/skills/stacks/styling/css-modules/SKILL.md +54 -0
- package/skills/stacks/styling/mui/SKILL.md +60 -0
- package/skills/stacks/styling/sass/SKILL.md +63 -0
- package/skills/stacks/styling/shadcn-ui/SKILL.md +58 -0
- package/skills/stacks/styling/styled-components/SKILL.md +62 -0
- package/skills/stacks/styling/tailwind/SKILL.md +59 -0
- package/skills/stacks/styling/unocss/SKILL.md +64 -0
- package/skills/stacks/styling/vanilla-extract/SKILL.md +64 -0
- package/skills/stacks/styling/vuetify/SKILL.md +89 -0
- package/skills/stacks/testing/cypress/SKILL.md +68 -0
- package/skills/stacks/testing/jasmine/SKILL.md +67 -0
- package/skills/stacks/testing/jest/SKILL.md +67 -0
- package/skills/stacks/testing/mocha/SKILL.md +71 -0
- package/skills/stacks/testing/playwright/SKILL.md +68 -0
- package/skills/stacks/testing/puppeteer/SKILL.md +70 -0
- package/skills/stacks/testing/selenium/SKILL.md +70 -0
- package/skills/stacks/testing/vitest/SKILL.md +68 -0
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
exports.id=7107,exports.ids=[7107,7912],exports.modules={107:(a,b,c)=>{"use strict";c.d(b,{r:()=>f});var d=c(18110),e=c(98444);let f=(0,d.CN)({is:a=>"MergeQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"MergeQueryNode",into:a,...b&&{with:b}}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:b}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens,b]):(0,d.CN)([b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens.slice(0,-1),e.t.cloneWithResult(a.whens[a.whens.length-1],b)]):void 0})})},412:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"ENCODED_TAGS",{enumerable:!0,get:function(){return c}});let c={OPENING:{HTML:new Uint8Array([60,104,116,109,108]),HEAD:new Uint8Array([60,104,101,97,100]),BODY:new Uint8Array([60,98,111,100,121])},CLOSED:{HEAD:new Uint8Array([60,47,104,101,97,100,62]),BODY:new Uint8Array([60,47,98,111,100,121,62]),HTML:new Uint8Array([60,47,104,116,109,108,62]),BODY_AND_HTML:new Uint8Array([60,47,98,111,100,121,62,60,47,104,116,109,108,62])},META:{ICON_MARK:new Uint8Array([60,109,101,116,97,32,110,97,109,101,61,34,194,171,110,120,116,45,105,99,111,110,194,187,34])}}},1159:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"createDedupeFetch",{enumerable:!0,get:function(){return i}});let d=function(a){if(a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var b=g(void 0);if(b&&b.has(a))return b.get(a);var c={__proto__:null},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a)if("default"!==e&&Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;f&&(f.get||f.set)?Object.defineProperty(c,e,f):c[e]=a[e]}return c.default=a,b&&b.set(a,c),c}(c(9499)),e=c(15092),f=c(85556);function g(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(g=function(a){return a?c:b})(a)}let h=new Set(["traceparent","tracestate"]);function i(a){let b=d.cache(a=>[]);return function(c,d){let g,i;if(d&&d.signal)return a(c,d);if("string"!=typeof c||d){let b,e="string"==typeof c||c instanceof URL?new Request(c,d):c;if("GET"!==e.method&&"HEAD"!==e.method||e.keepalive)return a(c,d);b=Array.from(e.headers.entries()).filter(([a])=>!h.has(a.toLowerCase())),i=JSON.stringify([e.method,b,e.mode,e.redirect,e.credentials,e.referrer,e.referrerPolicy,e.integrity]),g=e.url}else i='["GET",[],null,"follow",null,null,null,null]',g=c;let j=b(g);for(let a=0,b=j.length;a<b;a+=1){let[b,c]=j[a];if(b===i)return c.then(()=>{let b=j[a][2];if(!b)throw Object.defineProperty(new f.InvariantError("No cached response"),"__NEXT_ERROR_CODE",{value:"E579",enumerable:!1,configurable:!0});let[c,d]=(0,e.cloneResponse)(b);return j[a][2]=d,c})}let k=a(c,d),l=[i,k,null];return j.push(l),k.then(a=>{let[b,c]=(0,e.cloneResponse)(a);return l[2]=c,b})}}},1434:(a,b,c)=>{"use strict";c.d(b,{$:()=>g});var d=c(15214);let e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function f(a){if("string"==typeof a&&e.test(a)){let b=new Date(a);if(!isNaN(b.getTime()))return b}return a}function g(a){try{if("string"!=typeof a){if(null==a)return null;return function a(b){if(null==b)return b;if("string"==typeof b)return f(b);if(b instanceof Date)return b;if(Array.isArray(b))return b.map(a);if("object"==typeof b){let c={};for(let d of Object.keys(b))c[d]=a(b[d]);return c}return b}(a)}return JSON.parse(a,(a,b)=>f(b))}catch(a){return d.vF.error("Error parsing JSON",{error:a}),null}}},1887:a=>{a.exports={LOCHDR:30,LOCSIG:0x4034b50,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:0x8074b50,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:0x2014b50,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:0x6054b50,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:0x7064b50,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:0x6064b50,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:0xffffffff,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}},2529:(a,b,c)=>{"use strict";c.d(b,{l:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"BinaryOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"BinaryOperationNode",leftOperand:a,operator:b,rightOperand:c})})},2565:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"unstable_rethrow",{enumerable:!0,get:function(){return function a(b){if((0,g.isNextRouterError)(b)||(0,f.isBailoutToCSRError)(b)||(0,i.isDynamicServerError)(b)||(0,h.isDynamicPostpone)(b)||(0,e.isPostpone)(b)||(0,d.isHangingPromiseRejectionError)(b)||(0,h.isPrerenderInterruptedError)(b))throw b;b instanceof Error&&"cause"in b&&a(b.cause)}}});let d=c(87143),e=c(28528),f=c(39793),g=c(44805),h=c(4190),i=c(96690);("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},2636:a=>{(()=>{"use strict";let b,c,d,e,f;var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w={491:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.ContextAPI=void 0;let d=c(223),e=c(172),f=c(930),g="context",h=new d.NoopContextManager;class i{static getInstance(){return this._instance||(this._instance=new i),this._instance}setGlobalContextManager(a){return(0,e.registerGlobal)(g,a,f.DiagAPI.instance())}active(){return this._getContextManager().active()}with(a,b,c,...d){return this._getContextManager().with(a,b,c,...d)}bind(a,b){return this._getContextManager().bind(a,b)}_getContextManager(){return(0,e.getGlobal)(g)||h}disable(){this._getContextManager().disable(),(0,e.unregisterGlobal)(g,f.DiagAPI.instance())}}b.ContextAPI=i},930:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.DiagAPI=void 0;let d=c(56),e=c(912),f=c(957),g=c(172);class h{constructor(){function a(a){return function(...b){let c=(0,g.getGlobal)("diag");if(c)return c[a](...b)}}const b=this;b.setLogger=(a,c={logLevel:f.DiagLogLevel.INFO})=>{var d,h,i;if(a===b){let a=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return b.error(null!=(d=a.stack)?d:a.message),!1}"number"==typeof c&&(c={logLevel:c});let j=(0,g.getGlobal)("diag"),k=(0,e.createLogLevelDiagLogger)(null!=(h=c.logLevel)?h:f.DiagLogLevel.INFO,a);if(j&&!c.suppressOverrideMessage){let a=null!=(i=Error().stack)?i:"<failed to generate stacktrace>";j.warn(`Current logger will be overwritten from ${a}`),k.warn(`Current logger will overwrite one already registered from ${a}`)}return(0,g.registerGlobal)("diag",k,b,!0)},b.disable=()=>{(0,g.unregisterGlobal)("diag",b)},b.createComponentLogger=a=>new d.DiagComponentLogger(a),b.verbose=a("verbose"),b.debug=a("debug"),b.info=a("info"),b.warn=a("warn"),b.error=a("error")}static instance(){return this._instance||(this._instance=new h),this._instance}}b.DiagAPI=h},653:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.MetricsAPI=void 0;let d=c(660),e=c(172),f=c(930),g="metrics";class h{static getInstance(){return this._instance||(this._instance=new h),this._instance}setGlobalMeterProvider(a){return(0,e.registerGlobal)(g,a,f.DiagAPI.instance())}getMeterProvider(){return(0,e.getGlobal)(g)||d.NOOP_METER_PROVIDER}getMeter(a,b,c){return this.getMeterProvider().getMeter(a,b,c)}disable(){(0,e.unregisterGlobal)(g,f.DiagAPI.instance())}}b.MetricsAPI=h},181:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.PropagationAPI=void 0;let d=c(172),e=c(874),f=c(194),g=c(277),h=c(369),i=c(930),j="propagation",k=new e.NoopTextMapPropagator;class l{constructor(){this.createBaggage=h.createBaggage,this.getBaggage=g.getBaggage,this.getActiveBaggage=g.getActiveBaggage,this.setBaggage=g.setBaggage,this.deleteBaggage=g.deleteBaggage}static getInstance(){return this._instance||(this._instance=new l),this._instance}setGlobalPropagator(a){return(0,d.registerGlobal)(j,a,i.DiagAPI.instance())}inject(a,b,c=f.defaultTextMapSetter){return this._getGlobalPropagator().inject(a,b,c)}extract(a,b,c=f.defaultTextMapGetter){return this._getGlobalPropagator().extract(a,b,c)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,d.unregisterGlobal)(j,i.DiagAPI.instance())}_getGlobalPropagator(){return(0,d.getGlobal)(j)||k}}b.PropagationAPI=l},997:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.TraceAPI=void 0;let d=c(172),e=c(846),f=c(139),g=c(607),h=c(930),i="trace";class j{constructor(){this._proxyTracerProvider=new e.ProxyTracerProvider,this.wrapSpanContext=f.wrapSpanContext,this.isSpanContextValid=f.isSpanContextValid,this.deleteSpan=g.deleteSpan,this.getSpan=g.getSpan,this.getActiveSpan=g.getActiveSpan,this.getSpanContext=g.getSpanContext,this.setSpan=g.setSpan,this.setSpanContext=g.setSpanContext}static getInstance(){return this._instance||(this._instance=new j),this._instance}setGlobalTracerProvider(a){let b=(0,d.registerGlobal)(i,this._proxyTracerProvider,h.DiagAPI.instance());return b&&this._proxyTracerProvider.setDelegate(a),b}getTracerProvider(){return(0,d.getGlobal)(i)||this._proxyTracerProvider}getTracer(a,b){return this.getTracerProvider().getTracer(a,b)}disable(){(0,d.unregisterGlobal)(i,h.DiagAPI.instance()),this._proxyTracerProvider=new e.ProxyTracerProvider}}b.TraceAPI=j},277:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.deleteBaggage=b.setBaggage=b.getActiveBaggage=b.getBaggage=void 0;let d=c(491),e=(0,c(780).createContextKey)("OpenTelemetry Baggage Key");function f(a){return a.getValue(e)||void 0}b.getBaggage=f,b.getActiveBaggage=function(){return f(d.ContextAPI.getInstance().active())},b.setBaggage=function(a,b){return a.setValue(e,b)},b.deleteBaggage=function(a){return a.deleteValue(e)}},993:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.BaggageImpl=void 0;class c{constructor(a){this._entries=a?new Map(a):new Map}getEntry(a){let b=this._entries.get(a);if(b)return Object.assign({},b)}getAllEntries(){return Array.from(this._entries.entries()).map(([a,b])=>[a,b])}setEntry(a,b){let d=new c(this._entries);return d._entries.set(a,b),d}removeEntry(a){let b=new c(this._entries);return b._entries.delete(a),b}removeEntries(...a){let b=new c(this._entries);for(let c of a)b._entries.delete(c);return b}clear(){return new c}}b.BaggageImpl=c},830:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.baggageEntryMetadataSymbol=void 0,b.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")},369:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.baggageEntryMetadataFromString=b.createBaggage=void 0;let d=c(930),e=c(993),f=c(830),g=d.DiagAPI.instance();b.createBaggage=function(a={}){return new e.BaggageImpl(new Map(Object.entries(a)))},b.baggageEntryMetadataFromString=function(a){return"string"!=typeof a&&(g.error(`Cannot create baggage metadata from unknown type: ${typeof a}`),a=""),{__TYPE__:f.baggageEntryMetadataSymbol,toString:()=>a}}},67:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.context=void 0,b.context=c(491).ContextAPI.getInstance()},223:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NoopContextManager=void 0;let d=c(780);class e{active(){return d.ROOT_CONTEXT}with(a,b,c,...d){return b.call(c,...d)}bind(a,b){return b}enable(){return this}disable(){return this}}b.NoopContextManager=e},780:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.ROOT_CONTEXT=b.createContextKey=void 0,b.createContextKey=function(a){return Symbol.for(a)};class c{constructor(a){const b=this;b._currentContext=a?new Map(a):new Map,b.getValue=a=>b._currentContext.get(a),b.setValue=(a,d)=>{let e=new c(b._currentContext);return e._currentContext.set(a,d),e},b.deleteValue=a=>{let d=new c(b._currentContext);return d._currentContext.delete(a),d}}}b.ROOT_CONTEXT=new c},506:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.diag=void 0,b.diag=c(930).DiagAPI.instance()},56:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.DiagComponentLogger=void 0;let d=c(172);class e{constructor(a){this._namespace=a.namespace||"DiagComponentLogger"}debug(...a){return f("debug",this._namespace,a)}error(...a){return f("error",this._namespace,a)}info(...a){return f("info",this._namespace,a)}warn(...a){return f("warn",this._namespace,a)}verbose(...a){return f("verbose",this._namespace,a)}}function f(a,b,c){let e=(0,d.getGlobal)("diag");if(e)return c.unshift(b),e[a](...c)}b.DiagComponentLogger=e},972:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.DiagConsoleLogger=void 0;let c=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class d{constructor(){for(let a=0;a<c.length;a++)this[c[a].n]=function(a){return function(...b){if(console){let c=console[a];if("function"!=typeof c&&(c=console.log),"function"==typeof c)return c.apply(console,b)}}}(c[a].c)}}b.DiagConsoleLogger=d},912:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.createLogLevelDiagLogger=void 0;let d=c(957);b.createLogLevelDiagLogger=function(a,b){function c(c,d){let e=b[c];return"function"==typeof e&&a>=d?e.bind(b):function(){}}return a<d.DiagLogLevel.NONE?a=d.DiagLogLevel.NONE:a>d.DiagLogLevel.ALL&&(a=d.DiagLogLevel.ALL),b=b||{},{error:c("error",d.DiagLogLevel.ERROR),warn:c("warn",d.DiagLogLevel.WARN),info:c("info",d.DiagLogLevel.INFO),debug:c("debug",d.DiagLogLevel.DEBUG),verbose:c("verbose",d.DiagLogLevel.VERBOSE)}}},957:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.DiagLogLevel=void 0,(c=b.DiagLogLevel||(b.DiagLogLevel={}))[c.NONE=0]="NONE",c[c.ERROR=30]="ERROR",c[c.WARN=50]="WARN",c[c.INFO=60]="INFO",c[c.DEBUG=70]="DEBUG",c[c.VERBOSE=80]="VERBOSE",c[c.ALL=9999]="ALL"},172:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.unregisterGlobal=b.getGlobal=b.registerGlobal=void 0;let d=c(200),e=c(521),f=c(130),g=e.VERSION.split(".")[0],h=Symbol.for(`opentelemetry.js.api.${g}`),i=d._globalThis;b.registerGlobal=function(a,b,c,d=!1){var f;let g=i[h]=null!=(f=i[h])?f:{version:e.VERSION};if(!d&&g[a]){let b=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${a}`);return c.error(b.stack||b.message),!1}if(g.version!==e.VERSION){let b=Error(`@opentelemetry/api: Registration of version v${g.version} for ${a} does not match previously registered API v${e.VERSION}`);return c.error(b.stack||b.message),!1}return g[a]=b,c.debug(`@opentelemetry/api: Registered a global for ${a} v${e.VERSION}.`),!0},b.getGlobal=function(a){var b,c;let d=null==(b=i[h])?void 0:b.version;if(d&&(0,f.isCompatible)(d))return null==(c=i[h])?void 0:c[a]},b.unregisterGlobal=function(a,b){b.debug(`@opentelemetry/api: Unregistering a global for ${a} v${e.VERSION}.`);let c=i[h];c&&delete c[a]}},130:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.isCompatible=b._makeCompatibilityCheck=void 0;let d=c(521),e=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function f(a){let b=new Set([a]),c=new Set,d=a.match(e);if(!d)return()=>!1;let f={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};if(null!=f.prerelease)return function(b){return b===a};function g(a){return c.add(a),!1}return function(a){if(b.has(a))return!0;if(c.has(a))return!1;let d=a.match(e);if(!d)return g(a);let h={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};if(null!=h.prerelease||f.major!==h.major)return g(a);if(0===f.major)return f.minor===h.minor&&f.patch<=h.patch?(b.add(a),!0):g(a);return f.minor<=h.minor?(b.add(a),!0):g(a)}}b._makeCompatibilityCheck=f,b.isCompatible=f(d.VERSION)},886:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.metrics=void 0,b.metrics=c(653).MetricsAPI.getInstance()},901:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.ValueType=void 0,(c=b.ValueType||(b.ValueType={}))[c.INT=0]="INT",c[c.DOUBLE=1]="DOUBLE"},102:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.createNoopMeter=b.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=b.NOOP_OBSERVABLE_GAUGE_METRIC=b.NOOP_OBSERVABLE_COUNTER_METRIC=b.NOOP_UP_DOWN_COUNTER_METRIC=b.NOOP_HISTOGRAM_METRIC=b.NOOP_COUNTER_METRIC=b.NOOP_METER=b.NoopObservableUpDownCounterMetric=b.NoopObservableGaugeMetric=b.NoopObservableCounterMetric=b.NoopObservableMetric=b.NoopHistogramMetric=b.NoopUpDownCounterMetric=b.NoopCounterMetric=b.NoopMetric=b.NoopMeter=void 0;class c{createHistogram(a,c){return b.NOOP_HISTOGRAM_METRIC}createCounter(a,c){return b.NOOP_COUNTER_METRIC}createUpDownCounter(a,c){return b.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(a,c){return b.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(a,c){return b.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(a,c){return b.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(a,b){}removeBatchObservableCallback(a){}}b.NoopMeter=c;class d{}b.NoopMetric=d;class e extends d{add(a,b){}}b.NoopCounterMetric=e;class f extends d{add(a,b){}}b.NoopUpDownCounterMetric=f;class g extends d{record(a,b){}}b.NoopHistogramMetric=g;class h{addCallback(a){}removeCallback(a){}}b.NoopObservableMetric=h;class i extends h{}b.NoopObservableCounterMetric=i;class j extends h{}b.NoopObservableGaugeMetric=j;class k extends h{}b.NoopObservableUpDownCounterMetric=k,b.NOOP_METER=new c,b.NOOP_COUNTER_METRIC=new e,b.NOOP_HISTOGRAM_METRIC=new g,b.NOOP_UP_DOWN_COUNTER_METRIC=new f,b.NOOP_OBSERVABLE_COUNTER_METRIC=new i,b.NOOP_OBSERVABLE_GAUGE_METRIC=new j,b.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new k,b.createNoopMeter=function(){return b.NOOP_METER}},660:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NOOP_METER_PROVIDER=b.NoopMeterProvider=void 0;let d=c(102);class e{getMeter(a,b,c){return d.NOOP_METER}}b.NoopMeterProvider=e,b.NOOP_METER_PROVIDER=new e},200:function(a,b,c){var d=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c),Object.defineProperty(a,d,{enumerable:!0,get:function(){return b[c]}})}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),e=this&&this.__exportStar||function(a,b){for(var c in a)"default"===c||Object.prototype.hasOwnProperty.call(b,c)||d(b,a,c)};Object.defineProperty(b,"__esModule",{value:!0}),e(c(46),b)},651:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b._globalThis=void 0,b._globalThis="object"==typeof globalThis?globalThis:global},46:function(a,b,c){var d=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c),Object.defineProperty(a,d,{enumerable:!0,get:function(){return b[c]}})}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),e=this&&this.__exportStar||function(a,b){for(var c in a)"default"===c||Object.prototype.hasOwnProperty.call(b,c)||d(b,a,c)};Object.defineProperty(b,"__esModule",{value:!0}),e(c(651),b)},939:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.propagation=void 0,b.propagation=c(181).PropagationAPI.getInstance()},874:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NoopTextMapPropagator=void 0;class c{inject(a,b){}extract(a,b){return a}fields(){return[]}}b.NoopTextMapPropagator=c},194:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.defaultTextMapSetter=b.defaultTextMapGetter=void 0,b.defaultTextMapGetter={get(a,b){if(null!=a)return a[b]},keys:a=>null==a?[]:Object.keys(a)},b.defaultTextMapSetter={set(a,b,c){null!=a&&(a[b]=c)}}},845:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.trace=void 0,b.trace=c(997).TraceAPI.getInstance()},403:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NonRecordingSpan=void 0;let d=c(476);class e{constructor(a=d.INVALID_SPAN_CONTEXT){this._spanContext=a}spanContext(){return this._spanContext}setAttribute(a,b){return this}setAttributes(a){return this}addEvent(a,b){return this}setStatus(a){return this}updateName(a){return this}end(a){}isRecording(){return!1}recordException(a,b){}}b.NonRecordingSpan=e},614:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NoopTracer=void 0;let d=c(491),e=c(607),f=c(403),g=c(139),h=d.ContextAPI.getInstance();class i{startSpan(a,b,c=h.active()){var d;if(null==b?void 0:b.root)return new f.NonRecordingSpan;let i=c&&(0,e.getSpanContext)(c);return"object"==typeof(d=i)&&"string"==typeof d.spanId&&"string"==typeof d.traceId&&"number"==typeof d.traceFlags&&(0,g.isSpanContextValid)(i)?new f.NonRecordingSpan(i):new f.NonRecordingSpan}startActiveSpan(a,b,c,d){let f,g,i;if(arguments.length<2)return;2==arguments.length?i=b:3==arguments.length?(f=b,i=c):(f=b,g=c,i=d);let j=null!=g?g:h.active(),k=this.startSpan(a,f,j),l=(0,e.setSpan)(j,k);return h.with(l,i,void 0,k)}}b.NoopTracer=i},124:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.NoopTracerProvider=void 0;let d=c(614);class e{getTracer(a,b,c){return new d.NoopTracer}}b.NoopTracerProvider=e},125:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.ProxyTracer=void 0;let d=new(c(614)).NoopTracer;class e{constructor(a,b,c,d){this._provider=a,this.name=b,this.version=c,this.options=d}startSpan(a,b,c){return this._getTracer().startSpan(a,b,c)}startActiveSpan(a,b,c,d){let e=this._getTracer();return Reflect.apply(e.startActiveSpan,e,arguments)}_getTracer(){if(this._delegate)return this._delegate;let a=this._provider.getDelegateTracer(this.name,this.version,this.options);return a?(this._delegate=a,this._delegate):d}}b.ProxyTracer=e},846:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.ProxyTracerProvider=void 0;let d=c(125),e=new(c(124)).NoopTracerProvider;class f{getTracer(a,b,c){var e;return null!=(e=this.getDelegateTracer(a,b,c))?e:new d.ProxyTracer(this,a,b,c)}getDelegate(){var a;return null!=(a=this._delegate)?a:e}setDelegate(a){this._delegate=a}getDelegateTracer(a,b,c){var d;return null==(d=this._delegate)?void 0:d.getTracer(a,b,c)}}b.ProxyTracerProvider=f},996:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.SamplingDecision=void 0,(c=b.SamplingDecision||(b.SamplingDecision={}))[c.NOT_RECORD=0]="NOT_RECORD",c[c.RECORD=1]="RECORD",c[c.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"},607:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.getSpanContext=b.setSpanContext=b.deleteSpan=b.setSpan=b.getActiveSpan=b.getSpan=void 0;let d=c(780),e=c(403),f=c(491),g=(0,d.createContextKey)("OpenTelemetry Context Key SPAN");function h(a){return a.getValue(g)||void 0}function i(a,b){return a.setValue(g,b)}b.getSpan=h,b.getActiveSpan=function(){return h(f.ContextAPI.getInstance().active())},b.setSpan=i,b.deleteSpan=function(a){return a.deleteValue(g)},b.setSpanContext=function(a,b){return i(a,new e.NonRecordingSpan(b))},b.getSpanContext=function(a){var b;return null==(b=h(a))?void 0:b.spanContext()}},325:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.TraceStateImpl=void 0;let d=c(564);class e{constructor(a){this._internalState=new Map,a&&this._parse(a)}set(a,b){let c=this._clone();return c._internalState.has(a)&&c._internalState.delete(a),c._internalState.set(a,b),c}unset(a){let b=this._clone();return b._internalState.delete(a),b}get(a){return this._internalState.get(a)}serialize(){return this._keys().reduce((a,b)=>(a.push(b+"="+this.get(b)),a),[]).join(",")}_parse(a){!(a.length>512)&&(this._internalState=a.split(",").reverse().reduce((a,b)=>{let c=b.trim(),e=c.indexOf("=");if(-1!==e){let f=c.slice(0,e),g=c.slice(e+1,b.length);(0,d.validateKey)(f)&&(0,d.validateValue)(g)&&a.set(f,g)}return a},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let a=new e;return a._internalState=new Map(this._internalState),a}}b.TraceStateImpl=e},564:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.validateValue=b.validateKey=void 0;let c="[_0-9a-z-*/]",d=`[a-z]${c}{0,255}`,e=`[a-z0-9]${c}{0,240}@[a-z]${c}{0,13}`,f=RegExp(`^(?:${d}|${e})$`),g=/^[ -~]{0,255}[!-~]$/,h=/,|=/;b.validateKey=function(a){return f.test(a)},b.validateValue=function(a){return g.test(a)&&!h.test(a)}},98:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.createTraceState=void 0;let d=c(325);b.createTraceState=function(a){return new d.TraceStateImpl(a)}},476:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.INVALID_SPAN_CONTEXT=b.INVALID_TRACEID=b.INVALID_SPANID=void 0;let d=c(475);b.INVALID_SPANID="0000000000000000",b.INVALID_TRACEID="00000000000000000000000000000000",b.INVALID_SPAN_CONTEXT={traceId:b.INVALID_TRACEID,spanId:b.INVALID_SPANID,traceFlags:d.TraceFlags.NONE}},357:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.SpanKind=void 0,(c=b.SpanKind||(b.SpanKind={}))[c.INTERNAL=0]="INTERNAL",c[c.SERVER=1]="SERVER",c[c.CLIENT=2]="CLIENT",c[c.PRODUCER=3]="PRODUCER",c[c.CONSUMER=4]="CONSUMER"},139:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.wrapSpanContext=b.isSpanContextValid=b.isValidSpanId=b.isValidTraceId=void 0;let d=c(476),e=c(403),f=/^([0-9a-f]{32})$/i,g=/^[0-9a-f]{16}$/i;function h(a){return f.test(a)&&a!==d.INVALID_TRACEID}function i(a){return g.test(a)&&a!==d.INVALID_SPANID}b.isValidTraceId=h,b.isValidSpanId=i,b.isSpanContextValid=function(a){return h(a.traceId)&&i(a.spanId)},b.wrapSpanContext=function(a){return new e.NonRecordingSpan(a)}},847:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.SpanStatusCode=void 0,(c=b.SpanStatusCode||(b.SpanStatusCode={}))[c.UNSET=0]="UNSET",c[c.OK=1]="OK",c[c.ERROR=2]="ERROR"},475:(a,b)=>{var c;Object.defineProperty(b,"__esModule",{value:!0}),b.TraceFlags=void 0,(c=b.TraceFlags||(b.TraceFlags={}))[c.NONE=0]="NONE",c[c.SAMPLED=1]="SAMPLED"},521:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.VERSION=void 0,b.VERSION="1.6.0"}},x={};function y(a){var b=x[a];if(void 0!==b)return b.exports;var c=x[a]={exports:{}},d=!0;try{w[a].call(c.exports,c,c.exports,y),d=!1}finally{d&&delete x[a]}return c.exports}y.ab=__dirname+"/";var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.trace=z.propagation=z.metrics=z.diag=z.context=z.INVALID_SPAN_CONTEXT=z.INVALID_TRACEID=z.INVALID_SPANID=z.isValidSpanId=z.isValidTraceId=z.isSpanContextValid=z.createTraceState=z.TraceFlags=z.SpanStatusCode=z.SpanKind=z.SamplingDecision=z.ProxyTracerProvider=z.ProxyTracer=z.defaultTextMapSetter=z.defaultTextMapGetter=z.ValueType=z.createNoopMeter=z.DiagLogLevel=z.DiagConsoleLogger=z.ROOT_CONTEXT=z.createContextKey=z.baggageEntryMetadataFromString=void 0,g=y(369),Object.defineProperty(z,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return g.baggageEntryMetadataFromString}}),h=y(780),Object.defineProperty(z,"createContextKey",{enumerable:!0,get:function(){return h.createContextKey}}),Object.defineProperty(z,"ROOT_CONTEXT",{enumerable:!0,get:function(){return h.ROOT_CONTEXT}}),i=y(972),Object.defineProperty(z,"DiagConsoleLogger",{enumerable:!0,get:function(){return i.DiagConsoleLogger}}),j=y(957),Object.defineProperty(z,"DiagLogLevel",{enumerable:!0,get:function(){return j.DiagLogLevel}}),k=y(102),Object.defineProperty(z,"createNoopMeter",{enumerable:!0,get:function(){return k.createNoopMeter}}),l=y(901),Object.defineProperty(z,"ValueType",{enumerable:!0,get:function(){return l.ValueType}}),m=y(194),Object.defineProperty(z,"defaultTextMapGetter",{enumerable:!0,get:function(){return m.defaultTextMapGetter}}),Object.defineProperty(z,"defaultTextMapSetter",{enumerable:!0,get:function(){return m.defaultTextMapSetter}}),n=y(125),Object.defineProperty(z,"ProxyTracer",{enumerable:!0,get:function(){return n.ProxyTracer}}),o=y(846),Object.defineProperty(z,"ProxyTracerProvider",{enumerable:!0,get:function(){return o.ProxyTracerProvider}}),p=y(996),Object.defineProperty(z,"SamplingDecision",{enumerable:!0,get:function(){return p.SamplingDecision}}),q=y(357),Object.defineProperty(z,"SpanKind",{enumerable:!0,get:function(){return q.SpanKind}}),r=y(847),Object.defineProperty(z,"SpanStatusCode",{enumerable:!0,get:function(){return r.SpanStatusCode}}),s=y(475),Object.defineProperty(z,"TraceFlags",{enumerable:!0,get:function(){return s.TraceFlags}}),t=y(98),Object.defineProperty(z,"createTraceState",{enumerable:!0,get:function(){return t.createTraceState}}),u=y(139),Object.defineProperty(z,"isSpanContextValid",{enumerable:!0,get:function(){return u.isSpanContextValid}}),Object.defineProperty(z,"isValidTraceId",{enumerable:!0,get:function(){return u.isValidTraceId}}),Object.defineProperty(z,"isValidSpanId",{enumerable:!0,get:function(){return u.isValidSpanId}}),v=y(476),Object.defineProperty(z,"INVALID_SPANID",{enumerable:!0,get:function(){return v.INVALID_SPANID}}),Object.defineProperty(z,"INVALID_TRACEID",{enumerable:!0,get:function(){return v.INVALID_TRACEID}}),Object.defineProperty(z,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return v.INVALID_SPAN_CONTEXT}}),b=y(67),Object.defineProperty(z,"context",{enumerable:!0,get:function(){return b.context}}),c=y(506),Object.defineProperty(z,"diag",{enumerable:!0,get:function(){return c.diag}}),d=y(886),Object.defineProperty(z,"metrics",{enumerable:!0,get:function(){return d.metrics}}),e=y(939),Object.defineProperty(z,"propagation",{enumerable:!0,get:function(){return e.propagation}}),f=y(845),Object.defineProperty(z,"trace",{enumerable:!0,get:function(){return f.trace}}),z.default={context:b.context,diag:c.diag,metrics:d.metrics,propagation:e.propagation,trace:f.trace},a.exports=z})()},2929:(a,b,c)=>{"use strict";c.d(b,{$s:()=>j,U2:()=>i,dJ:()=>l,qH:()=>k});var d=c(26144),e=c(90588),f=c(76051),g=c(18110),h=c(37338);function i(a){var b;return(0,g.MH)(a)?(b=a).some(h.SS)?e.s.create(b.map(a=>j(a))):d.h.create(b):j(a)}function j(a){return(0,h.SS)(a)?(0,h.YK)(a):f.q.create(a)}function k(a){return(0,g.Et)(a)||(0,g.Lm)(a)||(0,g.kZ)(a)}function l(a){if(!k(a))throw Error(`unsafe immediate value ${JSON.stringify(a)}`);return f.q.createImmediate(a)}},3172:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"MISSING_ROOT_TAGS_ERROR",{enumerable:!0,get:function(){return c}});let c="NEXT_MISSING_ROOT_TAGS";("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},3687:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={indexOfUint8Array:function(){return e},isEquivalentUint8Arrays:function(){return f},removeFromUint8Array:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});function e(a,b){if(0===b.length)return 0;if(0===a.length||b.length>a.length)return -1;if("u">typeof Buffer)return(Buffer.isBuffer(a)?a:Buffer.from(a.buffer,a.byteOffset,a.byteLength)).indexOf(b);for(let c=0;c<=a.length-b.length;c++){let d=!0;for(let e=0;e<b.length;e++)if(a[c+e]!==b[e]){d=!1;break}if(d)return c}return -1}function f(a,b){if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}function g(a,b){let c=e(a,b);if(0===c)return a.subarray(b.length);if(!(c>-1))return a;{let d=new Uint8Array(a.length-b.length);return d.set(a.subarray(0,c)),d.set(a.subarray(c+b.length),c),d}}},3694:(a,b,c)=>{"use strict";c.d(b,{H:()=>f});var d=c(18110),e=c(4432);let f=(0,d.CN)({is:a=>"TableNode"===a.kind,create:a=>(0,d.CN)({kind:"TableNode",table:e.y.create(a)}),createWithSchema:(a,b)=>(0,d.CN)({kind:"TableNode",table:e.y.createWithSchema(a,b)})})},4028:(a,b,c)=>{"use strict";let d,e;Object.defineProperty(b,"__esModule",{value:!0});var f={BubbledError:function(){return q},SpanKind:function(){return o},SpanStatusCode:function(){return n},getTracer:function(){return y},isBubbledError:function(){return r}};for(var g in f)Object.defineProperty(b,g,{enumerable:!0,get:f[g]});let h=c(11010),i=c(79957),j=process.env.NEXT_OTEL_PERFORMANCE_PREFIX;try{d=c(2636)}catch(a){d=c(2636)}let{context:k,propagation:l,trace:m,SpanStatusCode:n,SpanKind:o,ROOT_CONTEXT:p}=d;class q extends Error{constructor(a,b){super(),this.bubble=a,this.result=b}}function r(a){return"object"==typeof a&&null!==a&&a instanceof q}let s=(a,b)=>{r(b)&&b.bubble?a.setAttribute("next.bubble",!0):(b&&(a.recordException(b),a.setAttribute("error.type",b.name)),a.setStatus({code:n.ERROR,message:null==b?void 0:b.message})),a.end()},t=new Map,u=d.createContextKey("next.rootSpanId"),v=0,w={set(a,b,c){a.push({key:b,value:c})}};class x{getTracerInstance(){return m.getTracer("next.js","0.0.1")}getContext(){return k}getTracePropagationData(){let a=k.active(),b=[];return l.inject(a,b,w),b}getActiveScopeSpan(){return m.getSpan(null==k?void 0:k.active())}withPropagatedContext(a,b,c,d=!1){let e=k.active();if(d){let d=l.extract(p,a,c);if(m.getSpanContext(d))return k.with(d,b);let f=l.extract(e,a,c);return k.with(f,b)}if(m.getSpanContext(e))return b();let f=l.extract(e,a,c);return k.with(f,b)}trace(...a){let[b,c,d]=a,{fn:e,options:f}="function"==typeof c?{fn:c,options:{}}:{fn:d,options:{...c}},g=f.spanName??b;if(!h.NextVanillaSpanAllowlist.has(b)&&"1"!==process.env.NEXT_OTEL_VERBOSE||f.hideSpan)return e();let l=this.getSpanContext((null==f?void 0:f.parentSpan)??this.getActiveScopeSpan());l||(l=(null==k?void 0:k.active())??p);let m=l.getValue(u),n="number"!=typeof m||!t.has(m),o=v++;return f.attributes={"next.span_name":g,"next.span_type":b,...f.attributes},k.with(l.setValue(u,o),()=>this.getTracerInstance().startActiveSpan(g,f,a=>{let c;j&&b&&h.LogSpanAllowList.has(b)&&(c="performance"in globalThis&&"measure"in performance?globalThis.performance.now():void 0);let d=!1,g=()=>{!d&&(d=!0,t.delete(o),c&&performance.measure(`${j}:next-${(b.split(".").pop()||"").replace(/[A-Z]/g,a=>"-"+a.toLowerCase())}`,{start:c,end:performance.now()}))};if(n&&t.set(o,new Map(Object.entries(f.attributes??{}))),e.length>1)try{return e(a,b=>s(a,b))}catch(b){throw s(a,b),b}finally{g()}try{let b=e(a);if((0,i.isThenable)(b))return b.then(b=>(a.end(),b)).catch(b=>{throw s(a,b),b}).finally(g);return a.end(),g(),b}catch(b){throw s(a,b),g(),b}}))}wrap(...a){let b=this,[c,d,e]=3===a.length?a:[a[0],{},a[1]];return h.NextVanillaSpanAllowlist.has(c)||"1"===process.env.NEXT_OTEL_VERBOSE?function(){let a=d;"function"==typeof a&&"function"==typeof e&&(a=a.apply(this,arguments));let f=arguments.length-1,g=arguments[f];if("function"!=typeof g)return b.trace(c,a,()=>e.apply(this,arguments));{let d=b.getContext().bind(k.active(),g);return b.trace(c,a,(a,b)=>(arguments[f]=function(a){return null==b||b(a),d.apply(this,arguments)},e.apply(this,arguments)))}}:e}startSpan(...a){let[b,c]=a,d=this.getSpanContext((null==c?void 0:c.parentSpan)??this.getActiveScopeSpan());return this.getTracerInstance().startSpan(b,c,d)}getSpanContext(a){return a?m.setSpan(k.active(),a):void 0}getRootSpanAttributes(){let a=k.active().getValue(u);return t.get(a)}setRootSpanAttribute(a,b){let c=k.active().getValue(u),d=t.get(c);d&&!d.has(a)&&d.set(a,b)}withSpan(a,b){let c=m.setSpan(k.active(),a);return k.with(c,b)}}let y=(e=new x,()=>e)},4190:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d,e,f,g={DynamicHoleKind:function(){return $},Postpone:function(){return D},PreludeState:function(){return af},abortAndThrowOnSynchronousRequestDataAccess:function(){return C},abortOnSynchronousPlatformIOAccess:function(){return B},accessedDynamicData:function(){return L},annotateDynamicAccess:function(){return Q},consumeDynamicAccess:function(){return M},createDynamicTrackingState:function(){return u},createDynamicValidationState:function(){return v},createHangingInputAbortSignal:function(){return P},createInstantValidationState:function(){return _},createRenderInBrowserAbortSignal:function(){return O},formatDynamicAPIAccesses:function(){return N},getFirstDynamicReason:function(){return w},getNavigationDisallowedDynamicReasons:function(){return aj},getStaticShellDisallowedDynamicReasons:function(){return ai},isDynamicPostpone:function(){return G},isPrerenderInterruptedError:function(){return K},logDisallowedDynamicError:function(){return ag},markCurrentScopeAsDynamic:function(){return x},postponeWithTracking:function(){return E},throwIfDisallowedDynamic:function(){return ah},throwToInterruptStaticGeneration:function(){return y},trackAllowedDynamicAccess:function(){return Z},trackDynamicDataInDynamicRender:function(){return z},trackDynamicHoleInNavigation:function(){return aa},trackDynamicHoleInRuntimeShell:function(){return ac},trackDynamicHoleInStaticShell:function(){return ad},trackThrownErrorInNavigation:function(){return ab},useDynamicRouteParams:function(){return R},useDynamicSearchParams:function(){return S}};for(var h in g)Object.defineProperty(b,h,{enumerable:!0,get:g[h]});let i=(d=c(9499))&&d.__esModule?d:{default:d},j=c(96690),k=c(27130),l=c(63033),m=c(29294),n=c(87143),o=c(28434),p=c(34310),q=c(39793),r=c(85556),s=c(65840),t="function"==typeof i.default.unstable_postpone;function u(a){return{isDebugDynamicAccesses:a,dynamicAccesses:[],syncDynamicErrorWithStack:null}}function v(){return{hasSuspenseAboveBody:!1,hasDynamicMetadata:!1,dynamicMetadata:null,hasDynamicViewport:!1,hasAllowedDynamic:!1,dynamicErrors:[]}}function w(a){var b;return null==(b=a.dynamicAccesses[0])?void 0:b.expression}function x(a,b,c){if(b)switch(b.type){case"cache":case"unstable-cache":case"private-cache":return}if(!a.forceDynamic&&!a.forceStatic){if(a.dynamicShouldError)throw Object.defineProperty(new k.StaticGenBailoutError(`Route ${a.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${c}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E553",enumerable:!1,configurable:!0});if(b)switch(b.type){case"prerender-ppr":return E(a.route,c,b.dynamicTracking);case"prerender-legacy":b.revalidate=0;let d=Object.defineProperty(new j.DynamicServerError(`Route ${a.route} couldn't be rendered statically because it used ${c}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`),"__NEXT_ERROR_CODE",{value:"E550",enumerable:!1,configurable:!0});throw a.dynamicUsageDescription=c,a.dynamicUsageStack=d.stack,d}}}function y(a,b,c){let d=Object.defineProperty(new j.DynamicServerError(`Route ${b.route} couldn't be rendered statically because it used \`${a}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`),"__NEXT_ERROR_CODE",{value:"E558",enumerable:!1,configurable:!0});throw c.revalidate=0,b.dynamicUsageDescription=a,b.dynamicUsageStack=d.stack,d}function z(a){switch(a.type){case"cache":case"unstable-cache":case"private-cache":return}}function A(a,b,c){let d=J(`Route ${a} needs to bail out of prerendering at this point because it used ${b}.`);c.controller.abort(d);let e=c.dynamicTracking;e&&e.dynamicAccesses.push({stack:e.isDebugDynamicAccesses?Error().stack:void 0,expression:b})}function B(a,b,c,d){let e=d.dynamicTracking;A(a,b,d),e&&null===e.syncDynamicErrorWithStack&&(e.syncDynamicErrorWithStack=c)}function C(a,b,c,d){if(!1===d.controller.signal.aborted){A(a,b,d);let e=d.dynamicTracking;e&&null===e.syncDynamicErrorWithStack&&(e.syncDynamicErrorWithStack=c)}throw J(`Route ${a} needs to bail out of prerendering at this point because it used ${b}.`)}function D({reason:a,route:b}){let c=l.workUnitAsyncStorage.getStore();E(b,a,c&&"prerender-ppr"===c.type?c.dynamicTracking:null)}function E(a,b,c){(function(){if(!t)throw Object.defineProperty(Error("Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E224",enumerable:!1,configurable:!0})})(),c&&c.dynamicAccesses.push({stack:c.isDebugDynamicAccesses?Error().stack:void 0,expression:b}),i.default.unstable_postpone(F(a,b))}function F(a,b){return`Route ${a} needs to bail out of prerendering at this point because it used ${b}. React throws this special object to indicate where. It should not be caught by your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`}function G(a){return"object"==typeof a&&null!==a&&"string"==typeof a.message&&H(a.message)}function H(a){return a.includes("needs to bail out of prerendering at this point because it used")&&a.includes("Learn more: https://nextjs.org/docs/messages/ppr-caught-error")}if(!1===H(F("%%%","^^^")))throw Object.defineProperty(Error("Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E296",enumerable:!1,configurable:!0});let I="NEXT_PRERENDER_INTERRUPTED";function J(a){let b=Object.defineProperty(Error(a),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return b.digest=I,b}function K(a){return"object"==typeof a&&null!==a&&a.digest===I&&"name"in a&&"message"in a&&a instanceof Error}function L(a){return a.length>0}function M(a,b){return a.dynamicAccesses.push(...b.dynamicAccesses),a.dynamicAccesses}function N(a){return a.filter(a=>"string"==typeof a.stack&&a.stack.length>0).map(({expression:a,stack:b})=>(b=b.split("\n").slice(4).filter(a=>!(a.includes("node_modules/next/")||a.includes(" (<anonymous>)")||a.includes(" (node:"))).join("\n"),`Dynamic API Usage Debug - ${a}:
|
|
2
|
+
${b}`))}function O(){let a=new AbortController;return a.abort(Object.defineProperty(new q.BailoutToCSRError("Render in Browser"),"__NEXT_ERROR_CODE",{value:"E721",enumerable:!1,configurable:!0})),a.signal}function P(a){switch(a.type){case"prerender":case"prerender-runtime":let b=new AbortController;if(a.cacheSignal)a.cacheSignal.inputReady().then(()=>{b.abort()});else if("prerender-runtime"===a.type&&a.stagedRendering){let{stagedRendering:c}=a;c.waitForStage((0,n.getRuntimeStage)(c)).then(()=>(0,p.scheduleOnNextTick)(()=>b.abort()))}else(0,p.scheduleOnNextTick)(()=>b.abort());return b.signal;case"prerender-client":case"validation-client":case"prerender-ppr":case"prerender-legacy":case"request":case"cache":case"private-cache":case"unstable-cache":case"generate-static-params":return}}function Q(a,b){let c=b.dynamicTracking;c&&c.dynamicAccesses.push({stack:c.isDebugDynamicAccesses?Error().stack:void 0,expression:a})}function R(a){let b=m.workAsyncStorage.getStore(),c=l.workUnitAsyncStorage.getStore();if(b&&c)switch(c.type){case"prerender-client":case"prerender":{let d=c.fallbackRouteParams;d&&d.size>0&&i.default.use((0,n.makeHangingPromise)(c.renderSignal,b.route,a));break}case"prerender-ppr":{let d=c.fallbackRouteParams;if(d&&d.size>0)return E(b.route,a,c.dynamicTracking);break}case"validation-client":case"prerender-legacy":case"request":case"unstable-cache":break;case"prerender-runtime":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called during a runtime prerender. Next.js should be preventing ${a} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E771",enumerable:!1,configurable:!0});case"cache":case"private-cache":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called inside a cache scope. Next.js should be preventing ${a} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E745",enumerable:!1,configurable:!0});case"generate-static-params":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called in \`generateStaticParams\`. Next.js should be preventing ${a} from being included in server component files statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E1130",enumerable:!1,configurable:!0})}}function S(a){let b=m.workAsyncStorage.getStore(),c=l.workUnitAsyncStorage.getStore();if(b)switch(!c&&(0,l.throwForMissingRequestStore)(a),c.type){case"validation-client":case"request":return;case"prerender-client":i.default.use((0,n.makeHangingPromise)(c.renderSignal,b.route,a));break;case"prerender-legacy":case"prerender-ppr":if(b.forceStatic)return;throw Object.defineProperty(new q.BailoutToCSRError(a),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});case"prerender":case"prerender-runtime":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called from a Server Component. Next.js should be preventing ${a} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E795",enumerable:!1,configurable:!0});case"cache":case"unstable-cache":case"private-cache":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called inside a cache scope. Next.js should be preventing ${a} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E745",enumerable:!1,configurable:!0});case"generate-static-params":throw Object.defineProperty(new r.InvariantError(`\`${a}\` was called in \`generateStaticParams\`. Next.js should be preventing ${a} from being included in server component files statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E1130",enumerable:!1,configurable:!0})}}let T=/\n\s+at Suspense \(<anonymous>\)/,U=RegExp(`\\n\\s+at Suspense \\(<anonymous>\\)(?:(?!\\n\\s+at (?:body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6) \\(<anonymous>\\))[\\s\\S])*?\\n\\s+at ${o.ROOT_LAYOUT_BOUNDARY_NAME} \\([^\\n]*\\)`),V=RegExp(`\\n\\s+at ${o.METADATA_BOUNDARY_NAME}[\\n\\s]`),W=RegExp(`\\n\\s+at ${o.VIEWPORT_BOUNDARY_NAME}[\\n\\s]`),X=RegExp(`\\n\\s+at ${o.OUTLET_BOUNDARY_NAME}[\\n\\s]`),Y=RegExp(`\\n\\s+at ${s.INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]`);function Z(a,b,c,d){if(!X.test(b)){if(V.test(b)){c.hasDynamicMetadata=!0;return}if(W.test(b)){c.hasDynamicViewport=!0;return}if(U.test(b)){c.hasAllowedDynamic=!0,c.hasSuspenseAboveBody=!0;return}else if(T.test(b)){c.hasAllowedDynamic=!0;return}else{if(d.syncDynamicErrorWithStack)return void c.dynamicErrors.push(d.syncDynamicErrorWithStack);let e=ae(Object.defineProperty(Error(`Route "${a.route}": Uncached data was accessed outside of <Suspense>. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`),"__NEXT_ERROR_CODE",{value:"E1079",enumerable:!1,configurable:!0}),b,null);return void c.dynamicErrors.push(e)}}}var $=((e={})[e.Runtime=1]="Runtime",e[e.Dynamic=2]="Dynamic",e);function _(a){return{hasDynamicMetadata:!1,hasAllowedClientDynamicAboveBoundary:!1,dynamicMetadata:null,hasDynamicViewport:!1,hasAllowedDynamic:!1,dynamicErrors:[],validationPreventingErrors:[],thrownErrorsOutsideBoundary:[],createInstantStack:a}}function aa(a,b,c,d,e,f){if(X.test(b))return;if(V.test(b)){let d=ae(Object.defineProperty(Error(`Route "${a.route}": ${1===e?"Runtime data such as `cookies()`, `headers()`, `params`, or `searchParams` was accessed inside `generateMetadata` or you have file-based metadata such as icons that depend on dynamic params segments.":"Uncached data or `connection()` was accessed inside `generateMetadata`."} Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`),"__NEXT_ERROR_CODE",{value:"E1076",enumerable:!1,configurable:!0}),b,c.createInstantStack);c.dynamicMetadata=d;return}if(W.test(b)){let d=ae(Object.defineProperty(Error(`Route "${a.route}": ${1===e?"Runtime data such as `cookies()`, `headers()`, `params`, or `searchParams` was accessed inside `generateViewport`.":"Uncached data or `connection()` was accessed inside `generateViewport`."} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`),"__NEXT_ERROR_CODE",{value:"E1086",enumerable:!1,configurable:!0}),b,c.createInstantStack);c.dynamicErrors.push(d);return}let g=Y.exec(b);if(g){let a=T.exec(b);if(a&&a.index<g.index){c.hasAllowedDynamic=!0;return}}else if(f.expectedIds.size===f.renderedIds.size){c.hasAllowedClientDynamicAboveBoundary=!0,c.hasAllowedDynamic=!0;return}else{let d=ae(Object.defineProperty(Error(`Route "${a.route}": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.`),"__NEXT_ERROR_CODE",{value:"E1082",enumerable:!1,configurable:!0}),b,c.createInstantStack);c.validationPreventingErrors.push(d);return}if(d.syncDynamicErrorWithStack){let a=d.syncDynamicErrorWithStack;null!==c.createInstantStack&&void 0===a.cause&&(a.cause=c.createInstantStack()),c.dynamicErrors.push(a);return}let h=ae(Object.defineProperty(Error(`Route "${a.route}": ${1===e?"Runtime data such as `cookies()`, `headers()`, `params`, or `searchParams` was accessed outside of `<Suspense>`.":"Uncached data or `connection()` was accessed outside of `<Suspense>`."} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`),"__NEXT_ERROR_CODE",{value:"E1078",enumerable:!1,configurable:!0}),b,c.createInstantStack);c.dynamicErrors.push(h)}function ab(a,b,c,d){let e=Y.exec(d);if(e){let f=T.exec(d);if(f&&f.index<e.index)return;let g=ae(Object.defineProperty(Error(`Route "${a.route}": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.`,{cause:c}),"__NEXT_ERROR_CODE",{value:"E1112",enumerable:!1,configurable:!0}),d,null);b.validationPreventingErrors.push(g)}else{let a=ae(Object.defineProperty(Error("An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.",{cause:c}),"__NEXT_ERROR_CODE",{value:"E1118",enumerable:!1,configurable:!0}),d,null);b.thrownErrorsOutsideBoundary.push(a)}}function ac(a,b,c,d){if(X.test(b))return;if(V.test(b)){c.dynamicMetadata=ae(Object.defineProperty(Error(`Route "${a.route}": Uncached data or \`connection()\` was accessed inside \`generateMetadata\`. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`),"__NEXT_ERROR_CODE",{value:"E1080",enumerable:!1,configurable:!0}),b,null);return}if(W.test(b)){let d=ae(Object.defineProperty(Error(`Route "${a.route}": Uncached data or \`connection()\` was accessed inside \`generateViewport\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`),"__NEXT_ERROR_CODE",{value:"E1077",enumerable:!1,configurable:!0}),b,null);c.dynamicErrors.push(d);return}if(U.test(b)){c.hasAllowedDynamic=!0,c.hasSuspenseAboveBody=!0;return}if(T.test(b)){c.hasAllowedDynamic=!0;return}else if(d.syncDynamicErrorWithStack)return void c.dynamicErrors.push(d.syncDynamicErrorWithStack);let e=ae(Object.defineProperty(Error(`Route "${a.route}": Uncached data or \`connection()\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`),"__NEXT_ERROR_CODE",{value:"E1084",enumerable:!1,configurable:!0}),b,null);c.dynamicErrors.push(e)}function ad(a,b,c,d){if(!X.test(b)){if(V.test(b)){c.dynamicMetadata=ae(Object.defineProperty(Error(`Route "${a.route}": Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed inside \`generateMetadata\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`),"__NEXT_ERROR_CODE",{value:"E1085",enumerable:!1,configurable:!0}),b,null);return}if(W.test(b)){let d=ae(Object.defineProperty(Error(`Route "${a.route}": Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed inside \`generateViewport\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`),"__NEXT_ERROR_CODE",{value:"E1081",enumerable:!1,configurable:!0}),b,null);c.dynamicErrors.push(d);return}if(U.test(b)){c.hasAllowedDynamic=!0,c.hasSuspenseAboveBody=!0;return}else if(T.test(b)){c.hasAllowedDynamic=!0;return}else{if(d.syncDynamicErrorWithStack)return void c.dynamicErrors.push(d.syncDynamicErrorWithStack);let e=ae(Object.defineProperty(Error(`Route "${a.route}": Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`),"__NEXT_ERROR_CODE",{value:"E1083",enumerable:!1,configurable:!0}),b,null);return void c.dynamicErrors.push(e)}}}function ae(a,b,c){return null!==c&&(a.cause=c()),a.stack=a.name+": "+a.message+b,a}var af=((f={})[f.Full=0]="Full",f[f.Empty=1]="Empty",f[f.Errored=2]="Errored",f);function ag(a,b){console.error(b),console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:
|
|
3
|
+
- Start the app in development mode by running \`next dev\`, then open "${a.route}" in your browser to investigate the error.
|
|
4
|
+
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.`)}function ah(a,b,c,d){if(d.syncDynamicErrorWithStack)throw ag(a,d.syncDynamicErrorWithStack),new k.StaticGenBailoutError;if(0!==b){if(c.hasSuspenseAboveBody)return;let d=c.dynamicErrors;if(d.length>0){for(let b=0;b<d.length;b++)ag(a,d[b]);throw new k.StaticGenBailoutError}if(c.hasDynamicViewport)throw console.error(`Route "${a.route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or uncached external data (\`fetch(...)\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`),new k.StaticGenBailoutError;if(1===b)throw console.error(`Route "${a.route}" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`),new k.StaticGenBailoutError}else if(!1===c.hasAllowedDynamic&&c.hasDynamicMetadata)throw console.error(`Route "${a.route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or uncached external data (\`fetch(...)\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`),new k.StaticGenBailoutError}function ai(a,b,c,d){if(d||c.hasSuspenseAboveBody)return[];if(0!==b){let d=c.dynamicErrors;if(d.length>0)return d;if(1===b)return[Object.defineProperty(new r.InvariantError(`Route "${a.route}" did not produce a static shell and Next.js was unable to determine a reason.`),"__NEXT_ERROR_CODE",{value:"E936",enumerable:!1,configurable:!0})]}else if(!1===c.hasAllowedDynamic&&0===c.dynamicErrors.length&&c.dynamicMetadata)return[c.dynamicMetadata];return[]}function aj(a,b,c,d,e){if(d){let{missingSampleErrors:a}=d;if(a.length>0)return a}let{validationPreventingErrors:f}=c;if(f.length>0)return f;if(e.renderedIds.size<e.expectedIds.size){let{thrownErrorsOutsideBoundary:b,createInstantStack:d}=c;if(0===b.length){let b=`Route "${a.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.`,c=null!==d?d():Error();return c.name="Error",c.message=b,[c]}if(1===b.length){let c=`Route "${a.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.`,e=null!==d?d():Error();return e.name="Error",e.message=c,[e,b[0]]}{let c=`Route "${a.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to one of the following errors.`,e=null!==d?d():Error();return e.name="Error",e.message=c,[e,...b]}}if(0!==b){let d=c.dynamicErrors;if(d.length>0)return d;if(1===b)return c.hasAllowedClientDynamicAboveBoundary?[]:[Object.defineProperty(new r.InvariantError(`Route "${a.route}" failed to render during instant validation and Next.js was unable to determine a reason.`),"__NEXT_ERROR_CODE",{value:"E1055",enumerable:!1,configurable:!0})]}else{let a=c.dynamicErrors;if(a.length>0)return a;if(!1===c.hasAllowedDynamic&&c.dynamicMetadata)return[c.dynamicMetadata]}return[]}},4224:(a,b,c)=>{"use strict";c.d(b,{v:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"ListNode"===a.kind,create:a=>(0,d.CN)({kind:"ListNode",items:(0,d.CN)(a)})})},4432:(a,b,c)=>{"use strict";c.d(b,{y:()=>f});var d=c(18110),e=c(98051);let f=(0,d.CN)({is:a=>"SchemableIdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"SchemableIdentifierNode",identifier:e.O.create(a)}),createWithSchema:(a,b)=>(0,d.CN)({kind:"SchemableIdentifierNode",schema:e.O.create(a),identifier:e.O.create(b)})})},4592:(a,b,c)=>{"use strict";Object.defineProperty(b,"U",{enumerable:!0,get:function(){return n}});let d=c(23656),e=c(29033),f=c(29294),g=c(63033),h=c(4190),i=c(27130),j=c(87143),k=c(55713),l=c(13370),m=c(85556);function n(){let a="cookies",b=f.workAsyncStorage.getStore(),c=g.workUnitAsyncStorage.getStore();if(b){if(c&&"after"===c.phase&&!(0,l.isRequestAPICallableInsideAfter)())throw Object.defineProperty(Error(`Route ${b.route} used \`cookies()\` inside \`after()\`. This is not supported. If you need this data inside an \`after()\` callback, use \`cookies()\` outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after`),"__NEXT_ERROR_CODE",{value:"E843",enumerable:!1,configurable:!0});if(b.forceStatic)return p(d.RequestCookiesAdapter.seal(new e.RequestCookies(new Headers({}))));if(b.dynamicShouldError)throw Object.defineProperty(new i.StaticGenBailoutError(`Route ${b.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E849",enumerable:!1,configurable:!0});if(c)switch(c.type){case"cache":let f=Object.defineProperty(Error(`Route ${b.route} used \`cookies()\` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`cookies()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E831",enumerable:!1,configurable:!0});throw Error.captureStackTrace(f,n),b.invalidDynamicUsageError??=f,f;case"unstable-cache":throw Object.defineProperty(Error(`Route ${b.route} used \`cookies()\` inside a function cached with \`unstable_cache()\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`cookies()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`),"__NEXT_ERROR_CODE",{value:"E846",enumerable:!1,configurable:!0});case"generate-static-params":throw Object.defineProperty(Error(`Route ${b.route} used \`cookies()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`),"__NEXT_ERROR_CODE",{value:"E1123",enumerable:!1,configurable:!0});case"prerender":var k=b,q=c;let r=o.get(q);if(r)return r;let s=(0,j.makeHangingPromise)(q.renderSignal,k.route,"`cookies()`");return o.set(q,s),s;case"prerender-client":case"validation-client":let t="`cookies`";throw Object.defineProperty(new m.InvariantError(`${t} must not be used within a Client Component. Next.js should be preventing ${t} from being included in Client Components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E1037",enumerable:!1,configurable:!0});case"prerender-ppr":return(0,h.postponeWithTracking)(b.route,a,c.dynamicTracking);case"prerender-legacy":return(0,h.throwToInterruptStaticGeneration)(a,b,c);case"prerender-runtime":return(0,j.delayUntilRuntimeStage)(c,p(c.cookies));case"private-cache":return p(c.cookies);case"request":let u;if((0,h.trackDynamicDataInDynamicRender)(c),u=(0,d.areCookiesMutableInCurrentPhase)(c)?c.userspaceMutableCookies:c.cookies,!c.asyncApiPromises)return p(u);{let a=(0,g.isInEarlyRenderStage)(c);if(u===c.mutableCookies)return a?c.asyncApiPromises.earlyMutableCookies:c.asyncApiPromises.mutableCookies;return a?c.asyncApiPromises.earlyCookies:c.asyncApiPromises.cookies}}}(0,g.throwForMissingRequestStore)(a)}c(94931);let o=new WeakMap;function p(a){let b=o.get(a);if(b)return b;let c=Promise.resolve(a);return o.set(a,c),c}(0,k.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`cookies()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E830",enumerable:!1,configurable:!0})})},5020:(a,b,c)=>{"use strict";let d=c(63033),e=c(29294),f=c(4190),g=c(55713),h=c(27130),i=c(96690),j=c(85556),k=c(87143);c(63574);new WeakMap;(0,g.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`draftMode()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E835",enumerable:!1,configurable:!0})})},5496:(a,b,c)=>{"use strict";c.d(b,{Gq:()=>p,UH:()=>n,Xm:()=>o,zX:()=>m});var d=c(18110);let e=(0,d.CN)({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0});Object.keys(e);let f=(0,d.CN)({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(f);let g=(0,d.CN)({"->":!0,"->>":!0}),h=Object.keys(g),i=(0,d.CN)({...e,...f,"||":!0}),j=Object.keys(i),k=(0,d.CN)({exists:!0,"not exists":!0});Object.keys(k);let l=(0,d.CN)({...k,"-":!0,not:!0});[...j,...h,...Object.keys(l)];let m=(0,d.CN)({is:a=>"OperatorNode"===a.kind,create:a=>(0,d.CN)({kind:"OperatorNode",operator:a})});function n(a){return(0,d.Kg)(a)&&i[a]}function o(a){return(0,d.Kg)(a)&&g[a]}function p(a){return(0,d.Kg)(a)&&l[a]}},5568:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={NextRequestAdapter:function(){return n},ResponseAborted:function(){return k},ResponseAbortedName:function(){return j},createAbortController:function(){return l},signalFromNodeResponse:function(){return m}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(97762),g=c(61259),h=c(13607),i=c(77509),j="ResponseAborted";class k extends Error{constructor(...a){super(...a),this.name=j}}function l(a){let b=new AbortController;return a.once("close",()=>{a.writableFinished||b.abort(new k)}),b}function m(a){let{errored:b,destroyed:c}=a;if(b||c)return AbortSignal.abort(b??new k);let{signal:d}=l(a);return d}class n{static fromBaseNextRequest(a,b){if((0,i.isNodeNextRequest)(a))return n.fromNodeNextRequest(a,b);throw Object.defineProperty(Error("Invariant: Unsupported NextRequest type"),"__NEXT_ERROR_CODE",{value:"E345",enumerable:!1,configurable:!0})}static fromNodeNextRequest(a,b){let c,d=null;if("GET"!==a.method&&"HEAD"!==a.method&&a.body&&(d=a.body),a.url.startsWith("http"))c=new URL(a.url);else{let b=(0,f.getRequestMeta)(a,"initURL");c=b&&b.startsWith("http")?new URL(a.url,b):new URL(a.url,"http://n")}return new h.NextRequest(c,{method:a.method,headers:(0,g.fromNodeOutgoingHttpHeaders)(a.headers),duplex:"half",signal:b,...b.aborted?{}:{body:d}})}static fromWebNextRequest(a){let b=null;return"GET"!==a.method&&"HEAD"!==a.method&&(b=a.body),new h.NextRequest(a.url,{method:a.method,headers:(0,g.fromNodeOutgoingHttpHeaders)(a.headers),duplex:"half",signal:a.request.signal,...a.request.signal.aborted?{}:{body:b}})}}},5590:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"ReadonlyURLSearchParams",{enumerable:!0,get:function(){return d}});class c extends Error{constructor(){super("Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams")}}class d extends URLSearchParams{append(){throw new c}delete(){throw new c}set(){throw new c}sort(){throw new c}}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},6228:(a,b,c)=>{"use strict";c.d(b,{E:()=>g});var d=c(80184),e=c(18110),f=c(19105);let g=(0,e.CN)({raw:(a,b=[])=>(0,e.CN)({sql:a,query:d.z.createWithSql(a),parameters:(0,e.CN)(b),queryId:(0,f.a)()})})},6292:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"addPathSuffix",{enumerable:!0,get:function(){return e}});let d=c(39098);function e(a,b){if(!a.startsWith("/")||!b)return a;let{pathname:c,query:e,hash:f}=(0,d.parsePath)(a);return`${c}${b}${e}${f}`}},6840:(a,b,c)=>{"use strict";c.d(b,{d3:()=>g,dS:()=>j,iD:()=>i,vp:()=>h});var d=c(79953),e=c(34248);let f=async()=>{let a=(0,d.Q)();if(!a.context.adapterAsyncStorage){let b=await (0,e.V)();a.context.adapterAsyncStorage=new b}return a.context.adapterAsyncStorage},g=async a=>f().then(b=>b.getStore()?.adapter||a).catch(()=>a),h=async(a,b)=>{let c=!1;return f().then(async d=>{let e,f;c=!0;let g=[],h=!1;try{e=await d.run({adapter:a,pendingHooks:g,isTransactionActive:!1},b)}catch(a){f=a,h=!0}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},i=async(a,b)=>{let c=!1;return f().then(async d=>{let e,f;if(c=!0,d.getStore()?.isTransactionActive)return b();let g=[],h=!1;try{e=await a.transaction(async a=>d.run({adapter:a,pendingHooks:g,isTransactionActive:!0},b))}catch(a){h=!0,f=a}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},j=async a=>f().then(b=>{let c=b.getStore();if(!c)return a();c.pendingHooks.push(a)}).catch(()=>a())},7656:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={bootstrap:function(){return k},error:function(){return m},errorOnce:function(){return v},event:function(){return q},info:function(){return p},prefixes:function(){return h},ready:function(){return o},trace:function(){return r},wait:function(){return l},warn:function(){return n},warnOnce:function(){return t}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(65928),g=c(68877),h={wait:(0,f.white)((0,f.bold)("○")),error:(0,f.red)((0,f.bold)("⨯")),warn:(0,f.yellow)((0,f.bold)("⚠")),ready:"▲",info:(0,f.white)((0,f.bold)(" ")),event:(0,f.green)((0,f.bold)("✓")),trace:(0,f.magenta)((0,f.bold)("\xbb"))},i={log:"log",warn:"warn",error:"error"};function j(a,...b){(""===b[0]||void 0===b[0])&&1===b.length&&b.shift();let c=a in i?i[a]:"log",d=h[a];0===b.length?console[c](""):1===b.length&&"string"==typeof b[0]?console[c](d+" "+b[0]):console[c](d,...b)}function k(a){console.log(a)}function l(...a){j("wait",...a)}function m(...a){j("error",...a)}function n(...a){j("warn",...a)}function o(...a){j("ready",...a)}function p(...a){j("info",...a)}function q(...a){j("event",...a)}function r(...a){j("trace",...a)}let s=new g.LRUCache(1e4,a=>a.length);function t(...a){let b=a.join(" ");s.has(b)||(s.set(b,b),n(...a))}let u=new g.LRUCache(1e4,a=>a.length);function v(...a){let b=a.join(" ");u.has(b)||(u.set(b,b),m(...a))}},8586:(a,b,c)=>{"use strict";c.d(b,{n:()=>ap});var d,e,f=c(60266),g=c(46489),h=c(37626),i=c(26144),j=c(90588),k=c(18110),l=c(2929);let m=(0,k.CN)({is:a=>"ValuesNode"===a.kind,create:a=>(0,k.CN)({kind:"ValuesNode",values:(0,k.CN)(a)})});var n=c(37338);let o=(0,k.CN)({is:a=>"DefaultInsertValueNode"===a.kind,create:()=>(0,k.CN)({kind:"DefaultInsertValueNode"})});var p=c(80627);function q(a){var b;let c,d=(0,k.Tn)(a)?a((0,p.A)()):a;return c=function(a){let b=new Map;for(let c of a)for(let a of Object.keys(c))b.has(a)||void 0===c[a]||b.set(a,b.size);return b}(b=(0,k.MH)(d)?d:(0,k.CN)([d])),[(0,k.CN)([...c.keys()].map(h.Z.create)),m.create(b.map(a=>(function(a,b){let c=Object.keys(a),d=Array.from({length:b.size}),e=!1,f=c.length;for(let g of c){let c=b.get(g);if((0,k.b0)(c)){f--;continue}let h=a[g];((0,k.b0)(h)||(0,n.SS)(h))&&(e=!0),d[c]=h}if(f<b.size||e){let a=o.create();return j.s.create(d.map(b=>(0,k.b0)(b)?a:(0,l.$s)(b)))}return i.h.create(d)})(a,c)))]}var r=c(91408),s=c(87301);let t=(0,k.CN)({is:a=>"ColumnUpdateNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"ColumnUpdateNode",column:a,value:b})});var u=c(45541);function v(a){return Object.entries((0,k.Tn)(a)?a((0,p.A)()):a).filter(([a,b])=>void 0!==b).map(([a,b])=>t.create(h.Z.create(a),(0,l.$s)(b)))}let w=(0,k.CN)({is:a=>"OnDuplicateKeyNode"===a.kind,create:a=>(0,k.CN)({kind:"OnDuplicateKeyNode",updates:a})});class x{insertId;numInsertedOrUpdatedRows;constructor(a,b){this.insertId=a,this.numInsertedOrUpdatedRows=b}}var y=c(38199),z=c(98051),A=c(21513);let B=(0,k.CN)({is:a=>"OnConflictNode"===a.kind,create:()=>(0,k.CN)({kind:"OnConflictNode"}),cloneWith:(a,b)=>(0,k.CN)({...a,...b}),cloneWithIndexWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"And",b):A.o.create(b)}),cloneWithIndexOrWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"Or",b):A.o.create(b)}),cloneWithUpdateWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"And",b):A.o.create(b)}),cloneWithUpdateOrWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"Or",b):A.o.create(b)}),cloneWithoutIndexWhere:a=>(0,k.CN)({...a,indexWhere:void 0}),cloneWithoutUpdateWhere:a=>(0,k.CN)({...a,updateWhere:void 0})});var C=c(31341);class D{#a;constructor(a){this.#a=(0,k.CN)(a)}column(a){let b=h.Z.create(a);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,b]):(0,k.CN)([b])})})}columns(a){let b=a.map(h.Z.create);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,...b]):(0,k.CN)(b)})})}constraint(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{constraint:z.O.create(a)})})}expression(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{indexExpression:a.toOperationNode()})})}where(...a){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new D({...this.#a,onConflictNode:B.cloneWithoutIndexWhere(this.#a.onConflictNode)})}doNothing(){return new E({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{doNothing:!0})})}doUpdateSet(a){return new F({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{updates:v(a)})})}$call(a){return a(this)}}class E{#a;constructor(a){this.#a=(0,k.CN)(a)}toOperationNode(){return this.#a.onConflictNode}}class F{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new F({...this.#a,onConflictNode:B.cloneWithoutUpdateWhere(this.#a.onConflictNode)})}$call(a){return a(this)}toOperationNode(){return this.#a.onConflictNode}}var G=c(80848);let H=(0,k.CN)({is:a=>"OrActionNode"===a.kind,create:a=>(0,k.CN)({kind:"OrActionNode",action:a})});class I{#a;constructor(a){this.#a=(0,k.CN)(a)}values(a){let[b,c]=q(a);return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:b,values:c})})}columns(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:(0,k.CN)(a.map(h.Z.create))})})}expression(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{values:(0,n.YK)(a)})})}defaultValues(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{defaultValues:!0})})}modifyEnd(a){return new I({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}ignore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orIgnore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orAbort(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("abort")})})}orFail(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("fail")})})}orReplace(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("replace")})})}orRollback(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("rollback")})})}top(a,b){return new I({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}onConflict(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onConflict:a(new D({onConflictNode:B.create()})).toOperationNode()})})}onDuplicateKeyUpdate(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onDuplicateKey:w.create(v(a))})})}returning(a){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)())})}output(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new I({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new I({...this.#a})}$castTo(){return new I(this.#a)}$narrowType(){return new I(this.#a)}$assertType(){return new I(this.#a)}withPlugin(a){return new I({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){let b=this.compile(),c=await this.#a.executor.executeQuery(b,a),{adapter:d}=this.#a.executor,e=b.query;return e.returning&&d.supportsReturning||e.output&&d.supportsOutput?c.rows:[new x(c.insertId,c.numAffectedRows??BigInt(0))]}async executeTakeFirst(a){let[b]=await this.execute(a);return b}async executeTakeFirstOrThrow(a){"function"==typeof a&&(a={errorConstructor:a});let b=await this.executeTakeFirst(a);if(void 0===b){let b=a?.errorConstructor??y.F;throw(0,y.x)(b)?new b(this.toOperationNode()):b(this.toOperationNode())}return b}async *stream(a){"object"!=typeof a&&(a={chunkSize:a});let b=this.compile();for await(let c of this.#a.executor.stream(b,a.chunkSize??100,a))yield*c.rows}async explain(a,b){let c=new I({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}var J=c(36688),K=c(27800);class L{numDeletedRows;constructor(a){this.numDeletedRows=a}}var M=c(22046),N=c(64829),O=c(10611);class P{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new d({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new d({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(a){return new d({...this.#a,queryNode:M.e.cloneWithUsing(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#b("InnerJoin",a)}leftJoin(...a){return this.#b("LeftJoin",a)}rightJoin(...a){return this.#b("RightJoin",a)}fullJoin(...a){return this.#b("FullJoin",a)}#b(a,b){return new d({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}returning(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new d({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:M.e.cloneWithoutLimit(this.#a.queryNode)})}orderBy(...a){return new d({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new d({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new d({...this.#a,queryNode:M.e.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}modifyEnd(a){return new d({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){let b=this.compile(),c=await this.#a.executor.executeQuery(b,a),{adapter:d}=this.#a.executor,e=b.query;return e.returning&&d.supportsReturning||e.output&&d.supportsOutput?c.rows:[new L(c.numAffectedRows??BigInt(0))]}async executeTakeFirst(a){let[b]=await this.execute(a);return b}async executeTakeFirstOrThrow(a){"function"==typeof a&&(a={errorConstructor:a});let b=await this.executeTakeFirst(a);if(void 0===b){let b=a?.errorConstructor??y.F;throw(0,y.x)(b)?new b(this.toOperationNode()):b(this.toOperationNode())}return b}async *stream(a){"object"!=typeof a&&(a={chunkSize:a});let b=this.compile();for await(let c of this.#a.executor.stream(b,a.chunkSize??100,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}d=P;var Q=c(69832);class R{numUpdatedRows;numChangedRows;constructor(a,b){this.numUpdatedRows=a,this.numChangedRows=b}}class S{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new e({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new e({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}from(a){return new e({...this.#a,queryNode:Q.U.cloneWithFromItems(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#b("InnerJoin",a)}leftJoin(...a){return this.#b("LeftJoin",a)}rightJoin(...a){return this.#b("RightJoin",a)}fullJoin(...a){return this.#b("FullJoin",a)}#b(a,b){return new e({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}orderBy(...a){return new e({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new e({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new e({...this.#a,queryNode:Q.U.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}set(...a){return new e({...this.#a,queryNode:Q.U.cloneWithUpdates(this.#a.queryNode,function(...a){return 2===a.length?[t.create((0,u.$O)(a[0]),(0,l.$s)(a[1]))]:v(a[0])}(...a))})}returning(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}modifyEnd(a){return new e({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}clearReturning(){return new e({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new e({...this.#a})}$castTo(){return new e(this.#a)}$narrowType(){return new e(this.#a)}$assertType(){return new e(this.#a)}withPlugin(a){return new e({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){let b=this.compile(),c=await this.#a.executor.executeQuery(b,a),{adapter:d}=this.#a.executor,e=b.query;return e.returning&&d.supportsReturning||e.output&&d.supportsOutput?c.rows:[new R(c.numAffectedRows??BigInt(0),c.numChangedRows)]}async executeTakeFirst(a){let[b]=await this.execute(a);return b}async executeTakeFirstOrThrow(a){"function"==typeof a&&(a={errorConstructor:a});let b=await this.executeTakeFirst(a);if(void 0===b){let b=a?.errorConstructor??y.F;throw(0,y.x)(b)?new b(this.toOperationNode()):b(this.toOperationNode())}return b}async *stream(a){"object"!=typeof a&&(a={chunkSize:a});let b=this.compile();for await(let c of this.#a.executor.stream(b,a.chunkSize??100,a))yield*c.rows}async explain(a,b){let c=new e({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}e=S;var T=c(37694),U=c(3694);let V=(0,k.CN)({is:a=>"CommonTableExpressionNameNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNameNode",table:U.H.create(a),columns:b?(0,k.CN)(b.map(h.Z.create)):void 0})});var W=c(59916);let X=(0,k.CN)({is:a=>"CommonTableExpressionNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNode",name:a,expression:b}),cloneWith:(a,b)=>(0,k.CN)({...a,...b})});class Y{#a;constructor(a){this.#a=(0,k.CN)(a)}materialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!0})})}notMaterialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!1})})}toOperationNode(){return this.#a.node}}var Z=c(60351);function $(a,b){var c;let d=(0,Z.N)(b)?b.toOperationNode():b((0,W.bl)()).toOperationNode();return(0,k.Tn)(a)?a((c=d,a=>new Y({node:X.create(_(a),c)}))).toOperationNode():X.create(_(a),d)}function _(a){if(!a.includes("("))return V.create(a);{let b=a.split(/[\(\)]/),c=b[0],d=b[1].split(",").map(a=>a.trim());return V.create(c,d)}}let aa=(0,k.CN)({is:a=>"WithNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"WithNode",expressions:(0,k.CN)([a]),...b}),cloneWithExpression:(a,b)=>(0,k.CN)({...a,expressions:(0,k.CN)([...a.expressions,b])})});var ab=c(19105),ac=c(89192),ad=c(107);let ae=(0,k.CN)({is:a=>"MatchedNode"===a.kind,create:(a,b=!1)=>(0,k.CN)({kind:"MatchedNode",not:a,bySource:b})});var af=c(80184),ag=c(98444);function ah(a,b,c){return ag.t.create((0,C.KN)([ae.create(!a.isMatched,a.bySource),...b&&b.length>0?[3===b.length&&c?(0,C.vC)(b[0],b[1],b[2]):(0,C.GB)(b)]:[]],"and",!1))}function ai(a){return(0,k.Kg)(a)?af.z.create([a],[]):(0,Z.N)(a)?a.toOperationNode():a}var aj=c(24492);class ak{numChangedRows;constructor(a){this.numChangedRows=a}}class al{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new al({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new al({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(...a){return new am({...this.#a,queryNode:ad.r.cloneWithUsing(this.#a.queryNode,(0,J.a)("Using",a))})}returning(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}}class am{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new am({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new am({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}whenMatched(){return this.#c([])}whenMatchedAnd(...a){return this.#c(a)}whenMatchedAndRef(a,b,c){return this.#c([a,b,c],!0)}#c(a,b){return new an({...this.#a,queryNode:ad.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!0},a,b))})}whenNotMatched(){return this.#d([])}whenNotMatchedAnd(...a){return this.#d(a)}whenNotMatchedAndRef(a,b,c){return this.#d([a,b,c],!0)}whenNotMatchedBySource(){return this.#d([],!1,!0)}whenNotMatchedBySourceAnd(...a){return this.#d(a,!1,!0)}whenNotMatchedBySourceAndRef(a,b,c){return this.#d([a,b,c],!0,!0)}returning(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}#d(a,b=!1,c=!1){let d={...this.#a,queryNode:ad.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!1,bySource:c},a,b))};return new(c?an:ao)(d)}$call(a){return a(this)}$if(a,b){return a?b(this):new am({...this.#a})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){let b=this.compile(),c=await this.#a.executor.executeQuery(b,a),{adapter:d}=this.#a.executor,e=b.query;return e.returning&&d.supportsReturning||e.output&&d.supportsOutput?c.rows:[new ak(c.numAffectedRows)]}async executeTakeFirst(a){let[b]=await this.execute(a);return b}async executeTakeFirstOrThrow(a){"function"==typeof a&&(a={errorConstructor:a});let b=await this.executeTakeFirst(a);if(void 0===b){let b=a?.errorConstructor??y.F;throw(0,y.x)(b)?new b(this.toOperationNode()):b(this.toOperationNode())}return b}}class an{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDelete(){return new am({...this.#a,queryNode:ad.r.cloneWithThen(this.#a.queryNode,ai("delete"))})}thenDoNothing(){return new am({...this.#a,queryNode:ad.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenUpdate(a){return new am({...this.#a,queryNode:ad.r.cloneWithThen(this.#a.queryNode,ai(a(new S({queryId:this.#a.queryId,executor:aj.W,queryNode:Q.U.createWithoutTable()}))))})}thenUpdateSet(...a){return this.thenUpdate(b=>b.set(...a))}}class ao{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDoNothing(){return new am({...this.#a,queryNode:ad.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenInsertValues(a){let[b,c]=q(a);return new am({...this.#a,queryNode:ad.r.cloneWithThen(this.#a.queryNode,ai(r.o.cloneWith(r.o.createWithoutInto(),{columns:b,values:c})))})}}class ap{#a;constructor(a){this.#a=(0,k.CN)(a)}selectFrom(a){return(0,f.c)({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:T.L.createFrom((0,K.JB)(a),this.#a.withNode)})}selectNoFrom(a){return(0,f.c)({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:T.L.cloneWithSelections(T.L.create(this.#a.withNode),(0,g.G)(a))})}insertInto(a){return new I({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode)})}replaceInto(a){return new I({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode,!0)})}deleteFrom(a){return new P({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:M.e.create((0,K.JB)(a),this.#a.withNode)})}updateTable(a){return new S({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:Q.U.create((0,K.JB)(a),this.#a.withNode)})}mergeInto(a){return new al({queryId:(0,ab.a)(),executor:this.#a.executor,queryNode:ad.r.create((0,K.Xm)(a),this.#a.withNode)})}with(a,b){let c=$(a,b);return new ap({...this.#a,withNode:this.#a.withNode?aa.cloneWithExpression(this.#a.withNode,c):aa.create(c)})}withRecursive(a,b){let c=$(a,b);return new ap({...this.#a,withNode:this.#a.withNode?aa.cloneWithExpression(this.#a.withNode,c):aa.create(c,{recursive:!0})})}withPlugin(a){return new ap({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new ap({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new ap({...this.#a,executor:this.#a.executor.withPluginAtFront(new ac.B(a))})}}},8932:(a,b,c)=>{var d=c(25296),e=d.Constants;a.exports=function(){var a=0,b=0,c=0,f=0,g=0;return{get diskEntries(){return a},set diskEntries(val){a=b=val},get totalEntries(){return b},set totalEntries(val){b=a=val},get size(){return c},set size(val){c=val},get offset(){return f},set offset(val){f=val},get commentLength(){return g},set commentLength(val){g=val},get mainHeaderSize(){return e.ENDHDR+g},loadFromBinary:function(h){if((h.length!==e.ENDHDR||h.readUInt32LE(0)!==e.ENDSIG)&&(h.length<e.ZIP64HDR||h.readUInt32LE(0)!==e.ZIP64SIG))throw d.Errors.INVALID_END();h.readUInt32LE(0)===e.ENDSIG?(a=h.readUInt16LE(e.ENDSUB),b=h.readUInt16LE(e.ENDTOT),c=h.readUInt32LE(e.ENDSIZ),f=h.readUInt32LE(e.ENDOFF),g=h.readUInt16LE(e.ENDCOM)):(a=d.readBigUInt64LE(h,e.ZIP64SUB),b=d.readBigUInt64LE(h,e.ZIP64TOT),c=d.readBigUInt64LE(h,e.ZIP64SIZE),f=d.readBigUInt64LE(h,e.ZIP64OFF),g=0)},toBinary:function(){var d=Buffer.alloc(e.ENDHDR+g);return d.writeUInt32LE(e.ENDSIG,0),d.writeUInt32LE(0,4),d.writeUInt16LE(a,e.ENDSUB),d.writeUInt16LE(b,e.ENDTOT),d.writeUInt32LE(c,e.ENDSIZ),d.writeUInt32LE(f,e.ENDOFF),d.writeUInt16LE(g,e.ENDCOM),d.fill(" ",e.ENDHDR),d},toJSON:function(){return{diskEntries:a,totalEntries:b,size:c+" bytes",offset:function(a){let b=a.toString(16).toUpperCase();for(;b.length<4;)b="0"+b;return"0x"+b}(f),commentLength:g}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}},9460:(a,b,c)=>{let d=c(9738),e=c(30408),f=c(25296);a.exports=function(a,b){var c=[],g={},h=Buffer.alloc(0),i=new e.MainHeader,j=!1;let k=new Set,{noSort:l,decoder:m}=b;function n(){if(j=!0,g={},i.diskEntries>(a.length-i.offset)/f.Constants.CENHDR)throw f.Errors.DISK_ENTRY_TOO_LARGE();c=Array(i.diskEntries);for(var e=i.offset,h=0;h<c.length;h++){var l=e,m=new d(b,a);m.header=a.slice(l,l+=f.Constants.CENHDR),m.entryName=a.slice(l,l+=m.header.fileNameLength),m.header.extraLength&&(m.extra=a.slice(l,l+=m.header.extraLength)),m.header.commentLength&&(m.comment=a.slice(l,l+m.header.commentLength)),e+=m.header.centralHeaderSize,c[h]=m,g[m.entryName]=m}k.clear(),function(){let a=new Set;for(let b of Object.keys(g)){let c=b.split("/");if(c.pop(),c.length)for(let b=0;b<c.length;b++){let d=c.slice(0,b+1).join("/")+"/";a.add(d)}}for(let e of a)if(!(e in g)){let a=new d(b);a.entryName=e,a.attr=16,a.temporary=!0,c.push(a),g[a.entryName]=a,k.add(a)}}()}function o(){c.length>1&&!l&&c.sort((a,b)=>a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase()))}return a?function(c){var d=a.length-f.Constants.ENDHDR,e=Math.max(0,d-65535),g=e,j=a.length,k=-1,l=0;for("boolean"==typeof b.trailingSpace&&b.trailingSpace&&(e=0);d>=g;d--)if(80===a[d]){if(a.readUInt32LE(d)===f.Constants.ENDSIG){k=d,l=d,j=d+f.Constants.ENDHDR,g=d-f.Constants.END64HDR;continue}if(a.readUInt32LE(d)===f.Constants.END64SIG){g=e;continue}if(a.readUInt32LE(d)===f.Constants.ZIP64SIG){k=d,j=d+f.readBigUInt64LE(a,d+f.Constants.ZIP64SIZE)+f.Constants.ZIP64LEAD;break}}if(-1==k)throw f.Errors.INVALID_FORMAT();i.loadFromBinary(a.slice(k,j)),i.commentLength&&(h=a.slice(l+f.Constants.ENDHDR)),c&&n()}(b.readEntries):j=!0,{get entries(){return j||n(),c.filter(a=>!k.has(a))},get comment(){return m.decode(h)},set comment(val){i.commentLength=(h=f.toBuffer(val,m.encode)).length},getEntryCount:function(){return j?c.length:i.diskEntries},forEach:function(a){this.entries.forEach(a)},getEntry:function(a){return j||n(),g[a]||null},setEntry:function(a){j||n(),c.push(a),g[a.entryName]=a,i.totalEntries=c.length},deleteFile:function(a,b=!0){j||n();let c=g[a];this.getEntryChildren(c,b).map(a=>a.entryName).forEach(this.deleteEntry)},deleteEntry:function(a){j||n();let b=g[a],d=c.indexOf(b);d>=0&&(c.splice(d,1),delete g[a],i.totalEntries=c.length)},getEntryChildren:function(a,b=!0){if(j||n(),"object"==typeof a)if(!a.isDirectory||!b)return[a];else{let b=[],d=a.entryName;for(let a of c)a.entryName.startsWith(d)&&b.push(a);return b}return[]},getChildCount:function(a){if(a&&a.isDirectory){let b=this.getEntryChildren(a);return b.includes(a)?b.length-1:b.length}return 0},compressToBuffer:function(){j||n(),o();let b=[],c=[],d=0,e=0;i.size=0,i.offset=0;let g=0;for(let a of this.entries){let f=a.getCompressedData();a.header.offset=e;let h=a.packLocalHeader(),j=h.length+f.length;e+=j,b.push(h),b.push(f);let k=a.packCentralHeader();c.push(k),i.size+=k.length,d+=j+k.length,g++}d+=i.mainHeaderSize,i.offset=e,i.totalEntries=g,e=0;let k=Buffer.alloc(d);for(let a of b)a.copy(k,e),e+=a.length;for(let a of c)a.copy(k,e),e+=a.length;let l=i.toBinary();return h&&h.copy(l,f.Constants.ENDHDR),l.copy(k,e),a=k,j=!1,k},toAsyncBuffer:function(b,c,d,e){try{j||n(),o();let c=[],g=[],k=0,l=0,m=0;i.size=0,i.offset=0;let p=function(n){if(n.length>0){let a=n.shift(),b=a.entryName+a.extra.toString();d&&d(b),a.getCompressedDataAsync(function(d){e&&e(b),a.header.offset=l;let f=a.packLocalHeader(),h=f.length+d.length;l+=h,c.push(f),c.push(d);let j=a.packCentralHeader();g.push(j),i.size+=j.length,k+=h+j.length,m++,p(n)})}else{k+=i.mainHeaderSize,i.offset=l,i.totalEntries=m,l=0;let d=Buffer.alloc(k);c.forEach(function(a){a.copy(d,l),l+=a.length}),g.forEach(function(a){a.copy(d,l),l+=a.length});let e=i.toBinary();h&&h.copy(e,f.Constants.ENDHDR),e.copy(d,l),a=d,j=!1,b(d)}};p(Array.from(this.entries))}catch(a){c(a)}}}}},9499:(a,b,c)=>{"use strict";a.exports=c(30811).vendored["react-rsc"].React},9738:(a,b,c)=>{var d=c(25296),e=c(30408),f=d.Constants,g=c(13e3);a.exports=function(a,b){var c=new e.EntryHeader,h=Buffer.alloc(0),i=Buffer.alloc(0),j=!1,k=null,l=Buffer.alloc(0),m=Buffer.alloc(0),n=!0;let o="object"==typeof a.decoder?a.decoder:d.decoder;function p(){return b&&b instanceof Uint8Array?(m=c.loadLocalHeaderFromBinary(b),b.slice(c.realDataOffset,c.realDataOffset+c.compressedSize)):Buffer.alloc(0)}function q(a){if(c.flags_desc||c.localHeader.flags_desc){let e={},g=c.realDataOffset+c.compressedSize;if(b.readUInt32LE(g)==f.LOCSIG||b.readUInt32LE(g)==f.CENSIG)throw d.Errors.DESCRIPTOR_NOT_EXIST();if(b.readUInt32LE(g)==f.EXTSIG)e.crc=b.readUInt32LE(g+f.EXTCRC),e.compressedSize=b.readUInt32LE(g+f.EXTSIZ),e.size=b.readUInt32LE(g+f.EXTLEN);else if(19280===b.readUInt16LE(g+12))e.crc=b.readUInt32LE(g+f.EXTCRC-4),e.compressedSize=b.readUInt32LE(g+f.EXTSIZ-4),e.size=b.readUInt32LE(g+f.EXTLEN-4);else throw d.Errors.DESCRIPTOR_UNKNOWN();if(e.compressedSize!==c.compressedSize||e.size!==c.size||e.crc!==c.crc)throw d.Errors.DESCRIPTOR_FAULTY();if(d.crc32(a)!==e.crc)return!1}else if(d.crc32(a)!==c.localHeader.crc)return!1;return!0}function r(a,b,e){if(void 0===b&&"string"==typeof a&&(e=a,a=void 0),j)return a&&b&&b(Buffer.alloc(0),d.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var f=p();if(0===f.length)return a&&b&&b(f),f;if(c.encrypted){if("string"!=typeof e&&!Buffer.isBuffer(e))throw d.Errors.INVALID_PASS_PARAM();f=g.ZipCrypto.decrypt(f,c,e)}var i=Buffer.alloc(c.size);switch(c.method){case d.Constants.STORED:if(f.copy(i),q(i))return a&&b&&b(i),i;throw a&&b&&b(i,d.Errors.BAD_CRC()),d.Errors.BAD_CRC();case d.Constants.DEFLATED:var k=new g.Inflater(f,c.size);if(a)k.inflateAsync(function(a){a.copy(a,0),b&&(q(a)?b(a):b(a,d.Errors.BAD_CRC()))});else{if(k.inflate(i).copy(i,0),!q(i))throw d.Errors.BAD_CRC(`"${o.decode(h)}"`);return i}break;default:throw a&&b&&b(Buffer.alloc(0),d.Errors.UNKNOWN_METHOD()),d.Errors.UNKNOWN_METHOD()}}function s(a,e){if((!k||!k.length)&&Buffer.isBuffer(b))return a&&e&&e(p()),p();if(k.length&&!j){var f;switch(c.method){case d.Constants.STORED:return c.compressedSize=c.size,f=Buffer.alloc(k.length),k.copy(f),a&&e&&e(f),f;default:case d.Constants.DEFLATED:var h=new g.Deflater(k);if(a)h.deflateAsync(function(a){f=Buffer.alloc(a.length),c.compressedSize=a.length,a.copy(f),e&&e(f)});else{var i=h.deflate();return c.compressedSize=i.length,i}h=null}}else{if(!a||!e)return Buffer.alloc(0);e(Buffer.alloc(0))}}function t(a,b){return d.readBigUInt64LE(a,b)}return n=!!o.hasOwnProperty("efs")&&o.efs,{get entryName(){return o.decode(h)},get rawEntryName(){return h},set entryName(val){var u=(h=d.toBuffer(val,o.encode))[h.length-1];j=47===u||92===u,c.fileNameLength=h.length},get efs(){if("function"==typeof n)return n(this.entryName);return n},get extra(){return l},set extra(val){l=val,c.extraLength=val.length;try{for(var v,w,x,y=0;y+4<val.length;)v=val.readUInt16LE(y),y+=2,w=val.readUInt16LE(y),y+=2,x=val.slice(y,y+w),y+=w,f.ID_ZIP64===v&&function(a){var b,d,e,g;a.length>=f.EF_ZIP64_SCOMP&&(b=t(a,f.EF_ZIP64_SUNCOMP),c.size===f.EF_ZIP64_OR_32&&(c.size=b)),a.length>=f.EF_ZIP64_RHO&&(d=t(a,f.EF_ZIP64_SCOMP),c.compressedSize===f.EF_ZIP64_OR_32&&(c.compressedSize=d)),a.length>=f.EF_ZIP64_DSN&&(e=t(a,f.EF_ZIP64_RHO),c.offset===f.EF_ZIP64_OR_32&&(c.offset=e)),a.length>=f.EF_ZIP64_DSN+4&&(g=a.readUInt32LE(f.EF_ZIP64_DSN),c.diskNumStart===f.EF_ZIP64_OR_16&&(c.diskNumStart=g))}(x)}catch(a){throw d.Errors.EXTRA_FIELD_PARSE_ERROR()}},get comment(){return o.decode(i)},set comment(val){if(c.commentLength=(i=d.toBuffer(val,o.encode)).length,i.length>65535)throw d.Errors.COMMENT_TOO_LONG()},get name(){var z=o.decode(h);return j?z.substr(z.length-1).split("/").pop():z.split("/").pop()},get isDirectory(){return j},getCompressedData:function(){return s(!1,null)},getCompressedDataAsync:function(a){s(!0,a)},setData:function(a){k=d.toBuffer(a,d.decoder.encode),!j&&k.length?(c.size=k.length,c.method=d.Constants.DEFLATED,c.crc=d.crc32(a),c.changed=!0):c.method=d.Constants.STORED},getData:function(a){return c.changed?k:r(!1,null,a)},getDataAsync:function(a,b){c.changed?a(k):r(!0,a,b)},set attr(attr){c.attr=attr},get attr(){return c.attr},set header(data){c.loadFromBinary(data)},get header(){return c},packCentralHeader:function(){c.flags_efs=this.efs,c.extraLength=l.length;var a=c.centralHeaderToBinary(),b=d.Constants.CENHDR;return h.copy(a,b),b+=h.length,l.copy(a,b),b+=c.extraLength,i.copy(a,b),a},packLocalHeader:function(){let a=0;c.flags_efs=this.efs,c.extraLocalLength=m.length;let b=c.localHeaderToBinary(),d=Buffer.alloc(b.length+h.length+c.extraLocalLength);return b.copy(d,a),a+=b.length,h.copy(d,a),a+=h.length,m.copy(d,a),a+=m.length,d},toJSON:function(){let a=function(a){return"<"+(a&&a.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:c.toJSON(),compressedData:a(b),data:a(k)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}},9853:(a,b,c)=>{"use strict";c.d(b,{$l:()=>e,LG:()=>f});var d=c(61793),e=class extends Error{constructor(a,b){super(a,b),this.name="BetterAuthError",this.message=a,this.stack=""}},f=class a extends d.LG{constructor(...a){super(...a)}static fromStatus(b,c){return new a(b,c)}static from(b,c){return new a(b,{message:c.message,code:c.code})}}},10045:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={compareAppPaths:function(){return i},normalizeAppPath:function(){return h},normalizeRscURL:function(){return j}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(28238),g=c(39649);function h(a){return(0,f.ensureLeadingSlash)(a.split("/").reduce((a,b,c,d)=>!b||(0,g.isGroupSegment)(b)||"@"===b[0]||("page"===b||"route"===b)&&c===d.length-1?a:`${a}/${b}`,""))}function i(a,b){let c=a.includes("/@"),d=b.includes("/@");return c&&!d?-1:!c&&d?1:a.localeCompare(b)}function j(a){return a.replace(/\.rsc($|\?)/,"$1")}},10375:(a,b)=>{"use strict";function c(a,b,c){if(a){for(let d of(c&&(c=c.toLowerCase()),a))if(b===d.domain?.split(":",1)[0].toLowerCase()||c===d.defaultLocale.toLowerCase()||d.locales?.some(a=>a.toLowerCase()===c))return d}}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"detectDomainLocale",{enumerable:!0,get:function(){return c}})},10469:(a,b,c)=>{"use strict";c.d(b,{t:()=>u});var d=c(14877),e=c(18110),f=c(21513),g=c(54254);let h=(0,e.CN)({is:a=>"AggregateFunctionNode"===a.kind,create:(a,b=[])=>(0,e.CN)({kind:"AggregateFunctionNode",func:a,aggregated:b}),cloneWithDistinct:a=>(0,e.CN)({...a,distinct:!0}),cloneWithOrderBy(a,b,c=!1){let d=c?"withinGroup":"orderBy";return(0,e.CN)({...a,[d]:a[d]?g.O.cloneWithItems(a[d],b):g.O.create(b)})},cloneWithFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"And",b):f.o.create(b)}),cloneWithOrFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"Or",b):f.o.create(b)}),cloneWithOver:(a,b)=>(0,e.CN)({...a,over:b})}),i=(0,e.CN)({is:a=>"FunctionNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"FunctionNode",func:a,arguments:b})});var j=c(45541),k=c(46489),l=c(50182),m=c(98051),n=c(59916),o=c(31341),p=c(10611),q=c(87301);class r{#a;constructor(a){this.#a=(0,e.CN)(a)}get expressionType(){}as(a){return new s(this,a)}distinct(){return new r({...this.#a,aggregateFunctionNode:h.cloneWithDistinct(this.#a.aggregateFunctionNode)})}orderBy(...a){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithOrderByItems(this.#a.aggregateFunctionNode,(0,p.xk)(a))})}clearOrderBy(){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithoutOrderBy(this.#a.aggregateFunctionNode)})}withinGroupOrderBy(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithOrderBy(this.#a.aggregateFunctionNode,(0,p.xk)(a),!0)})}filterWhere(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.GB)(a))})}filterWhereRef(a,b,c){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.vC)(a,b,c))})}over(a){let b=(0,n.EQ)();return new r({...this.#a,aggregateFunctionNode:h.cloneWithOver(this.#a.aggregateFunctionNode,(a?a(b):b).toOperationNode())})}$call(a){return a(this)}$castTo(){return new r(this.#a)}$notNull(){return new r(this.#a)}toOperationNode(){return this.#a.aggregateFunctionNode}}class s{#e;#f;constructor(a,b){this.#e=a,this.#f=b}get expression(){return this.#e}get alias(){return this.#f}toOperationNode(){return l.N.create(this.#e.toOperationNode(),m.O.create(this.#f))}}var t=c(27800);function u(){let a=(a,b)=>new d.Is(i.create(a,(0,j.kU)(b??[]))),b=(a,b)=>new r({aggregateFunctionNode:h.create(a,b?(0,j.kU)(b):void 0)});return Object.assign(a,{agg:b,avg:a=>b("avg",[a]),coalesce:(...b)=>a("coalesce",b),count:a=>b("count",[a]),countAll:a=>new r({aggregateFunctionNode:h.create("count",(0,k.J)(a))}),max:a=>b("max",[a]),min:a=>b("min",[a]),sum:a=>b("sum",[a]),any:b=>a("any",[b]),jsonAgg:a=>new r({aggregateFunctionNode:h.create("json_agg",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()])}),toJson:a=>new d.Is(i.create("to_json",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()]))})}},10611:(a,b,c)=>{"use strict";c.d(b,{bE:()=>o,xk:()=>p});var d=c(88035),e=c(38027),f=c(18110);let g=(0,f.CN)({is:a=>"OrderByItemNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"OrderByItemNode",orderBy:a,direction:b}),cloneWith:(a,b)=>(0,f.CN)({...a,...b})});var h=c(80184),i=c(98051);let j=(0,f.CN)({is:a=>"CollateNode"===a.kind,create:a=>(0,f.CN)({kind:"CollateNode",collation:i.O.create(a)})});class k{#a;constructor(a){this.#a=(0,f.CN)(a)}desc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("desc")})})}asc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("asc")})})}nullsLast(){return new k({node:g.cloneWith(this.#a.node,{nulls:"last"})})}nullsFirst(){return new k({node:g.cloneWith(this.#a.node,{nulls:"first"})})}collate(a){return new k({node:g.cloneWith(this.#a.node,{collation:j.create(a)})})}toOperationNode(){return this.#a.node}}var l=c(97551),m=c(37338),n=c(45541);function o(a){return"asc"===a||"desc"===a}function p(a){if(2===a.length)return[q(a[0],a[1])];if(1===a.length){let[b]=a;return Array.isArray(b)?((0,l.u)("orderBy(array) is deprecated, use multiple orderBy calls instead."),b.map(a=>q(a))):[q(b)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${a.length}`)}function q(a,b){let c=function(a){if((0,m.SS)(a))return(0,m.YK)(a);if((0,d.C)(a))return a.toOperationNode();let[b,c]=a.split(" ");return c?((0,l.u)("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),r((0,n.q5)(b),c)):(0,n.q5)(a)}(a);if(g.is(c)){if(b)throw Error("Cannot specify direction twice!");return c}return r(c,b)}function r(a,b){if("string"==typeof b){if(!o(b))throw Error(`Invalid order by direction: ${b}`);return g.create(a,h.z.createWithSql(b))}if((0,e.B)(b))return(0,l.u)("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),g.create(a,b.toOperationNode());let c=g.create(a);return b?b(new k({node:c})).toOperationNode():c}},10820:(a,b,c)=>{"use strict";Object.defineProperty(b,"M",{enumerable:!0,get:function(){return g}});let d=c(29294),e=c(63033),f=c(4190);function g(){let a=d.workAsyncStorage.getStore(),b=e.workUnitAsyncStorage.getStore();if(a){if(!a.forceStatic){if(a.isUnstableNoStore=!0,b)switch(b.type){case"prerender":case"prerender-client":case"validation-client":case"prerender-runtime":return}(0,f.markCurrentScopeAsDynamic)(a,b,"unstable_noStore()")}}}},11010:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c,d,e,f,g,h,i,j,k,l,m,n,o={AppRenderSpan:function(){return w},AppRouteRouteHandlersSpan:function(){return z},BaseServerSpan:function(){return q},LoadComponentsSpan:function(){return r},LogSpanAllowList:function(){return D},MiddlewareSpan:function(){return B},NextNodeServerSpan:function(){return t},NextServerSpan:function(){return s},NextVanillaSpanAllowlist:function(){return C},NodeSpan:function(){return y},RenderSpan:function(){return v},ResolveMetadataSpan:function(){return A},RouterSpan:function(){return x},StartServerSpan:function(){return u}};for(var p in o)Object.defineProperty(b,p,{enumerable:!0,get:o[p]});var q=((c=q||{}).handleRequest="BaseServer.handleRequest",c.run="BaseServer.run",c.pipe="BaseServer.pipe",c.getStaticHTML="BaseServer.getStaticHTML",c.render="BaseServer.render",c.renderToResponseWithComponents="BaseServer.renderToResponseWithComponents",c.renderToResponse="BaseServer.renderToResponse",c.renderToHTML="BaseServer.renderToHTML",c.renderError="BaseServer.renderError",c.renderErrorToResponse="BaseServer.renderErrorToResponse",c.renderErrorToHTML="BaseServer.renderErrorToHTML",c.render404="BaseServer.render404",c),r=((d=r||{}).loadDefaultErrorComponents="LoadComponents.loadDefaultErrorComponents",d.loadComponents="LoadComponents.loadComponents",d),s=((e=s||{}).getRequestHandler="NextServer.getRequestHandler",e.getRequestHandlerWithMetadata="NextServer.getRequestHandlerWithMetadata",e.getServer="NextServer.getServer",e.getServerRequestHandler="NextServer.getServerRequestHandler",e.createServer="createServer.createServer",e),t=((f=t||{}).compression="NextNodeServer.compression",f.getBuildId="NextNodeServer.getBuildId",f.createComponentTree="NextNodeServer.createComponentTree",f.clientComponentLoading="NextNodeServer.clientComponentLoading",f.getLayoutOrPageModule="NextNodeServer.getLayoutOrPageModule",f.generateStaticRoutes="NextNodeServer.generateStaticRoutes",f.generateFsStaticRoutes="NextNodeServer.generateFsStaticRoutes",f.generatePublicRoutes="NextNodeServer.generatePublicRoutes",f.generateImageRoutes="NextNodeServer.generateImageRoutes.route",f.sendRenderResult="NextNodeServer.sendRenderResult",f.proxyRequest="NextNodeServer.proxyRequest",f.runApi="NextNodeServer.runApi",f.render="NextNodeServer.render",f.renderHTML="NextNodeServer.renderHTML",f.imageOptimizer="NextNodeServer.imageOptimizer",f.getPagePath="NextNodeServer.getPagePath",f.getRoutesManifest="NextNodeServer.getRoutesManifest",f.findPageComponents="NextNodeServer.findPageComponents",f.getFontManifest="NextNodeServer.getFontManifest",f.getServerComponentManifest="NextNodeServer.getServerComponentManifest",f.getRequestHandler="NextNodeServer.getRequestHandler",f.renderToHTML="NextNodeServer.renderToHTML",f.renderError="NextNodeServer.renderError",f.renderErrorToHTML="NextNodeServer.renderErrorToHTML",f.render404="NextNodeServer.render404",f.startResponse="NextNodeServer.startResponse",f.route="route",f.onProxyReq="onProxyReq",f.apiResolver="apiResolver",f.internalFetch="internalFetch",f),u=((g=u||{}).startServer="startServer.startServer",g),v=((h=v||{}).getServerSideProps="Render.getServerSideProps",h.getStaticProps="Render.getStaticProps",h.renderToString="Render.renderToString",h.renderDocument="Render.renderDocument",h.createBodyResult="Render.createBodyResult",h),w=((i=w||{}).renderToString="AppRender.renderToString",i.renderToReadableStream="AppRender.renderToReadableStream",i.getBodyResult="AppRender.getBodyResult",i.fetch="AppRender.fetch",i),x=((j=x||{}).executeRoute="Router.executeRoute",j),y=((k=y||{}).runHandler="Node.runHandler",k),z=((l=z||{}).runHandler="AppRouteRouteHandlers.runHandler",l),A=((m=A||{}).generateMetadata="ResolveMetadata.generateMetadata",m.generateViewport="ResolveMetadata.generateViewport",m),B=((n=B||{}).execute="Middleware.execute",n);let C=new Set(["Middleware.execute","BaseServer.handleRequest","Render.getServerSideProps","Render.getStaticProps","AppRender.fetch","AppRender.getBodyResult","Render.renderDocument","Node.runHandler","AppRouteRouteHandlers.runHandler","ResolveMetadata.generateMetadata","ResolveMetadata.generateViewport","NextNodeServer.createComponentTree","NextNodeServer.findPageComponents","NextNodeServer.getLayoutOrPageModule","NextNodeServer.startResponse","NextNodeServer.clientComponentLoading"]),D=new Set(["NextNodeServer.findPageComponents","NextNodeServer.createComponentTree","NextNodeServer.clientComponentLoading"])},12757:(a,b,c)=>{"use strict";c.d(b,{B:()=>f,o:()=>e});var d=c(18110);let e=["preserve rows","delete rows","drop"],f=(0,d.CN)({is:a=>"CreateTableNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateTableNode",table:a,columns:(0,d.CN)([])}),cloneWithColumn:(a,b)=>(0,d.CN)({...a,columns:(0,d.CN)([...a.columns,b])}),cloneWithConstraint:(a,b)=>(0,d.CN)({...a,constraints:a.constraints?(0,d.CN)([...a.constraints,b]):(0,d.CN)([b])}),cloneWithIndex:(a,b)=>(0,d.CN)({...a,indexes:a.indexes?(0,d.CN)([...a.indexes,b]):(0,d.CN)([b])}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithEndModifier:(a,b)=>(0,d.CN)({...a,endModifiers:a.endModifiers?(0,d.CN)([...a.endModifiers,b]):(0,d.CN)([b])}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},13e3:(a,b,c)=>{b.Deflater=c(73769),b.Inflater=c(88825),b.ZipCrypto=c(46374)},13370:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={isRequestAPICallableInsideAfter:function(){return j},throwForSearchParamsAccessInUseCache:function(){return i},throwWithStaticGenerationBailoutErrorWithDynamicError:function(){return h}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(27130),g=c(3295);function h(a,b){throw Object.defineProperty(new f.StaticGenBailoutError(`Route ${a} with \`dynamic = "error"\` couldn't be rendered statically because it used ${b}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E543",enumerable:!1,configurable:!0})}function i(a,b){let c=Object.defineProperty(Error(`Route ${a.route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E842",enumerable:!1,configurable:!0});throw Error.captureStackTrace(c,b),a.invalidDynamicUsageError??=c,c}function j(){let a=g.afterTaskAsyncStorage.getStore();return(null==a?void 0:a.rootTaskSpawnPhase)==="action"}},13607:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={INTERNALS:function(){return j},NextRequest:function(){return k}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(49747),g=c(61259),h=c(84750),i=c(29033),j=Symbol("internal request");class k extends Request{constructor(a,b={}){const c="string"!=typeof a&&"url"in a?a.url:String(a);(0,g.validateURL)(c),b.body&&"half"!==b.duplex&&(b.duplex="half"),a instanceof Request?super(a,b):super(c,b);const d=new f.NextURL(c,{headers:(0,g.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:b.nextConfig});this[j]={cookies:new i.RequestCookies(this.headers),nextUrl:d,url:d.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[j].cookies}get nextUrl(){return this[j].nextUrl}get page(){throw new h.RemovedPageError}get ua(){throw new h.RemovedUAError}get url(){return this[j].url}}},14877:(a,b,c)=>{"use strict";c.d(b,{Is:()=>k});var d=c(50182),e=c(59255),f=c(98051),g=c(60351),h=c(67449),i=c(38441),j=c(31341);class k{#g;constructor(a){this.#g=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#g,(0,j.GB)(a)))}and(...a){return new n(e.s.create(this.#g,(0,j.GB)(a)))}$castTo(){return new k(this.#g)}$notNull(){return new k(this.#g)}toOperationNode(){return this.#g}}class l{#h;#f;constructor(a,b){this.#h=a,this.#f=b}get expression(){return this.#h}get alias(){return this.#f}toOperationNode(){return d.N.create(this.#h.toOperationNode(),(0,g.N)(this.#f)?this.#f.toOperationNode():f.O.create(this.#f))}}class m{#g;constructor(a){this.#g=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#g,(0,j.GB)(a)))}$castTo(){return new m(this.#g)}toOperationNode(){return i.k.create(this.#g)}}class n{#g;constructor(a){this.#g=a}get expressionType(){}as(a){return new l(this,a)}and(...a){return new n(e.s.create(this.#g,(0,j.GB)(a)))}$castTo(){return new n(this.#g)}toOperationNode(){return i.k.create(this.#g)}}},15092:(a,b)=>{"use strict";let c;Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"cloneResponse",{enumerable:!0,get:function(){return e}});let d=()=>{};function e(a){if(!a.body)return[a,a];let[b,d]=a.body.tee(),e=new Response(b,{status:a.status,statusText:a.statusText,headers:a.headers});Object.defineProperty(e,"url",{value:a.url,configurable:!0,enumerable:!0,writable:!1});let f=new Response(d,{status:a.status,statusText:a.statusText,headers:a.headers});return Object.defineProperty(f,"url",{value:a.url,configurable:!0,enumerable:!0,writable:!1}),c&&(e.body&&c.register(e,new WeakRef(e.body)),f.body&&c.register(f,new WeakRef(f.body))),[e,f]}globalThis.FinalizationRegistry&&(c=new FinalizationRegistry(a=>{let b=a.deref();b&&!b.locked&&b.cancel("Response object has been garbage collected").then(d)}))},15214:(a,b,c)=>{"use strict";c.d(b,{h:()=>i,p4:()=>e,p8:()=>g,vF:()=>j});var d=c(56603);let e={reset:"\x1b[0m",bright:"\x1b[1m",dim:"\x1b[2m",undim:"\x1b[22m",underscore:"\x1b[4m",blink:"\x1b[5m",reverse:"\x1b[7m",hidden:"\x1b[8m",fg:{black:"\x1b[30m",red:"\x1b[31m",green:"\x1b[32m",yellow:"\x1b[33m",blue:"\x1b[34m",magenta:"\x1b[35m",cyan:"\x1b[36m",white:"\x1b[37m"},bg:{black:"\x1b[40m",red:"\x1b[41m",green:"\x1b[42m",yellow:"\x1b[43m",blue:"\x1b[44m",magenta:"\x1b[45m",cyan:"\x1b[46m",white:"\x1b[47m"}},f=["debug","info","success","warn","error"];function g(a,b){return f.indexOf(b)>=f.indexOf(a)}let h={info:e.fg.blue,success:e.fg.green,warn:e.fg.yellow,error:e.fg.red,debug:e.fg.magenta},i=a=>{let b=a?.disabled!==!0,c=a?.level??"warn",i=a?.disableColors!==void 0?!a.disableColors:1!==(0,d.t)();return{...Object.fromEntries(f.map(d=>[d,(...[f,...j])=>((d,f,j=[])=>{let k;if(!b||!g(c,d))return;let l=(k=new Date().toISOString(),i?`${e.dim}${k}${e.reset} ${h[d]}${d.toUpperCase()}${e.reset} ${e.bright}[Better Auth]:${e.reset} ${f}`:`${k} ${d.toUpperCase()} [Better Auth]: ${f}`);a&&"function"==typeof a.log?a.log("success"===d?"info":d,f,...j):"error"===d?console.error(l,...j):"warn"===d?console.warn(l,...j):console.log(l,...j)})(d,f,j)])),get level(){return c}}},j=i()},15258:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={chainStreams:function(){return q},continueDynamicHTMLResume:function(){return N},continueDynamicPrerender:function(){return K},continueFizzStream:function(){return J},continueStaticFallbackPrerender:function(){return M},continueStaticPrerender:function(){return L},createBufferedTransformStream:function(){return x},createDocumentClosingStream:function(){return O},createInstantTestScriptInsertionTransformStream:function(){return C},createRootLayoutValidatorStream:function(){return H},createRuntimePrefetchTransformStream:function(){return P},renderToInitialFizzStream:function(){return y},streamFromBuffer:function(){return s},streamFromString:function(){return r},streamToBuffer:function(){return v},streamToString:function(){return w},streamToUint8Array:function(){return u}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(4028),g=c(11010),h=c(67017),i=c(34310),j=c(412),k=c(3687),l=c(3172),m=c(72188),n=c(98789);function o(){}let p=new TextEncoder;function q(...a){if(0===a.length)return new ReadableStream({start(a){a.close()}});if(1===a.length)return a[0];let{readable:b,writable:c}=new TransformStream,d=a[0].pipeTo(c,{preventClose:!0}),e=1;for(;e<a.length-1;e++){let b=a[e];d=d.then(()=>b.pipeTo(c,{preventClose:!0}))}let f=a[e];return(d=d.then(()=>f.pipeTo(c))).catch(o),b}function r(a){return new ReadableStream({start(b){b.enqueue(p.encode(a)),b.close()}})}function s(a){return new ReadableStream({start(b){b.enqueue(a),b.close()}})}async function t(a){let b=a.getReader(),c=[];for(;;){let{done:a,value:d}=await b.read();if(a)break;c.push(d)}return c}async function u(a){var b=await t(a);let c=new Uint8Array(b.reduce((a,b)=>a+b.length,0)),d=0;for(let a of b)c.set(a,d),d+=a.length;return c}async function v(a){return Buffer.concat(await t(a))}async function w(a,b){let c=new TextDecoder("utf-8",{fatal:!0}),d="";for await(let e of a){if(null==b?void 0:b.aborted)return d;d+=c.decode(e,{stream:!0})}return d+c.decode()}function x(a={}){let b,{maxBufferByteLength:c=1/0}=a,d=[],e=0,f=a=>{try{if(0===d.length)return;let b=new Uint8Array(e),c=0;for(let a=0;a<d.length;a++){let e=d[a];b.set(e,c),c+=e.byteLength}d.length=0,e=0,a.enqueue(b)}catch{}};return new TransformStream({transform(a,g){d.push(a),(e+=a.byteLength)>=c?f(g):(a=>{if(b)return;let c=new h.DetachedPromise;b=c,(0,i.scheduleImmediate)(()=>{try{f(a)}finally{b=void 0,c.resolve()}})})(g)},flush:()=>null==b?void 0:b.promise})}function y({ReactDOMServer:a,element:b,streamOptions:c}){return(0,f.getTracer)().trace(g.AppRenderSpan.renderToReadableStream,async()=>a.renderToReadableStream(b,c))}function z(a){let b=-1,c=!1;return new TransformStream({async transform(d,e){let f=-1,g=-1;if(b++,c)return void e.enqueue(d);let h=0;if(-1===f){if(-1===(f=(0,k.indexOfUint8Array)(d,j.ENCODED_TAGS.META.ICON_MARK)))return void e.enqueue(d);47===d[f+(h=j.ENCODED_TAGS.META.ICON_MARK.length)]?h+=2:h++}if(0===b){if(g=(0,k.indexOfUint8Array)(d,j.ENCODED_TAGS.CLOSED.HEAD),-1!==f){if(f<g){let a=new Uint8Array(d.length-h);a.set(d.subarray(0,f)),a.set(d.subarray(f+h),f),d=a}else{let b=await a(),c=p.encode(b),e=c.length,g=new Uint8Array(d.length-h+e);g.set(d.subarray(0,f)),g.set(c,f),g.set(d.subarray(f+h),f+e),d=g}c=!0}}else{let b=await a(),e=p.encode(b),g=e.length,i=new Uint8Array(d.length-h+g);i.set(d.subarray(0,f)),i.set(e,f),i.set(d.subarray(f+h),f+g),d=i,c=!0}e.enqueue(d)}})}function A(a){let b=!1,c=!1;return new TransformStream({async transform(d,e){c=!0;let f=await a();if(b){if(f){let a=p.encode(f);e.enqueue(a)}e.enqueue(d)}else{let a=(0,k.indexOfUint8Array)(d,j.ENCODED_TAGS.CLOSED.HEAD);if(-1!==a){if(f){let b=p.encode(f),c=new Uint8Array(d.length+b.length);c.set(d.slice(0,a)),c.set(b,a),c.set(d.slice(a),a+b.length),e.enqueue(c)}else e.enqueue(d);b=!0}else f&&e.enqueue(p.encode(f)),e.enqueue(d),b=!0}},async flush(b){if(c){let c=await a();c&&b.enqueue(p.encode(c))}}})}async function B(){let a=await (0,n.computeCacheBustingSearchParam)("1","/_full",void 0,void 0),b=`${m.NEXT_RSC_UNION_QUERY}=${a}`,c=`<script>__NEXT_CLIENT_RESUME=fetch(location.pathname+'?${b}',{credentials:'same-origin',headers:{'${m.RSC_HEADER}': '1','${m.NEXT_ROUTER_PREFETCH_HEADER}': '1','${m.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '/_full'}})</script>`,d=!1;return new TransformStream({transform(a,b){if(d)return void b.enqueue(a);let e=(0,k.indexOfUint8Array)(a,j.ENCODED_TAGS.CLOSED.HEAD);if(-1===e)return void b.enqueue(a);let f=p.encode(c),g=new Uint8Array(a.length+f.length);g.set(a.slice(0,e)),g.set(f,e),g.set(a.slice(e),e+f.length),b.enqueue(g),d=!0}})}async function C(a){let b="/_full",c=await (0,n.computeCacheBustingSearchParam)("1",b,void 0,void 0),d=`${m.NEXT_RSC_UNION_QUERY}=${c}`,e=null!==a?`self.__next_r=${JSON.stringify(a)};`:"",f=`<script>${e}self.__next_instant_test=fetch(location.pathname+'?${d}',{credentials:'same-origin',headers:{'${m.RSC_HEADER}':'1','${m.NEXT_ROUTER_PREFETCH_HEADER}':'1','${m.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}':'${b}','${m.NEXT_INSTANT_PREFETCH_HEADER}':'1'}})</script>`,g=!1;return new TransformStream({transform(a,b){if(g)return void b.enqueue(a);let c=(0,k.indexOfUint8Array)(a,j.ENCODED_TAGS.OPENING.HEAD);if(-1===c)return void b.enqueue(a);let d=a.indexOf(62,c+j.ENCODED_TAGS.OPENING.HEAD.length);if(-1===d)return void b.enqueue(a);let e=p.encode(f),h=d+1,i=new Uint8Array(a.length+e.length);i.set(a.slice(0,h)),i.set(e,h),i.set(a.slice(h),h+e.length),b.enqueue(i),g=!0},flush(a){a.enqueue(j.ENCODED_TAGS.CLOSED.BODY_AND_HTML)}})}function D(a,b){let c=!1,d=null,e=!1;function f(a){return d||(d=g(a)),d}async function g(d){let f=a.getReader();b&&await (0,i.atLeastOneTask)();try{for(;;){let{done:a,value:g}=await f.read();if(a){e=!0;return}b||c||await (0,i.atLeastOneTask)(),d.enqueue(g)}}catch(a){d.error(a)}}return new TransformStream({start(a){b||f(a)},transform(a,c){c.enqueue(a),b&&f(c)},flush(a){if(c=!0,!e)return f(a)}})}let E="</body></html>";function F(){let a=!1;return new TransformStream({transform(b,c){if(a)return c.enqueue(b);let d=(0,k.indexOfUint8Array)(b,j.ENCODED_TAGS.CLOSED.BODY_AND_HTML);if(d>-1){if(a=!0,b.length===j.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length)return;let e=b.slice(0,d);if(c.enqueue(e),b.length>j.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length+d){let a=b.slice(d+j.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length);c.enqueue(a)}}else c.enqueue(b)},flush(a){a.enqueue(j.ENCODED_TAGS.CLOSED.BODY_AND_HTML)}})}function G(a){let b=!1;return new TransformStream({transform(c,d){if(b)return void d.enqueue(c);let e=(0,k.indexOfUint8Array)(c,j.ENCODED_TAGS.OPENING.HTML);if(-1===e)return void d.enqueue(c);let f=e+j.ENCODED_TAGS.OPENING.HTML.length,g=` data-dpl-id="${a}"`,h=p.encode(g),i=new Uint8Array(c.length+h.length);i.set(c.subarray(0,f)),i.set(h,f),i.set(c.subarray(f),f+h.length),d.enqueue(i),b=!0}})}function H(){let a=!1,b=!1;return new TransformStream({async transform(c,d){!a&&(0,k.indexOfUint8Array)(c,j.ENCODED_TAGS.OPENING.HTML)>-1&&(a=!0),!b&&(0,k.indexOfUint8Array)(c,j.ENCODED_TAGS.OPENING.BODY)>-1&&(b=!0),d.enqueue(c)},flush(c){let d=[];a||d.push("html"),b||d.push("body"),d.length&&c.enqueue(p.encode(`<html id="__next_error__">
|
|
5
|
+
<template
|
|
6
|
+
data-next-error-message="Missing ${d.map(a=>`<${a}>`).join(d.length>1?" and ":"")} tags in the root layout.
|
|
7
|
+
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags"
|
|
8
|
+
data-next-error-digest="${l.MISSING_ROOT_TAGS_ERROR}"
|
|
9
|
+
data-next-error-stack=""
|
|
10
|
+
></template>
|
|
11
|
+
`))}})}function I(a,b){let c=a;for(let a of b)a&&(c=c.pipeThrough(a));return c}async function J(a,{suffix:b,inlinedDataStream:c,isStaticGeneration:d,deploymentId:e,getServerInsertedHTML:f,getServerInsertedMetadata:g,validateRootLayout:j}){let k,l,m=b?b.split(E,1)[0]:null;return d?await a.allReady:await (0,i.waitAtLeastOneReactRenderTask)(),I(a,[x(),e?G(e):null,z(g),null!=m&&m.length>0?(l=!1,new TransformStream({transform(a,b){if(b.enqueue(a),!l){let a;l=!0,k=a=new h.DetachedPromise,(0,i.scheduleImmediate)(()=>{try{b.enqueue(p.encode(m))}catch{}finally{k=void 0,a.resolve()}})}},flush(a){if(k)return k.promise;l||a.enqueue(p.encode(m))}})):null,c?D(c,!0):null,j?H():null,F(),A(f)])}async function K(a,{getServerInsertedHTML:b,getServerInsertedMetadata:c,deploymentId:d}){return I(a,[x(),new TransformStream({transform(a,b){(0,k.isEquivalentUint8Arrays)(a,j.ENCODED_TAGS.CLOSED.BODY_AND_HTML)||(0,k.isEquivalentUint8Arrays)(a,j.ENCODED_TAGS.CLOSED.BODY)||(0,k.isEquivalentUint8Arrays)(a,j.ENCODED_TAGS.CLOSED.HTML)||(a=(0,k.removeFromUint8Array)(a,j.ENCODED_TAGS.CLOSED.BODY),a=(0,k.removeFromUint8Array)(a,j.ENCODED_TAGS.CLOSED.HTML),b.enqueue(a))}}),d?G(d):null,A(b),z(c)])}async function L(a,{inlinedDataStream:b,getServerInsertedHTML:c,getServerInsertedMetadata:d,deploymentId:e}){return I(a,[x(),e?G(e):null,A(c),z(d),D(b,!0),F()])}async function M(a,{inlinedDataStream:b,getServerInsertedHTML:c,getServerInsertedMetadata:d,deploymentId:e}){return I(a,[x(),e?G(e):null,A(c),await B(),z(d),D(b,!0),F()])}async function N(a,{delayDataUntilFirstHtmlChunk:b,inlinedDataStream:c,getServerInsertedHTML:d,getServerInsertedMetadata:e,deploymentId:f}){return I(a,[x(),f?G(f):null,A(d),z(e),D(c,b),F()])}function O(){return r(E)}function P(a,b,c){let d=new TextEncoder,e=d.encode(`[${a}]`),f=e[0],g=d.encode(`[${b},${c}]`),h=e.length,i=null,j=!1;function k(a,b){if(j){b&&a.enqueue(b);return}if(i){let c=i.length-(h-1);if(b&&(c+=Math.min(b.length,h-1)),c<1){a.enqueue(i),i=b;return}let d=i.indexOf(f);a:for(;-1<d&&d<c;){let c=1;for(;c<h;){let a=d+c;if((a<i.length?i[a]:b[a-i.length])!==e[c]){d=i.indexOf(f,d+1);continue a}c++}if(j=!0,a.enqueue(i.subarray(0,d)),a.enqueue(g),d+h<i.length&&a.enqueue(i.slice(d+h)),b){let c=d+h-i.length,e=c>0?b.subarray(c):b;a.enqueue(e)}i=null;return}a.enqueue(i)}i=b}return new TransformStream({transform(a,b){k(b,a)},flush(a){k(a,null)}})}},15707:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={HTTPAccessErrorStatus:function(){return e},HTTP_ERROR_FALLBACK_ERROR_CODE:function(){return g},getAccessFallbackErrorTypeByStatus:function(){return j},getAccessFallbackHTTPStatus:function(){return i},isHTTPAccessFallbackError:function(){return h}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e={NOT_FOUND:404,FORBIDDEN:403,UNAUTHORIZED:401},f=new Set(Object.values(e)),g="NEXT_HTTP_ERROR_FALLBACK";function h(a){if("object"!=typeof a||null===a||!("digest"in a)||"string"!=typeof a.digest)return!1;let[b,c]=a.digest.split(";");return b===g&&f.has(Number(c))}function i(a){return Number(a.digest.split(";")[1])}function j(a){switch(a){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";default:return}}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},15793:(a,b,c)=>{"use strict";c.d(b,{$:()=>e});var d=c(81605);let e=a=>(0,d.q)("a-z","A-Z","0-9")(a||32)},16891:(a,b,c)=>{"use strict";c.d(b,{k:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"JSONOperatorChainNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONOperatorChainNode",operator:a,values:(0,d.CN)([])}),cloneWithValue:(a,b)=>(0,d.CN)({...a,values:(0,d.CN)([...a.values,b])})})},16935:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={ActionDidNotRevalidate:function(){return e},ActionDidRevalidateDynamicOnly:function(){return g},ActionDidRevalidateStaticAndDynamic:function(){return f}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e=0,f=1,g=2},17532:(a,b,c)=>{"use strict";c.d(b,{P:()=>f});var d=c(18110),e=c(98444);let f=(0,d.CN)({is:a=>"CaseNode"===a.kind,create:a=>(0,d.CN)({kind:"CaseNode",value:a}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,when:(0,d.CN)(a.when?[...a.when,b]:[b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,when:a.when?(0,d.CN)([...a.when.slice(0,-1),e.t.cloneWithResult(a.when[a.when.length-1],b)]):void 0}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},18110:(a,b,c)=>{"use strict";function d(a){return void 0===a||void 0===a}function e(a){return"string"==typeof a}function f(a){return"number"==typeof a}function g(a){return"boolean"==typeof a}function h(a){return null===a}function i(a){return a instanceof Date}function j(a){return"bigint"==typeof a}function k(a){return"u">typeof Buffer&&Buffer.isBuffer(a)}function l(a){return"function"==typeof a}function m(a){return"object"==typeof a&&null!==a}function n(a){return Object.freeze(a)}function o(a){return p(a)?a:[a]}function p(a){return Array.isArray(a)}function q(a){return a}function r(a){return a instanceof Error?a.message:String(a)}c.d(b,{$P:()=>i,CN:()=>n,Et:()=>f,Gv:()=>m,I4:()=>r,Kg:()=>e,Lm:()=>g,MH:()=>p,Pe:()=>k,Tn:()=>l,_j:()=>o,b0:()=>d,kZ:()=>h,lQ:()=>q,sI:()=>j}),Object.prototype.toString},19105:(a,b,c)=>{"use strict";c.d(b,{a:()=>e});var d=c(95260);function e(){return new f}class f{#i;get queryId(){return void 0===this.#i&&(this.#i=(0,d.D)(8)),this.#i}}},19523:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={HeadersAdapter:function(){return h},ReadonlyHeadersError:function(){return g}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(63574);class g extends Error{constructor(){super("Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers")}static callable(){throw new g}}class h extends Headers{constructor(a){super(),this.headers=new Proxy(a,{get(b,c,d){if("symbol"==typeof c)return f.ReflectAdapter.get(b,c,d);let e=c.toLowerCase(),g=Object.keys(a).find(a=>a.toLowerCase()===e);if(void 0!==g)return f.ReflectAdapter.get(b,g,d)},set(b,c,d,e){if("symbol"==typeof c)return f.ReflectAdapter.set(b,c,d,e);let g=c.toLowerCase(),h=Object.keys(a).find(a=>a.toLowerCase()===g);return f.ReflectAdapter.set(b,h??c,d,e)},has(b,c){if("symbol"==typeof c)return f.ReflectAdapter.has(b,c);let d=c.toLowerCase(),e=Object.keys(a).find(a=>a.toLowerCase()===d);return void 0!==e&&f.ReflectAdapter.has(b,e)},deleteProperty(b,c){if("symbol"==typeof c)return f.ReflectAdapter.deleteProperty(b,c);let d=c.toLowerCase(),e=Object.keys(a).find(a=>a.toLowerCase()===d);return void 0===e||f.ReflectAdapter.deleteProperty(b,e)}})}static seal(a){return new Proxy(a,{get(a,b,c){switch(b){case"append":case"delete":case"set":return g.callable;default:return f.ReflectAdapter.get(a,b,c)}}})}merge(a){return Array.isArray(a)?a.join(", "):a}static from(a){return a instanceof Headers?a:new h(a)}append(a,b){let c=this.headers[a];"string"==typeof c?this.headers[a]=[c,b]:Array.isArray(c)?c.push(b):this.headers[a]=b}delete(a){delete this.headers[a]}get(a){let b=this.headers[a];return void 0!==b?this.merge(b):null}has(a){return void 0!==this.headers[a]}set(a,b){this.headers[a]=b}forEach(a,b){for(let[c,d]of this.entries())a.call(b,d,c,this)}*entries(){for(let a of Object.keys(this.headers)){let b=a.toLowerCase(),c=this.get(b);yield[b,c]}}*keys(){for(let a of Object.keys(this.headers)){let b=a.toLowerCase();yield b}}*values(){for(let a of Object.keys(this.headers)){let b=this.get(a);yield b}}[Symbol.iterator](){return this.entries()}}},20177:(a,b)=>{"use strict";function c(a){for(let b=0;b<a.length;b++){let c=a[b];if("function"!=typeof c)throw Object.defineProperty(Error(`A "use server" file can only export async functions, found ${typeof c}.
|
|
12
|
+
Read more: https://nextjs.org/docs/messages/invalid-use-server-value`),"__NEXT_ERROR_CODE",{value:"E352",enumerable:!1,configurable:!0})}}Object.defineProperty(b,"D",{enumerable:!0,get:function(){return c}})},21513:(a,b,c)=>{"use strict";c.d(b,{o:()=>g});var d=c(18110),e=c(59255),f=c(67449);let g=(0,d.CN)({is:a=>"WhereNode"===a.kind,create:a=>(0,d.CN)({kind:"WhereNode",where:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,where:"And"===b?e.s.create(a.where,c):f.K.create(a.where,c)})})},21689:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"encodeCacheTag",{enumerable:!0,get:function(){return e}});let c=/[^\t\x20-\x7e]/,d=/[^\t\x20-\x7e]+/g;function e(a){return c.test(a)?a.replace(d,a=>encodeURIComponent(a)):a}},22046:(a,b,c)=>{"use strict";c.d(b,{e:()=>h});var d=c(18110),e=c(60812),f=c(62030),g=c(87301);let h=(0,d.CN)({is:a=>"DeleteQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"DeleteQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithOrderByItems:(a,b)=>g.L.cloneWithOrderByItems(a,b),cloneWithoutOrderBy:a=>g.L.cloneWithoutOrderBy(a),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:void 0!==a.using?f.f.cloneWithTables(a.using,b):f.f.create(b)})})},22475:(a,b,c)=>{"use strict";c.d(b,{q:()=>f});var d=c(90386),e=c(18110);let f=(0,e.CN)({is:a=>"ReferenceNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"ReferenceNode",table:b,column:a}),createSelectAll:a=>(0,e.CN)({kind:"ReferenceNode",table:a,column:d.U.create()})})},22817:(a,b,c)=>{"use strict";c.d(b,{y:()=>d});let d=a=>{let b=(a.plugins??[]).reduce((a,b)=>{let c=b.schema;if(!c)return a;for(let[b,d]of Object.entries(c))a[b]={fields:{...a[b]?.fields,...d.fields},modelName:d.modelName||b};return a},{}),c=a.rateLimit?.storage==="database",d={rateLimit:{modelName:a.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:a.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:a.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:a.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:e,session:f,account:g,verification:h,...i}=b,j={verification:{modelName:a.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:a.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:a.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:a.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:a.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:a.verification?.fields?.updatedAt||"updatedAt"},...h?.fields,...a.verification?.additionalFields},order:4}},k={session:{modelName:a.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:a.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:a.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:a.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:a.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:a.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:a.session?.fields?.userId||"userId",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...f?.fields,...a.session?.additionalFields},order:2}};return{user:{modelName:a.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:a.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:a.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:a.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:a.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:a.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:a.user?.fields?.updatedAt||"updatedAt"},...e?.fields,...a.user?.additionalFields},order:1},...!a.secondaryStorage||a.session?.storeSessionInDatabase?k:{},account:{modelName:a.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:a.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:a.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:a.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:a.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:a.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...g?.fields,...a.account?.additionalFields},order:3},...!a.secondaryStorage||a.verification?.storeInDatabase?j:{},...i,...c?d:{}}}},22943:(a,b,c)=>{"use strict";c.d(b,{OU:()=>k});var d=c(14877),e=c(18110),f=c(45541),g=c(17532),h=c(98444),i=c(31341),j=c(2929);class k{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new l({...this.#a,node:g.P.cloneWithWhen(this.#a.node,h.t.create((0,i.GB)(a)))})}whenRef(a,b,c){return new l({...this.#a,node:g.P.cloneWithWhen(this.#a.node,h.t.create((0,i.vC)(a,b,c)))})}}class l{#a;constructor(a){this.#a=(0,e.CN)(a)}then(a){return new m({...this.#a,node:g.P.cloneWithThen(this.#a.node,(0,j.qH)(a)?(0,j.dJ)(a):(0,j.$s)(a))})}thenRef(a){return new m({...this.#a,node:g.P.cloneWithThen(this.#a.node,(0,f.$O)(a))})}}class m{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new l({...this.#a,node:g.P.cloneWithWhen(this.#a.node,h.t.create((0,i.GB)(a)))})}whenRef(a,b,c){return new l({...this.#a,node:g.P.cloneWithWhen(this.#a.node,h.t.create((0,i.vC)(a,b,c)))})}else(a){return new n({...this.#a,node:g.P.cloneWith(this.#a.node,{else:(0,j.qH)(a)?(0,j.dJ)(a):(0,j.$s)(a)})})}elseRef(a){return new n({...this.#a,node:g.P.cloneWith(this.#a.node,{else:(0,f.$O)(a)})})}end(){return new d.Is(g.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(g.P.cloneWith(this.#a.node,{isStatement:!0}))}}class n{#a;constructor(a){this.#a=(0,e.CN)(a)}end(){return new d.Is(g.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(g.P.cloneWith(this.#a.node,{isStatement:!0}))}}},23121:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={refresh:function(){return r},revalidatePath:function(){return s},revalidateTag:function(){return p},updateTag:function(){return q}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(4190),g=c(83403),h=c(52730),i=c(29294),j=c(63033),k=c(96690),l=c(85556),m=c(16935),n=c(66554),o=c(21689);function p(a,b){return b||console.warn('"revalidateTag" without the second argument is now deprecated, add second argument of "max" or use "updateTag". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'),t([(0,o.encodeCacheTag)(a)],`revalidateTag ${a}`,b)}function q(a){let b=i.workAsyncStorage.getStore();if(!b||b.page.endsWith("/route"))throw Object.defineProperty(Error("updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag"),"__NEXT_ERROR_CODE",{value:"E872",enumerable:!1,configurable:!0});return t([(0,o.encodeCacheTag)(a)],`updateTag ${a}`,void 0)}function r(){let a=i.workAsyncStorage.getStore(),b=j.workUnitAsyncStorage.getStore();if(!a||a.page.endsWith("/route")||(null==b?void 0:b.phase)!=="action")throw Object.defineProperty(Error("refresh can only be called from within a Server Action. See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh"),"__NEXT_ERROR_CODE",{value:"E870",enumerable:!1,configurable:!0});a&&(a.pathWasRevalidated=m.ActionDidRevalidateDynamicOnly)}function s(a,b){if(a.length>h.NEXT_CACHE_SOFT_TAG_MAX_LENGTH)return void console.warn(`Warning: revalidatePath received "${a}" which exceeded max length of ${h.NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);let c=`${h.NEXT_CACHE_IMPLICIT_TAG_ID}${(0,o.encodeCacheTag)((0,n.removeTrailingSlash)(a))}`;b?c+=`${c.endsWith("/")?"":"/"}${b}`:(0,g.isDynamicRoute)(a)&&console.warn(`Warning: a dynamic page path "${a}" was passed to "revalidatePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);let d=[c];return c===`${h.NEXT_CACHE_IMPLICIT_TAG_ID}/`?d.push(`${h.NEXT_CACHE_IMPLICIT_TAG_ID}/index`):c===`${h.NEXT_CACHE_IMPLICIT_TAG_ID}/index`&&d.push(`${h.NEXT_CACHE_IMPLICIT_TAG_ID}/`),t(d,`revalidatePath ${a}`)}function t(a,b,c){var d;let e=i.workAsyncStorage.getStore();if(!e||!e.incrementalCache)throw Object.defineProperty(Error(`Invariant: static generation store missing in ${b}`),"__NEXT_ERROR_CODE",{value:"E263",enumerable:!1,configurable:!0});let g=j.workUnitAsyncStorage.getStore();if(g){if("render"===g.phase)throw Object.defineProperty(Error(`Route ${e.route} used "${b}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E7",enumerable:!1,configurable:!0});switch(g.type){case"cache":case"private-cache":throw Object.defineProperty(Error(`Route ${e.route} used "${b}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E181",enumerable:!1,configurable:!0});case"unstable-cache":throw Object.defineProperty(Error(`Route ${e.route} used "${b}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E306",enumerable:!1,configurable:!0});case"generate-static-params":throw Object.defineProperty(Error(`Route ${e.route} used "${b}" inside \`generateStaticParams\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E1127",enumerable:!1,configurable:!0});case"prerender":case"prerender-runtime":let a=Object.defineProperty(Error(`Route ${e.route} used ${b} without first calling \`await connection()\`.`),"__NEXT_ERROR_CODE",{value:"E406",enumerable:!1,configurable:!0});return(0,f.abortAndThrowOnSynchronousRequestDataAccess)(e.route,b,a,g);case"prerender-client":case"validation-client":throw Object.defineProperty(new l.InvariantError(`${b} must not be used within a client component. Next.js should be preventing ${b} from being included in client components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E693",enumerable:!1,configurable:!0});case"prerender-ppr":return(0,f.postponeWithTracking)(e.route,b,g.dynamicTracking);case"prerender-legacy":g.revalidate=0;let c=Object.defineProperty(new k.DynamicServerError(`Route ${e.route} couldn't be rendered statically because it used \`${b}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`),"__NEXT_ERROR_CODE",{value:"E558",enumerable:!1,configurable:!0});throw e.dynamicUsageDescription=b,e.dynamicUsageStack=c.stack,c}}for(let b of(e.pendingRevalidatedTags||(e.pendingRevalidatedTags=[]),a))-1===e.pendingRevalidatedTags.findIndex(a=>a.tag===b&&("string"==typeof a.profile&&"string"==typeof c?a.profile===c:"object"==typeof a.profile&&"object"==typeof c?JSON.stringify(a.profile)===JSON.stringify(c):a.profile===c))&&e.pendingRevalidatedTags.push({tag:b,profile:c});let h=c&&"object"==typeof c?c:c&&"string"==typeof c&&(null==e||null==(d=e.cacheLifeProfiles)?void 0:d[c])?e.cacheLifeProfiles[c]:void 0;c&&(null==h?void 0:h.expire)!==0||(e.pathWasRevalidated=m.ActionDidRevalidateStaticAndDynamic)}},23632:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"formatNextPathnameInfo",{enumerable:!0,get:function(){return h}});let d=c(66554),e=c(85239),f=c(6292),g=c(24501);function h(a){let b=(0,g.addLocale)(a.pathname,a.locale,a.buildId?void 0:a.defaultLocale,a.ignorePrefix);return(a.buildId||!a.trailingSlash)&&(b=(0,d.removeTrailingSlash)(b)),a.buildId&&(b=(0,f.addPathSuffix)((0,e.addPathPrefix)(b,`/_next/data/${a.buildId}`),"/"===a.pathname?"index.json":".json")),b=(0,e.addPathPrefix)(b,a.basePath),!a.buildId&&a.trailingSlash?b.endsWith("/")?b:(0,f.addPathSuffix)(b,"/"):(0,d.removeTrailingSlash)(b)}},23656:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={MutableRequestCookiesAdapter:function(){return o},ReadonlyRequestCookiesError:function(){return j},RequestCookiesAdapter:function(){return k},appendMutableCookies:function(){return n},areCookiesMutableInCurrentPhase:function(){return q},createCookiesWithMutableAccessCheck:function(){return p},getModifiedCookieValues:function(){return m},responseCookiesToRequestCookies:function(){return s}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(29033),g=c(63574),h=c(29294),i=c(16935);class j extends Error{constructor(){super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options")}static callable(){throw new j}}class k{static seal(a){return new Proxy(a,{get(a,b,c){switch(b){case"clear":case"delete":case"set":return j.callable;default:return g.ReflectAdapter.get(a,b,c)}}})}}let l=Symbol.for("next.mutated.cookies");function m(a){let b=a[l];return b&&Array.isArray(b)&&0!==b.length?b:[]}function n(a,b){let c=m(b);if(0===c.length)return!1;let d=new f.ResponseCookies(a),e=d.getAll();for(let a of c)d.set(a);for(let a of e)d.set(a);return!0}class o{static wrap(a,b){let c=new f.ResponseCookies(new Headers);for(let b of a.getAll())c.set(b);let d=[],e=new Set,j=()=>{let a=h.workAsyncStorage.getStore();if(a&&(a.pathWasRevalidated=i.ActionDidRevalidateStaticAndDynamic),d=c.getAll().filter(a=>e.has(a.name)),b){let a=[];for(let b of d){let c=new f.ResponseCookies(new Headers);c.set(b),a.push(c.toString())}b(a)}},k=new Proxy(c,{get(a,b,c){switch(b){case l:return d;case"delete":return function(...b){e.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.delete(...b),k}finally{j()}};case"set":return function(...b){e.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.set(...b),k}finally{j()}};default:return g.ReflectAdapter.get(a,b,c)}}});return k}}function p(a){let b=new Proxy(a.mutableCookies,{get(c,d,e){switch(d){case"delete":return function(...d){return r(a,"cookies().delete"),c.delete(...d),b};case"set":return function(...d){return r(a,"cookies().set"),c.set(...d),b};default:return g.ReflectAdapter.get(c,d,e)}}});return b}function q(a){return"action"===a.phase}function r(a,b){if(!q(a))throw new j}function s(a){let b=new f.RequestCookies(new Headers);for(let c of a.getAll())b.set(c);return b}},24191:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={getClientComponentLoaderMetrics:function(){return i},wrapClientComponentLoader:function(){return h}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e=0,f=0,g=0;function h(a){return"performance"in globalThis?{require:(...b)=>{let c=performance.now();0===e&&(e=c);try{return g+=1,a.__next_app__.require(...b)}finally{f+=performance.now()-c}},loadChunk:(...b)=>{let c=performance.now(),d=a.__next_app__.loadChunk(...b);return d.finally(()=>{f+=performance.now()-c}),d}}:a.__next_app__}function i(a={}){let b=0===e?void 0:{clientComponentLoadStart:e,clientComponentLoadTimes:f,clientComponentLoadCount:g};return a.reset&&(e=0,f=0,g=0),b}},24492:(a,b,c)=>{"use strict";c.d(b,{W:()=>f});var d=c(49479);class e extends d.R{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(a){return new e([...this.plugins,a])}withPlugins(a){return new e([...this.plugins,...a])}withPluginAtFront(a){return new e([a,...this.plugins])}withoutPlugins(){return new e([])}}let f=new e},24501:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"addLocale",{enumerable:!0,get:function(){return f}});let d=c(85239),e=c(42960);function f(a,b,c,f){if(!b||b===c)return a;let g=a.toLowerCase();return!f&&((0,e.pathHasPrefix)(g,"/api")||(0,e.pathHasPrefix)(g,`/${b.toLowerCase()}`))?a:(0,d.addPathPrefix)(a,`/${b}`)}},24543:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"RedirectStatusCode",{enumerable:!0,get:function(){return d}});var c,d=((c={})[c.SeeOther=303]="SeeOther",c[c.TemporaryRedirect=307]="TemporaryRedirect",c[c.PermanentRedirect=308]="PermanentRedirect",c);("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},24607:(a,b,c)=>{"use strict";c.d(b,{n:()=>p});var d=c(12757),e=c(91408),f=c(18110);class g{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#j=(0,f.CN)({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=a=>{this.nodeStack.push(a),this.#j[a.kind](a),this.nodeStack.pop()}}var h=c(5496),i=c(38441),j=c(80184),k=c(55112),l=c(44382),m=c(98444);let n=/'/g,o=/['"]/g;class p extends g{#k="";#l=[];get numParameters(){return this.#l.length}compileQuery(a,b){return this.#k="",this.#l=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(a),(0,f.CN)({query:a,queryId:b,sql:this.getSql(),parameters:[...this.#l]})}getSql(){return this.#k}visitSelectQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!e.o.is(this.parentNode)&&!d.B.is(this.parentNode)&&!k.Y.is(this.parentNode)&&!l.i.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("select"),a.distinctOn&&(this.append(" "),this.compileDistinctOn(a.distinctOn)),a.frontModifiers?.length&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.top&&(this.append(" "),this.visitNode(a.top)),a.selections&&(this.append(" "),this.compileList(a.selections)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.groupBy&&(this.append(" "),this.visitNode(a.groupBy)),a.having&&(this.append(" "),this.visitNode(a.having)),a.setOperations&&(this.append(" "),this.compileList(a.setOperations," ")),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.offset&&(this.append(" "),this.visitNode(a.offset)),a.fetch&&(this.append(" "),this.visitNode(a.fetch)),a.endModifiers?.length&&(this.append(" "),this.compileList(this.sortSelectModifiers(a.endModifiers)," ")),b&&this.append(")")}visitFrom(a){this.append("from "),this.compileList(a.froms)}visitSelection(a){this.visitNode(a.selection)}visitColumn(a){this.visitNode(a.column)}compileDistinctOn(a){this.append("distinct on ("),this.compileList(a),this.append(")")}compileList(a,b=", "){let c=a.length-1;for(let d=0;d<=c;d++)this.visitNode(a[d]),d<c&&this.append(b)}visitWhere(a){this.append("where "),this.visitNode(a.where)}visitHaving(a){this.append("having "),this.visitNode(a.having)}visitInsertQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append(a.replace?"replace":"insert"),a.orAction&&(this.append(" "),this.visitNode(a.orAction)),a.top&&(this.append(" "),this.visitNode(a.top)),a.into&&(this.append(" into "),this.visitNode(a.into)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.output&&(this.append(" "),this.visitNode(a.output)),a.values&&(this.append(" "),this.visitNode(a.values)),a.defaultValues&&(this.append(" "),this.append("default values")),a.onConflict&&(this.append(" "),this.visitNode(a.onConflict)),a.onDuplicateKey&&(this.append(" "),this.visitNode(a.onDuplicateKey)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitValues(a){this.append("values "),this.compileList(a.values)}visitDeleteQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("delete "),a.top&&(this.visitNode(a.top),this.append(" ")),this.visitNode(a.from),a.output&&(this.append(" "),this.visitNode(a.output)),a.using&&(this.append(" "),this.visitNode(a.using)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitReturning(a){this.append("returning "),this.compileList(a.selections)}visitAlias(a){this.visitNode(a.node),this.append(" as "),this.visitNode(a.alias)}visitReference(a){a.table&&(this.visitNode(a.table),this.append(".")),this.visitNode(a.column)}visitSelectAll(a){this.append("*")}visitIdentifier(a){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(a),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(a){if(!(0,f.Kg)(a.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(a.name))}visitAnd(a){this.visitNode(a.left),this.append(" and "),this.visitNode(a.right)}visitOr(a){this.visitNode(a.left),this.append(" or "),this.visitNode(a.right)}visitValue(a){a.immediate?this.appendImmediateValue(a.value):this.appendValue(a.value)}visitValueList(a){this.append("("),this.compileList(a.values),this.append(")")}visitTuple(a){this.append("("),this.compileList(a.values),this.append(")")}visitPrimitiveValueList(a){this.append("(");let{values:b}=a;for(let a=0;a<b.length;++a)this.appendValue(b[a]),a!==b.length-1&&this.append(", ");this.append(")")}visitParens(a){this.append("("),this.visitNode(a.node),this.append(")")}visitJoin(a){this.append(s[a.joinType]),this.append(" "),this.visitNode(a.table),a.on&&(this.append(" "),this.visitNode(a.on))}visitOn(a){this.append("on "),this.visitNode(a.on)}visitRaw(a){let{sqlFragments:b,parameters:c}=a;for(let a=0;a<b.length;++a)this.append(b[a]),c.length>a&&this.visitNode(c[a])}visitOperator(a){this.append(a.operator)}visitTable(a){this.visitNode(a.table)}visitSchemableIdentifier(a){a.schema&&(this.visitNode(a.schema),this.append(".")),this.visitNode(a.identifier)}visitCreateTable(a){this.append("create "),a.frontModifiers?.length&&(this.compileList(a.frontModifiers," "),this.append(" ")),a.temporary&&this.append("temporary "),this.append("table "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.table),a.selectQuery||(this.append(" ("),this.compileList([...a.columns,...a.constraints??[],...a.indexes??[]]),this.append(")")),a.onCommit&&(this.append(" on commit "),this.append(a.onCommit)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," ")),a.selectQuery&&(this.append(" as "),this.visitNode(a.selectQuery))}visitColumnDefinition(a){a.ifNotExists&&this.append("if not exists "),this.visitNode(a.column),this.append(" "),this.visitNode(a.dataType),a.unsigned&&this.append(" unsigned"),a.frontModifiers&&a.frontModifiers.length>0&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.generated&&(this.append(" "),this.visitNode(a.generated)),a.identity&&this.append(" identity"),a.defaultTo&&(this.append(" "),this.visitNode(a.defaultTo)),a.notNull&&this.append(" not null"),a.unique&&this.append(" unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.primaryKey&&this.append(" primary key"),a.autoIncrement&&(this.append(" "),this.append(this.getAutoIncrement())),a.references&&(this.append(" "),this.visitNode(a.references)),a.check&&(this.append(" "),this.visitNode(a.check)),a.endModifiers&&a.endModifiers.length>0&&(this.append(" "),this.compileList(a.endModifiers," "))}getAutoIncrement(){return"auto_increment"}visitReferences(a){this.append("references "),this.visitNode(a.table),this.append(" ("),this.compileList(a.columns),this.append(")"),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate))}visitDropTable(a){this.append("drop "),a.temporary&&this.append("temporary "),this.append("table "),a.ifExists&&this.append("if exists "),this.visitNode(a.table),a.cascade&&this.append(" cascade")}visitDataType(a){this.append(a.dataType)}visitOrderBy(a){this.append("order by "),this.compileList(a.items)}visitOrderByItem(a){this.visitNode(a.orderBy),a.collation&&(this.append(" "),this.visitNode(a.collation)),a.direction&&(this.append(" "),this.visitNode(a.direction)),a.nulls&&(this.append(" nulls "),this.append(a.nulls))}visitGroupBy(a){this.append("group by "),this.compileList(a.items)}visitGroupByItem(a){this.visitNode(a.groupBy)}visitUpdateQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);if(void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("update "),a.top&&(this.visitNode(a.top),this.append(" ")),a.table&&(this.visitNode(a.table),this.append(" ")),this.append("set "),a.updates&&this.compileList(a.updates),a.output&&(this.append(" "),this.visitNode(a.output)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins){if(!a.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(a.joins," ")}a.where&&(this.append(" "),this.visitNode(a.where)),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitColumnUpdate(a){this.visitNode(a.column),this.append(" = "),this.visitNode(a.value)}visitLimit(a){this.append("limit "),this.visitNode(a.limit)}visitOffset(a){this.append("offset "),this.visitNode(a.offset)}visitOnConflict(a){this.append("on conflict"),a.columns?(this.append(" ("),this.compileList(a.columns),this.append(")")):a.constraint?(this.append(" on constraint "),this.visitNode(a.constraint)):a.indexExpression&&(this.append(" ("),this.visitNode(a.indexExpression),this.append(")")),a.indexWhere&&(this.append(" "),this.visitNode(a.indexWhere)),!0===a.doNothing?this.append(" do nothing"):a.updates&&(this.append(" do update set "),this.compileList(a.updates),a.updateWhere&&(this.append(" "),this.visitNode(a.updateWhere)))}visitOnDuplicateKey(a){this.append("on duplicate key update "),this.compileList(a.updates)}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.using&&(this.append(" using "),this.visitNode(a.using)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.where&&(this.append(" "),this.visitNode(a.where))}visitDropIndex(a){this.append("drop index "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.cascade&&this.append(" cascade")}visitCreateSchema(a){this.append("create schema "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.schema)}visitDropSchema(a){this.append("drop schema "),a.ifExists&&this.append("if exists "),this.visitNode(a.schema),a.cascade&&this.append(" cascade")}visitPrimaryKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("primary key ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}buildDeferrable(a){void 0!==a.deferrable&&(a.deferrable?this.append(" deferrable"):this.append(" not deferrable")),void 0!==a.initiallyDeferred&&(a.initiallyDeferred?this.append(" initially deferred"):this.append(" initially immediate"))}visitUniqueConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),this.append(" ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}visitCheckConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("check ("),this.visitNode(a.expression),this.append(")")}visitForeignKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("foreign key ("),this.compileList(a.columns),this.append(") "),this.visitNode(a.references),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate)),this.buildDeferrable(a)}visitList(a){this.compileList(a.items)}visitWith(a){this.append("with "),a.recursive&&this.append("recursive "),this.compileList(a.expressions)}visitCommonTableExpression(a){this.visitNode(a.name),this.append(" as "),(0,f.Lm)(a.materialized)&&(a.materialized||this.append("not "),this.append("materialized ")),this.visitNode(a.expression)}visitCommonTableExpressionName(a){this.visitNode(a.table),a.columns&&(this.append("("),this.compileList(a.columns),this.append(")"))}visitAlterTable(a){this.append("alter table "),this.visitNode(a.table),this.append(" "),a.renameTo&&(this.append("rename to "),this.visitNode(a.renameTo)),a.setSchema&&(this.append("set schema "),this.visitNode(a.setSchema)),a.addConstraint&&this.visitNode(a.addConstraint),a.dropConstraint&&this.visitNode(a.dropConstraint),a.renameConstraint&&this.visitNode(a.renameConstraint),a.columnAlterations&&this.compileColumnAlterations(a.columnAlterations),a.addIndex&&this.visitNode(a.addIndex),a.dropIndex&&this.visitNode(a.dropIndex)}visitAddColumn(a){this.append("add column "),this.visitNode(a.column)}visitRenameColumn(a){this.append("rename column "),this.visitNode(a.column),this.append(" to "),this.visitNode(a.renameTo)}visitDropColumn(a){this.append("drop column "),a.ifExists&&this.append("if exists "),this.visitNode(a.column)}visitAlterColumn(a){this.append("alter column "),this.visitNode(a.column),this.append(" "),a.dataType&&(this.announcesNewColumnDataType()&&this.append("type "),this.visitNode(a.dataType),a.dataTypeExpression&&(this.append("using "),this.visitNode(a.dataTypeExpression))),a.setDefault&&(this.append("set default "),this.visitNode(a.setDefault)),a.dropDefault&&this.append("drop default"),a.setNotNull&&this.append("set not null"),a.dropNotNull&&this.append("drop not null")}visitModifyColumn(a){this.append("modify column "),this.visitNode(a.column)}visitAddConstraint(a){this.append("add "),this.visitNode(a.constraint)}visitDropConstraint(a){this.append("drop constraint "),a.ifExists&&this.append("if exists "),this.visitNode(a.constraintName),"cascade"===a.modifier?this.append(" cascade"):"restrict"===a.modifier&&this.append(" restrict")}visitRenameConstraint(a){this.append("rename constraint "),this.visitNode(a.oldName),this.append(" to "),this.visitNode(a.newName)}visitSetOperation(a){this.append(a.operator),this.append(" "),a.all&&this.append("all "),this.visitNode(a.expression)}visitCreateView(a){this.append("create "),a.orReplace&&this.append("or replace "),a.materialized&&this.append("materialized "),a.temporary&&this.append("temporary "),this.append("view "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),this.append(" "),a.columns&&(this.append("("),this.compileList(a.columns),this.append(") ")),a.as&&(this.append("as "),this.visitNode(a.as))}visitRefreshMaterializedView(a){this.append("refresh materialized view "),a.concurrently&&this.append("concurrently "),this.visitNode(a.name),a.withNoData?this.append(" with no data"):this.append(" with data")}visitDropView(a){this.append("drop "),a.materialized&&this.append("materialized "),this.append("view "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.cascade&&this.append(" cascade")}visitGenerated(a){this.append("generated "),a.always&&this.append("always "),a.byDefault&&this.append("by default "),this.append("as "),a.identity&&this.append("identity"),a.expression&&(this.append("("),this.visitNode(a.expression),this.append(")")),a.stored&&this.append(" stored")}visitDefaultValue(a){this.append("default "),this.visitNode(a.defaultValue)}visitSelectModifier(a){a.rawModifier?this.visitNode(a.rawModifier):this.append(q[a.modifier]),a.of&&(this.append(" of "),this.compileList(a.of,", "))}visitCreateType(a){this.append("create type "),this.visitNode(a.name),a.enum&&(this.append(" as enum "),this.visitNode(a.enum))}visitDropType(a){this.append("drop type "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.additionalNames?.length&&(this.append(", "),this.compileList(a.additionalNames)),a.cascade&&this.append(" cascade")}visitAlterType(a){this.append("alter type "),this.visitNode(a.name),this.append(" "),a.addValue?this.visitNode(a.addValue):a.renameTo?(this.append("rename to "),this.visitNode(a.renameTo)):a.renameValue?this.visitNode(a.renameValue):a.setSchema&&(this.append("set schema "),this.visitNode(a.setSchema))}visitAddValue(a){this.append("add value "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.value),a.neighborValue&&(this.append(a.isBefore?" before ":" after "),this.visitNode(a.neighborValue))}visitRenameValue(a){this.append("rename value "),this.visitNode(a.oldValue),this.append(" to "),this.visitNode(a.newValue)}visitExplain(a){this.append("explain"),(a.options||a.format)&&(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),a.options&&(this.visitNode(a.options),a.format&&this.append(this.getExplainOptionsDelimiter())),a.format&&(this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(a.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(a){this.append("default")}visitAggregateFunction(a){this.append(a.func),this.append("("),a.distinct&&this.append("distinct "),this.compileList(a.aggregated),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),this.append(")"),a.withinGroup&&(this.append(" within group ("),this.visitNode(a.withinGroup),this.append(")")),a.filter&&(this.append(" filter("),this.visitNode(a.filter),this.append(")")),a.over&&(this.append(" "),this.visitNode(a.over))}visitOver(a){this.append("over("),a.partitionBy&&(this.visitNode(a.partitionBy),a.orderBy&&this.append(" ")),a.orderBy&&this.visitNode(a.orderBy),this.append(")")}visitPartitionBy(a){this.append("partition by "),this.compileList(a.items)}visitPartitionByItem(a){this.visitNode(a.partitionBy)}visitBinaryOperation(a){this.visitNode(a.leftOperand),this.append(" "),this.visitNode(a.operator),this.append(" "),this.visitNode(a.rightOperand)}visitUnaryOperation(a){this.visitNode(a.operator),this.isMinusOperator(a.operator)||this.append(" "),this.visitNode(a.operand)}isMinusOperator(a){return h.zX.is(a)&&"-"===a.operator}visitUsing(a){this.append("using "),this.compileList(a.tables)}visitFunction(a){this.append(a.func),this.append("("),this.compileList(a.arguments),this.append(")")}visitCase(a){this.append("case"),a.value&&(this.append(" "),this.visitNode(a.value)),a.when&&(this.append(" "),this.compileList(a.when," ")),a.else&&(this.append(" else "),this.visitNode(a.else)),this.append(" end"),a.isStatement&&this.append(" case")}visitWhen(a){this.append("when "),this.visitNode(a.condition),a.result&&(this.append(" then "),this.visitNode(a.result))}visitJSONReference(a){this.visitNode(a.reference),this.visitNode(a.traversal)}visitJSONPath(a){for(let b of(a.inOperator&&this.visitNode(a.inOperator),this.append("'$"),a.pathLegs))this.visitNode(b);this.append("'")}visitJSONPathLeg(a){let b="ArrayLocation"===a.type,c=String(a.value);b?(this.append("["),this.append(this.sanitizeStringLiteral(c)),this.append("]")):(this.append('."'),this.append(this.sanitizeJSONPathMemberValue(c)),this.append('"'))}visitJSONOperatorChain(a){for(let b=0,c=a.values.length;b<c;b++)b===c-1?this.visitNode(a.operator):this.append("->"),this.visitNode(a.values[b])}visitMergeQuery(a){a.with&&(this.visitNode(a.with),this.append(" ")),this.append("merge "),a.top&&(this.visitNode(a.top),this.append(" ")),this.append("into "),this.visitNode(a.into),a.using&&(this.append(" "),this.visitNode(a.using)),a.whens&&(this.append(" "),this.compileList(a.whens," ")),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.output&&(this.append(" "),this.visitNode(a.output)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitMatched(a){a.not&&this.append("not "),this.append("matched"),a.bySource&&this.append(" by source")}visitAddIndex(a){this.parentNode&&d.B.is(this.parentNode)||this.append("add "),a.unique&&this.append("unique "),this.append("index "),this.visitNode(a.name),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.using&&(this.append(" using "),this.visitNode(a.using))}visitCast(a){this.append("cast("),this.visitNode(a.expression),this.append(" as "),this.visitNode(a.dataType),this.append(")")}visitFetch(a){this.append("fetch next "),this.visitNode(a.rowCount),this.append(` rows ${a.modifier}`)}visitOutput(a){this.append("output "),this.compileList(a.selections)}visitTop(a){this.append(`top(${a.expression})`),a.modifiers&&this.append(` ${a.modifiers}`)}visitOrAction(a){this.append(a.action)}visitCollate(a){this.append("collate "),this.visitNode(a.collation)}append(a){this.#k+=a}appendValue(a){this.addParameter(a),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(a){let b=this.getLeftIdentifierWrapper(),c=this.getRightIdentifierWrapper(),d="";for(let e of a)d+=e,e===b?d+=b:e===c&&(d+=c);return d}sanitizeStringLiteral(a){return a.replace(n,"''")}sanitizeJSONPathMemberValue(a){return a.replace(o,a=>"'"===a?"''":'\\"')}addParameter(a){this.#l.push(a)}appendImmediateValue(a){if((0,f.Kg)(a))this.appendStringLiteral(a);else if((0,f.Et)(a)||(0,f.Lm)(a)||(0,f.sI)(a))this.append(a.toString());else if((0,f.kZ)(a))this.append("null");else if((0,f.$P)(a))this.appendImmediateValue(a.toISOString());else throw Error(`invalid immediate value ${a}`)}appendStringLiteral(a){this.append("'"),this.append(this.sanitizeStringLiteral(a)),this.append("'")}sortSelectModifiers(a){return(0,f.CN)(a.toSorted((a,b)=>a.modifier&&b.modifier?r[a.modifier]-r[b.modifier]:1))}compileColumnAlterations(a){this.compileList(a)}announcesNewColumnDataType(){return!0}}let q=(0,f.CN)({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),r=(0,f.CN)({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),s=(0,f.CN)({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})},25296:(a,b,c)=>{a.exports=c(83707),a.exports.Constants=c(1887),a.exports.Errors=c(81769),a.exports.FileAttr=c(32459),a.exports.decoder=c(57100)},26144:(a,b,c)=>{"use strict";c.d(b,{h:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"PrimitiveValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"PrimitiveValueListNode",values:(0,d.CN)([...a])})})},26675:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={ReadonlyURLSearchParams:function(){return f.ReadonlyURLSearchParams},RedirectType:function(){return m},forbidden:function(){return i.forbidden},notFound:function(){return h.notFound},permanentRedirect:function(){return g.permanentRedirect},redirect:function(){return g.redirect},unauthorized:function(){return j.unauthorized},unstable_isUnrecognizedActionError:function(){return l},unstable_rethrow:function(){return k.unstable_rethrow}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(5590),g=c(59324),h=c(50472),i=c(84643),j=c(47070),k=c(81222);function l(){throw Object.defineProperty(Error("`unstable_isUnrecognizedActionError` can only be used on the client."),"__NEXT_ERROR_CODE",{value:"E776",enumerable:!1,configurable:!0})}let m={push:"push",replace:"replace"};("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},27130:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={StaticGenBailoutError:function(){return f},isStaticGenBailoutError:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="NEXT_STATIC_GEN_BAILOUT";class f extends Error{constructor(...a){super(...a),this.code=e}}function g(a){return"object"==typeof a&&null!==a&&"code"in a&&a.code===e}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},27800:(a,b,c)=>{"use strict";c.d(b,{JB:()=>j,M$:()=>m,Xm:()=>l,uJ:()=>k});var d=c(18110),e=c(50182),f=c(3694),g=c(37338),h=c(98051),i=c(34716);function j(a){return(0,d.MH)(a)?a.map(a=>k(a)):[k(a)]}function k(a){return(0,d.Kg)(a)?l(a):(0,i.uc)(a)?a.toOperationNode():(0,g.v0)(a)}function l(a){let b=" as ";if(!a.includes(b))return m(a);{let[c,d]=a.split(b).map(n);return e.N.create(m(c),h.O.create(d))}}function m(a){if(!a.includes("."))return f.H.create(a);{let[b,c]=a.split(".").map(n);return f.H.createWithSchema(b,c)}}function n(a){return a.trim()}},27912:(a,b,c)=>{"use strict";c.d(b,{redactForLog:()=>f});let d=["CONSTELLA_VAULT_KEY","BETTER_AUTH_SECRET","CONSTELLA_WORKER_SECRET"],e=RegExp("sk-[A-Za-z0-9_-]{16,}|gh[posru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{40,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[baprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{6,}|-----BEGIN[\\s\\S]*?PRIVATE KEY-----[\\s\\S]*?-----END[\\s\\S]*?-----|\\bcn_[A-Za-z0-9_-]{24,}\\b|\\b\\d{6,}:[A-Za-z0-9_-]{30,}\\b","g");function f(a){return function(a,b=[]){if(!a)return a;let c=a;for(let a of[...b,...d.map(a=>process.env[a])])a&&a.length>=8&&(c=c.split(a).join("[redacted]"));return c.replace(e,"[redacted]")}(String(a??""))}},28238:(a,b)=>{"use strict";function c(a){return a.startsWith("/")?a:`/${a}`}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"ensureLeadingSlash",{enumerable:!0,get:function(){return c}})},28333:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return g}});let d=c(15258),e=c(80178),f=c(85556);class g{static #m=this.EMPTY=new g(null,{metadata:{},contentType:null});static fromStatic(a,b){return new g(a,{metadata:{},contentType:b})}constructor(a,{contentType:b,waitUntil:c,metadata:d}){this.response=a,this.contentType=b,this.metadata=d,this.waitUntil=c}assignMetadata(a){Object.assign(this.metadata,a)}get isNull(){return null===this.response}get isDynamic(){return"string"!=typeof this.response}toUnchunkedString(a=!1){if(null===this.response)return"";if("string"!=typeof this.response){if(!a)throw Object.defineProperty(new f.InvariantError("dynamic responses cannot be unchunked. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E732",enumerable:!1,configurable:!0});return(0,d.streamToString)(this.readable)}return this.response}get readable(){return null===this.response?new ReadableStream({start(a){a.close()}}):"string"==typeof this.response?(0,d.streamFromString)(this.response):Buffer.isBuffer(this.response)?(0,d.streamFromBuffer)(this.response):Array.isArray(this.response)?(0,d.chainStreams)(...this.response):this.response}coerce(){return null===this.response?[]:"string"==typeof this.response?[(0,d.streamFromString)(this.response)]:Array.isArray(this.response)?this.response:Buffer.isBuffer(this.response)?[(0,d.streamFromBuffer)(this.response)]:[this.response]}pipeThrough(a){this.response=this.readable.pipeThrough(a)}unshift(a){this.response=this.coerce(),this.response.unshift(a)}push(a){this.response=this.coerce(),this.response.push(a)}async pipeTo(a){try{await this.readable.pipeTo(a,{preventClose:!0}),this.waitUntil&&await this.waitUntil,await a.close()}catch(b){if((0,e.isAbortError)(b))return void await a.abort(b);throw b}}async pipeToNodeResponse(a){await (0,e.pipeToNodeResponse)(this.readable,a,this.waitUntil)}}},28434:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={METADATA_BOUNDARY_NAME:function(){return e},OUTLET_BOUNDARY_NAME:function(){return g},ROOT_LAYOUT_BOUNDARY_NAME:function(){return h},VIEWPORT_BOUNDARY_NAME:function(){return f}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="__next_metadata_boundary__",f="__next_viewport_boundary__",g="__next_outlet_boundary__",h="__next_root_layout_boundary__"},28528:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"isPostpone",{enumerable:!0,get:function(){return d}});let c=Symbol.for("react.postpone");function d(a){return"object"==typeof a&&null!==a&&a.$$typeof===c}},29033:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={RequestCookies:function(){return f.RequestCookies},ResponseCookies:function(){return f.ResponseCookies},stringifyCookie:function(){return f.stringifyCookie}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(68454)},30408:(a,b,c)=>{b.EntryHeader=c(59055),b.MainHeader=c(8932)},30811:(a,b,c)=>{"use strict";a.exports=c(10846)},31341:(a,b,c)=>{"use strict";c.d(b,{GB:()=>n,KN:()=>r,Ve:()=>q,ds:()=>o,vC:()=>p});var d=c(2529),e=c(18110),f=c(60351),g=c(5496),h=c(45541),i=c(2929),j=c(76051),k=c(59255),l=c(38441),m=c(67449);function n(a){if(3===a.length)return o(a[0],a[1],a[2]);if(1===a.length)return(0,i.$s)(a[0]);throw Error(`invalid arguments: ${JSON.stringify(a)}`)}function o(a,b,c){var e;return("is"===(e=b)||"is not"===e)&&s(c)?d.l.create((0,h.$O)(a),t(b),j.q.createImmediate(c)):d.l.create((0,h.$O)(a),t(b),(0,i.U2)(c))}function p(a,b,c){return d.l.create((0,h.$O)(a),t(b),(0,h.$O)(c))}function q(a,b){return r(Object.entries(a).filter(([,a])=>!(0,e.b0)(a)).map(([a,b])=>o(a,s(b)?"is":"=",b)),b)}function r(a,b,c=!0){let e="and"===b?k.s.create:m.K.create;if(0===a.length)return d.l.create(j.q.createImmediate(1),g.zX.create("="),j.q.createImmediate(+("and"===b)));let f=u(a[0]);for(let b=1;b<a.length;++b)f=e(f,u(a[b]));return a.length>1&&c?l.k.create(f):f}function s(a){return(0,e.kZ)(a)||(0,e.Lm)(a)}function t(a){if((0,g.UH)(a))return g.zX.create(a);if((0,f.N)(a))return a.toOperationNode();throw Error(`invalid operator ${JSON.stringify(a)}`)}function u(a){return(0,f.N)(a)?a.toOperationNode():a}},32459:(a,b,c)=>{let d=c(33873);a.exports=function(a,{fs:b}){var c=a||"",e={directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0},f=null;return c&&b.existsSync(c)?(e.directory=(f=b.statSync(c)).isDirectory(),e.mtime=f.mtime,e.atime=f.atime,e.executable=(73&f.mode)!=0,e.readonly=(128&f.mode)==0,e.hidden="."===d.basename(c)[0]):console.warn("Invalid path: "+c),{get directory(){return e.directory},get readOnly(){return e.readonly},get hidden(){return e.hidden},get mtime(){return e.mtime},get atime(){return e.atime},get executable(){return e.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:c,isDirectory:e.directory,isReadOnly:e.readonly,isHidden:e.hidden,isExecutable:e.executable,mTime:e.mtime,aTime:e.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}},33583:(a,b,c)=>{"use strict";let d,e,f,g;c.d(b,{f:()=>m});var h,i=c(64561);let j={SpanStatusCode:{UNSET:0,OK:1,ERROR:2},trace:(h=f={end(){},setAttribute(a,b){},setStatus(a){},recordException(a){},updateName:a=>f},g={startActiveSpan:function(a,...b){return(0,b[b.length-1])(h)}},{getTracer:(a,b)=>g,getActiveSpan(){}})};function k(){return d||(d=Promise.resolve().then(c.t.bind(c,2636,19)).then(a=>{e=a}).catch(()=>void 0)),e??j}function l(a,b){let{SpanStatusCode:c}=k();!function(a){if(null!=a&&"object"==typeof a&&"name"in a&&"APIError"===a.name&&"statusCode"in a){let b=a.statusCode;return b>=300&&b<400}return!1}(b)?(a.recordException(b),a.setStatus({code:c.ERROR,message:String(b?.message??b)})):(a.setAttribute(i.OR,b.statusCode),a.setStatus({code:c.OK})),a.end()}function m(a,b,c){let{trace:d}=k();return d.getTracer("better-auth","1.6.19").startActiveSpan(a,{attributes:b},a=>{try{let b=c();if(b instanceof Promise)return b.then(b=>(a.end(),b)).catch(b=>{throw l(a,b),b});return a.end(),b}catch(b){throw l(a,b),b}})}},33866:(a,b,c)=>{"use strict";c.d(b,{Q:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"JSONReferenceNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JSONReferenceNode",reference:a,traversal:b}),cloneWithTraversal:(a,b)=>(0,d.CN)({...a,traversal:b})})},34219:(a,b,c)=>{"use strict";function d(a){throw Object.defineProperty(Error("`cacheLife()` is only available with the `cacheComponents` config."),"__NEXT_ERROR_CODE",{value:"E887",enumerable:!1,configurable:!0})}Object.defineProperty(b,"F",{enumerable:!0,get:function(){return d}}),c(85556),c(29294),c(63033)},34248:(a,b,c)=>{"use strict";c.d(b,{V:()=>e});let d=import("node:async_hooks").then(a=>a.AsyncLocalStorage).catch(a=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if("u">typeof window)return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),a});async function e(){let a=await d;if(null!==a)return a;throw Error("getAsyncLocalStorage is only available in server code")}},34310:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={atLeastOneTask:function(){return g},scheduleImmediate:function(){return f},scheduleOnNextTick:function(){return e},waitAtLeastOneReactRenderTask:function(){return h}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e=a=>{Promise.resolve().then(()=>{process.nextTick(a)})},f=a=>{setImmediate(a)};function g(){return new Promise(a=>f(a))}function h(){return new Promise(a=>setImmediate(a))}},34716:(a,b,c)=>{"use strict";c.d(b,{bj:()=>i,uc:()=>k});var d=c(50182),e=c(98051),f=c(60351),g=c(27800),h=c(18110);class i{#n;get table(){return this.#n}constructor(a){this.#n=a}as(a){return new j(this.#n,a)}}class j{#n;#f;get table(){return this.#n}get alias(){return this.#f}constructor(a,b){this.#n=a,this.#f=b}toOperationNode(){return d.N.create((0,g.M$)(this.#n),e.O.create(this.#f))}}function k(a){return(0,h.Gv)(a)&&(0,f.N)(a)&&(0,h.Kg)(a.table)&&(0,h.Kg)(a.alias)}},36688:(a,b,c)=>{"use strict";c.d(b,{a:()=>h});var d=c(48145),e=c(31341),f=c(59916),g=c(27800);function h(a,b){var c,h,i,j,k,l,m,n;if(3===b.length){return c=a,h=b[0],i=b[1],j=b[2],d.b.createWithOn(c,(0,g.uJ)(h),(0,e.vC)(i,"=",j))}if(2===b.length){return k=a,l=b[0],(0,b[1])((0,f.GQ)(k,l)).toOperationNode()}if(1===b.length){return m=a,n=b[0],d.b.create(m,(0,g.uJ)(n))}throw Error("not implemented")}},37338:(a,b,c)=>{"use strict";c.d(b,{SS:()=>j,YK:()=>h,v0:()=>i});var d=c(38027),e=c(60351),f=c(80627),g=c(18110);function h(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(a)}`)}function i(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(a)}`)}function j(a){return(0,d.B)(a)||(0,d.q)(a)||(0,g.Tn)(a)}},37626:(a,b,c)=>{"use strict";c.d(b,{Z:()=>f});var d=c(18110),e=c(98051);let f=(0,d.CN)({is:a=>"ColumnNode"===a.kind,create:a=>(0,d.CN)({kind:"ColumnNode",column:e.O.create(a)})})},37694:(a,b,c)=>{"use strict";c.d(b,{L:()=>k});var d=c(18110),e=c(60812);let f=(0,d.CN)({is:a=>"GroupByNode"===a.kind,create:a=>(0,d.CN)({kind:"GroupByNode",items:(0,d.CN)(a)}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})});var g=c(59255),h=c(67449);let i=(0,d.CN)({is:a=>"HavingNode"===a.kind,create:a=>(0,d.CN)({kind:"HavingNode",having:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,having:"And"===b?g.s.create(a.having,c):h.K.create(a.having,c)})});var j=c(87301);let k=(0,d.CN)({is:a=>"SelectQueryNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectQueryNode",...a&&{with:a}}),createFrom:(a,b)=>(0,d.CN)({kind:"SelectQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithSelections:(a,b)=>(0,d.CN)({...a,selections:a.selections?(0,d.CN)([...a.selections,...b]):(0,d.CN)(b)}),cloneWithDistinctOn:(a,b)=>(0,d.CN)({...a,distinctOn:a.distinctOn?(0,d.CN)([...a.distinctOn,...b]):(0,d.CN)(b)}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithOrderByItems:(a,b)=>j.L.cloneWithOrderByItems(a,b),cloneWithGroupByItems:(a,b)=>(0,d.CN)({...a,groupBy:a.groupBy?f.cloneWithItems(a.groupBy,b):f.create(b)}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithOffset:(a,b)=>(0,d.CN)({...a,offset:b}),cloneWithFetch:(a,b)=>(0,d.CN)({...a,fetch:b}),cloneWithHaving:(a,b)=>(0,d.CN)({...a,having:a.having?i.cloneWithOperation(a.having,"And",b):i.create(b)}),cloneWithSetOperations:(a,b)=>(0,d.CN)({...a,setOperations:a.setOperations?(0,d.CN)([...a.setOperations,...b]):(0,d.CN)([...b])}),cloneWithoutSelections:a=>(0,d.CN)({...a,selections:[]}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithoutOffset:a=>(0,d.CN)({...a,offset:void 0}),cloneWithoutOrderBy:a=>j.L.cloneWithoutOrderBy(a),cloneWithoutGroupBy:a=>(0,d.CN)({...a,groupBy:void 0})})},37807:(a,b,c)=>{"use strict";c.d(b,{I:()=>t});var d=c(6840),e=c(9853),f=c(22817),g=c(56603),h=c(15214),i=c(1434),j=c(62547),k=c(85680),l=c(15793);let m=({usePlural:a,schema:b,disableIdGeneration:c,options:d,customIdGenerator:e,supportsUUIDs:f})=>{let g=(0,j.G)({usePlural:a,schema:b});return({customModelName:a,forceAllowId:b})=>{let i=d.advanced?.database?.generateId==="serial",j=d.advanced?.database?.generateId==="uuid",k=!c&&(!i||!!b)&&(!j||!f),m=g(a??"id");return{type:i?"number":"string",required:!!k,...k?{defaultValue(){if(c)return;let a=d.advanced?.database?.generateId;if(!1!==a&&"serial"!==a)return"function"==typeof a?a({model:m}):"uuid"===a?crypto.randomUUID():e?e({model:m}):(0,l.$)()}}:{},transform:{input:a=>{if(a){if(i){let b=Number(a);if(isNaN(b))return;return b}if(j){if(k&&!b)return a;if(c)return;if(b&&"string"==typeof a)if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a))return a;else{let a=Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","");h.vF.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.",a)}return f||"string"==typeof a||f?void 0:crypto.randomUUID()}return a}},output:a=>{if(a)return String(a)}}}}};var n=c(43876),o=c(66351),p=c(33583),q=c(64561);let r=[],s=-1,t=({adapter:a,config:b})=>c=>{let g=Math.random().toString(36).substring(2,15),l={...b,supportsBooleans:b.supportsBooleans??!0,supportsDates:b.supportsDates??!0,supportsJSON:b.supportsJSON??!1,adapterName:b.adapterName??b.adapterId,supportsNumericIds:b.supportsNumericIds??!0,supportsUUIDs:b.supportsUUIDs??!1,supportsArrays:b.supportsArrays??!1,transaction:b.transaction??!1,disableTransformInput:b.disableTransformInput??!1,disableTransformOutput:b.disableTransformOutput??!1,disableTransformJoin:b.disableTransformJoin??!1};if(c.advanced?.database?.generateId==="serial"&&!1===l.supportsNumericIds)throw new e.$l(`[${l.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);let t=(0,f.y)(c),y=(...a)=>{if(!0===l.debugLogs||"object"==typeof l.debugLogs){let b=(0,h.h)({level:"info"});if("object"==typeof l.debugLogs&&"isRunningAdapterTests"in l.debugLogs){l.debugLogs.isRunningAdapterTests&&(a.shift(),r.push({instance:g,args:a}));return}if("object"!=typeof l.debugLogs||!l.debugLogs.logCondition||l.debugLogs.logCondition?.())if("object"==typeof a[0]&&"method"in a[0]){let c=a.shift().method;if("object"==typeof l.debugLogs){if("create"===c&&!l.debugLogs.create)return;else if("update"===c&&!l.debugLogs.update)return;else if("updateMany"===c&&!l.debugLogs.updateMany)return;else if("findOne"===c&&!l.debugLogs.findOne)return;else if("findMany"===c&&!l.debugLogs.findMany)return;else if("delete"===c&&!l.debugLogs.delete)return;else if("deleteMany"===c&&!l.debugLogs.deleteMany)return;else if("consumeOne"===c&&!l.debugLogs.consumeOne)return;else if("incrementOne"===c&&!l.debugLogs.incrementOne)return;else if("count"===c&&!l.debugLogs.count)return}b.info(`[${l.adapterName}]`,...a)}else b.info(`[${l.adapterName}]`,...a)}},z=(0,h.h)(c.logger),A=(0,j.G)({usePlural:l.usePlural,schema:t}),B=(0,k.z)({usePlural:l.usePlural,schema:t}),C=(0,o.j)({usePlural:l.usePlural,schema:t}),D=(0,n.y)({schema:t,usePlural:l.usePlural}),E=m({schema:t,options:c,usePlural:l.usePlural,disableIdGeneration:l.disableIdGeneration,customIdGenerator:l.customIdGenerator,supportsUUIDs:l.supportsUUIDs}),F=(({usePlural:a,schema:b,options:c,customIdGenerator:d,disableIdGeneration:f})=>{let g=(0,j.G)({usePlural:a,schema:b}),h=(0,k.z)({usePlural:a,schema:b}),i=m({usePlural:a,schema:b,options:c,customIdGenerator:d,disableIdGeneration:f});return({model:a,field:c})=>{let d=g(a),f=h({field:c,model:d}),j=b[d].fields;j.id=i({customModelName:d});let k=j[f];if(!k)throw new e.$l(`Field ${c} not found in model ${a}`);return k}})({schema:t,options:c,usePlural:l.usePlural,disableIdGeneration:l.disableIdGeneration,customIdGenerator:l.customIdGenerator}),G=async(a,b,d,e)=>{let f={},g=t[b].fields,h=l.mapKeysTransformInput??{},i=c.advanced?.database?.generateId==="serial";for(let j in g.id=E({customModelName:b,forceAllowId:e&&"id"in a}),g){let e=a[j],k=g[j],m=h[j]||g[j].fieldName||j;if(void 0===e&&(void 0===k.defaultValue&&!k.transform?.input&&!("update"===d&&k.onUpdate)||"update"===d&&!k.onUpdate))continue;if(k&&"date"===k.type&&!(e instanceof Date)&&"string"==typeof e)try{e=new Date(e)}catch{z.error("[Adapter Factory] Failed to convert string to date",{value:e,field:j})}let n=function(a,b,c){if("update"===c)return void 0===a&&void 0!==b.onUpdate?"function"==typeof b.onUpdate?b.onUpdate():b.onUpdate:a;return"create"===c&&(void 0===a||!0===b.required&&null===a)&&void 0!==b.defaultValue?"function"==typeof b.defaultValue?b.defaultValue():b.defaultValue:a}(e,k,d);k.transform?.input&&(n=await k.transform.input(n)),k.references?.field==="id"&&i?n=Array.isArray(n)?n.map(a=>null!==a?Number(a):null):null!==n?Number(n):null:!1===l.supportsJSON&&"object"==typeof n&&"json"===k.type||!1===l.supportsArrays&&Array.isArray(n)&&("string[]"===k.type||"number[]"===k.type)?n=JSON.stringify(n):!1===l.supportsDates&&n instanceof Date&&"date"===k.type?n=n.toISOString():!1===l.supportsBooleans&&"boolean"==typeof n&&(n=+!!n),l.customTransformInput&&(n=l.customTransformInput({data:n,action:d,field:m,fieldAttributes:k,model:C(b),schema:t,options:c})),void 0!==n&&(f[m]=n)}return f},H=async(a,b,d=[],e)=>{let f=async(a,b,d=[])=>{if(!a)return null;let e=l.mapKeysTransformOutput??{},f={},g=t[A(b)].fields;for(let h in g[Object.entries(e).find(([a,b])=>"id"===b)?.[0]??"id"]={type:c.advanced?.database?.generateId==="serial"?"number":"string"},g){if(d.length&&!d.includes(h))continue;let j=g[h];if(j){let g=j.fieldName||h,k=a[Object.entries(e).find(([a,b])=>b===g)?.[0]||g];j.transform?.output&&(k=await j.transform.output(k));let m=e[h]||h;"id"===g||j.references?.field==="id"?null!=k&&(k=String(k)):!1===l.supportsJSON&&"string"==typeof k&&"json"===j.type||!1===l.supportsArrays&&"string"==typeof k&&("string[]"===j.type||"number[]"===j.type)?k=(0,i.$)(k):!1===l.supportsDates&&"string"==typeof k&&"date"===j.type?k=new Date(k):!1===l.supportsBooleans&&"number"==typeof k&&"boolean"===j.type&&(k=1===k),l.customTransformOutput&&(k=l.customTransformOutput({data:k,field:m,fieldAttributes:j,select:d,model:C(b),schema:t,options:c})),f[m]=k}}return f};if(!e||0===Object.keys(e).length)return await f(a,b,d);b=A(b);let g=await f(a,b,d),h=Object.entries(e).map(([a,b])=>({modelName:C(a),defaultModelName:A(a),joinConfig:b}));if(!a)return null;for(let{modelName:d,defaultModelName:e,joinConfig:i}of h){let h=await (async()=>c.experimental?.joins?a[d]:await K({baseModel:b,baseData:g,joinModel:d,specificJoinConfig:i}))();null==h&&(h="one-to-one"===i.relation?null:[]),"one-to-many"!==i.relation||Array.isArray(h)||(h=[h]);let j=[];if(Array.isArray(h))for(let a of h){let b=await f(a,d,[]);j.push(b)}else{let a=await f(h,d,[]);j.push(a)}g[e]=("one-to-one"===i.relation?j[0]:j)??null}return g},I=({model:a,where:b,action:d})=>{if(!b)return;let f=l.mapKeysTransformInput??{};return b.map(b=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:k="sensitive"}=b;if("in"===i&&!Array.isArray(h))throw new e.$l("Value must be an array");let m=h,n=A(a),o=B({field:g,model:a}),p=f[o]||D({field:o,model:n}),q=F({field:o,model:n}),r=c.advanced?.database?.generateId==="serial";if(("id"===o||q.references?.field==="id")&&r&&(m=Array.isArray(h)?h.map(Number):Number(h)),"date"===q.type&&h instanceof Date&&!l.supportsDates&&(m=h.toISOString()),"boolean"===q.type&&"string"==typeof m&&(m="true"===m),"number"===q.type){if("string"==typeof m&&""!==m.trim()){let a=Number(m);Number.isNaN(a)||(m=a)}else if(Array.isArray(m)){let a=m.map(a=>"string"==typeof a&&""!==a.trim()?Number(a):NaN);a.every(a=>!Number.isNaN(a))&&(m=a)}}if("boolean"!==q.type||"boolean"!=typeof m||l.supportsBooleans||(m=+!!m),"json"===q.type&&"object"==typeof h&&!l.supportsJSON)try{m=JSON.stringify(h)}catch(a){throw Error(`Failed to stringify JSON value for field ${p}`,{cause:a})}return l.customTransformInput&&(m=l.customTransformInput({data:m,fieldAttributes:q,field:p,model:C(a),schema:t,options:c,action:d})),{operator:i,connector:j,field:p,value:m,mode:k}})},J=(a,b,d)=>{if(!b||0===Object.keys(b).length)return;let f={};for(let[g,h]of Object.entries(b)){let b,i,j;if(!h)continue;let k=A(g),l=A(a),m=Object.entries(t[k].fields).filter(([a,b])=>b.references&&A(b.references.model)===l),n=!0;if(m.length||(m=Object.entries(t[l].fields).filter(([a,b])=>b.references&&A(b.references.model)===k),n=!1),m.length){if(m.length>1)throw new e.$l(`Multiple foreign keys found for model ${g} and base model ${a} while performing join operation. Only one foreign key is supported.`)}else throw new e.$l(`No foreign key found for model ${g} and base model ${a} while performing join operation.`);let[o,p]=m[0];if(!p.references)throw new e.$l(`No references found for foreign key ${o} on model ${g} while performing join operation.`);n?(b=D({model:a,field:j=p.references.field}),i=D({model:g,field:o})):(b=D({model:a,field:j=o}),i=D({model:g,field:p.references.field})),d&&!d.includes(j)&&d.push(j);let q="id"===i||(p.unique??!1),r=c.advanced?.database?.defaultFindManyLimit??100;q?r=1:"object"==typeof h&&"number"==typeof h.limit&&(r=h.limit),f[C(g)]={on:{from:b,to:i},limit:r,relation:q?"one-to-one":"one-to-many"}}return{join:f,select:d}},K=async({baseModel:a,baseData:b,joinModel:d,specificJoinConfig:e})=>{let f;if(!b)return b;let g=C(d),h=e.on.to,i=b[B({field:e.on.from,model:a})];if(null==i)return"one-to-one"===e.relation?null:[];let j=I({model:g,where:[{field:h,value:i,operator:"eq",connector:"AND"}],action:"findOne"});try{if("one-to-one"===e.relation)f=await (0,p.f)(`db findOne ${g}`,{[q.Xu]:"findOne",[q.qU]:g},()=>L.findOne({model:g,where:j}));else{let a=e.limit??c.advanced?.database?.defaultFindManyLimit??100;f=await (0,p.f)(`db findMany ${g}`,{[q.Xu]:"findMany",[q.qU]:g},()=>L.findMany({model:g,where:j,limit:a}))}}catch(a){throw z.error(`Failed to query fallback join for model ${g}:`,{where:j,limit:e.limit}),console.error(a),a}return f},L=a({options:c,schema:t,debugLog:y,getFieldName:D,getModelName:C,getDefaultModelName:A,getDefaultFieldName:B,getFieldAttributes:F,transformInput:G,transformOutput:H,transformWhereClause:I}),M=null,N={transaction:async a=>{if(!M)if(l.transaction)z.debug(`[${l.adapterName}] - Using provided transaction implementation.`),M=l.transaction;else M=a=>a(N);return M(a)},create:async({data:a,model:b,select:c,forceAllowId:d=!1})=>{let e=++s,f=C(b);b=A(b),"id"in a&&void 0!==a.id&&!d&&(z.warn(`[${l.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`),console.log(Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","Create method with `id` being called at:")),a.id=void 0),y({method:"create"},`${u(e)} ${v(1,4)}`,`${w("create")} ${x("Unsafe Input")}:`,{model:f,data:a});let g=a;l.disableTransformInput||(g=await G(a,b,"create",d)),y({method:"create"},`${u(e)} ${v(2,4)}`,`${w("create")} ${x("Parsed Input")}:`,{model:f,data:g});let h=await (0,p.f)(`db create ${f}`,{[q.Xu]:"create",[q.qU]:f},()=>L.create({data:g,model:f}));y({method:"create"},`${u(e)} ${v(3,4)}`,`${w("create")} ${x("DB Result")}:`,{model:f,res:h});let i=h;return l.disableTransformOutput||(i=await H(h,b,c,void 0)),y({method:"create"},`${u(e)} ${v(4,4)}`,`${w("create")} ${x("Parsed Result")}:`,{model:f,data:i}),i},update:async({model:a,where:b,update:c})=>{let d=++s,e=C(a=A(a)),f=I({model:a,where:b,action:"update"});y({method:"update"},`${u(d)} ${v(1,4)}`,`${w("update")} ${x("Unsafe Input")}:`,{model:e,data:c});let g=c;l.disableTransformInput||(g=await G(c,a,"update")),y({method:"update"},`${u(d)} ${v(2,4)}`,`${w("update")} ${x("Parsed Input")}:`,{model:e,data:g});let h=await (0,p.f)(`db update ${e}`,{[q.Xu]:"update",[q.qU]:e},()=>L.update({model:e,where:f,update:g}));y({method:"update"},`${u(d)} ${v(3,4)}`,`${w("update")} ${x("DB Result")}:`,{model:e,data:h});let i=h;return l.disableTransformOutput||(i=await H(h,a,void 0,void 0)),y({method:"update"},`${u(d)} ${v(4,4)}`,`${w("update")} ${x("Parsed Result")}:`,{model:e,data:i}),i},updateMany:async({model:a,where:b,update:c})=>{let d=++s,e=C(a),f=I({model:a,where:b,action:"updateMany"});a=A(a),y({method:"updateMany"},`${u(d)} ${v(1,4)}`,`${w("updateMany")} ${x("Unsafe Input")}:`,{model:e,data:c});let g=c;l.disableTransformInput||(g=await G(c,a,"update")),y({method:"updateMany"},`${u(d)} ${v(2,4)}`,`${w("updateMany")} ${x("Parsed Input")}:`,{model:e,data:g});let h=await (0,p.f)(`db updateMany ${e}`,{[q.Xu]:"updateMany",[q.qU]:e},()=>L.updateMany({model:e,where:f,update:g}));return y({method:"updateMany"},`${u(d)} ${v(3,4)}`,`${w("updateMany")} ${x("DB Result")}:`,{model:e,data:h}),y({method:"updateMany"},`${u(d)} ${v(4,4)}`,`${w("updateMany")} ${x("Parsed Result")}:`,{model:e,data:h}),h},findOne:async({model:a,where:b,select:d,join:e})=>{let f,g=++s,h=C(a),i=I({model:a,where:b,action:"findOne"});a=A(a);let j=!0;if(l.disableTransformJoin)f=e;else{let b=J(a,e,d);b&&(f=b.join,d=b.select),!c.experimental?.joins&&f&&Object.keys(f).length>0&&(j=!1)}y({method:"findOne"},`${u(g)} ${v(1,3)}`,`${w("findOne")}:`,{model:h,where:i,select:d,join:f});let k=await (0,p.f)(`db findOne ${h}`,{[q.Xu]:"findOne",[q.qU]:h},()=>L.findOne({model:h,where:i,select:d,join:j?f:void 0}));y({method:"findOne"},`${u(g)} ${v(2,3)}`,`${w("findOne")} ${x("DB Result")}:`,{model:h,data:k});let m=k;return l.disableTransformOutput||(m=await H(k,a,d,f)),y({method:"findOne"},`${u(g)} ${v(3,3)}`,`${w("findOne")} ${x("Parsed Result")}:`,{model:h,data:m}),m},findMany:async({model:a,where:b,limit:d,select:e,sortBy:f,offset:g,join:h})=>{let i,j=++s,k=d??c.advanced?.database?.defaultFindManyLimit??100,m=C(a),n=I({model:a,where:b,action:"findMany"});a=A(a);let o=!0;if(l.disableTransformJoin)i=h;else{let b=J(a,h,e);b&&(i=b.join,e=b.select),!c.experimental?.joins&&i&&Object.keys(i).length>0&&(o=!1)}y({method:"findMany"},`${u(j)} ${v(1,3)}`,`${w("findMany")}:`,{model:m,where:n,limit:k,sortBy:f,offset:g,join:i});let r=await (0,p.f)(`db findMany ${m}`,{[q.Xu]:"findMany",[q.qU]:m},()=>L.findMany({model:m,where:n,limit:k,select:e,sortBy:f,offset:g,join:o?i:void 0}));y({method:"findMany"},`${u(j)} ${v(2,3)}`,`${w("findMany")} ${x("DB Result")}:`,{model:m,data:r});let t=r;return l.disableTransformOutput||(t=await Promise.all(r.map(async b=>await H(b,a,void 0,i)))),y({method:"findMany"},`${u(j)} ${v(3,3)}`,`${w("findMany")} ${x("Parsed Result")}:`,{model:m,data:t}),t},delete:async({model:a,where:b})=>{let c=++s,d=C(a),e=I({model:a,where:b,action:"delete"});a=A(a),y({method:"delete"},`${u(c)} ${v(1,2)}`,`${w("delete")}:`,{model:d,where:e}),await (0,p.f)(`db delete ${d}`,{[q.Xu]:"delete",[q.qU]:d},()=>L.delete({model:d,where:e})),y({method:"delete"},`${u(c)} ${v(2,2)}`,`${w("delete")} ${x("DB Result")}:`,{model:d})},deleteMany:async({model:a,where:b})=>{let c=++s,d=C(a),e=I({model:a,where:b,action:"deleteMany"});a=A(a),y({method:"deleteMany"},`${u(c)} ${v(1,2)}`,`${w("deleteMany")} ${x("DeleteMany")}:`,{model:d,where:e});let f=await (0,p.f)(`db deleteMany ${d}`,{[q.Xu]:"deleteMany",[q.qU]:d},()=>L.deleteMany({model:d,where:e}));return y({method:"deleteMany"},`${u(c)} ${v(2,2)}`,`${w("deleteMany")} ${x("DB Result")}:`,{model:d,data:f}),f},consumeOne:async({model:a,where:b})=>{let c,f=++s,g=C(a),h=I({model:a,where:b,action:"consumeOne"});a=A(a),y({method:"consumeOne"},`${u(f)} ${v(1,3)}`,`${w("consumeOne")} ${x("ConsumeOne")}:`,{model:g,where:h});let i=!0;L.consumeOne?c=await (0,p.f)(`db consumeOne ${g}`,{[q.Xu]:"consumeOne",[q.qU]:g},()=>L.consumeOne({model:g,where:h})):(c=await (0,p.f)(`db consumeOne ${g}`,{[q.Xu]:"consumeOne",[q.qU]:g},()=>(0,d.iD)(N,async()=>{let c=await (0,d.d3)(N),f=(await c.findMany({model:a,where:b,limit:1}))[0];if(!f)return null;let g=await c.deleteMany({model:a,where:[...b,{field:"id",value:f.id,operator:"eq",connector:"AND",mode:"sensitive"}]});if("number"!=typeof g)throw new e.$l(`Adapter "${l.adapterId}" returned a non-numeric value from deleteMany during the consumeOne fallback. Return the number of deleted rows, or implement a native consumeOne for atomic single-use consumption.`);return g>0?f:null})),i=!1),y({method:"consumeOne"},`${u(f)} ${v(2,3)}`,`${w("consumeOne")} ${x("DB Result")}:`,{model:g,data:c});let j=c;return!l.disableTransformOutput&&i&&c&&(j=await H(c,a,void 0,void 0)),y({method:"consumeOne"},`${u(f)} ${v(3,3)}`,`${w("consumeOne")} ${x("Parsed Result")}:`,{model:g,data:j}),j},incrementOne:async({model:a,where:b,increment:c,set:f})=>{let g,h=Object.keys(c).length>0,i=!!f&&Object.keys(f).length>0;if(!h&&!i)throw new e.$l("incrementOne requires a non-empty `increment` or `set`; both were empty.");let j=++s,k=C(a),m=I({model:a,where:b,action:"incrementOne"});a=A(a),y({method:"incrementOne"},`${u(j)} ${v(1,3)}`,`${w("incrementOne")} ${x("IncrementOne")}:`,{model:k,where:m,increment:c,set:f});let n=!0;if(L.incrementOne){let b,d=l.mapKeysTransformInput??{},h={};for(let[b,e]of Object.entries(c))h[d[b]||D({model:a,field:b})]=e;if(b=f&&!l.disableTransformInput?await G(f,a,"update"):f,0===Object.keys(h).length&&(!b||0===Object.keys(b).length))throw new e.$l("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away.");g=await (0,p.f)(`db incrementOne ${k}`,{[q.Xu]:"incrementOne",[q.qU]:k},()=>L.incrementOne({model:k,where:m,increment:h,set:b}))}else g=await (0,p.f)(`db incrementOne ${k}`,{[q.Xu]:"incrementOne",[q.qU]:k},()=>(0,d.iD)(N,async()=>{let g=await (0,d.d3)(N),h=(await g.findMany({model:a,where:b,limit:1}))[0];if(!h)return null;let i={...f??{}};for(let[a,b]of Object.entries(c))i[a]=("number"==typeof h[a]?h[a]:0)+b;let j=await g.updateMany({model:a,where:[...b,{field:"id",value:h.id,operator:"eq",connector:"AND",mode:"sensitive"}],update:i});if("number"!=typeof j)throw new e.$l(`Adapter "${l.adapterId}" returned a non-numeric value from updateMany during the incrementOne fallback. Return the number of updated rows, or implement a native incrementOne for atomic guarded counter updates.`);return j>0?{...h,...i}:null})),n=!1;y({method:"incrementOne"},`${u(j)} ${v(2,3)}`,`${w("incrementOne")} ${x("DB Result")}:`,{model:k,data:g});let o=g;return!l.disableTransformOutput&&n&&g&&(o=await H(g,a,void 0,void 0)),y({method:"incrementOne"},`${u(j)} ${v(3,3)}`,`${w("incrementOne")} ${x("Parsed Result")}:`,{model:k,data:o}),o},count:async({model:a,where:b})=>{let c=++s,d=C(a),e=I({model:a,where:b,action:"count"});a=A(a),y({method:"count"},`${u(c)} ${v(1,2)}`,`${w("count")}:`,{model:d,where:e});let f=await (0,p.f)(`db count ${d}`,{[q.Xu]:"count",[q.qU]:d},()=>L.count({model:d,where:e}));return y({method:"count"},`${u(c)} ${v(2,2)}`,`${w("count")}:`,{model:d,data:f}),f},createSchema:L.createSchema?async(a,b)=>{let d=(0,f.y)(c);return c.secondaryStorage&&!c.session?.storeSessionInDatabase&&delete d.session,L.createSchema({file:b,tables:d})}:void 0,options:{adapterConfig:l,...L.options??{}},id:l.adapterId,...l.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){r=r.filter(a=>a.instance!==g)},printDebugLogs(){let a="─".repeat(80),b=r.filter(a=>a.instance===g);0===b.length||console.log(...b.reverse().map(a=>(a.args[0]=`
|
|
13
|
+
${a.args[0]}`,[...a.args,"\n"])).reduce((a,b)=>[...b,...a],[`
|
|
14
|
+
${a}`]))}}}:{}};return N};function u(a){return 8>(0,g.t)()?`#${a}`:`${h.p4.fg.magenta}#${a}${h.p4.reset}`}function v(a,b){return`${h.p4.bg.black}${h.p4.fg.yellow}[${a}/${b}]${h.p4.reset}`}function w(a){return`${h.p4.bright}${a}${h.p4.reset}`}function x(a){return`${h.p4.dim}(${a})${h.p4.reset}`}},38027:(a,b,c)=>{"use strict";c.d(b,{B:()=>f,q:()=>g});var d=c(60351),e=c(18110);function f(a){return(0,e.Gv)(a)&&"expressionType"in a&&(0,d.N)(a)}function g(a){return(0,e.Gv)(a)&&"expression"in a&&(0,e.Kg)(a.alias)&&(0,d.N)(a)}},38199:(a,b,c)=>{"use strict";c.d(b,{F:()=>d,x:()=>e});class d extends Error{node;constructor(a){super("no result"),this.node=a}}function e(a){return Object.prototype.hasOwnProperty.call(a,"prototype")}},38441:(a,b,c)=>{"use strict";c.d(b,{k:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"ParensNode"===a.kind,create:a=>(0,d.CN)({kind:"ParensNode",node:a})})},38697:(a,b)=>{"use strict";function c(){let a,b,c=new Promise((c,d)=>{a=c,b=d});return{resolve:a,reject:b,promise:c}}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"createPromiseWithResolvers",{enumerable:!0,get:function(){return c}})},39098:(a,b)=>{"use strict";function c(a){let b=a.indexOf("#"),c=a.indexOf("?"),d=c>-1&&(b<0||c<b);return d||b>-1?{pathname:a.substring(0,d?c:b),query:d?a.substring(c,b>-1?b:void 0):"",hash:b>-1?a.slice(b):""}:{pathname:a,query:"",hash:""}}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"parsePath",{enumerable:!0,get:function(){return c}})},39649:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={DEFAULT_SEGMENT_KEY:function(){return k},NOT_FOUND_SEGMENT_KEY:function(){return l},PAGE_SEGMENT_KEY:function(){return j},addSearchParamsIfPageSegment:function(){return h},computeSelectedLayoutSegment:function(){return i},getSegmentValue:function(){return e},getSelectedLayoutSegmentPath:function(){return function a(b,c,d=!0,f=[]){let g;if(d)g=b[1][c];else{let a=b[1];g=a.children??Object.values(a)[0]}if(!g)return f;let h=e(g[0]);return!h||h.startsWith(j)?f:(f.push(h),a(g,c,!1,f))}},isGroupSegment:function(){return f},isParallelRouteSegment:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});function e(a){return Array.isArray(a)?a[1]:a}function f(a){return"("===a[0]&&a.endsWith(")")}function g(a){return a.startsWith("@")&&"@children"!==a}function h(a,b){if(a.includes(j)){let a=JSON.stringify(b);return"{}"!==a?j+"?"+a:j}return a}function i(a,b){if(!a||0===a.length)return null;let c="children"===b?a[0]:a[a.length-1];return c===k?null:c}let j="__PAGE__",k="__DEFAULT__",l="/_not-found"},39793:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={BailoutToCSRError:function(){return f},isBailoutToCSRError:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="BAILOUT_TO_CLIENT_SIDE_RENDERING";class f extends Error{constructor(a){super(`Bail out to client-side rendering: ${a}`),this.reason=a,this.digest=e}}function g(a){return"object"==typeof a&&null!==a&&"digest"in a&&a.digest===e}},42315:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"RouteKind",{enumerable:!0,get:function(){return d}});var c,d=((c={}).PAGES="PAGES",c.PAGES_API="PAGES_API",c.APP_PAGE="APP_PAGE",c.APP_ROUTE="APP_ROUTE",c.IMAGE="IMAGE",c)},42960:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"pathHasPrefix",{enumerable:!0,get:function(){return e}});let d=c(39098);function e(a,b){if("string"!=typeof a)return!1;let{pathname:c}=(0,d.parsePath)(a);return c===b||c.startsWith(b+"/")}},43543:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c,d,e={CachedRouteKind:function(){return g},IncrementalCacheKind:function(){return h}};for(var f in e)Object.defineProperty(b,f,{enumerable:!0,get:e[f]});var g=((c={}).APP_PAGE="APP_PAGE",c.APP_ROUTE="APP_ROUTE",c.PAGES="PAGES",c.FETCH="FETCH",c.REDIRECT="REDIRECT",c.IMAGE="IMAGE",c),h=((d={}).APP_PAGE="APP_PAGE",d.APP_ROUTE="APP_ROUTE",d.PAGES="PAGES",d.FETCH="FETCH",d.IMAGE="IMAGE",d)},43876:(a,b,c)=>{"use strict";c.d(b,{y:()=>f});var d=c(62547),e=c(85680);let f=({schema:a,usePlural:b})=>{let c=(0,d.G)({schema:a,usePlural:b}),f=(0,e.z)({schema:a,usePlural:b});return function({model:b,field:d}){let e=c(b),g=f({model:e,field:d});return a[e]?.fields[g]?.fieldName||g}}},44382:(a,b,c)=>{"use strict";c.d(b,{i:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"SetOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"SetOperationNode",operator:a,expression:b,all:c})})},44805:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"isNextRouterError",{enumerable:!0,get:function(){return f}});let d=c(15707),e=c(45461);function f(a){return(0,e.isRedirectError)(a)||(0,d.isHTTPAccessFallbackError)(a)}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},44901:(a,b,c)=>{"use strict";c.d(b,{Q:()=>i});var d=c(18110);let e=(0,d.CN)({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),f=(0,d.CN)([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),g=(0,d.CN)({is:a=>"DataTypeNode"===a.kind,create:a=>(0,d.CN)({kind:"DataTypeNode",dataType:a})});var h=c(60351);function i(a){if((0,h.N)(a))return a.toOperationNode();if(e[a]||f.some(b=>b.test(a)))return g.create(a);throw Error(`invalid column data type ${JSON.stringify(a)}`)}},45461:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={REDIRECT_ERROR_CODE:function(){return g},isRedirectError:function(){return h}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(24543),g="NEXT_REDIRECT";function h(a){if("object"!=typeof a||null===a||!("digest"in a)||"string"!=typeof a.digest)return!1;let b=a.digest.split(";"),[c,d]=b,e=b.slice(2,-2).join(";"),h=Number(b.at(-2));return c===g&&("replace"===d||"push"===d)&&"string"==typeof e&&!isNaN(h)&&h in f.RedirectStatusCode}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},45541:(a,b,c)=>{"use strict";c.d(b,{$O:()=>r,DT:()=>u,NF:()=>s,Ow:()=>w,RY:()=>v,kU:()=>q,q5:()=>t,vd:()=>p});var d=c(50182),e=c(37626),f=c(22475),g=c(3694),h=c(18110),i=c(37338),j=c(98051),k=c(10611),l=c(5496),m=c(33866),n=c(16891),o=c(47536);function p(a){return(0,h.Kg)(a)?t(a):a.toOperationNode()}function q(a){return(0,h.MH)(a)?a.map(a=>r(a)):[r(a)]}function r(a){return(0,i.SS)(a)?(0,i.YK)(a):p(a)}function s(a,b){if((0,l.Xm)(b))return m.Q.create(t(a),n.k.create(l.zX.create(b)));if("->$"===b||"->>$"===b)return m.Q.create(t(a),o.c.create(l.zX.create(b.slice(0,-1))));throw Error(`Invalid JSON operator: ${b}`)}function t(a){if(!a.includes("."))return f.q.create(e.Z.create(a));let b=a.split(".").map(x);if(3===b.length)return function(a){let[b,c,d]=a;return f.q.create(e.Z.create(d),g.H.createWithSchema(b,c))}(b);if(2===b.length)return function(a){let[b,c]=a;return f.q.create(e.Z.create(c),g.H.create(b))}(b);throw Error(`invalid column reference ${a}`)}function u(a){let b=" as ";if(!a.includes(b))return t(a);{let[c,e]=a.split(b).map(x);return d.N.create(t(c),j.O.create(e))}}function v(a){return e.Z.create(a)}function w(a){if(!a.includes(" "))return v(a);{let[b,c]=a.split(" ").map(x);if(!(0,k.bE)(c))throw Error(`invalid order direction "${c}" next to "${b}"`);return(0,k.xk)([b,c])[0]}}function x(a){return a.trim()}},46076:(a,b,c)=>{"use strict";a.exports=c(30811).vendored["react-rsc"].ReactServerDOMWebpackServer},46374:(a,b,c)=>{"use strict";let{randomFillSync:d}=c(55511),e=c(81769),f=new Uint32Array(256).map((a,b)=>{for(let a=0;a<8;a++)0!=(1&b)?b=b>>>1^0xedb88320:b>>>=1;return b>>>0}),g=(a,b)=>Math.imul(a,b)>>>0,h=(a,b)=>f[(a^b)&255]^a>>>8,i=()=>"function"==typeof d?d(Buffer.alloc(12)):i.node();i.node=()=>{let a=Buffer.alloc(12),b=a.length;for(let c=0;c<b;c++)a[c]=256*Math.random()&255;return a};let j={genSalt:i};function k(a){let b=Buffer.isBuffer(a)?a:Buffer.from(a);this.keys=new Uint32Array([0x12345678,0x23456789,0x34567890]);for(let a=0;a<b.length;a++)this.updateKeys(b[a])}k.prototype.updateKeys=function(a){let b=this.keys;return b[0]=h(b[0],a),b[1]+=255&b[0],b[1]=g(b[1],0x8088405)+1,b[2]=h(b[2],b[1]>>>24),a},k.prototype.next=function(){let a=(2|this.keys[2])>>>0;return g(a,1^a)>>8&255},a.exports={decrypt:function(a,b,c){let d;if(!a||!Buffer.isBuffer(a)||a.length<12)return Buffer.alloc(0);let f=(d=new k(c),function(a){let b=Buffer.alloc(a.length),c=0;for(let e of a)b[c++]=d.updateKeys(e^d.next());return b}),g=f(a.slice(0,12)),h=(8&b.flags)==8?b.timeHighByte:b.crc>>>24;if(g[11]!==h)throw e.WRONG_PASSWORD();return f(a.slice(12))},encrypt:function(a,b,c,d=!1){let e;null==a&&(a=Buffer.alloc(0)),Buffer.isBuffer(a)||(a=Buffer.from(a.toString()));let f=(e=new k(c),function(a,b,c=0){for(let d of(b||(b=Buffer.alloc(a.length)),a)){let a=e.next();b[c++]=d^a,e.updateKeys(d)}return b}),g=j.genSalt();g[11]=b.crc>>>24&255,d&&(g[10]=b.crc>>>16&255);let h=Buffer.alloc(a.length+12);return f(g,h),f(a,h,12)},_salter:function(a){Buffer.isBuffer(a)&&a.length>=12?j.genSalt=function(){return a.slice(0,12)}:"node"===a?j.genSalt=i.node:j.genSalt=i}}},46404:(a,b,c)=>{"use strict";c.d(b,{xA:()=>b3,dG:()=>b2,rV:()=>b5});var d,e=c(37694),f=c(98051),g=c(80184);function h(a,b){return g.z.createWithChildren([g.z.createWithSql(`${a} `),f.O.create(b)])}var i=c(6228),j=c(18110),k=c(19105);class l{#o;#p;#q;constructor(a){this.#o=(0,j.CN)({...a})}async init(a){this.#p=(0,j.Tn)(this.#o.database)?await this.#o.database(a):this.#o.database,this.#q=new m(this.#p),this.#o.onCreateConnection&&await this.#o.onCreateConnection(this.#q,a)}async acquireConnection(){return this.#q}async beginTransaction(a){await a.executeQuery(i.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(i.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(i.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(h("savepoint",b),(0,k.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(h("rollback to",b),(0,k.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(h("release",b),(0,k.a)()))}async releaseConnection(){}async destroy(){this.#p?.close()}}class m{#p;constructor(a){this.#p=a}async executeQuery(a){let{sql:b,parameters:c}=a,d=this.#p.prepare(b);if(d.reader)return{rows:d.all(c)};let{changes:e,lastInsertRowid:f}=d.run(c);return{insertId:null!=f?BigInt(f):void 0,numAffectedRows:null!=e?BigInt(e):void 0,rows:[]}}async *streamQuery(a,b){let{sql:c,parameters:d,query:f}=a,g=this.#p.prepare(c);if(!e.L.is(f))throw Error("Sqlite driver only supports streaming of select queries");for(let a of g.iterate(d))yield{rows:[a]}}}var n=c(88891);let o="kysely_migration",p="kysely_migration_lock";(0,j.CN)({__noMigrations__:!0});var q=c(80185);class r{#p;constructor(a){this.#p=a}async getSchemas(){return[]}async getTables(a={withInternalKyselyTables:!1}){return await this.#r(a)}#s(a,b){let c=a.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");return b.withInternalKyselyTables||(c=c.where("name","!=",o).where("name","!=",p)),c}async #r(a){let b=await this.#s(this.#p,a).execute(),c=await this.#p.with("table_list",b=>this.#s(b,a)).selectFrom(["table_list as tl",(0,q.l)`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),d={};for(let a of c)d[a.table]??=[],d[a.table].push(a);return b.map(({name:a,sql:b,type:c})=>{let e=b?.split(/[\(\),]/)?.find(a=>a.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),f=d[a]??[];if(!e){let a=f.filter(a=>a.pk>0);1===a.length&&"integer"===a[0].type.toLowerCase()&&(e=a[0].name)}return{name:a,isView:"view"===c,isForeign:!1,columns:f.map(a=>({name:a.name,dataType:a.type,isNullable:!a.notnull,isAutoIncrementing:a.name===e,hasDefaultValue:null!=a.dflt_value,comment:void 0}))}})}}var s=c(79458);class t{#o;constructor(a){this.#o=(0,j.CN)({...a})}createDriver(){return new l(this.#o)}createQueryCompiler(){return new n.s}createAdapter(){return new s.U}createIntrospector(a){return new r(a)}}function u(a,b){var c;if(c=a,(0,j.Gv)(c)&&(0,j.Kg)(c.stack)&&b.stack){let c=b.stack.split("\n").slice(1).join("\n");a.stack+=`
|
|
15
|
+
${c}`}return a}let v=Symbol();class w{#o;#t=new WeakMap;#u;constructor(a){this.#o=(0,j.CN)({...a})}async init(a){this.#u=(0,j.Tn)(this.#o.pool)?await this.#o.pool(a):this.#o.pool}async acquireConnection(a){let b=await this.#v(),c=this.#t.get(b);return!c&&(c=new x(b,this.#o.controlConnection),this.#t.set(b,c),this.#o?.onCreateConnection&&await this.#o.onCreateConnection(c,a)),this.#o?.onReserveConnection&&await this.#o.onReserveConnection(c,a),c}async beginTransaction(a,b){if(b.isolationLevel||b.accessMode){let c=[];b.isolationLevel&&c.push(`isolation level ${b.isolationLevel}`),b.accessMode&&c.push(b.accessMode);let d=`set transaction ${c.join(", ")}`;await a.executeQuery(i.E.raw(d))}await a.executeQuery(i.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(i.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(i.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(h("savepoint",b),(0,k.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(h("rollback to",b),(0,k.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(h("release savepoint",b),(0,k.a)()))}async releaseConnection(a){a[v]()}async destroy(){return new Promise((a,b)=>{this.#u.end(c=>{c?b(c):a()})})}async #v(){return new Promise((a,b)=>{this.#u.getConnection(async(c,d)=>{c?b(c):a(d)})})}}class x{#q;#w;#x;#i;constructor(a,b){this.#q=a,this.#w=b}async cancelQuery(a){await this.#y(`kill query ${this.#x}`,a)}async collectSessionInfo(){if(this.#x)return;let{threadId:a}=this.#q;if(null!=a)this.#x=a;else{let[{cid:a}]=await this.#z(i.E.raw("select connection_id() as cid"));this.#x=Number(a)}}async executeQuery(a){try{this.#i=a.queryId;let b=await this.#z(a);if(!(0,j.Gv)(b)||!("insertId"in b)||!("affectedRows"in b))return{rows:Array.isArray(b)?b:[]};let{insertId:c,affectedRows:d,changedRows:e}=b;return{insertId:null!=c&&"0"!==c.toString()?BigInt(c):void 0,numAffectedRows:null!=d?BigInt(d):void 0,numChangedRows:null!=e?BigInt(e):void 0,rows:[]}}catch(a){throw u(a,Error())}finally{this.#i=void 0}}async killSession(a){try{this.#q.destroy()}catch{}await this.#y(`kill connection ${this.#x}`,a)}async *streamQuery(a,b){this.#i=a.queryId;let c=this.#q.query(a.sql,a.parameters).stream({objectMode:!0});try{for await(let a of c)yield{rows:[a]}}catch(a){if((0,j.Gv)(a)&&"code"in a&&"ERR_STREAM_PREMATURE_CLOSE"===a.code)return;throw a}finally{this.#i=void 0}}[v](){this.#q.release()}#z(a){return new Promise((b,c)=>{this.#q.query(a.sql,a.parameters,(a,d)=>{a?c(a):b(d)})})}async #y(a,b){if(!this.#i)return;let{config:c}=this.#q,d=this.#i;if(!this.#w||!c)return await b(async b=>{d.queryId===this.#i?.queryId&&await b.executeQuery(i.E.raw(a,[]))});let{clientFlags:e,maxPacketSize:f,...g}=c,h=this.#w(g);try{await new Promise((b,c)=>{h.connect(e=>e?c(e):d.queryId!==this.#i?.queryId?b():void h.query(a,[],a=>{if(a)return c(a);b()}))})}finally{h.destroy()}}}var y=c(24607);let z=/[\\']/g,A=/`/g,B=/[\\'"]/g;class C extends y.n{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return A.source}getRightIdentifierWrapper(){return A.source}sanitizeIdentifier(a){return a.replace(A,"``")}sanitizeStringLiteral(a){return a.replace(z,a=>"\\"===a?"\\\\":"''")}sanitizeJSONPathMemberValue(a){return a.replace(B,a=>"\\"===a?"\\\\\\\\":"'"===a?"''":'\\\\"')}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.using&&(this.append(" using "),this.visitNode(a.using)),a.table&&(this.append(" on "),this.visitNode(a.table)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.where&&(this.append(" "),this.visitNode(a.where))}}class D{#p;constructor(a){this.#p=a}async getSchemas(){return(await this.#p.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map(a=>({name:a.SCHEMA_NAME}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#p.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",a=>a.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","tables.ENGINE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",(0,q.l)`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();a.withInternalKyselyTables||(b=b.where("columns.TABLE_NAME","!=",o).where("columns.TABLE_NAME","!=",p));let c=await b.execute();return this.#A(c)}#A(a){return a.reduce((a,b)=>{let c=a.find(a=>a.name===b.TABLE_NAME);return c||(c=(0,j.CN)({name:b.TABLE_NAME,isView:"VIEW"===b.TABLE_TYPE,isForeign:"FEDERATED"===b.ENGINE,schema:b.TABLE_SCHEMA,columns:[]}),a.push(c)),c.columns.push((0,j.CN)({name:b.COLUMN_NAME,dataType:b.DATA_TYPE,isNullable:"YES"===b.IS_NULLABLE,isAutoIncrementing:b.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:null!==b.COLUMN_DEFAULT,comment:""===b.COLUMN_COMMENT?void 0:b.COLUMN_COMMENT})),a},[])}}var E=c(88743);let F="ea586330-2c93-47c8-908d-981d9d270f9d";class G extends E.l{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(a,b){await (0,q.l)`select get_lock(${q.l.lit(F)}, ${q.l.lit(3600)})`.execute(a)}async releaseMigrationLock(a,b){await (0,q.l)`select release_lock(${q.l.lit(F)})`.execute(a)}}class H{#o;constructor(a){this.#o=a}createDriver(){return new w(this.#o)}createQueryCompiler(){return new C}createAdapter(){return new G}createIntrospector(a){return new D(a)}}let I=Symbol();class J{#o;#t=new WeakMap;#u;constructor(a){this.#o=(0,j.CN)({...a})}async init(a){this.#u=(0,j.Tn)(this.#o.pool)?await this.#o.pool(a):this.#o.pool}async acquireConnection(a){let b=await this.#u.connect(),c=this.#t.get(b);return!c&&(c=new K(b,{controlClient:this.#o.controlClient||this.#u.Client,cursor:this.#o.cursor??null,poolOptions:this.#u.options}),this.#t.set(b,c),this.#o.onCreateConnection&&await this.#o.onCreateConnection(c,a)),this.#o.onReserveConnection&&await this.#o.onReserveConnection(c,a),c}async beginTransaction(a,b){let c="begin";(b.isolationLevel||b.accessMode)&&(c="start transaction",b.isolationLevel&&(c+=` isolation level ${b.isolationLevel}`),b.accessMode&&(c+=` ${b.accessMode}`)),await a.executeQuery(i.E.raw(c))}async commitTransaction(a){await a.executeQuery(i.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(i.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(h("savepoint",b),(0,k.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(h("rollback to",b),(0,k.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(h("release",b),(0,k.a)()))}async releaseConnection(a){a[I]()}async destroy(){if(this.#u){let a=this.#u;this.#u=void 0,await a.end()}}}class K{#B;#C;#i;#D;constructor(a,b){this.#B=a,this.#C=b}async cancelQuery(a){return await this.#y(`select pg_cancel_backend(${this.#D})`,a)}async collectSessionInfo(){if(this.#D)return;let{processID:a}=this.#B;if(a)this.#D=a;else{let{rows:[{pid:a}]}=await this.#B.query("select pg_backend_pid() as pid",[]);this.#D=Number(a)}}async executeQuery(a){try{this.#i=a.queryId;let{command:b,rowCount:c,rows:d}=await this.#B.query(a.sql,a.parameters);return{numAffectedRows:"INSERT"===b||"UPDATE"===b||"DELETE"===b||"MERGE"===b?BigInt(c):void 0,rows:d??[]}}catch(a){throw u(a,Error())}finally{this.#i=void 0}}async killSession(a){return await this.#y(`select pg_terminate_backend(${this.#D})`,a)}async *streamQuery(a,b){if(!this.#C.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#i=a.queryId;let c=this.#B.query(new this.#C.cursor(a.sql,a.parameters.slice()));try{for(;;){let a=await c.read(b);if(0===a.length)break;yield{rows:a}}}finally{await c.close(),this.#i=void 0}}[I](){this.#B.release()}async #y(a,b){if(!this.#i)return;let{controlClient:c,poolOptions:d}=this.#C,e=this.#i;if(!c)return await b(async b=>{e.queryId===this.#i?.queryId&&await b.executeQuery(i.E.raw(a,[]))});let f=new c({...d});try{if(await f.connect(),e.queryId!==this.#i.queryId)return;await f.query(a,[])}finally{f.end()}}}class L{#p;constructor(a){this.#p=a}async getSchemas(){return(await this.#p.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(a=>({name:a.nspname}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#p.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",(0,q.l)`col_description(a.attrelid, a.attnum)`.as("column_description"),(0,q.l)`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p","f"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where((0,q.l)`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();a.withInternalKyselyTables||(b=b.where("c.relname","!=",o).where("c.relname","!=",p));let c=await b.execute();return this.#A(c)}#A(a){let b=[],c=new Map;for(let d of a){let a=c.get(d.schema);a||(a=new Map,c.set(d.schema,a));let e=a.get(d.table);e||(e=(0,j.CN)({columns:[],isForeign:"f"===d.table_type,isView:"v"===d.table_type,name:d.table,schema:d.schema}),a.set(d.table,e),b.push(e)),e.columns.push((0,j.CN)({comment:d.column_description??void 0,dataType:d.type,dataTypeSchema:d.type_schema,hasDefaultValue:d.has_default,isAutoIncrementing:null!==d.auto_incrementing,isNullable:!d.not_null,name:d.column}))}return b}}let M=/"/g;class N extends y.n{sanitizeIdentifier(a){return a.replace(M,'""')}}let O=BigInt("3853314791062309107");class P extends E.l{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(a,b){await (0,q.l)`select pg_advisory_xact_lock(${q.l.lit(O)})`.execute(a)}async releaseMigrationLock(a,b){}}class Q{#o;constructor(a){this.#o=a}createDriver(){return new J(this.#o)}createQueryCompiler(){return new N}createAdapter(){return new P}createIntrospector(a){return new L(a)}}class R extends E.l{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(a){await (0,q.l)`exec sp_getapplock @DbPrincipal = ${q.l.lit("dbo")}, @Resource = ${q.l.lit(o)}, @LockMode = ${q.l.lit("Exclusive")}`.execute(a)}async releaseMigrationLock(){}}var S=c(95260),T=c(79362);let U=Symbol(),V=Symbol(),W=Symbol();class X{#o;#u;constructor(a){this.#o=(0,j.CN)({...a});const{tarn:b,tedious:c,validateConnections:d}=this.#o;this.#u=new b.Pool({...b.options,create:async()=>{let a=await c.connectionFactory();return await new Y(a,c).connect()},destroy:async a=>{await a[V]()},validate:!1===d?void 0:a=>a[W]()})}async init(){}async acquireConnection(){return await this.#u.acquire().promise}async beginTransaction(a,b){await a.beginTransaction(b)}async commitTransaction(a){await a.commitTransaction()}async rollbackTransaction(a){await a.rollbackTransaction()}async savepoint(a,b){await a.savepoint(b)}async rollbackToSavepoint(a,b){await a.rollbackTransaction(b)}async releaseConnection(a){this.#o.resetConnectionsOnRelease&&await a[U](),this.#u.release(a)}async destroy(){await this.#u.destroy()}}class Y{#q;#E;#F;#G;constructor(a,b){this.#q=a,this.#E=!1,this.#F=b}async beginTransaction(a){let{isolationLevel:b}=a;await new Promise((a,c)=>this.#q.beginTransaction(b=>{b?c(b):a(void 0)},b?(0,S.D)(8):void 0,b?this.#H(b):void 0))}async cancelQuery(){if(this.#G)return new Promise(a=>{this.#G?.request.once("requestCompleted",a),this.#q.cancel()||(this.#G?.request.off("requestCompleted",a),a())})}async commitTransaction(){await new Promise((a,b)=>this.#q.commitTransaction(c=>{c?b(c):a(void 0)}))}async connect(){let{promise:a,reject:b,resolve:c}=new T.c;function d(){b(Error("The connection ended without ever completing the connection"))}return this.#q.connect(a=>{if(a)return b(a);c()}),this.#q.on("error",a=>{a instanceof Error&&"code"in a&&"ESOCKET"===a.code&&(this.#E=!0),console.error(a),b(a)}),this.#q.once("end",d),await a,this.#q.off("end",d),this}async executeQuery(a){try{let b=new T.c;this.#G=new Z({compiledQuery:a,tedious:this.#F,onDone:b}),this.#q.execSql(this.#G.request);let{rowCount:c,rows:d}=await b.promise;return{numAffectedRows:void 0!==c?BigInt(c):void 0,rows:d}}catch(a){throw u(a,Error())}finally{this.#G=void 0}}async rollbackTransaction(a){await new Promise((b,c)=>this.#q.rollbackTransaction(a=>{a?c(a):b(void 0)},a))}async savepoint(a){await new Promise((b,c)=>this.#q.saveTransaction(a=>{a?c(a):b(void 0)},a))}async *streamQuery(a,b){this.#G=new Z({compiledQuery:a,streamChunkSize:b,tedious:this.#F}),this.#q.execSql(this.#G.request);try{for(;;){let a=await this.#G.readChunk();if(0===a.length||(yield{rows:a},a.length<b))break}}finally{await this.cancelQuery(),this.#G=void 0}}#H(a){let{ISOLATION_LEVEL:b}=this.#F,c={"read committed":b.READ_COMMITTED,"read uncommitted":b.READ_UNCOMMITTED,"repeatable read":b.REPEATABLE_READ,serializable:b.SERIALIZABLE,snapshot:b.SNAPSHOT}[a];if(void 0===c)throw Error(`Unknown isolation level: ${a}`);return c}[V](){return"closed"in this.#q&&this.#q.closed?Promise.resolve():new Promise(a=>{this.#q.once("end",a),this.#q.close()})}async [U](){await new Promise((a,b)=>{this.#q.reset(c=>{if(c)return b(c);a()})})}async [W](){if(this.#E||this.#I())return!1;try{let a=new T.c,b=new Z({compiledQuery:i.E.raw("select 1"),onDone:a,tedious:this.#F});return this.#q.execSql(b.request),await a.promise,!0}catch{return!1}}#I(){return"closed"in this.#q&&!!this.#q.closed}}class Z{#J;#K;#L;#M;#F;#N;constructor(a){const{compiledQuery:b,onDone:c,streamChunkSize:d,tedious:e}=a;if(this.#K=[],this.#L=d,this.#M={},this.#F=e,c){const a="onDone";this.#M[a]=(b,d)=>{if("chunkReady"!==b){if(delete this.#M[a],"error"===b)return c.reject(d);c.resolve({rowCount:this.#N,rows:this.#K})}}}this.#J=new this.#F.Request(b.sql,(a,b)=>{if(a)return Object.values(this.#M).forEach(b=>b("error",a instanceof AggregateError?a.errors:a));this.#N=b}),this.#O(b.parameters),this.#P()}get request(){return this.#J}readChunk(){let a=this.readChunk.name;return new Promise((b,c)=>{this.#M[a]=(d,e)=>{if(delete this.#M[a],"error"===d)return c(e);b(this.#K.splice(0,this.#L))},this.#J.resume()})}#O(a){for(let b=0;b<a.length;b++){let c=a[b];this.#J.addParameter(String(b+1),this.#Q(c),c)}}#P(){let a=this.#L?()=>{this.#L<=this.#K.length&&(this.#J.pause(),Object.values(this.#M).forEach(a=>a("chunkReady")))}:()=>{},b=b=>{let c={};for(let a of b)c[a.metadata.colName]=a.value;this.#K.push(c),a()};this.#J.on("row",b),this.#J.once("requestCompleted",()=>{Object.values(this.#M).forEach(a=>a("completed")),this.#J.off("row",b)})}#Q(a){if((0,j.kZ)(a)||(0,j.b0)(a)||(0,j.Kg)(a))return this.#F.TYPES.NVarChar;if((0,j.sI)(a)||(0,j.Et)(a)&&a%1==0)if(a<-0x80000000||a>0x7fffffff)return this.#F.TYPES.BigInt;else return this.#F.TYPES.Int;return(0,j.Et)(a)?this.#F.TYPES.Float:(0,j.Lm)(a)?this.#F.TYPES.Bit:(0,j.$P)(a)?this.#F.TYPES.DateTime:(0,j.Pe)(a)?this.#F.TYPES.VarBinary:this.#F.TYPES.NVarChar}}class ${#p;constructor(a){this.#p=a}async getSchemas(){return await this.#p.selectFrom("sys.schemas").select("name").execute()}async getTables(a={withInternalKyselyTables:!1}){let b=await this.#p.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!a.withInternalKyselyTables,a=>a.where("tables.name","!=",o).where("tables.name","!=",p)).select(["tables.name as table_name",a=>a.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#p.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),c={};for(let a of b){let b=`${a.table_schema_name}.${a.table_name}`;(c[b]=c[b]||(0,j.CN)({columns:[],isForeign:!1,isView:"V "===a.table_type,name:a.table_name,schema:a.table_schema_name??void 0})).columns.push((0,j.CN)({dataType:a.type_name,dataTypeSchema:a.type_schema_name??void 0,hasDefaultValue:a.column_default_object_id>0||"NOT_APPLICABLE"!==a.column_generated_always_type||a.column_is_identity||a.column_is_computed||a.column_is_rowguidcol,isAutoIncrementing:a.column_is_identity,isNullable:a.column_is_nullable&&a.type_is_nullable,name:a.column_name,comment:a.column_comment??void 0}))}return Object.values(c)}}let _=/^[a-z0-9_]$/i;class aa extends y.n{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(a){super.visitOffset(a),this.append(" rows")}compileColumnAlterations(a){let b={};for(let c of a)b[c.kind]||(b[c.kind]=[]),b[c.kind].push(c);let c=!0;b.AddColumnNode&&(this.append("add "),this.compileList(b.AddColumnNode),c=!1),b.AlterColumnNode&&(c||this.append(", "),this.compileList(b.AlterColumnNode)),b.DropColumnNode&&(c||this.append(", "),this.append("drop "),this.compileList(b.DropColumnNode),c=!1),b.ModifyColumnNode&&(c||this.append(", "),this.compileList(b.ModifyColumnNode)),b.RenameColumnNode&&(c||this.append(", "),this.compileList(b.RenameColumnNode))}visitAddColumn(a){this.visitNode(a.column)}visitDropColumn(a){this.append("column "),a.ifExists&&this.append("if exists "),this.visitNode(a.column)}visitMergeQuery(a){super.visitMergeQuery(a),this.append(";")}visitCollate(a){this.append("collate ");let{name:b}=a.collation;for(let a of b)if(!_.test(a))throw Error(`Invalid collation: ${b}`);this.append(b)}announcesNewColumnDataType(){return!1}}class ab{#o;constructor(a){this.#o=a}createDriver(){return new X(this.#o)}createQueryCompiler(){return new aa}createAdapter(){return new R}createIntrospector(a){return new $(a)}}let ac=(0,j.CN)({is:a=>"AlterTableNode"===a.kind,create:a=>(0,j.CN)({kind:"AlterTableNode",table:a}),cloneWithTableProps:(a,b)=>(0,j.CN)({...a,...b}),cloneWithColumnAlteration:(a,b)=>(0,j.CN)({...a,columnAlterations:a.columnAlterations?[...a.columnAlterations,b]:[b]})}),ad=(0,j.CN)({is:a=>"CreateIndexNode"===a.kind,create:a=>(0,j.CN)({kind:"CreateIndexNode",name:f.O.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,j.CN)({...a,columns:[...a.columns||[],...b]})}),ae=(0,j.CN)({is:a=>"CreateSchemaNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"CreateSchemaNode",schema:f.O.create(a),...b}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});var af=c(12757),ag=c(4432);let ah=(0,j.CN)({is:a=>"DropIndexNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"DropIndexNode",name:ag.y.create(a),...b}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),ai=(0,j.CN)({is:a=>"DropSchemaNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"DropSchemaNode",schema:f.O.create(a),...b}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),aj=(0,j.CN)({is:a=>"DropTableNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"DropTableNode",table:a,...b}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});var ak=c(27800);let al=(0,j.CN)({is:a=>"AddColumnNode"===a.kind,create:a=>(0,j.CN)({kind:"AddColumnNode",column:a})});var am=c(37626);let an=(0,j.CN)({is:a=>"ColumnDefinitionNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"ColumnDefinitionNode",column:am.Z.create(a),dataType:b}),cloneWithFrontModifier:(a,b)=>(0,j.CN)({...a,frontModifiers:a.frontModifiers?(0,j.CN)([...a.frontModifiers,b]):[b]}),cloneWithEndModifier:(a,b)=>(0,j.CN)({...a,endModifiers:a.endModifiers?(0,j.CN)([...a.endModifiers,b]):[b]}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),ao=(0,j.CN)({is:a=>"DropColumnNode"===a.kind,create:a=>(0,j.CN)({kind:"DropColumnNode",column:am.Z.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),ap=(0,j.CN)({is:a=>"RenameColumnNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"RenameColumnNode",column:am.Z.create(a),renameTo:am.Z.create(b)})}),aq=(0,j.CN)({is:a=>"CheckConstraintNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"CheckConstraintNode",expression:a,name:b?f.O.create(b):void 0})}),ar=(0,j.CN)({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(ar);let as=(0,j.CN)({is:a=>"ReferencesNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"ReferencesNode",table:a,columns:(0,j.CN)([...b])}),cloneWithOnDelete:(a,b)=>(0,j.CN)({...a,onDelete:b}),cloneWithOnUpdate:(a,b)=>(0,j.CN)({...a,onUpdate:b})});var at=c(90386),au=c(45541),av=c(60351),aw=c(76051);function ax(a){return(0,av.N)(a)?a.toOperationNode():aw.q.createImmediate(a)}let ay=(0,j.CN)({is:a=>"GeneratedNode"===a.kind,create:a=>(0,j.CN)({kind:"GeneratedNode",...a}),createWithExpression:a=>(0,j.CN)({kind:"GeneratedNode",always:!0,expression:a}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),az=(0,j.CN)({is:a=>"DefaultValueNode"===a.kind,create:a=>(0,j.CN)({kind:"DefaultValueNode",defaultValue:a})});function aA(a){if((0,j.Kg)(a)&&ar[a])return a;throw Error(`invalid OnModifyForeignAction ${a}`)}class aB{#g;constructor(a){this.#g=a}autoIncrement(){return new aB(an.cloneWith(this.#g,{autoIncrement:!0}))}identity(){return new aB(an.cloneWith(this.#g,{identity:!0}))}primaryKey(){return new aB(an.cloneWith(this.#g,{primaryKey:!0}))}references(a){let b=(0,au.q5)(a);if(!b.table||at.U.is(b.column))throw Error(`invalid call references('${a}'). The reference must have format table.column or schema.table.column`);return new aB(an.cloneWith(this.#g,{references:as.create(b.table,[b.column])}))}onDelete(a){if(!this.#g.references)throw Error("on delete constraint can only be added for foreign keys");return new aB(an.cloneWith(this.#g,{references:as.cloneWithOnDelete(this.#g.references,aA(a))}))}onUpdate(a){if(!this.#g.references)throw Error("on update constraint can only be added for foreign keys");return new aB(an.cloneWith(this.#g,{references:as.cloneWithOnUpdate(this.#g.references,aA(a))}))}unique(){return new aB(an.cloneWith(this.#g,{unique:!0}))}notNull(){return new aB(an.cloneWith(this.#g,{notNull:!0}))}unsigned(){return new aB(an.cloneWith(this.#g,{unsigned:!0}))}defaultTo(a){return new aB(an.cloneWith(this.#g,{defaultTo:az.create(ax(a))}))}check(a){return new aB(an.cloneWith(this.#g,{check:aq.create(a.toOperationNode())}))}generatedAlwaysAs(a){return new aB(an.cloneWith(this.#g,{generated:ay.createWithExpression(a.toOperationNode())}))}generatedAlwaysAsIdentity(){return new aB(an.cloneWith(this.#g,{generated:ay.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new aB(an.cloneWith(this.#g,{generated:ay.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#g.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new aB(an.cloneWith(this.#g,{generated:ay.cloneWith(this.#g.generated,{stored:!0})}))}modifyFront(a){return new aB(an.cloneWithFrontModifier(this.#g,a.toOperationNode()))}nullsNotDistinct(){return new aB(an.cloneWith(this.#g,{nullsNotDistinct:!0}))}ifNotExists(){return new aB(an.cloneWith(this.#g,{ifNotExists:!0}))}modifyEnd(a){return new aB(an.cloneWithEndModifier(this.#g,a.toOperationNode()))}$call(a){return a(this)}toOperationNode(){return this.#g}}let aC=(0,j.CN)({is:a=>"ModifyColumnNode"===a.kind,create:a=>(0,j.CN)({kind:"ModifyColumnNode",column:a})});var aD=c(44901);let aE=(0,j.CN)({is:a=>"ForeignKeyConstraintNode"===a.kind,create:(a,b,c,d)=>(0,j.CN)({kind:"ForeignKeyConstraintNode",columns:a,references:as.create(b,c),name:d?f.O.create(d):void 0}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});class aF{#g;constructor(a){this.#g=a}onDelete(a){return new aF(aE.cloneWith(this.#g,{onDelete:aA(a)}))}onUpdate(a){return new aF(aE.cloneWith(this.#g,{onUpdate:aA(a)}))}deferrable(){return new aF(aE.cloneWith(this.#g,{deferrable:!0}))}notDeferrable(){return new aF(aE.cloneWith(this.#g,{deferrable:!1}))}initiallyDeferred(){return new aF(aE.cloneWith(this.#g,{initiallyDeferred:!0}))}initiallyImmediate(){return new aF(aE.cloneWith(this.#g,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#g}}let aG=(0,j.CN)({is:a=>"AddConstraintNode"===a.kind,create:a=>(0,j.CN)({kind:"AddConstraintNode",constraint:a})});var aH=c(97551);let aI=(0,j.CN)({is:a=>"UniqueConstraintNode"===a.kind,create:(a,b,c)=>((0,j.Kg)(a.at(0))&&((0,aH.u)("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),a=a.map(am.Z.create)),(0,j.CN)({kind:"UniqueConstraintNode",columns:(0,j.CN)(a),name:b?f.O.create(b):void 0,nullsNotDistinct:c})),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),aJ=(0,j.CN)({is:a=>"DropConstraintNode"===a.kind,create:a=>(0,j.CN)({kind:"DropConstraintNode",constraintName:f.O.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),aK=(0,j.CN)({is:a=>"AlterColumnNode"===a.kind,create:(a,b,c)=>(0,j.CN)({kind:"AlterColumnNode",column:am.Z.create(a),[b]:c})});class aL{#R;constructor(a){this.#R=a}setDataType(a){return new aM(aK.create(this.#R,"dataType",(0,aD.Q)(a)))}setDefault(a){return new aM(aK.create(this.#R,"setDefault",ax(a)))}dropDefault(){return new aM(aK.create(this.#R,"dropDefault",!0))}setNotNull(){return new aM(aK.create(this.#R,"setNotNull",!0))}dropNotNull(){return new aM(aK.create(this.#R,"dropNotNull",!0))}$call(a){return a(this)}}class aM{#S;constructor(a){this.#S=a}toOperationNode(){return this.#S}}class aN{#a;constructor(a){this.#a=(0,j.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class aO{#a;constructor(a){this.#a=(0,j.CN)(a)}onDelete(a){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.onDelete(a)})}onUpdate(a){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.onUpdate(a)})}deferrable(){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.deferrable()})}notDeferrable(){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new aO({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyImmediate()})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(ac.cloneWithTableProps(this.#a.node,{addConstraint:aG.create(this.#a.constraintBuilder.toOperationNode())}),this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class aP{#a;constructor(a){this.#a=(0,j.CN)(a)}ifExists(){return new aP({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{dropConstraint:aJ.cloneWith(this.#a.node.dropConstraint,{ifExists:!0})})})}cascade(){return new aP({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{dropConstraint:aJ.cloneWith(this.#a.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new aP({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{dropConstraint:aJ.cloneWith(this.#a.node.dropConstraint,{modifier:"restrict"})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}let aQ=(0,j.CN)({is:a=>"PrimaryKeyConstraintNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"PrimaryKeyConstraintNode",columns:(0,j.CN)(a.map(am.Z.create)),name:b?f.O.create(b):void 0}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),aR=(0,j.CN)({is:a=>"AddIndexNode"===a.kind,create:a=>(0,j.CN)({kind:"AddIndexNode",name:f.O.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,j.CN)({...a,columns:[...a.columns||[],...b]})});class aS{#a;constructor(a){this.#a=(0,j.CN)(a)}unique(){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.cloneWith(this.#a.node.addIndex,{unique:!0})})})}column(a){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.cloneWithColumns(this.#a.node.addIndex,[(0,j.Kg)(a)?(0,au.Ow)(a):a.toOperationNode()])})})}columns(a){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.cloneWithColumns(this.#a.node.addIndex,a.map(a=>(0,j.Kg)(a)?(0,au.Ow)(a):a.toOperationNode()))})})}expression(a){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.cloneWithColumns(this.#a.node.addIndex,[a.toOperationNode()])})})}using(a){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.cloneWith(this.#a.node.addIndex,{using:g.z.createWithSql(a)})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class aT{#g;constructor(a){this.#g=a}nullsNotDistinct(){return new aT(aI.cloneWith(this.#g,{nullsNotDistinct:!0}))}deferrable(){return new aT(aI.cloneWith(this.#g,{deferrable:!0}))}notDeferrable(){return new aT(aI.cloneWith(this.#g,{deferrable:!1}))}initiallyDeferred(){return new aT(aI.cloneWith(this.#g,{initiallyDeferred:!0}))}initiallyImmediate(){return new aT(aI.cloneWith(this.#g,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#g}}class aU{#g;constructor(a){this.#g=a}deferrable(){return new aU(aQ.cloneWith(this.#g,{deferrable:!0}))}notDeferrable(){return new aU(aQ.cloneWith(this.#g,{deferrable:!1}))}initiallyDeferred(){return new aU(aQ.cloneWith(this.#g,{initiallyDeferred:!0}))}initiallyImmediate(){return new aU(aQ.cloneWith(this.#g,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#g}}class aV{#g;constructor(a){this.#g=a}$call(a){return a(this)}toOperationNode(){return this.#g}}let aW=(0,j.CN)({is:a=>"RenameConstraintNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"RenameConstraintNode",oldName:f.O.create(a),newName:f.O.create(b)})});var aX=c(37338);class aY{#a;constructor(a){this.#a=(0,j.CN)({...a})}ifExists(){return new aY({...this.#a,node:ao.cloneWith(this.#a.node,{ifExists:!0})})}toOperationNode(){return this.#a.node}}class aZ{#a;constructor(a){this.#a=(0,j.CN)(a)}renameTo(a){return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{renameTo:(0,ak.M$)(a)})})}setSchema(a){return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{setSchema:f.O.create(a)})})}alterColumn(a,b){let c=b(new aL(a));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a,b=j.lQ){let c=b(new aY({node:ao.create(a)}));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}renameColumn(a,b){return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,ap.create(a,b))})}addColumn(a,b,c=j.lQ){let d=c(new aB(an.create(a,(0,aD.Q)(b))));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,al.create(d.toOperationNode()))})}modifyColumn(a,b,c=j.lQ){let d=c(new aB(an.create(a,(0,aD.Q)(b))));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,aC.create(d.toOperationNode()))})}addUniqueConstraint(a,b,c=j.lQ){let d=c(new aT(aI.create(b.map(a=>(0,j.Kg)(a)?am.Z.create(a):(0,aX.YK)(a)),a)));return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addConstraint:aG.create(d.toOperationNode())})})}addCheckConstraint(a,b,c=j.lQ){let d=c(new aV(aq.create(b.toOperationNode(),a)));return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addConstraint:aG.create(d.toOperationNode())})})}addForeignKeyConstraint(a,b,c,d,e=j.lQ){let f=e(new aF(aE.create(b.map(am.Z.create),(0,ak.M$)(c),d.map(am.Z.create),a)));return new aO({...this.#a,constraintBuilder:f})}addPrimaryKeyConstraint(a,b,c=j.lQ){let d=c(new aU(aQ.create(b,a)));return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addConstraint:aG.create(d.toOperationNode())})})}dropConstraint(a){return new aP({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{dropConstraint:aJ.create(a)})})}renameConstraint(a,b){return new aP({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{renameConstraint:aW.create(a,b)})})}addIndex(a){return new aS({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{addIndex:aR.create(a)})})}dropIndex(a){return new aN({...this.#a,node:ac.cloneWithTableProps(this.#a.node,{dropIndex:ah.create(a)})})}$call(a){return a(this)}}class a${#a;constructor(a){this.#a=(0,j.CN)(a)}alterColumn(a,b){let c=b(new aL(a));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a,b=j.lQ){let c=b(new aY({node:ao.create(a)}));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}renameColumn(a,b){return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,ap.create(a,b))})}addColumn(a,b,c=j.lQ){let d=c(new aB(an.create(a,(0,aD.Q)(b))));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,al.create(d.toOperationNode()))})}modifyColumn(a,b,c=j.lQ){let d=c(new aB(an.create(a,(0,aD.Q)(b))));return new a$({...this.#a,node:ac.cloneWithColumnAlteration(this.#a.node,aC.create(d.toOperationNode()))})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}var a_=c(31341),a0=c(87301),a1=c(75525),a2=c(90588);class a3 extends a1.V{transformPrimitiveValueList(a){return a2.s.create(a.values.map(aw.q.createImmediate))}transformValue(a){return aw.q.createImmediate(a.value)}}class a4{#a;constructor(a){this.#a=(0,j.CN)(a)}ifNotExists(){return new a4({...this.#a,node:ad.cloneWith(this.#a.node,{ifNotExists:!0})})}unique(){return new a4({...this.#a,node:ad.cloneWith(this.#a.node,{unique:!0})})}nullsNotDistinct(){return new a4({...this.#a,node:ad.cloneWith(this.#a.node,{nullsNotDistinct:!0})})}on(a){return new a4({...this.#a,node:ad.cloneWith(this.#a.node,{table:(0,ak.M$)(a)})})}column(a){return new a4({...this.#a,node:ad.cloneWithColumns(this.#a.node,[(0,j.Kg)(a)?(0,au.Ow)(a):a.toOperationNode()])})}columns(a){return new a4({...this.#a,node:ad.cloneWithColumns(this.#a.node,a.map(a=>(0,j.Kg)(a)?(0,au.Ow)(a):a.toOperationNode()))})}expression(a){return new a4({...this.#a,node:ad.cloneWithColumns(this.#a.node,[a.toOperationNode()])})}using(a){return new a4({...this.#a,node:ad.cloneWith(this.#a.node,{using:g.z.createWithSql(a)})})}where(...a){let b=new a3;return new a4({...this.#a,node:a0.L.cloneWithWhere(this.#a.node,b.transformNode((0,a_.GB)(a),this.#a.queryId))})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class a5{#a;constructor(a){this.#a=(0,j.CN)(a)}ifNotExists(){return new a5({...this.#a,node:ae.cloneWith(this.#a.node,{ifNotExists:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class a6{#g;constructor(a){this.#g=a}using(a){return new a6(aR.cloneWith(this.#g,{using:g.z.createWithSql(a)}))}$call(a){return a(this)}toOperationNode(){return this.#g}}class a7{#a;constructor(a){this.#a=(0,j.CN)(a)}temporary(){return new a7({...this.#a,node:af.B.cloneWith(this.#a.node,{temporary:!0})})}onCommit(a){return new a7({...this.#a,node:af.B.cloneWith(this.#a.node,{onCommit:function(a){if(af.o.includes(a))return a;throw Error(`invalid OnCommitAction ${a}`)}(a)})})}ifNotExists(){return new a7({...this.#a,node:af.B.cloneWith(this.#a.node,{ifNotExists:!0})})}addColumn(a,b,c=j.lQ){let d=c(new aB(an.create(a,(0,aD.Q)(b))));return new a7({...this.#a,node:af.B.cloneWithColumn(this.#a.node,d.toOperationNode())})}addPrimaryKeyConstraint(a,b,c=j.lQ){let d=c(new aU(aQ.create(b,a)));return new a7({...this.#a,node:af.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addUniqueConstraint(a,b,c=j.lQ){let d=c(new aT(aI.create(b.map(a=>(0,j.Kg)(a)?am.Z.create(a):(0,aX.YK)(a)),a)));return new a7({...this.#a,node:af.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addIndex(a,b,c=j.lQ){let d=c(new a6(aR.cloneWithColumns(aR.create(a),b.map(a=>(0,j.Kg)(a)?am.Z.create(a):(0,aX.YK)(a)))));return new a7({...this.#a,node:af.B.cloneWithIndex(this.#a.node,d.toOperationNode())})}addCheckConstraint(a,b,c=j.lQ){let d=c(new aV(aq.create(b.toOperationNode(),a)));return new a7({...this.#a,node:af.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addForeignKeyConstraint(a,b,c,d,e=j.lQ){let f=e(new aF(aE.create(b.map(am.Z.create),(0,ak.M$)(c),d.map(am.Z.create),a)));return new a7({...this.#a,node:af.B.cloneWithConstraint(this.#a.node,f.toOperationNode())})}modifyFront(a){return new a7({...this.#a,node:af.B.cloneWithFrontModifier(this.#a.node,a.toOperationNode())})}modifyEnd(a){return new a7({...this.#a,node:af.B.cloneWithEndModifier(this.#a.node,a.toOperationNode())})}as(a){return new a7({...this.#a,node:af.B.cloneWith(this.#a.node,{selectQuery:(0,aX.YK)(a)})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class a8{#a;constructor(a){this.#a=(0,j.CN)(a)}on(a){return new a8({...this.#a,node:ah.cloneWith(this.#a.node,{table:(0,ak.M$)(a)})})}ifExists(){return new a8({...this.#a,node:ah.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a8({...this.#a,node:ah.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class a9{#a;constructor(a){this.#a=(0,j.CN)(a)}ifExists(){return new a9({...this.#a,node:ai.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a9({...this.#a,node:ai.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}class ba{#a;constructor(a){this.#a=(0,j.CN)(a)}temporary(){return new ba({...this.#a,node:aj.cloneWith(this.#a.node,{temporary:!0})})}ifExists(){return new ba({...this.#a,node:aj.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new ba({...this.#a,node:aj.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}var bb=c(89192),bc=c(55112);class bd{#T=new a3;transformQuery(a){return this.#T.transformNode(a.node,a.queryId)}transformResult(a){return Promise.resolve(a.result)}}class be{#a;constructor(a){this.#a=(0,j.CN)(a)}temporary(){return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{temporary:!0})})}materialized(){return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{materialized:!0})})}ifNotExists(){return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{ifNotExists:!0})})}orReplace(){return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{orReplace:!0})})}columns(a){return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{columns:a.map(au.RY)})})}as(a){let b=a.withPlugin(new bd).toOperationNode();return new be({...this.#a,node:bc.Y.cloneWith(this.#a.node,{as:b})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}let bf=(0,j.CN)({is:a=>"DropViewNode"===a.kind,create:a=>(0,j.CN)({kind:"DropViewNode",name:ag.y.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});class bg{#a;constructor(a){this.#a=(0,j.CN)(a)}materialized(){return new bg({...this.#a,node:bf.cloneWith(this.#a.node,{materialized:!0})})}ifExists(){return new bg({...this.#a,node:bf.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new bg({...this.#a,node:bf.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}let bh=(0,j.CN)({is:a=>"CreateTypeNode"===a.kind,create:a=>(0,j.CN)({kind:"CreateTypeNode",name:a}),cloneWithEnum:(a,b)=>(0,j.CN)({...a,enum:a2.s.create(b.map(aw.q.createImmediate))})});class bi{#a;constructor(a){this.#a=(0,j.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}asEnum(a){return new bi({...this.#a,node:bh.cloneWithEnum(this.#a.node,a)})}$call(a){return a(this)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}let bj=(0,j.CN)({is:a=>"DropTypeNode"===a.kind,create:a=>(Array.isArray(a)||(a=[a]),(0,j.CN)({kind:"DropTypeNode",name:a[0],additionalNames:a.slice(1)})),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});class bk{#a;constructor(a){this.#a=(0,j.CN)(a)}ifExists(){return new bk({...this.#a,node:bj.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new bk({...this.#a,node:bj.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}function bl(a){if(!a.includes("."))return ag.y.create(a);{let b=a.split(".").map(bm);if(2===b.length)return ag.y.createWithSchema(b[0],b[1]);throw Error(`invalid schemable identifier ${a}`)}}function bm(a){return a.trim()}let bn=(0,j.CN)({is:a=>"RefreshMaterializedViewNode"===a.kind,create:a=>(0,j.CN)({kind:"RefreshMaterializedViewNode",name:ag.y.create(a)}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});class bo{#a;constructor(a){this.#a=(0,j.CN)(a)}concurrently(){return new bo({...this.#a,node:bn.cloneWith(this.#a.node,{concurrently:!0,withNoData:!1})})}withData(){return new bo({...this.#a,node:bn.cloneWith(this.#a.node,{withNoData:!1})})}withNoData(){return new bo({...this.#a,node:bn.cloneWith(this.#a.node,{withNoData:!0,concurrently:!1})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){await this.#a.executor.executeQuery(this.compile(),a)}}let bp=(0,j.CN)({is:a=>"AlterTypeNode"===a.kind,create:a=>(0,j.CN)({kind:"AlterTypeNode",name:a}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})}),bq=(0,j.CN)({is:a=>"AddValueNode"===a.kind,create:a=>(0,j.CN)({kind:"AddValueNode",value:a}),cloneWith:(a,b)=>(0,j.CN)({...a,...b})});class br{#a;constructor(a){this.#a=(0,j.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){return await this.#a.executor.executeQuery(this.compile(),a)}}class bs extends br{#a;constructor(a){super(a),this.#a=a}ifNotExists(){return new d({...this.#a,node:bp.cloneWith(this.#a.node,{addValue:bq.cloneWith(this.#a.node.addValue,{ifNotExists:!0})})})}before(a){return this.#U(a,!0)}after(a){return this.#U(a,!1)}#U(a,b){return new d({...this.#a,node:bp.cloneWith(this.#a.node,{addValue:bq.cloneWith(this.#a.node.addValue,{isBefore:b,neighborValue:aw.q.createImmediate(a)})})})}}d=bs;let bt=(0,j.CN)({is:a=>"RenameValueNode"===a.kind,create:(a,b)=>(0,j.CN)({kind:"RenameValueNode",oldValue:a,newValue:b})});class bu{#a;constructor(a){this.#a=(0,j.CN)(a)}addValue(a){return new bs({...this.#a,node:bp.cloneWith(this.#a.node,{addValue:bq.create(aw.q.createImmediate(a))})})}renameTo(a){return new br({...this.#a,node:bp.cloneWith(this.#a.node,{renameTo:f.O.create(a)})})}renameValue(a,b){return new br({...this.#a,node:bp.cloneWith(this.#a.node,{renameValue:bt.create(aw.q.createImmediate(a),aw.q.createImmediate(b))})})}setSchema(a){return new br({...this.#a,node:bp.cloneWith(this.#a.node,{setSchema:f.O.create(a)})})}}class bv{#V;constructor(a){this.#V=a}createTable(a){return new a7({queryId:(0,k.a)(),executor:this.#V,node:af.B.create((0,ak.M$)(a))})}dropTable(a){return new ba({queryId:(0,k.a)(),executor:this.#V,node:aj.create((0,ak.M$)(a))})}createIndex(a){return new a4({queryId:(0,k.a)(),executor:this.#V,node:ad.create(a)})}dropIndex(a){return new a8({queryId:(0,k.a)(),executor:this.#V,node:ah.create(a)})}createSchema(a){return new a5({queryId:(0,k.a)(),executor:this.#V,node:ae.create(a)})}dropSchema(a){return new a9({queryId:(0,k.a)(),executor:this.#V,node:ai.create(a)})}alterTable(a){return new aZ({queryId:(0,k.a)(),executor:this.#V,node:ac.create((0,ak.M$)(a))})}createView(a){return new be({queryId:(0,k.a)(),executor:this.#V,node:bc.Y.create(a)})}refreshMaterializedView(a){return new bo({queryId:(0,k.a)(),executor:this.#V,node:bn.create(a)})}dropView(a){return new bg({queryId:(0,k.a)(),executor:this.#V,node:bf.create(a)})}createType(a){return new bi({queryId:(0,k.a)(),executor:this.#V,node:bh.create(bl(a))})}alterType(a){return new bu({executor:this.#V,node:bp.create(bl(a)),queryId:(0,k.a)()})}dropType(a){var b;return new bk({queryId:(0,k.a)(),executor:this.#V,node:bj.create((Array.isArray(b=a)||(b=[b]),b.map(bl)))})}withPlugin(a){return new bv(this.#V.withPlugin(a))}withoutPlugins(){return new bv(this.#V.withoutPlugins())}withSchema(a){return new bv(this.#V.withPluginAtFront(new bb.B(a)))}}var bw=c(88035),bx=c(34716);class by{ref(a){return new bw.g(a)}table(a){return new bx.bj(a)}}class bz{#W;constructor(a){this.#W=a}async provideConnection(a,b){let c=await this.#W.acquireConnection(b);try{return await a(c)}finally{await this.#W.releaseConnection(c,b)}}}var bA=c(8586),bB=c(49479);class bC extends bB.R{#X;#Y;#Z;constructor(a,b,c,d=[]){super(d),this.#X=a,this.#Y=b,this.#Z=c}get adapter(){return this.#Y}compileQuery(a,b){return this.#X.compileQuery(a,b)}provideConnection(a,b){return this.#Z.provideConnection(a,b)}withPlugins(a){return new bC(this.#X,this.#Y,this.#Z,[...this.plugins,...a])}withPlugin(a){return new bC(this.#X,this.#Y,this.#Z,[...this.plugins,a])}withPluginAtFront(a){return new bC(this.#X,this.#Y,this.#Z,[a,...this.plugins])}withConnectionProvider(a){return new bC(this.#X,this.#Y,a,[...this.plugins])}withoutPlugins(){return new bC(this.#X,this.#Y,this.#Z,[])}}var bD=c(61359);function bE(){return"u">typeof performance&&(0,j.Tn)(performance.now)?performance.now():Date.now()}class bF{#$;#_;async obtainLock(){for(;this.#$;)await this.#$;this.#$=new Promise(a=>{this.#_=a})}releaseLock(){let a=this.#_;this.#$=void 0,this.#_=void 0,a?.()}}class bG{#W;#aa;#ab;#ac;#ad;#t=new WeakSet;#ae;constructor(a,b,c){this.#W=a,this.#ac=!1,this.#aa=c,!1===b.supportsMultipleConnections&&(this.#ae=new bF)}async init(a){if(this.#ad)throw Error("driver has already been destroyed");this.#ab??=this.#W.init(a).then(()=>{this.#ac=!0}).catch(a=>{throw this.#ab=void 0,a}),await (0,bD.Hl)(this.#ab,a?.signal,"init")}async acquireConnection(a){if(this.#ad)throw Error("driver has already been destroyed");if(this.#ac||await this.init(a),this.#ae){let b=this.#ae.obtainLock();await (0,bD.Hl)(b,a?.signal,"acquireConnection:mutex",()=>b.then(()=>this.#ae?.releaseLock()))}let b=this.#W.acquireConnection(a),c=await (0,bD.Hl)(b,a?.signal,"acquireConnection:acquire",()=>b?.then(a=>this.releaseConnection(a).catch((0,bD.gx)("driver.releaseConnection"))).catch((0,bD.gx)("driver.acquireConnection")));return this.#t.has(c)||(this.#af()&&this.#ag(c),this.#t.add(c)),c}async releaseConnection(a,b){await this.#W.releaseConnection(a,b),this.#ae?.releaseLock()}async beginTransaction(a,b){return await this.#W.beginTransaction(a,b)}async commitTransaction(a){return await this.#W.commitTransaction(a)}async rollbackTransaction(a){return await this.#W.rollbackTransaction(a)}async savepoint(a,b,c){if(this.#W.savepoint)return await this.#W.savepoint(a,b,c);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(a,b,c){if(this.#W.rollbackToSavepoint)return await this.#W.rollbackToSavepoint(a,b,c);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(a,b,c){if(this.#W.releaseSavepoint)return await this.#W.releaseSavepoint(a,b,c);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(a){this.#ab&&(await (0,bD.Hl)(this.#ab,a?.signal,"destroy:initPromise"),this.#ad??=this.#W.destroy(a).catch(a=>{throw this.#ad=void 0,a}),await (0,bD.Hl)(this.#ad,a?.signal,"destroy"))}#af(){return this.#aa.isLevelEnabled("query")||this.#aa.isLevelEnabled("error")}#ag(a){let b=a.executeQuery,c=a.streamQuery,d=this;a.executeQuery=async(c,e)=>{let f,g=bE();try{return await b.call(a,c,e)}catch(a){throw f=a,await d.#ah(a,c,g),a}finally{f||await d.#ai(c,g)}},a.streamQuery=async function*(b,e,f){let g,h=bE();try{for await(let d of c.call(a,b,e,f))yield d}catch(a){throw g=a,await d.#ah(a,b,h),a}finally{g||await d.#ai(b,h,!0)}}}async #ah(a,b,c){await this.#aa.error(()=>({level:"error",error:a,query:b,queryDurationMillis:this.#aj(c)}))}async #ai(a,b,c=!1){await this.#aa.query(()=>({level:"query",isStream:c,query:a,queryDurationMillis:this.#aj(b)}))}#aj(a){return bE()-a}}let bH=()=>{};class bI{#q;#ak;constructor(a){this.#q=a}async provideConnection(a){for(;this.#ak;)await this.#ak.catch(bH);return this.#ak=this.#al(a).finally(()=>{this.#ak=void 0}),this.#ak}async #al(a){return await a(this.#q)}}let bJ=["read only","read write"],bK=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function bL(a){if(a.accessMode&&!bJ.includes(a.accessMode))throw Error(`invalid transaction access mode ${a.accessMode}`);if(a.isolationLevel&&!bK.includes(a.isolationLevel))throw Error(`invalid transaction isolation level ${a.isolationLevel}`)}var bM=c(10469);(0,j.CN)(["query","error"]);class bN{#am;#an;constructor(a){(0,j.Tn)(a)?(this.#an=a,this.#am=(0,j.CN)({query:!0,error:!0})):(this.#an=bO,this.#am=(0,j.CN)({query:a.includes("query"),error:a.includes("error")}))}isLevelEnabled(a){return this.#am[a]}async query(a){this.#am.query&&await this.#an(a())}async error(a){this.#am.error&&await this.#an(a())}}function bO(a){if("query"===a.level){let b=`kysely:query:${a.isStream?"stream:":""}`;console.log(`${b} ${a.query.sql}`),console.log(`${b} duration: ${a.queryDurationMillis.toFixed(1)}ms`)}else"error"===a.level&&(a.error instanceof Error?console.error(`kysely:error: ${a.error.stack??a.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:a.error,query:a.query.sql,queryDurationMillis:a.queryDurationMillis})}`))}var bP=c(22943),bQ=c(17532),bR=c(95962);Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class bS extends bA.n{#a;constructor(a){let b,c;if(function(a){return(0,j.Gv)(a)&&(0,j.Gv)(a.config)&&(0,j.Gv)(a.driver)&&(0,j.Gv)(a.executor)&&(0,j.Gv)(a.dialect)}(a))b={executor:a.executor},c={...a};else{const d=a.dialect,e=d.createDriver(),f=d.createQueryCompiler(),g=d.createAdapter(),h=new bG(e,g,new bN(a.log??[])),i=new bC(f,g,new bz(h),a.plugins??[]);b={executor:i},c={config:a,executor:i,dialect:d,driver:h}}super(b),this.#a=(0,j.CN)(c)}get schema(){return new bv(this.#a.executor)}get dynamic(){return new by}get introspection(){return this.#a.dialect.createIntrospector(this.withoutPlugins())}case(a){return new bP.OU({node:bQ.P.create((0,j.b0)(a)?void 0:(0,aX.YK)(a))})}get fn(){return(0,bM.t)()}transaction(){return new bV({...this.#a})}startTransaction(){return new bW({...this.#a})}connection(){return new bU({...this.#a})}withPlugin(a){return new bS({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bS({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bS({...this.#a,executor:this.#a.executor.withPluginAtFront(new bb.B(a))})}$extendTables(){return new bS({...this.#a})}$omitTables(){return new bS({...this.#a})}$pickTables(){return new bS({...this.#a})}withTables(){return this.$extendTables()}async destroy(){await this.#a.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#a.executor}async executeQuery(a,b){let c=(0,j.Gv)(a)&&(0,j.Tn)(a.compile)?a.compile():a;return await this.#a.executor.executeQuery(c,b)}async [Symbol.asyncDispose](){await this.destroy()}}class bT extends bS{#a;constructor(a){super(a),this.#a=a}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(a){return new bT({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bT({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bT({...this.#a,executor:this.#a.executor.withPluginAtFront(new bb.B(a))})}withTables(){return new bT({...this.#a})}$extendTables(){return new bT({...this.#a})}$omitTables(){return new bT({...this.#a})}$pickTables(){return new bT({...this.#a})}}class bU{#a;constructor(a){this.#a=(0,j.CN)(a)}async execute(a,b){return this.#a.executor.provideConnection(async b=>{let c=this.#a.executor.withConnectionProvider(new bI(b)),d=new bS({...this.#a,executor:c});return await a(d)},(0,j.CN)({signal:b?.signal}))}}class bV{#a;constructor(a){this.#a=(0,j.CN)(a)}setAccessMode(a){return new bV({...this.#a,accessMode:a})}setIsolationLevel(a){return new bV({...this.#a,isolationLevel:a})}async execute(a){let{isolationLevel:b,accessMode:c,...d}=this.#a,e={isolationLevel:b,accessMode:c};return bL(e),this.#a.executor.provideConnection(async b=>{let c={isCommitted:!1,isRolledBack:!1},f=new b$(this.#a.executor.withConnectionProvider(new bI(b)),c),g=new bT({...d,executor:f}),h=!1;try{await this.#a.driver.beginTransaction(b,e),h=!0;let d=await a(g);return await this.#a.driver.commitTransaction(b),c.isCommitted=!0,d}catch(a){throw h&&(await this.#a.driver.rollbackTransaction(b),c.isRolledBack=!0),a}})}}class bW{#a;constructor(a){this.#a=(0,j.CN)(a)}setAccessMode(a){return new bW({...this.#a,accessMode:a})}setIsolationLevel(a){return new bW({...this.#a,isolationLevel:a})}async execute(){let{isolationLevel:a,accessMode:b,...c}=this.#a,d={isolationLevel:a,accessMode:b};bL(d);let e=await (0,bR.G)(this.#a.executor);return await this.#a.driver.beginTransaction(e.connection,d),new bX({...c,connection:e,executor:this.#a.executor.withConnectionProvider(new bI(e.connection))})}}class bX extends bT{#a;#ao;#ap;constructor(a){const b={isCommitted:!1,isRolledBack:!1},{connection:c,...d}=a={...a,executor:new b$(a.executor,b)};super(d),this.#a=(0,j.CN)(a),this.#ap=b;const e=(0,k.a)();this.#ao=b=>a.executor.compileQuery(b,e)}get isCommitted(){return this.#ap.isCommitted}get isRolledBack(){return this.#ap.isRolledBack}commit(){return bZ(this.#ap),new bY(async()=>{await this.#a.driver.commitTransaction(this.#a.connection.connection),this.#ap.isCommitted=!0,this.#a.connection.release()})}rollback(){return bZ(this.#ap),new bY(async()=>{await this.#a.driver.rollbackTransaction(this.#a.connection.connection),this.#ap.isRolledBack=!0,this.#a.connection.release()})}savepoint(a){return bZ(this.#ap),new bY(async()=>(await this.#a.driver.savepoint?.(this.#a.connection.connection,a,this.#ao),new bX({...this.#a})))}rollbackToSavepoint(a){return bZ(this.#ap),new bY(async()=>(await this.#a.driver.rollbackToSavepoint?.(this.#a.connection.connection,a,this.#ao),new bX({...this.#a})))}releaseSavepoint(a){return bZ(this.#ap),new bY(async()=>(await this.#a.driver.releaseSavepoint?.(this.#a.connection.connection,a,this.#ao),new bX({...this.#a})))}withPlugin(a){return new bX({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bX({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bX({...this.#a,executor:this.#a.executor.withPluginAtFront(new bb.B(a))})}withTables(){return new bX({...this.#a})}$extendTables(){return new bX({...this.#a})}$omitTables(){return new bX({...this.#a})}$pickTables(){return new bX({...this.#a})}}class bY{#aq;constructor(a){this.#aq=a}async execute(){return await this.#aq()}}function bZ(a){if(a.isCommitted)throw Error("Transaction is already committed");if(a.isRolledBack)throw Error("Transaction is already rolled back")}class b${#V;#ap;constructor(a,b){this.#V=a instanceof b$?a.#V:a,this.#ap=b}get adapter(){return this.#V.adapter}get plugins(){return this.#V.plugins}transformQuery(a,b){return this.#V.transformQuery(a,b)}compileQuery(a,b){return this.#V.compileQuery(a,b)}provideConnection(a,b){return this.#V.provideConnection(a,b)}executeQuery(a,b){return bZ(this.#ap),this.#V.executeQuery(a,b)}stream(a,b,c){return bZ(this.#ap),this.#V.stream(a,b,c)}withConnectionProvider(a){return new b$(this.#V.withConnectionProvider(a),this.#ap)}withPlugin(a){return new b$(this.#V.withPlugin(a),this.#ap)}withPlugins(a){return new b$(this.#V.withPlugins(a),this.#ap)}withPluginAtFront(a){return new b$(this.#V.withPluginAtFront(a),this.#ap)}withoutPlugins(){return new b$(this.#V.withoutPlugins(),this.#ap)}}var b_=c(37807),b0=c(15214);function b1(a){return a.charAt(0).toUpperCase()+a.slice(1)}function b2(a){if(!a)return null;if("dialect"in a)return b2(a.dialect);if("createDriver"in a){if(a instanceof t)return"sqlite";if(a instanceof H)return"mysql";if(a instanceof Q)return"postgres";if(a instanceof ab)return"mssql"}return"aggregate"in a?"sqlite":"getConnection"in a?"mysql":"connect"in a?"postgres":"fileControl"in a||"open"in a&&"close"in a&&"prepare"in a||"batch"in a&&"exec"in a&&"prepare"in a?"sqlite":null}let b3=async a=>{let b,d=a.database;if(!d)return{kysely:null,databaseType:null,transaction:void 0};if("db"in d)return{kysely:d.db,databaseType:d.type,transaction:d.transaction};if("dialect"in d)return{kysely:new bS({dialect:d.dialect}),databaseType:d.type,transaction:d.transaction};let e=b2(d);if("createDriver"in d&&(b=d),"aggregate"in d&&!("createSession"in d)&&(b=new t({database:d})),"getConnection"in d&&(b=new H(d)),"connect"in d&&(b=new Q({pool:d})),"fileControl"in d){let{BunSqliteDialect:a}=await c.e(6658).then(c.bind(c,36658));b=new a({database:d})}if("createSession"in d){let a;try{({DatabaseSync:a}=await import("node:sqlite"))}catch(a){if(null!==a&&"object"==typeof a&&"code"in a&&"ERR_UNKNOWN_BUILTIN_MODULE"!==a.code)throw a}if(a&&d instanceof a){let{NodeSqliteDialect:a}=await c.e(6706).then(c.bind(c,26706));b=new a({database:d})}}if("batch"in d&&"exec"in d&&"prepare"in d){let{D1SqliteDialect:a}=await c.e(7514).then(c.bind(c,47514));b=new a({database:d})}return{kysely:b?new bS({dialect:b}):null,databaseType:e,transaction:void 0}};function b4(a,b,c){return"postgres"===c?(0,q.l)`${q.l.ref(a)} ILIKE ${b}`:(0,q.l)`LOWER(${q.l.ref(a)}) LIKE LOWER(${b})`}let b5=(a,b)=>{let c=null,d=!1,e=(a,c=!1)=>({getFieldName:e,schema:f,getDefaultFieldName:g,getDefaultModelName:h,getFieldAttributes:i,getModelName:j,options:k})=>{b?.type!=="mysql"||k.advanced?.database?.generateId!==!1||d||(d=!0,b0.vF.warn('[Kysely Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth\'s default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.'));let l=a=>{let b=[],c=[];if(a)for(let[d,e]of Object.entries(a)){let a=f[h(d)]?.fields,[e,g]=d.includes(".")?d.split("."):[void 0,d];if(a)for(let[e,f]of(a.id={type:"string"},Object.entries(a)))b.push((0,q.l)`${q.l.ref(`join_${g}`)}.${q.l.ref(f.fieldName||e)} as ${q.l.ref(`_joined_${g}_${f.fieldName||e}`)}`),c.push({joinModel:d,joinModelRef:g,fieldName:f.fieldName||e})}return{allSelectsStr:c,allSelects:b}},m=async(d,g,i,j)=>{if(b?.type==="mysql"){if(await g.execute(),j.length>0){let b=d.id?"id":j[0]?.field?j[0].field:"id",c=void 0!==d[b]?d[b]:j[0]?.value;return await a.selectFrom(i).selectAll().where(e({model:i,field:b}),null===c?"is":"=",c).limit(1).executeTakeFirst()}let b=async a=>{if(d.id)return await a.selectFrom(i).selectAll().where(e({model:i,field:"id"}),"=",d.id).limit(1).executeTakeFirst();if(k.advanced?.database?.generateId==="serial"){let b=(await (0,q.l)`SELECT LAST_INSERT_ID() as id`.execute(a)).rows[0]?.id;if(b)return await a.selectFrom(i).selectAll().where(e({model:i,field:"id"}),"=",b).limit(1).executeTakeFirst()}let b=f[h(i)]?.fields;if(b)for(let[c,f]of Object.entries(b)){if(!f.unique)continue;let b=e({model:i,field:c}),g=d[b];if(null==g)continue;let h=await a.selectFrom(i).selectAll().where(b,"=",g).limit(1).executeTakeFirst();if(h)return h}let c=a.selectFrom(i).selectAll(),g=!1;for(let[a,b]of Object.entries(d))void 0!==b&&(c=c.where(a,null===b?"is":"=",b),g=!0);if(g){let a=await c.limit(2).execute();if(1===a.length)return a[0]}return b0.vF.warn(`[Kysely Adapter] Unable to safely identify the inserted "${i}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return c?b(a):a.transaction().execute(b)}return b?.type==="mssql"?await g.outputAll("inserted").executeTakeFirst():await g.returningAll().executeTakeFirst()};function n(a,c){if(!c)return{and:null,or:null};let d=[],f=[];return c.forEach(c=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:k="sensitive"}=c,l=e({model:a,field:g}),m="insensitive"===k&&("string"==typeof h||Array.isArray(h)&&h.every(a=>"string"==typeof a)),n=c=>{var d,e;let f=`${a}.${l}`;if("in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(d=Array.isArray(h)?h:[h],{lhs:(0,q.l)`LOWER(${q.l.ref(f)})`,values:d.map(a=>a.toLowerCase())});return c(a,"in",b)}return c(f,"in",Array.isArray(h)?h:[h])}if("not_in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(e=Array.isArray(h)?h:[h],{lhs:(0,q.l)`LOWER(${q.l.ref(f)})`,values:e.map(a=>a.toLowerCase())});return c(a,"not in",b)}return c(f,"not in",Array.isArray(h)?h:[h])}if("contains"===i)return m&&"string"==typeof h?b4(f,`%${h}%`,b?.type):c(f,"like",`%${h}%`);if("starts_with"===i)return m&&"string"==typeof h?b4(f,`${h}%`,b?.type):c(f,"like",`${h}%`);if("ends_with"===i)return m&&"string"==typeof h?b4(f,`%${h}`,b?.type):c(f,"like",`%${h}`);if("eq"===i){if(null===h)return c(f,"is",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,q.l)`LOWER(${q.l.ref(f)})`,value:h.toLowerCase()};return c(a,"=",b)}return c(f,"=",h)}if("ne"===i){if(null===h)return c(f,"is not",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,q.l)`LOWER(${q.l.ref(f)})`,value:h.toLowerCase()};return c(a,"<>",b)}return c(f,"<>",h)}return c(f,"gt"===i?">":"gte"===i?">=":"lt"===i?"<":"lte"===i?"<=":i,h)};"OR"===j?f.push(n):d.push(n)}),{and:d.length?d:null,or:f.length?f:null}}function o(a,b,c){if(!b||!a.length)return a;let d=new Map;for(let f of a){let a={},g={};for(let[a]of Object.entries(b))g[j(a)]={};for(let[b,d]of Object.entries(f)){let f=String(b),h=!1;for(let{joinModel:a,fieldName:b,joinModelRef:i}of c)if(f===`_joined_${i}_${b}`||f===`_Joined${b1(i)}${b1(b)}`){g[j(a)][e({model:a,field:b})]=d,h=!0;break}h||(a[b]=d)}let h=a.id;if(!h)continue;if(!d.has(h)){let c={...a};for(let[a,d]of Object.entries(b))c[j(a)]="one-to-one"===d.relation?null:[];d.set(h,c)}let i=d.get(h);for(let[a,c]of Object.entries(b)){let b="one-to-one"===c.relation,d=c.limit??100,f=g[j(a)],h=f&&Object.keys(f).length>0&&Object.values(f).some(a=>null!=a);if(b)i[j(a)]=h?f:null;else{let b=j(a);if(Array.isArray(i[b])&&h){if(i[b].length>=d)continue;let c=e({model:a,field:"id"}),g=f[c];g?!i[b].some(a=>a[c]===g)&&i[b].length<d&&i[b].push(f):i[b].length<d&&i[b].push(f)}}}}let f=Array.from(d.values());for(let a of f)for(let[c,d]of Object.entries(b))if("one-to-one"!==d.relation){let b=j(c);if(Array.isArray(a[b])){let c=d.limit??100;a[b].length>c&&(a[b]=a[b].slice(0,c))}}return f}return{create:async({data:b,model:c})=>await m(b,a.insertInto(c).values(b),c,[]),async findOne({model:b,where:c,select:d,join:f}){let{and:g,or:h}=n(b,c),i=a.selectFrom(a=>{let c=a.selectFrom(b);return g&&(c=c.where(a=>a.and(g.map(b=>b(a))))),h&&(c=c.where(a=>a.or(h.map(b=>b(a))))),(c=d?.length&&d.length>0?c.select(d.map(a=>e({model:b,field:a}))):c.selectAll()).as("primary")}).selectAll("primary");if(f)for(let[a,b]of Object.entries(f)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];i=i.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:j,allSelects:k}=l(f);i=i.select(k);let m=await i.execute();if(!m||!Array.isArray(m)||0===m.length)return null;let p=m[0];return f?o(m,f,j)[0]:p},async findMany({model:c,where:d,limit:f,select:g,offset:h,sortBy:i,join:j}){let{and:k,or:m}=n(c,d),p=a.selectFrom(a=>{let d=a.selectFrom(c);return b?.type==="mssql"?void 0!==h?(i||(d=d.orderBy(e({model:c,field:"id"}))),d=d.offset(h).fetch(f||100)):void 0!==f&&(d=d.top(f)):(void 0!==f&&(d=d.limit(f)),void 0!==h&&(d=d.offset(h))),i?.field&&(d=d.orderBy(`${e({model:c,field:i.field})}`,i.direction)),k&&(d=d.where(a=>a.and(k.map(b=>b(a))))),m&&(d=d.where(a=>a.or(m.map(b=>b(a))))),(d=g?.length&&g.length>0?d.select(g.map(a=>e({model:c,field:a}))):d.selectAll()).as("primary")}).selectAll("primary");if(j)for(let[a,b]of Object.entries(j)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];p=p.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:q,allSelects:r}=l(j);p=p.select(r),i?.field&&(p=p.orderBy(`${e({model:c,field:i.field})}`,i.direction));let s=await p.execute();return s?j?o(s,j,q):s:[]},async update({model:b,where:c,update:d}){let{and:e,or:f}=n(b,c),g=a.updateTable(b).set(d);return e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a))))),await m(d,g,b,c)},async updateMany({model:b,where:c,update:d}){let{and:e,or:f}=n(b,c),g=a.updateTable(b).set(d);e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a)))));let h=(await g.executeTakeFirst()).numUpdatedRows;return h>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(h)},async count({model:b,where:c}){let{and:d,or:e}=n(b,c),f=a.selectFrom(b).select(a.fn.count("id").as("count"));d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=await f.execute();return"number"==typeof g[0].count?g[0].count:"bigint"==typeof g[0].count?Number(g[0].count):parseInt(g[0].count)},async delete({model:b,where:c}){let{and:d,or:e}=n(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a))))),await f.execute()},async deleteMany({model:b,where:c}){let{and:d,or:e}=n(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=(await f.executeTakeFirst()).numDeletedRows;return g>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(g)},async consumeOne({model:d,where:f}){let{and:g,or:h}=n(d,f),i=a=>(g&&(a=a.where(a=>a.and(g.map(b=>b(a))))),h&&(a=a.where(a=>a.or(h.map(b=>b(a))))),a),j=e({model:d,field:"id"}),k=async(a,c)=>{let e=c[j]??c.id;if(null==e)return null;let f=a.deleteFrom(d).where(`${d}.${j}`,"=",e);return b?.type==="mysql"?Number((await f.executeTakeFirst()).numDeletedRows)>0?c:null:b?.type==="mssql"?await f.outputAll("deleted").executeTakeFirst()??null:await f.returningAll().executeTakeFirst()??null},l=async a=>b?.type==="mssql"?await a.outputAll("deleted").executeTakeFirst()??null:await a.returningAll().executeTakeFirst()??null;if(b?.type==="mysql"){let b=async a=>{let b=await i(a.selectFrom(d).selectAll().forUpdate()).limit(1).executeTakeFirst();return b?k(a,b):null};return c?b(a):a.transaction().execute(b)}let m=i(a.selectFrom(d).select(`${d}.${j}`)),o=b?.type==="mssql"?m.top(1):m.limit(1);return l(a.deleteFrom(d).where(`${d}.${j}`,"in",o))},async incrementOne({model:d,where:f,increment:g,set:h}){let{and:i,or:j}=n(d,f),k=a=>(i&&(a=a.where(a=>a.and(i.map(b=>b(a))))),j&&(a=a.where(a=>a.or(j.map(b=>b(a))))),a),l={...h??{}};for(let[a,b]of Object.entries(g))l[a]=(0,q.l)`${q.l.ref(a)} + ${b}`;let m=e({model:d,field:"id"});if(b?.type==="mysql"){let b=async a=>{let b=await k(a.selectFrom(d).select(`${d}.${m}`).forUpdate()).limit(1).executeTakeFirst();if(!b)return null;let c=b[m]??b.id;return null==c||0===Number((await k(a.updateTable(d).set(l)).where(`${d}.${m}`,"=",c).executeTakeFirst()).numUpdatedRows)?null:await a.selectFrom(d).selectAll().where(`${d}.${m}`,"=",c).limit(1).executeTakeFirst()??null};return c?b(a):a.transaction().execute(b)}let o=k(a.selectFrom(d).select(`${d}.${m}`)),p=b?.type==="mssql"?o.top(1):o.limit(1),r=a.updateTable(d).set(l).where(`${d}.${m}`,"in",p);return b?.type==="mssql"?await r.outputAll("inserted").executeTakeFirst()??null:await r.returningAll().executeTakeFirst()??null},options:b}},f=null;f={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:b?.usePlural,debugLogs:b?.debugLogs,supportsBooleans:b?.type!=="sqlite"&&b?.type!=="mssql"&&b?.type!=="mysql"&&!!b?.type,supportsDates:b?.type!=="sqlite"&&b?.type!=="mssql"&&!!b?.type,supportsJSON:b?.type==="postgres",supportsArrays:!1,supportsUUIDs:b?.type==="postgres",transaction:!!b?.transaction&&(b=>a.transaction().execute(a=>b((0,b_.I)({config:{...f.config,transaction:!1},adapter:e(a,!0)})(c))))},adapter:e(a)};let g=(0,b_.I)(f);return a=>(c=a,g(a))}},46489:(a,b,c)=>{"use strict";c.d(b,{J:()=>n,G:()=>function a(b){return(0,d.Tn)(b)?a(b((0,l.A)())):(0,d.MH)(b)?b.map(a=>m(a)):[m(b)]}});var d=c(18110),e=c(22475),f=c(90386);let g=(0,d.CN)({is:a=>"SelectionNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectionNode",selection:a}),createSelectAll:()=>(0,d.CN)({kind:"SelectionNode",selection:f.U.create()}),createSelectAllFromTable:a=>(0,d.CN)({kind:"SelectionNode",selection:e.q.createSelectAll(a)})});var h=c(45541),i=c(88035),j=c(37338),k=c(27800),l=c(80627);function m(a){return(0,d.Kg)(a)?g.create((0,h.DT)(a)):(0,i.C)(a)?g.create(a.toOperationNode()):g.create((0,j.v0)(a))}function n(a){return a?Array.isArray(a)?a.map(o):[o(a)]:[g.createSelectAll()]}function o(a){if((0,d.Kg)(a))return g.createSelectAllFromTable((0,k.M$)(a));throw Error(`invalid value selectAll expression: ${JSON.stringify(a)}`)}},46752:(a,b,c)=>{"use strict";var d,e;Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return p}});let f=c(79308),g=c(68877),h=c(7656),i=c(34310),j=c(50315);function k(a,b){if(!a)return b;let c=parseInt(a,10);return Number.isFinite(c)&&c>0?c:b}d=c(43543),e=b,Object.keys(d).forEach(function(a){"default"===a||Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{enumerable:!0,get:function(){return d[a]}})});let l=k(process.env.NEXT_PRIVATE_RESPONSE_CACHE_TTL,1e4),m=k(process.env.NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE,150),n="__ttl_sentinel__";function o(a,b){return`${a}\0${b??n}`}class p{constructor(a,b=m,c=l){this.getBatcher=f.Batcher.create({cacheKeyFn:({key:a,isOnDemandRevalidate:b})=>`${a}-${b?"1":"0"}`,schedulerFn:i.scheduleOnNextTick}),this.revalidateBatcher=f.Batcher.create({schedulerFn:i.scheduleOnNextTick}),this.evictedInvocationIDs=new Set,this.minimal_mode=a,this.maxSize=b,this.ttl=c,this.cache=new g.LRUCache(b,void 0,a=>{let b=function(a){let b=a.lastIndexOf("\0");if(-1===b)return;let c=a.slice(b+1);return c===n?void 0:c}(a);if(b){if(this.evictedInvocationIDs.size>=100){let a=this.evictedInvocationIDs.values().next().value;a&&this.evictedInvocationIDs.delete(a)}this.evictedInvocationIDs.add(b)}})}async get(a,b,c){if(!a)return b({hasResolved:!1,previousCacheEntry:null});if(this.minimal_mode){let b=o(a,c.invocationID),d=this.cache.get(b);if(d){if(void 0!==c.invocationID)return(0,j.toResponseCacheEntry)(d.entry);let a=Date.now();if(d.expiresAt>a)return(0,j.toResponseCacheEntry)(d.entry);this.cache.remove(b)}c.invocationID&&this.evictedInvocationIDs.has(c.invocationID)&&(0,h.warnOnce)(`Response cache entry was evicted for invocation ${c.invocationID}. Consider increasing NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE (current: ${this.maxSize}).`)}let{incrementalCache:d,isOnDemandRevalidate:e=!1,isFallback:f=!1,isRoutePPREnabled:g=!1,isPrefetch:i=!1,waitUntil:k,routeKind:l,invocationID:m}=c,n=await this.getBatcher.batch({key:a,isOnDemandRevalidate:e},({resolve:c})=>{let h=this.handleGet(a,b,{incrementalCache:d,isOnDemandRevalidate:e,isFallback:f,isRoutePPREnabled:g,isPrefetch:i,routeKind:l,invocationID:m},c);return k&&k(h),h});return(0,j.toResponseCacheEntry)(n)}async handleGet(a,b,c,d){let e=null,f=!1;try{if((e=this.minimal_mode?null:await c.incrementalCache.get(a,{kind:(0,j.routeKindToIncrementalCacheKind)(c.routeKind),isRoutePPREnabled:c.isRoutePPREnabled,isFallback:c.isFallback}))&&!c.isOnDemandRevalidate&&(d(e),f=!0,!e.isStale||c.isPrefetch))return e;let g=await this.revalidate(a,c.incrementalCache,c.isRoutePPREnabled,c.isFallback,b,e,null!==e&&!c.isOnDemandRevalidate,void 0,c.invocationID);if(!g){if(this.minimal_mode){let b=o(a,c.invocationID);this.cache.remove(b)}return null}return c.isOnDemandRevalidate,g}catch(a){if(f)return console.error(a),null;throw a}}async revalidate(a,b,c,d,e,f,g,h,i){return this.revalidateBatcher.batch(a,()=>{let j=this.handleRevalidate(a,b,c,d,e,f,g,i);return h&&h(j),j})}async handleRevalidate(a,b,c,d,e,f,g,h){try{let i=await e({hasResolved:g,previousCacheEntry:f,isRevalidating:!0});if(!i)return null;let k=await (0,j.fromResponseCacheEntry)({...i,isMiss:!f});if(k.cacheControl)if(this.minimal_mode){let b=o(a,h);this.cache.set(b,{entry:k,expiresAt:Date.now()+this.ttl})}else await b.set(a,k.value,{cacheControl:k.cacheControl,isRoutePPREnabled:c,isFallback:d});return k}catch(e){if(null==f?void 0:f.cacheControl){let e=Math.min(Math.max(f.cacheControl.revalidate||3,3),30),g=void 0===f.cacheControl.expire?void 0:Math.max(e+3,f.cacheControl.expire);await b.set(a,f.value,{cacheControl:{revalidate:e,expire:g},isRoutePPREnabled:c,isFallback:d})}throw e}}}},47070:(a,b,c)=>{"use strict";function d(){throw Object.defineProperty(Error("`unauthorized()` is experimental and only allowed to be used when `experimental.authInterrupts` is enabled."),"__NEXT_ERROR_CODE",{value:"E411",enumerable:!1,configurable:!0})}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"unauthorized",{enumerable:!0,get:function(){return d}}),c(15707).HTTP_ERROR_FALLBACK_ERROR_CODE,("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},47536:(a,b,c)=>{"use strict";c.d(b,{c:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"JSONPathNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONPathNode",inOperator:a,pathLegs:(0,d.CN)([])}),cloneWithLeg:(a,b)=>(0,d.CN)({...a,pathLegs:(0,d.CN)([...a.pathLegs,b])})})},48145:(a,b,c)=>{"use strict";c.d(b,{b:()=>h});var d=c(18110),e=c(59255),f=c(67449);let g=(0,d.CN)({is:a=>"OnNode"===a.kind,create:a=>(0,d.CN)({kind:"OnNode",on:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,on:"And"===b?e.s.create(a.on,c):f.K.create(a.on,c)})}),h=(0,d.CN)({is:a=>"JoinNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:void 0}),createWithOn:(a,b,c)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:g.create(c)}),cloneWithOn:(a,b)=>(0,d.CN)({...a,on:a.on?g.cloneWithOperation(a.on,"And",b):g.create(b)})})},49479:(a,b,c)=>{"use strict";c.d(b,{R:()=>i});var d=c(18110),e=c(95962),f=c(61359),g=c(79362);let h=(0,d.CN)([]);class i{#ar;constructor(a=h){this.#ar=a}get plugins(){return this.#ar}transformQuery(a,b){for(let c of this.#ar){let d=c.transformQuery({node:a,queryId:b});if(d.kind===a.kind)a=d;else throw Error(`KyselyPlugin.transformQuery must return a node of the same kind that was given to it. The plugin was given a ${a.kind} but it returned a ${d.kind}`)}return a}async executeQuery(a,b){let{inflightQueryAbortStrategy:c="ignore query",signal:h}=b||{};if(!h){let c=await this.provideConnection(async b=>await b.executeQuery(a),b);return await this.#as(c,a.queryId)}(0,f.JJ)(h,"before query execution"),b=(0,d.CN)({signal:h});let{connection:i,release:j}=await (0,e.G)(this,b),k=this.provideConnection.bind(this),{promise:l,resolve:m}=new g.c,n=()=>m(f.wp);h.addEventListener("abort",n,{once:!0});try{(0,f.JJ)(h,"before query execution",j);let d=(0,f.u8)(c,i,j);if(d&&i.collectSessionInfo){(0,f.JJ)(h,"before query execution",j);let a=i.collectSessionInfo();await Promise.race([l,a]).catch(a=>{throw j(),a})===f.wp&&(a.catch((0,f.gx)("collectSessionInfo")).finally(j),(0,f.x)(h.reason,"before query execution"))}let e=i.executeQuery(a,b),g=await Promise.race([l,e]).catch(a=>{throw j(),a});g===f.wp?(Promise.allSettled([e.catch((0,f.gx)("query")),d?.(k).catch((0,f.gx)("inflightQueryAbortHandler"))]).finally(j),(0,f.x)(h.reason,"during query execution")):j();let m=this.#as(g,a.queryId,b),n=await Promise.race([l,m]);return n===f.wp&&(m.catch((0,f.gx)("plugins.transformResult")),(0,f.x)(h.reason,"during result transformation")),n}finally{m(f.wp),h.removeEventListener("abort",n)}}async *stream(a,b,c){let h,i,{signal:j}=c||{};if(!j){let{connection:d,release:f}=await (0,e.G)(this);try{for await(let e of d.streamQuery(a,b))yield await this.#as(e,a.queryId,c)}finally{f()}return}c=(0,d.CN)({signal:j}),(0,f.JJ)(j,"before connection acquisition");let{connection:k,release:l}=await (0,e.G)(this,c),{promise:m,resolve:n}=new g.c,o=()=>n(f.wp);j.addEventListener("abort",o,{once:!0}),(0,f.JJ)(j,"before query streaming",l);let{queryId:p}=a;try{for(h=k.streamQuery(a,b,c);;){(0,f.JJ)(j,"during query streaming");let a=h.next(),b=await Promise.race([m,a]);if(b===f.wp&&(i=a.catch((0,f.gx)("iterator.next")),(0,f.x)(j.reason,"during query streaming")),b.done)break;let d=this.#as(b.value,p,c),e=await Promise.race([m,d]);e===f.wp&&(i=d.catch((0,f.gx)("plugins.transformResult")),(0,f.x)(j.reason,"during result transformation")),yield e}}finally{n(f.wp),j.removeEventListener("abort",o);let a=(h?.return?.()||Promise.resolve()).finally(()=>i).finally(l);i||await a}}async #as(a,b,c){let{signal:e}=c||{};for(let c of this.#ar)a=await c.transformResult((0,d.CN)({queryId:b,result:a,signal:e}));return a}}},49747:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"NextURL",{enumerable:!0,get:function(){return k}});let d=c(10375),e=c(23632),f=c(65661),g=c(82069),h=/^(?:127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)$/;function i(a,b){let c=new URL(String(a),b&&String(b));return h.test(c.hostname)&&(c.hostname="localhost"),c}let j=Symbol("NextURLInternal");class k{constructor(a,b,c){let d,e;"object"==typeof b&&"pathname"in b||"string"==typeof b?(d=b,e=c||{}):e=c||b||{},this[j]={url:i(a,d??e.base),options:e,basePath:""},this.analyze()}analyze(){var a,b,c,e,h;let i=(0,g.getNextPathnameInfo)(this[j].url.pathname,{nextConfig:this[j].options.nextConfig,parseData:!0,i18nProvider:this[j].options.i18nProvider}),k=(0,f.getHostname)(this[j].url,this[j].options.headers);this[j].domainLocale=this[j].options.i18nProvider?this[j].options.i18nProvider.detectDomainLocale(k):(0,d.detectDomainLocale)(null==(b=this[j].options.nextConfig)||null==(a=b.i18n)?void 0:a.domains,k);let l=(null==(c=this[j].domainLocale)?void 0:c.defaultLocale)||(null==(h=this[j].options.nextConfig)||null==(e=h.i18n)?void 0:e.defaultLocale);this[j].url.pathname=i.pathname,this[j].defaultLocale=l,this[j].basePath=i.basePath??"",this[j].buildId=i.buildId,this[j].locale=i.locale??l,this[j].trailingSlash=i.trailingSlash}formatPathname(){return(0,e.formatNextPathnameInfo)({basePath:this[j].basePath,buildId:this[j].buildId,defaultLocale:this[j].options.forceLocale?void 0:this[j].defaultLocale,locale:this[j].locale,pathname:this[j].url.pathname,trailingSlash:this[j].trailingSlash})}formatSearch(){return this[j].url.search}get buildId(){return this[j].buildId}set buildId(a){this[j].buildId=a}get locale(){return this[j].locale??""}set locale(a){var b,c;if(!this[j].locale||!(null==(c=this[j].options.nextConfig)||null==(b=c.i18n)?void 0:b.locales.includes(a)))throw Object.defineProperty(TypeError(`The NextURL configuration includes no locale "${a}"`),"__NEXT_ERROR_CODE",{value:"E597",enumerable:!1,configurable:!0});this[j].locale=a}get defaultLocale(){return this[j].defaultLocale}get domainLocale(){return this[j].domainLocale}get searchParams(){return this[j].url.searchParams}get host(){return this[j].url.host}set host(a){this[j].url.host=a}get hostname(){return this[j].url.hostname}set hostname(a){this[j].url.hostname=a}get port(){return this[j].url.port}set port(a){this[j].url.port=a}get protocol(){return this[j].url.protocol}set protocol(a){this[j].url.protocol=a}get href(){let a=this.formatPathname(),b=this.formatSearch();return`${this.protocol}//${this.host}${a}${b}${this.hash}`}set href(a){this[j].url=i(a),this.analyze()}get origin(){return this[j].url.origin}get pathname(){return this[j].url.pathname}set pathname(a){this[j].url.pathname=a}get hash(){return this[j].url.hash}set hash(a){this[j].url.hash=a}get search(){return this[j].url.search}set search(a){this[j].url.search=a}get password(){return this[j].url.password}set password(a){this[j].url.password=a}get username(){return this[j].url.username}set username(a){this[j].url.username=a}get basePath(){return this[j].basePath}set basePath(a){this[j].basePath=a.startsWith("/")?a:`/${a}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new k(String(this),this[j].options)}}},50182:(a,b,c)=>{"use strict";c.d(b,{N:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"AliasNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AliasNode",node:a,alias:b})})},50315:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d,e={fromResponseCacheEntry:function(){return k},routeKindToIncrementalCacheKind:function(){return m},toResponseCacheEntry:function(){return l}};for(var f in e)Object.defineProperty(b,f,{enumerable:!0,get:e[f]});let g=c(43543),h=(d=c(28333))&&d.__esModule?d:{default:d},i=c(42315),j=c(52730);async function k(a){var b,c;return{...a,value:(null==(b=a.value)?void 0:b.kind)===g.CachedRouteKind.PAGES?{kind:g.CachedRouteKind.PAGES,html:await a.value.html.toUnchunkedString(!0),pageData:a.value.pageData,headers:a.value.headers,status:a.value.status}:(null==(c=a.value)?void 0:c.kind)===g.CachedRouteKind.APP_PAGE?{kind:g.CachedRouteKind.APP_PAGE,html:await a.value.html.toUnchunkedString(!0),postponed:a.value.postponed,rscData:a.value.rscData,headers:a.value.headers,status:a.value.status,segmentData:a.value.segmentData}:a.value}}async function l(a){var b,c;return a?{isMiss:a.isMiss,isStale:a.isStale,cacheControl:a.cacheControl,isFallback:a.isFallback,value:(null==(b=a.value)?void 0:b.kind)===g.CachedRouteKind.PAGES?{kind:g.CachedRouteKind.PAGES,html:h.default.fromStatic(a.value.html,j.HTML_CONTENT_TYPE_HEADER),pageData:a.value.pageData,headers:a.value.headers,status:a.value.status}:(null==(c=a.value)?void 0:c.kind)===g.CachedRouteKind.APP_PAGE?{kind:g.CachedRouteKind.APP_PAGE,html:h.default.fromStatic(a.value.html,j.HTML_CONTENT_TYPE_HEADER),rscData:a.value.rscData,headers:a.value.headers,status:a.value.status,postponed:a.value.postponed,segmentData:a.value.segmentData}:a.value}:null}function m(a){switch(a){case i.RouteKind.PAGES:return g.IncrementalCacheKind.PAGES;case i.RouteKind.APP_PAGE:return g.IncrementalCacheKind.APP_PAGE;case i.RouteKind.IMAGE:return g.IncrementalCacheKind.IMAGE;case i.RouteKind.APP_ROUTE:return g.IncrementalCacheKind.APP_ROUTE;case i.RouteKind.PAGES_API:throw Object.defineProperty(Error(`Unexpected route kind ${a}`),"__NEXT_ERROR_CODE",{value:"E64",enumerable:!1,configurable:!0});default:return a}}},50472:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"notFound",{enumerable:!0,get:function(){return f}});let d=c(15707),e=`${d.HTTP_ERROR_FALLBACK_ERROR_CODE};404`;function f(){let a=Object.defineProperty(Error(e),"__NEXT_ERROR_CODE",{value:"E1041",enumerable:!1,configurable:!0});throw a.digest=e,a}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},52730:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={ACTION_SUFFIX:function(){return p},APP_DIR_ALIAS:function(){return O},CACHE_ONE_YEAR_SECONDS:function(){return E},DOT_NEXT_ALIAS:function(){return M},ESLINT_DEFAULT_DIRS:function(){return ag},GSP_NO_RETURNED_VALUE:function(){return aa},GSSP_COMPONENT_MEMBER_ERROR:function(){return ad},GSSP_NO_RETURNED_VALUE:function(){return ab},HTML_CONTENT_TYPE_HEADER:function(){return f},INFINITE_CACHE:function(){return F},INSTRUMENTATION_HOOK_FILENAME:function(){return K},JSON_CONTENT_TYPE_HEADER:function(){return g},MATCHED_PATH_HEADER:function(){return j},MIDDLEWARE_FILENAME:function(){return G},MIDDLEWARE_LOCATION_REGEXP:function(){return H},NEXT_BODY_SUFFIX:function(){return s},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return C},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return v},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return w},NEXT_CACHE_ROOT_PARAM_TAG_ID:function(){return D},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return B},NEXT_CACHE_TAGS_HEADER:function(){return u},NEXT_CACHE_TAG_MAX_ITEMS:function(){return z},NEXT_CACHE_TAG_MAX_LENGTH:function(){return A},NEXT_DATA_SUFFIX:function(){return q},NEXT_INTERCEPTION_MARKER_PREFIX:function(){return i},NEXT_META_SUFFIX:function(){return r},NEXT_NAV_DEPLOYMENT_ID_HEADER:function(){return t},NEXT_QUERY_PARAM_PREFIX:function(){return h},NEXT_RESUME_HEADER:function(){return x},NEXT_RESUME_STATE_LENGTH_HEADER:function(){return y},NON_STANDARD_NODE_ENV:function(){return ae},PAGES_DIR_ALIAS:function(){return L},PRERENDER_REVALIDATE_HEADER:function(){return k},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return l},PROXY_FILENAME:function(){return I},PROXY_LOCATION_REGEXP:function(){return J},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return W},ROOT_DIR_ALIAS:function(){return N},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return V},RSC_ACTION_ENCRYPTION_ALIAS:function(){return U},RSC_ACTION_PROXY_ALIAS:function(){return R},RSC_ACTION_VALIDATE_ALIAS:function(){return Q},RSC_CACHE_WRAPPER_ALIAS:function(){return S},RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS:function(){return T},RSC_MOD_REF_PROXY_ALIAS:function(){return P},RSC_SEGMENTS_DIR_SUFFIX:function(){return m},RSC_SEGMENT_SUFFIX:function(){return n},RSC_SUFFIX:function(){return o},SERVER_PROPS_EXPORT_ERROR:function(){return _},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return Y},SERVER_PROPS_SSG_CONFLICT:function(){return Z},SERVER_RUNTIME:function(){return ah},SSG_FALLBACK_EXPORT_ERROR:function(){return af},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return X},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return $},TEXT_PLAIN_CONTENT_TYPE_HEADER:function(){return e},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return ac},WEBPACK_LAYERS:function(){return ak},WEBPACK_RESOURCE_QUERIES:function(){return al},WEB_SOCKET_MAX_RECONNECTIONS:function(){return ai}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="text/plain",f="text/html; charset=utf-8",g="application/json; charset=utf-8",h="nxtP",i="nxtI",j="x-matched-path",k="x-prerender-revalidate",l="x-prerender-revalidate-if-generated",m=".segments",n=".segment.rsc",o=".rsc",p=".action",q=".json",r=".meta",s=".body",t="x-nextjs-deployment-id",u="x-next-cache-tags",v="x-next-revalidated-tags",w="x-next-revalidate-tag-token",x="next-resume",y="x-next-resume-state-length",z=128,A=256,B=1024,C="_N_T_",D="_N_RP_",E=31536e3,F=0xfffffffe,G="middleware",H=`(?:src/)?${G}`,I="proxy",J=`(?:src/)?${I}`,K="instrumentation",L="private-next-pages",M="private-dot-next",N="private-next-root-dir",O="private-next-app-dir",P="next/dist/build/webpack/loaders/next-flight-loader/module-proxy",Q="private-next-rsc-action-validate",R="private-next-rsc-server-reference",S="private-next-rsc-cache-wrapper",T="private-next-rsc-track-dynamic-import",U="private-next-rsc-action-encryption",V="private-next-rsc-action-client-wrapper",W="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",X="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",Y="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",Z="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",$="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",_="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",aa="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",ab="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",ac="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",ad="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",ae='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',af="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",ag=["app","pages","components","lib","src"],ah={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},ai=12,aj={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",apiNode:"api-node",apiEdge:"api-edge",middleware:"middleware",instrument:"instrument",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",pagesDirBrowser:"pages-dir-browser",pagesDirEdge:"pages-dir-edge",pagesDirNode:"pages-dir-node"},ak={...aj,GROUP:{builtinReact:[aj.reactServerComponents,aj.actionBrowser],serverOnly:[aj.reactServerComponents,aj.actionBrowser,aj.instrument,aj.middleware],neutralTarget:[aj.apiNode,aj.apiEdge],clientOnly:[aj.serverSideRendering,aj.appPagesBrowser],bundled:[aj.reactServerComponents,aj.actionBrowser,aj.serverSideRendering,aj.appPagesBrowser,aj.shared,aj.instrument,aj.middleware],appPages:[aj.reactServerComponents,aj.serverSideRendering,aj.appPagesBrowser,aj.actionBrowser]}},al={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},54254:(a,b,c)=>{"use strict";c.d(b,{O:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"OrderByNode"===a.kind,create:a=>(0,d.CN)({kind:"OrderByNode",items:(0,d.CN)([...a])}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})})},54410:(a,b,c)=>{let d;d={unstable_cache:c(86965).e,updateTag:c(23121).updateTag,revalidateTag:c(23121).revalidateTag,revalidatePath:c(23121).revalidatePath,refresh:c(23121).refresh,unstable_noStore:c(10820).M,cacheLife:c(34219).F,cacheTag:c(67103).z};let e=!1,f=!1;d.unstable_cacheLife=function(){return e||(e=!0,console.error(Error("`unstable_cacheLife` was recently stabilized and should be imported as `cacheLife`. The `unstable` prefixed form will be removed in a future version of Next.js."))),d.cacheLife.apply(this,arguments)},d.unstable_cacheTag=function(){return f||(f=!0,console.error(Error("`unstable_cacheTag` was recently stabilized and should be imported as `cacheTag`. The `unstable` prefixed form will be removed in a future version of Next.js."))),d.cacheTag.apply(this,arguments)},a.exports=d,b.unstable_cache=d.unstable_cache,b.revalidatePath=d.revalidatePath,b.revalidateTag=d.revalidateTag,b.updateTag=d.updateTag,b.unstable_noStore=d.unstable_noStore,b.cacheLife=d.cacheLife,b.unstable_cacheLife=d.unstable_cacheLife,b.cacheTag=d.cacheTag,b.unstable_cacheTag=d.unstable_cacheTag,b.refresh=d.refresh},55112:(a,b,c)=>{"use strict";c.d(b,{Y:()=>f});var d=c(18110),e=c(4432);let f=(0,d.CN)({is:a=>"CreateViewNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateViewNode",name:e.y.create(a)}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},55713:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"createDedupedByCallsiteServerErrorLoggerDev",{enumerable:!0,get:function(){return i}});let d=function(a){if(a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var b=e(void 0);if(b&&b.has(a))return b.get(a);var c={__proto__:null},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in a)if("default"!==f&&Object.prototype.hasOwnProperty.call(a,f)){var g=d?Object.getOwnPropertyDescriptor(a,f):null;g&&(g.get||g.set)?Object.defineProperty(c,f,g):c[f]=a[f]}return c.default=a,b&&b.set(a,c),c}(c(9499));function e(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(e=function(a){return a?c:b})(a)}let f={current:null},g="function"==typeof d.cache?d.cache:a=>a,h=console.warn;function i(a){return function(...b){h(a(...b))}}g(a=>{try{h(f.current)}finally{f.current=null}})},56603:(a,b,c)=>{"use strict";c.d(b,{t:()=>h});var d=c(59310);let e={eterm:4,cons25:4,console:4,cygwin:4,dtterm:4,gnome:4,hurd:4,jfbterm:4,konsole:4,kterm:4,mlterm:4,mosh:24,putty:4,st:4,"rxvt-unicode-24bit":24,terminator:24,"xterm-kitty":24},f=new Map(Object.entries({APPVEYOR:8,BUILDKITE:8,CIRCLECI:24,DRONE:8,GITEA_ACTIONS:24,GITHUB_ACTIONS:24,GITLAB_CI:8,TRAVIS:8})),g=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function h(){if(void 0!==(0,d.lh)("FORCE_COLOR"))switch((0,d.lh)("FORCE_COLOR")){case"":case"1":case"true":return 4;case"2":return 8;case"3":return 24;default:return 1}if(void 0!==(0,d.lh)("NODE_DISABLE_COLORS")&&""!==(0,d.lh)("NODE_DISABLE_COLORS")||void 0!==(0,d.lh)("NO_COLOR")&&""!==(0,d.lh)("NO_COLOR")||"dumb"===(0,d.lh)("TERM"))return 1;if((0,d.lh)("TMUX"))return 24;if("TF_BUILD"in d._K&&"AGENT_NAME"in d._K)return 4;if("CI"in d._K){for(let{0:a,1:b}of f)if(a in d._K)return b;return"codeship"===(0,d.lh)("CI_NAME")?8:1}if("TEAMCITY_VERSION"in d._K)return null!==/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec((0,d.lh)("TEAMCITY_VERSION"))?4:1;switch((0,d.lh)("TERM_PROGRAM")){case"iTerm.app":if(!(0,d.lh)("TERM_PROGRAM_VERSION")||null!==/^[0-2]\./.exec((0,d.lh)("TERM_PROGRAM_VERSION")))return 8;return 24;case"HyperTerm":case"MacTerm":return 24;case"Apple_Terminal":return 8}if("truecolor"===(0,d.lh)("COLORTERM")||"24bit"===(0,d.lh)("COLORTERM"))return 24;if((0,d.lh)("TERM")){if(null!==/truecolor/.exec((0,d.lh)("TERM")))return 24;if(null!==/^xterm-256/.exec((0,d.lh)("TERM")))return 8;let a=(0,d.lh)("TERM").toLowerCase();if(e[a])return e[a];if(g.some(b=>null!==b.exec(a)))return 4}return(0,d.lh)("COLORTERM")?4:1}},57100:a=>{a.exports={efs:!0,encode:a=>Buffer.from(a,"utf8"),decode:a=>a.toString("utf8")}},59055:(a,b,c)=>{var d=c(25296),e=d.Constants;a.exports=function(){var a,b=10,c=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;a=20|(d.isWin?2560:768),c|=e.FLG_EFS;let r={extraLen:0},s=a=>Math.max(0,a)>>>0;return g=d.fromDate2DOS(new Date),{get made(){return a},set made(val){a=val},get version(){return b},set version(val){b=val},get flags(){return c},set flags(val){c=val},get flags_efs(){return(c&e.FLG_EFS)>0},set flags_efs(val){val?c|=e.FLG_EFS:c&=~e.FLG_EFS},get flags_desc(){return(c&e.FLG_DESC)>0},set flags_desc(val){val?c|=e.FLG_DESC:c&=~e.FLG_DESC},get method(){return f},set method(val){switch(val){case e.STORED:this.version=10;case e.DEFLATED:default:this.version=20}f=val},get time(){return d.fromDOS2Date(this.timeval)},set time(val){val=new Date(val),this.timeval=d.fromDate2DOS(val)},get timeval(){return g},set timeval(val){g=s(val)},get timeHighByte(){return 255&Math.max(0,g>>>8)},get crc(){return h},set crc(val){h=s(val)},get compressedSize(){return i},set compressedSize(val){i=s(val)},get size(){return j},set size(val){j=s(val)},get fileNameLength(){return k},set fileNameLength(val){k=val},get extraLength(){return l},set extraLength(val){l=val},get extraLocalLength(){return r.extraLen},set extraLocalLength(val){r.extraLen=val},get commentLength(){return m},set commentLength(val){m=val},get diskNumStart(){return n},set diskNumStart(val){n=s(val)},get inAttr(){return o},set inAttr(val){o=s(val)},get attr(){return p},set attr(val){p=s(val)},get fileAttr(){return(p||0)>>16&4095},get offset(){return q},set offset(val){q=s(val)},get encrypted(){return(c&e.FLG_ENC)===e.FLG_ENC},get centralHeaderSize(){return e.CENHDR+k+l+m},get realDataOffset(){return q+e.LOCHDR+r.fnameLen+r.extraLen},get localHeader(){return r},loadLocalHeaderFromBinary:function(a){var b=a.slice(q,q+e.LOCHDR);if(b.readUInt32LE(0)!==e.LOCSIG)throw d.Errors.INVALID_LOC();r.version=b.readUInt16LE(e.LOCVER),r.flags=b.readUInt16LE(e.LOCFLG),r.flags_desc=(r.flags&e.FLG_DESC)>0,r.method=b.readUInt16LE(e.LOCHOW),r.time=b.readUInt32LE(e.LOCTIM),r.crc=b.readUInt32LE(e.LOCCRC),r.compressedSize=b.readUInt32LE(e.LOCSIZ),r.size=b.readUInt32LE(e.LOCLEN),r.fnameLen=b.readUInt16LE(e.LOCNAM),r.extraLen=b.readUInt16LE(e.LOCEXT);let c=q+e.LOCHDR+r.fnameLen,f=c+r.extraLen;return a.slice(c,f)},loadFromBinary:function(r){if(r.length!==e.CENHDR||r.readUInt32LE(0)!==e.CENSIG)throw d.Errors.INVALID_CEN();a=r.readUInt16LE(e.CENVEM),b=r.readUInt16LE(e.CENVER),c=r.readUInt16LE(e.CENFLG),f=r.readUInt16LE(e.CENHOW),g=r.readUInt32LE(e.CENTIM),h=r.readUInt32LE(e.CENCRC),i=r.readUInt32LE(e.CENSIZ),j=r.readUInt32LE(e.CENLEN),k=r.readUInt16LE(e.CENNAM),l=r.readUInt16LE(e.CENEXT),m=r.readUInt16LE(e.CENCOM),n=r.readUInt16LE(e.CENDSK),o=r.readUInt16LE(e.CENATT),p=r.readUInt32LE(e.CENATX),q=r.readUInt32LE(e.CENOFF)},localHeaderToBinary:function(){var a=Buffer.alloc(e.LOCHDR);return a.writeUInt32LE(e.LOCSIG,0),a.writeUInt16LE(b,e.LOCVER),a.writeUInt16LE(c,e.LOCFLG),a.writeUInt16LE(f,e.LOCHOW),a.writeUInt32LE(g,e.LOCTIM),a.writeUInt32LE(h,e.LOCCRC),a.writeUInt32LE(i,e.LOCSIZ),a.writeUInt32LE(j,e.LOCLEN),a.writeUInt16LE(k,e.LOCNAM),a.writeUInt16LE(r.extraLen,e.LOCEXT),a},centralHeaderToBinary:function(){var d=Buffer.alloc(e.CENHDR+k+l+m);return d.writeUInt32LE(e.CENSIG,0),d.writeUInt16LE(a,e.CENVEM),d.writeUInt16LE(b,e.CENVER),d.writeUInt16LE(c,e.CENFLG),d.writeUInt16LE(f,e.CENHOW),d.writeUInt32LE(g,e.CENTIM),d.writeUInt32LE(h,e.CENCRC),d.writeUInt32LE(i,e.CENSIZ),d.writeUInt32LE(j,e.CENLEN),d.writeUInt16LE(k,e.CENNAM),d.writeUInt16LE(l,e.CENEXT),d.writeUInt16LE(m,e.CENCOM),d.writeUInt16LE(n,e.CENDSK),d.writeUInt16LE(o,e.CENATT),d.writeUInt32LE(p,e.CENATX),d.writeUInt32LE(q,e.CENOFF),d},toJSON:function(){let g=function(a){return a+" bytes"};return{made:a,version:b,flags:c,method:d.methodToString(f),time:this.time,crc:"0x"+h.toString(16).toUpperCase(),compressedSize:g(i),size:g(j),fileNameLength:g(k),extraLength:g(l),commentLength:g(m),diskNumStart:n,inAttr:o,attr:p,offset:q,centralHeaderSize:g(e.CENHDR+k+l+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}},59255:(a,b,c)=>{"use strict";c.d(b,{s:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"AndNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AndNode",left:a,right:b})})},59310:(a,b,c)=>{"use strict";c.d(b,{$F:()=>l,KV:()=>h,Km:()=>m,Nu:()=>j,_K:()=>f,lh:()=>k,yz:()=>i});let d=Object.create(null),e=a=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(a?d:globalThis),f=new Proxy(d,{get:(a,b)=>e()[b]??d[b],has:(a,b)=>b in e()||b in d,set:(a,b,c)=>(e(!0)[b]=c,!0),deleteProperty(a,b){if(!b)return!1;let c=e(!0);return delete c[b],!0},ownKeys:()=>Object.keys(e(!0))}),g=f.NODE_ENV??"",h="production"===g,i=()=>"dev"===g||"development"===g,j=()=>{var a;return"test"===g||!!(a=f.TEST)&&"false"!==a};function k(a,b){return"u">typeof process&&process.env?process.env[a]??b:"u">typeof Deno?Deno.env.get(a)??b:"u">typeof Bun?Bun.env[a]??b:b}function l(a,b=!0){let c=k(a);return c?"0"!==c&&"false"!==c.toLowerCase()&&""!==c:b}let m=Object.freeze({get BETTER_AUTH_SECRET(){return k("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return k("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return k("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return k("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return k("NODE_ENV","development")},get PACKAGE_VERSION(){return k("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return k("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})},59324:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={getRedirectError:function(){return i},getRedirectStatusCodeFromError:function(){return n},getRedirectTypeFromError:function(){return m},getURLFromRedirectError:function(){return l},permanentRedirect:function(){return k},redirect:function(){return j}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(24543),g=c(45461),h=c(19121).actionAsyncStorage;function i(a,b,c=f.RedirectStatusCode.TemporaryRedirect){let d=Object.defineProperty(Error(g.REDIRECT_ERROR_CODE),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return d.digest=`${g.REDIRECT_ERROR_CODE};${b};${a};${c};`,d}function j(a,b){throw i(a,b??=h?.getStore()?.isAction?"push":"replace",f.RedirectStatusCode.TemporaryRedirect)}function k(a,b="replace"){throw i(a,b,f.RedirectStatusCode.PermanentRedirect)}function l(a){return(0,g.isRedirectError)(a)?a.digest.split(";").slice(2,-2).join(";"):null}function m(a){if(!(0,g.isRedirectError)(a))throw Object.defineProperty(Error("Not a redirect error"),"__NEXT_ERROR_CODE",{value:"E260",enumerable:!1,configurable:!0});return a.digest.split(";",2)[1]}function n(a){if(!(0,g.isRedirectError)(a))throw Object.defineProperty(Error("Not a redirect error"),"__NEXT_ERROR_CODE",{value:"E260",enumerable:!1,configurable:!0});return Number(a.digest.split(";").at(-2))}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},59916:(a,b,c)=>{"use strict";c.d(b,{GQ:()=>u,EQ:()=>v,bl:()=>t});var d=c(48145),e=c(18110),f=c(54254);let g=(0,e.CN)({is:a=>"PartitionByNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByNode",items:(0,e.CN)(a)}),cloneWithItems:(a,b)=>(0,e.CN)({...a,items:(0,e.CN)([...a.items,...b])})}),h=(0,e.CN)({is:a=>"OverNode"===a.kind,create:()=>(0,e.CN)({kind:"OverNode"}),cloneWithOrderByItems:(a,b)=>(0,e.CN)({...a,orderBy:a.orderBy?f.O.cloneWithItems(a.orderBy,b):f.O.create(b)}),cloneWithPartitionByItems:(a,b)=>(0,e.CN)({...a,partitionBy:a.partitionBy?g.cloneWithItems(a.partitionBy,b):g.create(b)})});var i=c(80184),j=c(31341);class k{#a;constructor(a){this.#a=(0,e.CN)(a)}on(...a){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.GB)(a))})}onRef(a,b,c){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.vC)(a,b,c))})}onTrue(){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,i.z.createWithSql("true"))})}$call(a){return a(this)}toOperationNode(){return this.#a.joinNode}}var l=c(87301),m=c(10611);let n=(0,e.CN)({is:a=>"PartitionByItemNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByItemNode",partitionBy:a})});var o=c(45541);class p{#a;constructor(a){this.#a=(0,e.CN)(a)}orderBy(...a){return new p({overNode:h.cloneWithOrderByItems(this.#a.overNode,(0,m.xk)(a))})}clearOrderBy(){return new p({overNode:l.L.cloneWithoutOrderBy(this.#a.overNode)})}partitionBy(a){return new p({overNode:h.cloneWithPartitionByItems(this.#a.overNode,(0,o.kU)(a).map(n.create))})}$call(a){return a(this)}toOperationNode(){return this.#a.overNode}}var q=c(8586),r=c(24492),s=c(27800);function t(){return new q.n({executor:r.W})}function u(a,b){return new k({joinNode:d.b.create(a,(0,s.uJ)(b))})}function v(){return new p({overNode:h.create()})}},60266:(a,b,c)=>{"use strict";c.d(b,{c:()=>E});var d,e=c(50182),f=c(18110);let g=(0,f.CN)({is:a=>"SelectModifierNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"SelectModifierNode",modifier:a,of:b}),createWithExpression:a=>(0,f.CN)({kind:"SelectModifierNode",rawModifier:a})});var h=c(36688),i=c(27800),j=c(46489),k=c(45541),l=c(37694),m=c(87301),n=c(10611),o=c(64829);let p=(0,f.CN)({is:a=>"OffsetNode"===a.kind,create:a=>(0,f.CN)({kind:"OffsetNode",offset:a})}),q=(0,f.CN)({is:a=>"GroupByItemNode"===a.kind,create:a=>(0,f.CN)({kind:"GroupByItemNode",groupBy:a})});var r=c(80627),s=c(38199),t=c(98051),u=c(44382),v=c(37338);function w(a,b,c){return(0,f.Tn)(b)&&(b=b((0,r.O)())),(0,f.MH)(b)||(b=[b]),b.map(b=>u.i.create(a,(0,v.YK)(b),c))}var x=c(31341),y=c(14877),z=c(2929),A=c(76051);let B=(0,f.CN)({is:a=>"FetchNode"===a.kind,create:(a,b)=>({kind:"FetchNode",rowCount:A.q.create(a),modifier:b})});var C=c(80848);class D{#a;constructor(a){this.#a=(0,f.CN)(a)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...a){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.vC)(a,b,c))})}having(...a){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.GB)(a))})}havingRef(a,b,c){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.vC)(a,b,c))})}select(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.G)(a))})}distinctOn(a){return new d({...this.#a,queryNode:l.L.cloneWithDistinctOn(this.#a.queryNode,(0,k.kU)(a))})}modifyFront(a){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}modifyEnd(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}distinct(){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.create("Distinct"))})}forUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}forShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForShare",a?(0,f._j)(a).map(i.M$):void 0))})}forKeyShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForKeyShare",a?(0,f._j)(a).map(i.M$):void 0))})}forNoKeyUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForNoKeyUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}skipLocked(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("SkipLocked"))})}noWait(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("NoWait"))})}selectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.J)(a))})}innerJoin(...a){return this.#b("InnerJoin",a)}leftJoin(...a){return this.#b("LeftJoin",a)}rightJoin(...a){return this.#b("RightJoin",a)}fullJoin(...a){return this.#b("FullJoin",a)}crossJoin(...a){return this.#b("CrossJoin",a)}innerJoinLateral(...a){return this.#b("LateralInnerJoin",a)}leftJoinLateral(...a){return this.#b("LateralLeftJoin",a)}crossJoinLateral(...a){return this.#b("LateralCrossJoin",a)}crossApply(...a){return this.#b("CrossApply",a)}outerApply(...a){return this.#b("OuterApply",a)}#b(a,b){return new d({...this.#a,queryNode:m.L.cloneWithJoin(this.#a.queryNode,(0,h.a)(a,b))})}orderBy(...a){return new d({...this.#a,queryNode:m.L.cloneWithOrderByItems(this.#a.queryNode,(0,n.xk)(a))})}groupBy(a){var b;return new d({...this.#a,queryNode:l.L.cloneWithGroupByItems(this.#a.queryNode,(b=a,b=(0,f.Tn)(b)?b((0,r.A)()):b,(0,k.kU)(b).map(q.create)))})}limit(a){return new d({...this.#a,queryNode:l.L.cloneWithLimit(this.#a.queryNode,o.a.create((0,z.$s)(a)))})}offset(a){return new d({...this.#a,queryNode:l.L.cloneWithOffset(this.#a.queryNode,p.create((0,z.$s)(a)))})}fetch(a,b="only"){return new d({...this.#a,queryNode:l.L.cloneWithFetch(this.#a.queryNode,function(a,b){var c;if(!(0,f.Et)(a)&&!(0,f.sI)(a))throw Error(`Invalid fetch row count: ${a}`);if("only"!==(c=b)&&"with ties"!==c)throw Error(`Invalid fetch modifier: ${b}`);return B.create(a,b)}(a,b))})}top(a,b){return new d({...this.#a,queryNode:m.L.cloneWithTop(this.#a.queryNode,(0,C.f)(a,b))})}union(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!1))})}unionAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!0))})}intersect(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!1))})}intersectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!0))})}except(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!1))})}exceptAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!0))})}as(a){return new F(this,a)}clearSelect(){return new d({...this.#a,queryNode:l.L.cloneWithoutSelections(this.#a.queryNode)})}clearWhere(){return new d({...this.#a,queryNode:m.L.cloneWithoutWhere(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:l.L.cloneWithoutLimit(this.#a.queryNode)})}clearOffset(){return new d({...this.#a,queryNode:l.L.cloneWithoutOffset(this.#a.queryNode)})}clearOrderBy(){return new d({...this.#a,queryNode:m.L.cloneWithoutOrderBy(this.#a.queryNode)})}clearGroupBy(){return new d({...this.#a,queryNode:l.L.cloneWithoutGroupBy(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}$asTuple(){return new y.Is(this.toOperationNode())}$asScalar(){return new y.Is(this.toOperationNode())}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(a){let b=this.compile();return(await this.#a.executor.executeQuery(b,a)).rows}async executeTakeFirst(a){let[b]=await this.execute(a);return b}async executeTakeFirstOrThrow(a){"function"==typeof a&&(a={errorConstructor:a});let b=await this.executeTakeFirst(a);if(void 0===b){let b=a?.errorConstructor??s.F;throw(0,s.x)(b)?new b(this.toOperationNode()):b(this.toOperationNode())}return b}async *stream(a){"object"!=typeof a&&(a={chunkSize:a});let b=this.compile();for await(let c of this.#a.executor.stream(b,a.chunkSize??100,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:m.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}function E(a){return new D(a)}d=D;class F{#at;#f;constructor(a,b){this.#at=a,this.#f=b}get expression(){return this.#at}get alias(){return this.#f}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return e.N.create(this.#at.toOperationNode(),t.O.create(this.#f))}}},60351:(a,b,c)=>{"use strict";c.d(b,{N:()=>e});var d=c(18110);function e(a){return(0,d.Gv)(a)&&(0,d.Tn)(a.toOperationNode)}},60525:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={getSortedRouteObjects:function(){return g},getSortedRoutes:function(){return f}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});class e{insert(a){this._insert(a.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(a="/"){let b=[...this.children.keys()].sort();null!==this.slugName&&b.splice(b.indexOf("[]"),1),null!==this.restSlugName&&b.splice(b.indexOf("[...]"),1),null!==this.optionalRestSlugName&&b.splice(b.indexOf("[[...]]"),1);let c=b.map(b=>this.children.get(b)._smoosh(`${a}${b}/`)).reduce((a,b)=>[...a,...b],[]);if(null!==this.slugName&&c.push(...this.children.get("[]")._smoosh(`${a}[${this.slugName}]/`)),!this.placeholder){let b="/"===a?"/":a.slice(0,-1);if(null!=this.optionalRestSlugName)throw Object.defineProperty(Error(`You cannot define a route with the same specificity as a optional catch-all route ("${b}" and "${b}[[...${this.optionalRestSlugName}]]").`),"__NEXT_ERROR_CODE",{value:"E458",enumerable:!1,configurable:!0});c.unshift(b)}return null!==this.restSlugName&&c.push(...this.children.get("[...]")._smoosh(`${a}[...${this.restSlugName}]/`)),null!==this.optionalRestSlugName&&c.push(...this.children.get("[[...]]")._smoosh(`${a}[[...${this.optionalRestSlugName}]]/`)),c}_insert(a,b,c){if(0===a.length){this.placeholder=!1;return}if(c)throw Object.defineProperty(Error("Catch-all must be the last part of the URL."),"__NEXT_ERROR_CODE",{value:"E392",enumerable:!1,configurable:!0});let d=a[0];if(d.startsWith("[")&&d.endsWith("]")){let e=d.slice(1,-1),g=!1;if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1),g=!0),e.startsWith("…"))throw Object.defineProperty(Error(`Detected a three-dot character ('…') at ('${e}'). Did you mean ('...')?`),"__NEXT_ERROR_CODE",{value:"E147",enumerable:!1,configurable:!0});if(e.startsWith("...")&&(e=e.substring(3),c=!0),e.startsWith("[")||e.endsWith("]"))throw Object.defineProperty(Error(`Segment names may not start or end with extra brackets ('${e}').`),"__NEXT_ERROR_CODE",{value:"E421",enumerable:!1,configurable:!0});if(e.startsWith("."))throw Object.defineProperty(Error(`Segment names may not start with erroneous periods ('${e}').`),"__NEXT_ERROR_CODE",{value:"E288",enumerable:!1,configurable:!0});function f(a,c){if(null!==a&&a!==c)throw Object.defineProperty(Error(`You cannot use different slug names for the same dynamic path ('${a}' !== '${c}').`),"__NEXT_ERROR_CODE",{value:"E337",enumerable:!1,configurable:!0});b.forEach(a=>{if(a===c)throw Object.defineProperty(Error(`You cannot have the same slug name "${c}" repeat within a single dynamic path`),"__NEXT_ERROR_CODE",{value:"E247",enumerable:!1,configurable:!0});if(a.replace(/\W/g,"")===d.replace(/\W/g,""))throw Object.defineProperty(Error(`You cannot have the slug names "${a}" and "${c}" differ only by non-word symbols within a single dynamic path`),"__NEXT_ERROR_CODE",{value:"E499",enumerable:!1,configurable:!0})}),b.push(c)}if(c)if(g){if(null!=this.restSlugName)throw Object.defineProperty(Error(`You cannot use both an required and optional catch-all route at the same level ("[...${this.restSlugName}]" and "${a[0]}" ).`),"__NEXT_ERROR_CODE",{value:"E299",enumerable:!1,configurable:!0});f(this.optionalRestSlugName,e),this.optionalRestSlugName=e,d="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Object.defineProperty(Error(`You cannot use both an optional and required catch-all route at the same level ("[[...${this.optionalRestSlugName}]]" and "${a[0]}").`),"__NEXT_ERROR_CODE",{value:"E300",enumerable:!1,configurable:!0});f(this.restSlugName,e),this.restSlugName=e,d="[...]"}else{if(g)throw Object.defineProperty(Error(`Optional route parameters are not yet supported ("${a[0]}").`),"__NEXT_ERROR_CODE",{value:"E435",enumerable:!1,configurable:!0});f(this.slugName,e),this.slugName=e,d="[]"}}this.children.has(d)||this.children.set(d,new e),this.children.get(d)._insert(a.slice(1),b,c)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}}function f(a){let b=new e;return a.forEach(a=>b.insert(a)),b.smoosh()}function g(a,b){let c={},d=[];for(let e=0;e<a.length;e++){let f=b(a[e]);c[f]=e,d[e]=f}return f(d).map(b=>a[c[b]])}},60812:(a,b,c)=>{"use strict";c.d(b,{N:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"FromNode"===a.kind,create:a=>(0,d.CN)({kind:"FromNode",froms:(0,d.CN)(a)}),cloneWithFroms:(a,b)=>(0,d.CN)({...a,froms:(0,d.CN)([...a.froms,...b])})})},61259:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={fromNodeOutgoingHttpHeaders:function(){return g},normalizeNextQueryParam:function(){return k},splitCookiesString:function(){return h},toNodeOutgoingHttpHeaders:function(){return i},validateURL:function(){return j}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(52730);function g(a){let b=new Headers;for(let[c,d]of Object.entries(a))for(let a of Array.isArray(d)?d:[d])void 0!==a&&("number"==typeof a&&(a=a.toString()),b.append(c,a));return b}function h(a){var b,c,d,e,f,g=[],h=0;function i(){for(;h<a.length&&/\s/.test(a.charAt(h));)h+=1;return h<a.length}for(;h<a.length;){for(b=h,f=!1;i();)if(","===(c=a.charAt(h))){for(d=h,h+=1,i(),e=h;h<a.length&&"="!==(c=a.charAt(h))&&";"!==c&&","!==c;)h+=1;h<a.length&&"="===a.charAt(h)?(f=!0,h=e,g.push(a.substring(b,d)),b=h):h=d+1}else h+=1;(!f||h>=a.length)&&g.push(a.substring(b,a.length))}return g}function i(a){let b={},c=[];if(a)for(let[d,e]of a.entries())"set-cookie"===d.toLowerCase()?(c.push(...h(e)),b[d]=1===c.length?c[0]:c):b[d]=e;return b}function j(a){try{return String(new URL(String(a)))}catch(b){throw Object.defineProperty(Error(`URL is malformed "${String(a)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:b}),"__NEXT_ERROR_CODE",{value:"E61",enumerable:!1,configurable:!0})}}function k(a){for(let b of[f.NEXT_QUERY_PARAM_PREFIX,f.NEXT_INTERCEPTION_MARKER_PREFIX])if(a!==b&&a.startsWith(b))return a.substring(b.length);return null}},61359:(a,b,c)=>{"use strict";c.d(b,{Hl:()=>k,JJ:()=>h,gx:()=>l,u8:()=>f,wp:()=>j,x:()=>i});var d=c(79362),e=c(18110);function f(a="ignore query",b,c){if("ignore query"!==a){if("cancel query"===a){let c=b.cancelQuery;return c||g(a,b.killSession?"kill session":void 0),c.bind(b)}if("kill session"===a){let c=b.killSession;return c||g(a,b.cancelQuery?"cancel query":void 0),c.bind(b)}throw c(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${a}"`)}}function g(a,b){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${a}". Use "ignore query"${b?` or "${b}"`:""} instead.`)}function h(a,b,c){a?.aborted&&(c?.(),i(a.reason,b))}function i(a,b){var c,d;throw c=a,d=b,null===c||"object"!=typeof c||Object.isFrozen(c)||Object.defineProperty(c,"__kysely_timing__",{configurable:!0,enumerable:!1,value:d,writable:!1}),a}let j={};async function k(a,b,c,e){if(!b)return a;h(b,`before ${c}`,e);let{promise:f,resolve:g}=new d.c,k=()=>g(j);b.addEventListener("abort",k);try{h(b,`before ${c}`,e);let d=await Promise.race([a,f]);if(d!==j)return d;e?.(),i(b.reason,`during ${c}`)}finally{b.removeEventListener("abort",k),g(j)}}function l(a){return b=>console.error(`\`${a}\` failed in the background after abortion: ${(0,e.I4)(b)}`)}},61634:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"normalizeLocalePath",{enumerable:!0,get:function(){return d}});let c=new WeakMap;function d(a,b){let d;if(!b)return{pathname:a};let e=c.get(b);e||(e=b.map(a=>a.toLowerCase()),c.set(b,e));let f=a.split("/",2);if(!f[1])return{pathname:a};let g=f[1].toLowerCase(),h=e.indexOf(g);return h<0?{pathname:a}:(d=b[h],{pathname:a=a.slice(d.length+1)||"/",detectedLocale:d})}},61793:(a,b,c)=>{"use strict";c.d(b,{LG:()=>i,Ri:()=>h,xH:()=>g,yI:()=>f});let d={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var e=class extends Error{constructor(a="INTERNAL_SERVER_ERROR",b,c={},e="number"==typeof a?a:d[a]){super(b?.message,b?.cause?{cause:b.cause}:void 0),this.status=a,this.body=b,this.headers=c,this.statusCode=e,this.name="APIError",this.status=a,this.headers=c,this.statusCode=e,this.body=b}},f=class extends e{constructor(a,b){super(400,{message:a,code:"VALIDATION_ERROR"}),this.message=a,this.issues=b,this.issues=b}},g=class extends Error{constructor(a){super(a),this.name="BetterCallError"}};let h=Symbol.for("better-call:api-error-headers"),i=function(a,b){class c extends a{#au;constructor(...a){if(function(){let a=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return void 0===a?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(a,"writable")?a.writable:void 0!==a.set}()){const b=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...a),Error.stackTraceLimit=b}else super(...a);const b=Error().stack;b&&(this.#au=function(a){let b=a.split("\n at ");return b.length<=1?a:(b.splice(1,1),b.join("\n at "))}(b.replace(/^Error/,this.name)))}get errorStack(){return this.#au}}return Object.defineProperty(c.prototype,"constructor",{get:()=>b,enumerable:!1,configurable:!0}),c}(e,Error)},62030:(a,b,c)=>{"use strict";c.d(b,{f:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"UsingNode"===a.kind,create:a=>(0,d.CN)({kind:"UsingNode",tables:(0,d.CN)(a)}),cloneWithTables:(a,b)=>(0,d.CN)({...a,tables:(0,d.CN)([...a.tables,...b])})})},62547:(a,b,c)=>{"use strict";c.d(b,{G:()=>e});var d=c(9853);let e=({usePlural:a,schema:b})=>c=>{if(a&&"s"===c.charAt(c.length-1)){let a=c.slice(0,-1),d=b[a]?a:void 0;if(d||(d=Object.entries(b).find(([b,c])=>c.modelName===a)?.[0]),d)return d}let e=b[c]?c:void 0;if(e||(e=Object.entries(b).find(([a,b])=>b.modelName===c)?.[0]),!e)throw new d.$l(`Model "${c}" not found in schema`);return e}},63574:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"ReflectAdapter",{enumerable:!0,get:function(){return c}});class c{static get(a,b,c){let d=Reflect.get(a,b,c);return"function"==typeof d?d.bind(a):d}static set(a,b,c,d){return Reflect.set(a,b,c,d)}static has(a,b){return Reflect.has(a,b)}static deleteProperty(a,b){return Reflect.deleteProperty(a,b)}}},64561:(a,b,c)=>{"use strict";c.d(b,{DR:()=>g,OR:()=>f,Xu:()=>e,qU:()=>d});let d="db.collection.name",e="db.operation.name",f="http.response.status_code",g="http.route"},64829:(a,b,c)=>{"use strict";c.d(b,{a:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"LimitNode"===a.kind,create:a=>(0,d.CN)({kind:"LimitNode",limit:a})})},65211:(a,b,c)=>{"use strict";Object.defineProperty(b,"b",{enumerable:!0,get:function(){return m}});let d=c(19523),e=c(29294),f=c(63033),g=c(4190),h=c(27130),i=c(87143),j=c(55713),k=c(13370),l=c(85556);function m(){let a="headers",b=e.workAsyncStorage.getStore(),c=f.workUnitAsyncStorage.getStore();if(b){if(c&&"after"===c.phase&&!(0,k.isRequestAPICallableInsideAfter)())throw Object.defineProperty(Error(`Route ${b.route} used \`headers()\` inside \`after()\`. This is not supported. If you need this data inside an \`after()\` callback, use \`headers()\` outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after`),"__NEXT_ERROR_CODE",{value:"E839",enumerable:!1,configurable:!0});if(b.forceStatic)return o(d.HeadersAdapter.seal(new Headers({})));if(c)switch(c.type){case"cache":{let a=Object.defineProperty(Error(`Route ${b.route} used \`headers()\` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`headers()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E833",enumerable:!1,configurable:!0});throw Error.captureStackTrace(a,m),b.invalidDynamicUsageError??=a,a}case"unstable-cache":throw Object.defineProperty(Error(`Route ${b.route} used \`headers()\` inside a function cached with \`unstable_cache()\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`headers()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`),"__NEXT_ERROR_CODE",{value:"E838",enumerable:!1,configurable:!0});case"generate-static-params":throw Object.defineProperty(Error(`Route ${b.route} used \`headers()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`),"__NEXT_ERROR_CODE",{value:"E1134",enumerable:!1,configurable:!0})}if(b.dynamicShouldError)throw Object.defineProperty(new h.StaticGenBailoutError(`Route ${b.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E828",enumerable:!1,configurable:!0});if(c)switch(c.type){case"prerender":var j=b,p=c;let e=n.get(p);if(e)return e;let q=(0,i.makeHangingPromise)(p.renderSignal,j.route,"`headers()`");return n.set(p,q),q;case"prerender-client":case"validation-client":let r="`headers`";throw Object.defineProperty(new l.InvariantError(`${r} must not be used within a client component. Next.js should be preventing ${r} from being included in client components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E1017",enumerable:!1,configurable:!0});case"prerender-ppr":return(0,g.postponeWithTracking)(b.route,a,c.dynamicTracking);case"prerender-legacy":return(0,g.throwToInterruptStaticGeneration)(a,b,c);case"prerender-runtime":return(0,i.delayUntilRuntimeStage)(c,o(c.headers));case"private-cache":return o(c.headers);case"request":if((0,g.trackDynamicDataInDynamicRender)(c),c.asyncApiPromises)return(0,f.isInEarlyRenderStage)(c)?c.asyncApiPromises.earlyHeaders:c.asyncApiPromises.headers;return o(c.headers)}}(0,f.throwForMissingRequestStore)(a)}c(94931);let n=new WeakMap;function o(a){let b=n.get(a);if(b)return b;let c=Promise.resolve(a);return n.set(a,c),c}(0,j.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`headers()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E836",enumerable:!1,configurable:!0})})},65661:(a,b)=>{"use strict";function c(a,b){let c;if(b?.host&&!Array.isArray(b.host))c=b.host.toString().split(":",1)[0];else{if(!a.hostname)return;c=a.hostname}return c.toLowerCase()}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"getHostname",{enumerable:!0,get:function(){return c}})},65840:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"INSTANT_VALIDATION_BOUNDARY_NAME",{enumerable:!0,get:function(){return c}});let c="__next_instant_validation_boundary__"},65928:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c,d={bgBlack:function(){return C},bgBlue:function(){return G},bgCyan:function(){return I},bgGreen:function(){return E},bgMagenta:function(){return H},bgRed:function(){return D},bgWhite:function(){return J},bgYellow:function(){return F},black:function(){return s},blue:function(){return w},bold:function(){return l},cyan:function(){return z},dim:function(){return m},gray:function(){return B},green:function(){return u},hidden:function(){return q},inverse:function(){return p},italic:function(){return n},magenta:function(){return x},purple:function(){return y},red:function(){return t},reset:function(){return k},strikethrough:function(){return r},underline:function(){return o},white:function(){return A},yellow:function(){return v}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let{env:f,stdout:g}=(null==(c=globalThis)?void 0:c.process)??{},h=f&&!f.NO_COLOR&&(f.FORCE_COLOR||(null==g?void 0:g.isTTY)&&!f.CI&&"dumb"!==f.TERM),i=(a,b,c,d)=>{let e=a.substring(0,d)+c,f=a.substring(d+b.length),g=f.indexOf(b);return~g?e+i(f,b,c,g):e+f},j=(a,b,c=a)=>h?d=>{let e=""+d,f=e.indexOf(b,a.length);return~f?a+i(e,b,c,f)+b:a+e+b}:String,k=h?a=>`\x1b[0m${a}\x1b[0m`:String,l=j("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),m=j("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),n=j("\x1b[3m","\x1b[23m"),o=j("\x1b[4m","\x1b[24m"),p=j("\x1b[7m","\x1b[27m"),q=j("\x1b[8m","\x1b[28m"),r=j("\x1b[9m","\x1b[29m"),s=j("\x1b[30m","\x1b[39m"),t=j("\x1b[31m","\x1b[39m"),u=j("\x1b[32m","\x1b[39m"),v=j("\x1b[33m","\x1b[39m"),w=j("\x1b[34m","\x1b[39m"),x=j("\x1b[35m","\x1b[39m"),y=j("\x1b[38;2;173;127;168m","\x1b[39m"),z=j("\x1b[36m","\x1b[39m"),A=j("\x1b[37m","\x1b[39m"),B=j("\x1b[90m","\x1b[39m"),C=j("\x1b[40m","\x1b[49m"),D=j("\x1b[41m","\x1b[49m"),E=j("\x1b[42m","\x1b[49m"),F=j("\x1b[43m","\x1b[49m"),G=j("\x1b[44m","\x1b[49m"),H=j("\x1b[45m","\x1b[49m"),I=j("\x1b[46m","\x1b[49m"),J=j("\x1b[47m","\x1b[49m")},66351:(a,b,c)=>{"use strict";c.d(b,{j:()=>e});var d=c(62547);let e=({usePlural:a,schema:b})=>{let c=(0,d.G)({schema:b,usePlural:a});return d=>{let e=c(d);return b&&b[e]&&b[e].modelName!==d?a?`${b[e].modelName}s`:b[e].modelName:a?`${d}s`:d}}},66554:(a,b)=>{"use strict";function c(a){return a.replace(/\/$/,"")||"/"}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"removeTrailingSlash",{enumerable:!0,get:function(){return c}})},67017:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"DetachedPromise",{enumerable:!0,get:function(){return c}});class c{constructor(){let a,b;this.promise=new Promise((c,d)=>{a=c,b=d}),this.resolve=a,this.reject=b}}},67103:(a,b,c)=>{"use strict";function d(){throw Object.defineProperty(Error("`cacheTag()` is only available with the `cacheComponents` config."),"__NEXT_ERROR_CODE",{value:"E886",enumerable:!1,configurable:!0})}Object.defineProperty(b,"z",{enumerable:!0,get:function(){return d}}),c(63033),c(84698)},67107:(a,b,c)=>{"use strict";let d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M;c.d(b,{reconcileOnBoot:()=>tv});var N,O,P,Q,R,S,T,U,V,W={};c.r(W),c.d(W,{account:()=>dp,activity:()=>d0,agent:()=>du,agentSkill:()=>dx,backlogItem:()=>d1,blockProposal:()=>d8,budget:()=>dM,channelRead:()=>dL,chatSession:()=>dP,costEntry:()=>dN,cronJob:()=>dW,cronRun:()=>dX,decision:()=>dT,deployRun:()=>dR,docIndex:()=>d3,event:()=>dQ,file:()=>dU,fileLock:()=>d5,finding:()=>dY,goal:()=>dC,goalFile:()=>dD,inboxItem:()=>dZ,issue:()=>dH,kbEntry:()=>d4,kbQueryLog:()=>d6,localModel:()=>dB,member:()=>ds,message:()=>dO,messageSummary:()=>dS,notification:()=>dK,notificationPref:()=>d9,organization:()=>dr,passkey:()=>ec,personalAccessToken:()=>ea,plan:()=>dI,plugin:()=>d$,provider:()=>dy,providerModel:()=>dA,pulse:()=>dv,ragChunk:()=>d2,report:()=>dJ,routine:()=>dV,session:()=>dn,skill:()=>dw,spec:()=>dG,syncedBlock:()=>d7,task:()=>dE,taskStep:()=>dF,testRun:()=>d_,twoFactor:()=>eb,user:()=>dm,vault:()=>dz,verification:()=>dq,workspace:()=>dt});let X=Symbol.for("drizzle:entityKind");function Y(a,b){if(!a||"object"!=typeof a)return!1;if(a instanceof b)return!0;if(!Object.prototype.hasOwnProperty.call(b,X))throw Error(`Class "${b.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let c=Object.getPrototypeOf(a).constructor;if(c)for(;c;){if(X in c&&c[X]===b[X])return!0;c=Object.getPrototypeOf(c)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class Z{constructor(a,b){this.table=a,this.config=b,this.name=b.name,this.keyAsName=b.keyAsName,this.notNull=b.notNull,this.default=b.default,this.defaultFn=b.defaultFn,this.onUpdateFn=b.onUpdateFn,this.hasDefault=b.hasDefault,this.primary=b.primaryKey,this.isUnique=b.isUnique,this.uniqueName=b.uniqueName,this.uniqueType=b.uniqueType,this.dataType=b.dataType,this.columnType=b.columnType,this.generated=b.generated,this.generatedIdentity=b.generatedIdentity}static [X]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(a){return a}mapToDriverValue(a){return a}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}let $=Symbol.for("drizzle:Name"),_=Symbol.for("drizzle:Schema"),aa=Symbol.for("drizzle:Columns"),ab=Symbol.for("drizzle:ExtraConfigColumns"),ac=Symbol.for("drizzle:OriginalName"),ad=Symbol.for("drizzle:BaseName"),ae=Symbol.for("drizzle:IsAlias"),af=Symbol.for("drizzle:ExtraConfigBuilder"),ag=Symbol.for("drizzle:IsDrizzleTable");class ah{static [X]="Table";static Symbol={Name:$,Schema:_,OriginalName:ac,Columns:aa,ExtraConfigColumns:ab,BaseName:ad,IsAlias:ae,ExtraConfigBuilder:af};[$];[ac];[_];[aa];[ab];[ad];[ae]=!1;[ag]=!0;[af]=void 0;constructor(a,b,c){this[$]=this[ac]=a,this[_]=b,this[ad]=c}}function ai(a){return`${a[_]??"public"}.${a[$]}`}class aj{static [X]="ColumnBuilder";config;constructor(a,b,c){this.config={name:a,keyAsName:""===a,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:b,columnType:c,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(a){return this.config.default=a,this.config.hasDefault=!0,this}$defaultFn(a){return this.config.defaultFn=a,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(a){return this.config.onUpdateFn=a,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(a){""===this.config.name&&(this.config.name=a)}}class ak{static [X]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(a,b){this.reference=()=>{let{name:b,columns:c,foreignColumns:d}=a();return{name:b,columns:c,foreignTable:d[0].table,foreignColumns:d}},b&&(this._onUpdate=b.onUpdate,this._onDelete=b.onDelete)}onUpdate(a){return this._onUpdate=void 0===a?"no action":a,this}onDelete(a){return this._onDelete=void 0===a?"no action":a,this}build(a){return new al(a,this)}}class al{constructor(a,b){this.table=a,this.reference=b.reference,this.onUpdate=b._onUpdate,this.onDelete=b._onDelete}static [X]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:a,columns:b,foreignColumns:c}=this.reference(),d=b.map(a=>a.name),e=c.map(a=>a.name),f=[this.table[$],...d,c[0].table[$],...e];return a??`${f.join("_")}_fk`}}function am(a,...b){return a(...b)}function an(a,b){return`${a[$]}_${b.join("_")}_unique`}class ao{constructor(a,b){this.name=b,this.columns=a}static [X]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(a){return new aq(a,this.columns,this.nullsNotDistinctConfig,this.name)}}class ap{static [X]=null;name;constructor(a){this.name=a}on(...a){return new ao(a,this.name)}}class aq{constructor(a,b,c,d){this.table=a,this.columns=b,this.name=d??an(this.table,this.columns.map(a=>a.name)),this.nullsNotDistinct=c}static [X]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function ar(a,b,c){for(let d=b;d<a.length;d++){let e=a[d];if("\\"===e){d++;continue}if('"'===e)return[a.slice(b,d).replace(/\\/g,""),d+1];if(!c&&(","===e||"}"===e))return[a.slice(b,d).replace(/\\/g,""),d]}return[a.slice(b).replace(/\\/g,""),a.length]}class as extends aj{foreignKeyConfigs=[];static [X]="PgColumnBuilder";array(a){return new aw(this.config.name,this,a)}references(a,b={}){return this.foreignKeyConfigs.push({ref:a,actions:b}),this}unique(a,b){return this.config.isUnique=!0,this.config.uniqueName=a,this.config.uniqueType=b?.nulls,this}generatedAlwaysAs(a){return this.config.generated={as:a,type:"always",mode:"stored"},this}buildForeignKeys(a,b){return this.foreignKeyConfigs.map(({ref:c,actions:d})=>am((c,d)=>{let e=new ak(()=>({columns:[a],foreignColumns:[c()]}));return d.onUpdate&&e.onUpdate(d.onUpdate),d.onDelete&&e.onDelete(d.onDelete),e.build(b)},c,d))}buildExtraConfigColumn(a){return new au(a,this.config)}}class at extends Z{constructor(a,b){b.uniqueName||(b.uniqueName=an(a,[b.name])),super(a,b),this.table=a}static [X]="PgColumn"}class au extends at{static [X]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(a){return this.indexConfig.opClass=a,this}}class av{static [X]=null;constructor(a,b,c,d){this.name=a,this.keyAsName=b,this.type=c,this.indexConfig=d}name;keyAsName;type;indexConfig}class aw extends as{static [X]="PgArrayBuilder";constructor(a,b,c){super(a,"array","PgArray"),this.config.baseBuilder=b,this.config.size=c}build(a){let b=this.config.baseBuilder.build(a);return new ax(a,this.config,b)}}class ax extends at{constructor(a,b,c,d){super(a,b),this.baseColumn=c,this.range=d,this.size=b.size}size;static [X]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(a){return"string"==typeof a&&(a=function(a){let[b]=function a(b,c=0){let d=[],e=c,f=!1;for(;e<b.length;){let g=b[e];if(","===g){(f||e===c)&&d.push(""),f=!0,e++;continue}if(f=!1,"\\"===g){e+=2;continue}if('"'===g){let[a,c]=ar(b,e+1,!0);d.push(a),e=c;continue}if("}"===g)return[d,e+1];if("{"===g){let[c,f]=a(b,e+1);d.push(c),e=f;continue}let[h,i]=ar(b,e,!1);d.push(h),e=i}return[d,e]}(a,1);return b}(a)),a.map(a=>this.baseColumn.mapFromDriverValue(a))}mapToDriverValue(a,b=!1){let c=a.map(a=>null===a?null:Y(this.baseColumn,ax)?this.baseColumn.mapToDriverValue(a,!0):this.baseColumn.mapToDriverValue(a));return b?c:function a(b){return`{${b.map(b=>Array.isArray(b)?a(b):"string"==typeof b?`"${b.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${b}`).join(",")}}`}(c)}}class ay extends as{static [X]="PgEnumObjectColumnBuilder";constructor(a,b){super(a,"string","PgEnumObjectColumn"),this.config.enum=b}build(a){return new az(a,this.config)}}class az extends at{static [X]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}let aA=Symbol.for("drizzle:isPgEnum");class aB extends as{static [X]="PgEnumColumnBuilder";constructor(a,b){super(a,"string","PgEnumColumn"),this.config.enum=b}build(a){return new aC(a,this.config)}}class aC extends at{static [X]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}class aD{static [X]="Subquery";constructor(a,b,c,d=!1,e=[]){this._={brand:"Subquery",sql:a,selectedFields:b,alias:c,isWith:d,usedTables:e}}}class aE extends aD{static [X]="WithSubquery"}let aF=(a,b)=>d?(e||(e=d.trace.getTracer("drizzle-orm","0.45.2")),am((c,d)=>d.startActiveSpan(a,a=>{try{return b(a)}catch(b){throw a.setStatus({code:c.SpanStatusCode.ERROR,message:b instanceof Error?b.message:"Unknown error"}),b}finally{a.end()}}),d,e)):b(),aG=Symbol.for("drizzle:ViewBaseConfig");class aH{static [X]=null}function aI(a){return null!=a&&"function"==typeof a.getSQL}class aJ{static [X]="StringChunk";value;constructor(a){this.value=Array.isArray(a)?a:[a]}getSQL(){return new aK([this])}}class aK{constructor(a){for(const b of(this.queryChunks=a,a))if(Y(b,ah)){const a=b[ah.Symbol.Schema];this.usedTables.push(void 0===a?b[ah.Symbol.Name]:a+"."+b[ah.Symbol.Name])}}static [X]="SQL";decoder=aM;shouldInlineParams=!1;usedTables=[];append(a){return this.queryChunks.push(...a.queryChunks),this}toQuery(a){return aF("drizzle.buildSQL",b=>{let c=this.buildQueryFromSourceParams(this.queryChunks,a);return b?.setAttributes({"drizzle.query.text":c.sql,"drizzle.query.params":JSON.stringify(c.params)}),c})}buildQueryFromSourceParams(a,b){let c=Object.assign({},b,{inlineParams:b.inlineParams||this.shouldInlineParams,paramStartIndex:b.paramStartIndex||{value:0}}),{casing:d,escapeName:e,escapeParam:f,prepareTyping:g,inlineParams:h,paramStartIndex:i}=c;var j=a.map(a=>{if(Y(a,aJ))return{sql:a.value.join(""),params:[]};if(Y(a,aL))return{sql:e(a.value),params:[]};if(void 0===a)return{sql:"",params:[]};if(Array.isArray(a)){let b=[new aJ("(")];for(let[c,d]of a.entries())b.push(d),c<a.length-1&&b.push(new aJ(", "));return b.push(new aJ(")")),this.buildQueryFromSourceParams(b,c)}if(Y(a,aK))return this.buildQueryFromSourceParams(a.queryChunks,{...c,inlineParams:h||a.shouldInlineParams});if(Y(a,ah)){let b=a[ah.Symbol.Schema],c=a[ah.Symbol.Name];return{sql:void 0===b||a[ae]?e(c):e(b)+"."+e(c),params:[]}}if(Y(a,Z)){let c=d.getColumnCasing(a);if("indexes"===b.invokeSource)return{sql:e(c),params:[]};let f=a.table[ah.Symbol.Schema];return{sql:a.table[ae]||void 0===f?e(a.table[ah.Symbol.Name])+"."+e(c):e(f)+"."+e(a.table[ah.Symbol.Name])+"."+e(c),params:[]}}if(Y(a,aV)){let b=a[aG].schema,c=a[aG].name;return{sql:void 0===b||a[aG].isAlias?e(c):e(b)+"."+e(c),params:[]}}if(Y(a,aO)){if(Y(a.value,aS))return{sql:f(i.value++,a),params:[a],typings:["none"]};let b=null===a.value?null:a.encoder.mapToDriverValue(a.value);if(Y(b,aK))return this.buildQueryFromSourceParams([b],c);if(h)return{sql:this.mapInlineParam(b,c),params:[]};let d=["none"];return g&&(d=[g(a.encoder)]),{sql:f(i.value++,b),params:[b],typings:d}}return Y(a,aS)?{sql:f(i.value++,a),params:[a],typings:["none"]}:Y(a,aK.Aliased)&&void 0!==a.fieldAlias?{sql:e(a.fieldAlias),params:[]}:Y(a,aD)?a._.isWith?{sql:e(a._.alias),params:[]}:this.buildQueryFromSourceParams([new aJ("("),a._.sql,new aJ(") "),new aL(a._.alias)],c):a&&"function"==typeof a&&aA in a&&!0===a[aA]?a.schema?{sql:e(a.schema)+"."+e(a.enumName),params:[]}:{sql:e(a.enumName),params:[]}:aI(a)?a.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([a.getSQL()],c):this.buildQueryFromSourceParams([new aJ("("),a.getSQL(),new aJ(")")],c):h?{sql:this.mapInlineParam(a,c),params:[]}:{sql:f(i.value++,a),params:[a],typings:["none"]}});let k={sql:"",params:[]};for(let a of j)k.sql+=a.sql,k.params.push(...a.params),a.typings?.length&&(k.typings||(k.typings=[]),k.typings.push(...a.typings));return k}mapInlineParam(a,{escapeString:b}){if(null===a)return"null";if("number"==typeof a||"boolean"==typeof a)return a.toString();if("string"==typeof a)return b(a);if("object"==typeof a){let c=a.toString();return"[object Object]"===c?b(JSON.stringify(a)):b(c)}throw Error("Unexpected param value: "+a)}getSQL(){return this}as(a){return void 0===a?this:new aK.Aliased(this,a)}mapWith(a){return this.decoder="function"==typeof a?{mapFromDriverValue:a}:a,this}inlineParams(){return this.shouldInlineParams=!0,this}if(a){return a?this:void 0}}class aL{constructor(a){this.value=a}static [X]="Name";brand;getSQL(){return new aK([this])}}let aM={mapFromDriverValue:a=>a},aN={mapToDriverValue:a=>a};({...aM,...aN});class aO{constructor(a,b=aN){this.value=a,this.encoder=b}static [X]="Param";brand;getSQL(){return new aK([this])}}function aP(a,...b){let c=[];for(let[d,e]of((b.length>0||a.length>0&&""!==a[0])&&c.push(new aJ(a[0])),b.entries()))c.push(e,new aJ(a[d+1]));return new aK(c)}(N=aP||(aP={})).empty=function(){return new aK([])},N.fromList=function(a){return new aK(a)},N.raw=function(a){return new aK([new aJ(a)])},N.join=function(a,b){let c=[];for(let[d,e]of a.entries())d>0&&void 0!==b&&c.push(b),c.push(e);return new aK(c)},N.identifier=function(a){return new aL(a)},N.placeholder=function(a){return new aS(a)},N.param=function(a,b){return new aO(a,b)};var aQ=aK||(aK={});class aR{constructor(a,b){this.sql=a,this.fieldAlias=b}static [X]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new aR(this.sql,this.fieldAlias)}}aQ.Aliased=aR;class aS{constructor(a){this.name=a}static [X]="Placeholder";getSQL(){return new aK([this])}}function aT(a,b){return a.map(a=>{if(Y(a,aS)){if(!(a.name in b))throw Error(`No value for placeholder "${a.name}" was provided`);return b[a.name]}if(Y(a,aO)&&Y(a.value,aS)){if(!(a.value.name in b))throw Error(`No value for placeholder "${a.value.name}" was provided`);return a.encoder.mapToDriverValue(b[a.value.name])}return a})}let aU=Symbol.for("drizzle:IsDrizzleView");class aV{static [X]="View";[aG];[aU]=!0;constructor({name:a,schema:b,selectedFields:c,query:d}){this[aG]={name:a,originalName:a,schema:b,selectedFields:c,query:d,isExisting:!d,isAlias:!1}}getSQL(){return new aK([this])}}function aW(a,b){return"object"!=typeof b||null===b||!("mapToDriverValue"in b)||"function"!=typeof b.mapToDriverValue||aI(a)||Y(a,aO)||Y(a,aS)||Y(a,Z)||Y(a,ah)||Y(a,aV)?a:new aO(a,b)}Z.prototype.getSQL=function(){return new aK([this])},ah.prototype.getSQL=function(){return new aK([this])},aD.prototype.getSQL=function(){return new aK([this])};let aX=(a,b)=>aP`${a} = ${aW(b,a)}`,aY=(a,b)=>aP`${a} <> ${aW(b,a)}`;function aZ(...a){let b=a.filter(a=>void 0!==a);if(0!==b.length)return new aK(1===b.length?b:[new aJ("("),aP.join(b,new aJ(" and ")),new aJ(")")])}function a$(...a){let b=a.filter(a=>void 0!==a);if(0!==b.length)return new aK(1===b.length?b:[new aJ("("),aP.join(b,new aJ(" or ")),new aJ(")")])}function a_(a){return aP`not ${a}`}let a0=(a,b)=>aP`${a} > ${aW(b,a)}`,a1=(a,b)=>aP`${a} >= ${aW(b,a)}`,a2=(a,b)=>aP`${a} < ${aW(b,a)}`,a3=(a,b)=>aP`${a} <= ${aW(b,a)}`;function a4(a,b){return Array.isArray(b)?0===b.length?aP`false`:aP`${a} in ${b.map(b=>aW(b,a))}`:aP`${a} in ${aW(b,a)}`}function a5(a,b){return Array.isArray(b)?0===b.length?aP`true`:aP`${a} not in ${b.map(b=>aW(b,a))}`:aP`${a} not in ${aW(b,a)}`}function a6(a){return aP`${a} is null`}function a7(a){return aP`${a} is not null`}function a8(a){return aP`exists ${a}`}function a9(a){return aP`not exists ${a}`}function ba(a,b,c){return aP`${a} between ${aW(b,a)} and ${aW(c,a)}`}function bb(a,b,c){return aP`${a} not between ${aW(b,a)} and ${aW(c,a)}`}function bc(a,b){return aP`${a} like ${b}`}function bd(a,b){return aP`${a} not like ${b}`}function be(a,b){return aP`${a} ilike ${b}`}function bf(a,b){return aP`${a} not ilike ${b}`}var bg=c(87550),bh=c.n(bg);class bi{static [X]="ConsoleLogWriter";write(a){console.log(a)}}class bj{static [X]="DefaultLogger";writer;constructor(a){this.writer=a?.writer??new bi}logQuery(a,b){let c=b.map(a=>{try{return JSON.stringify(a)}catch{return String(a)}}),d=c.length?` -- params: [${c.join(", ")}]`:"";this.writer.write(`Query: ${a}${d}`)}}class bk{static [X]="NoopLogger";logQuery(){}}let bl=Symbol.for("drizzle:PgInlineForeignKeys"),bm=Symbol.for("drizzle:EnableRLS");class bn extends ah{static [X]="PgTable";static Symbol=Object.assign({},ah.Symbol,{InlineForeignKeys:bl,EnableRLS:bm});[bl]=[];[bm]=!1;[ah.Symbol.ExtraConfigBuilder]=void 0;[ah.Symbol.ExtraConfigColumns]={}}class bo{static [X]="PgPrimaryKeyBuilder";columns;name;constructor(a,b){this.columns=a,this.name=b}build(a){return new bp(a,this.columns,this.name)}}class bp{constructor(a,b,c){this.table=a,this.columns=b,this.name=c}static [X]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[bn.Symbol.Name]}_${this.columns.map(a=>a.name).join("_")}_pk`}}function bq(a){return aP`${a} asc`}function br(a){return aP`${a} desc`}class bs{constructor(a,b,c){this.sourceTable=a,this.referencedTable=b,this.relationName=c,this.referencedTableName=b[ah.Symbol.Name]}static [X]="Relation";referencedTableName;fieldName}class bt{constructor(a,b){this.table=a,this.config=b}static [X]="Relations"}class bu extends bs{constructor(a,b,c,d){super(a,b,c?.relationName),this.config=c,this.isNullable=d}static [X]="One";withFieldName(a){let b=new bu(this.sourceTable,this.referencedTable,this.config,this.isNullable);return b.fieldName=a,b}}class bv extends bs{constructor(a,b,c){super(a,b,c?.relationName),this.config=c}static [X]="Many";withFieldName(a){let b=new bv(this.sourceTable,this.referencedTable,this.config);return b.fieldName=a,b}}function bw(a){return{one:function(b,c){return new bu(a,b,c,c?.fields.reduce((a,b)=>a&&b.notNull,!0)??!1)},many:function(b,c){return new bv(a,b,c)}}}class bx{constructor(a){this.table=a}static [X]="ColumnAliasProxyHandler";get(a,b){return"table"===b?this.table:a[b]}}class by{constructor(a,b){this.alias=a,this.replaceOriginalName=b}static [X]="TableAliasProxyHandler";get(a,b){if(b===ah.Symbol.IsAlias)return!0;if(b===ah.Symbol.Name||this.replaceOriginalName&&b===ah.Symbol.OriginalName)return this.alias;if(b===aG)return{...a[aG],name:this.alias,isAlias:!0};if(b===ah.Symbol.Columns){let b=a[ah.Symbol.Columns];if(!b)return b;let c={};return Object.keys(b).map(d=>{c[d]=new Proxy(b[d],new bx(new Proxy(a,this)))}),c}let c=a[b];return Y(c,Z)?new Proxy(c,new bx(new Proxy(a,this))):c}}class bz{constructor(a){this.alias=a}static [X]=null;get(a,b){return"sourceTable"===b?bA(a.sourceTable,this.alias):a[b]}}function bA(a,b){return new Proxy(a,new by(b,!1))}function bB(a,b){return new Proxy(a,new bx(new Proxy(a.table,new by(b,!1))))}function bC(a,b){return new aK.Aliased(bD(a.sql,b),a.fieldAlias)}function bD(a,b){return aP.join(a.queryChunks.map(a=>Y(a,Z)?bB(a,b):Y(a,aK)?bD(a,b):Y(a,aK.Aliased)?bC(a,b):a))}class bE{static [X]="SelectionProxyHandler";config;constructor(a){this.config={...a}}get(a,b){if("_"===b)return{...a._,selectedFields:new Proxy(a._.selectedFields,this)};if(b===aG)return{...a[aG],selectedFields:new Proxy(a[aG].selectedFields,this)};if("symbol"==typeof b)return a[b];let c=(Y(a,aD)?a._.selectedFields:Y(a,aV)?a[aG].selectedFields:a)[b];if(Y(c,aK.Aliased)){if("sql"===this.config.sqlAliasedBehavior&&!c.isSelectionField)return c.sql;let a=c.clone();return a.isSelectionField=!0,a}if(Y(c,aK)){if("sql"===this.config.sqlBehavior)return c;throw Error(`You tried to reference "${b}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return Y(c,Z)?this.config.alias?new Proxy(c,new bx(new Proxy(c.table,new by(this.config.alias,this.config.replaceOriginalName??!1)))):c:"object"!=typeof c||null===c?c:new Proxy(c,new bE(this.config))}}function bF(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(a=>a.toLowerCase()).join("_")}function bG(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((a,b,c)=>a+(0===c?b.toLowerCase():`${b[0].toUpperCase()}${b.slice(1)}`),"")}function bH(a){return a}class bI{static [X]="CasingCache";cache={};cachedTables={};convert;constructor(a){this.convert="snake_case"===a?bF:"camelCase"===a?bG:bH}getColumnCasing(a){if(!a.keyAsName)return a.name;let b=a.table[ah.Symbol.Schema]??"public",c=a.table[ah.Symbol.OriginalName],d=`${b}.${c}.${a.name}`;return this.cache[d]||this.cacheTable(a.table),this.cache[d]}cacheTable(a){let b=a[ah.Symbol.Schema]??"public",c=a[ah.Symbol.OriginalName],d=`${b}.${c}`;if(!this.cachedTables[d]){for(let b of Object.values(a[ah.Symbol.Columns])){let a=`${d}.${b.name}`;this.cache[a]=this.convert(b.name)}this.cachedTables[d]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class bJ extends Error{static [X]="DrizzleError";constructor({message:a,cause:b}){super(a),this.name="DrizzleError",this.cause=b}}class bK extends Error{constructor(a,b,c){super(`Failed query: ${a}
|
|
16
|
+
params: ${b}`),this.query=a,this.params=b,this.cause=c,Error.captureStackTrace(this,bK),c&&(this.cause=c)}}class bL extends bJ{static [X]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class bM{static [X]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(a,b){this.reference=()=>{let{name:b,columns:c,foreignColumns:d}=a();return{name:b,columns:c,foreignTable:d[0].table,foreignColumns:d}},b&&(this._onUpdate=b.onUpdate,this._onDelete=b.onDelete)}onUpdate(a){return this._onUpdate=a,this}onDelete(a){return this._onDelete=a,this}build(a){return new bN(a,this)}}class bN{constructor(a,b){this.table=a,this.reference=b.reference,this.onUpdate=b._onUpdate,this.onDelete=b._onDelete}static [X]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:a,columns:b,foreignColumns:c}=this.reference(),d=b.map(a=>a.name),e=c.map(a=>a.name),f=[this.table[$],...d,c[0].table[$],...e];return a??`${f.join("_")}_fk`}}function bO(a,b){return`${a[$]}_${b.join("_")}_unique`}class bP{constructor(a,b){this.name=b,this.columns=a}static [X]=null;columns;build(a){return new bR(a,this.columns,this.name)}}class bQ{static [X]=null;name;constructor(a){this.name=a}on(...a){return new bP(a,this.name)}}class bR{constructor(a,b,c){this.table=a,this.columns=b,this.name=c??bO(this.table,this.columns.map(a=>a.name))}static [X]=null;columns;name;getName(){return this.name}}class bS extends aj{static [X]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(a,b={}){return this.foreignKeyConfigs.push({ref:a,actions:b}),this}unique(a){return this.config.isUnique=!0,this.config.uniqueName=a,this}generatedAlwaysAs(a,b){return this.config.generated={as:a,type:"always",mode:b?.mode??"virtual"},this}buildForeignKeys(a,b){return this.foreignKeyConfigs.map(({ref:c,actions:d})=>{let e;return e=new bM(()=>({columns:[a],foreignColumns:[c()]})),d.onUpdate&&e.onUpdate(d.onUpdate),d.onDelete&&e.onDelete(d.onDelete),e.build(b)})}}class bT extends Z{constructor(a,b){b.uniqueName||(b.uniqueName=bO(a,[b.name])),super(a,b),this.table=a}static [X]="SQLiteColumn"}function bU(a,b,c){let d={},e=a.reduce((a,{path:e,field:f},g)=>{let h;h=Y(f,Z)?f:Y(f,aK)?f.decoder:Y(f,aD)?f._.sql.decoder:f.sql.decoder;let i=a;for(let[a,j]of e.entries())if(a<e.length-1)j in i||(i[j]={}),i=i[j];else{let a=b[g],k=i[j]=null===a?null:h.mapFromDriverValue(a);if(c&&Y(f,Z)&&2===e.length){let a=e[0];a in d?"string"==typeof d[a]&&d[a]!==f.table[$]&&(d[a]=!1):d[a]=null===k&&f.table[$]}}return a},{});if(c&&Object.keys(d).length>0)for(let[a,b]of Object.entries(d))"string"!=typeof b||c[b]||(e[a]=null);return e}function bV(a,b){return Object.entries(a).reduce((a,[c,d])=>{if("string"!=typeof c)return a;let e=b?[...b,c]:[c];return Y(d,Z)||Y(d,aK)||Y(d,aK.Aliased)||Y(d,aD)?a.push({path:e,field:d}):Y(d,ah)?a.push(...bV(d[ah.Symbol.Columns],e)):a.push(...bV(d,e)),a},[])}function bW(a,b){let c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(let[a,b]of c.entries())if(b!==d[a])return!1;return!0}function bX(a,b){let c=Object.entries(b).filter(([,a])=>void 0!==a).map(([b,c])=>Y(c,aK)||Y(c,Z)?[b,c]:[b,new aO(c,a[ah.Symbol.Columns][b])]);if(0===c.length)throw Error("No values to set");return Object.fromEntries(c)}function bY(a){return Y(a,aD)?a._.alias:Y(a,aV)?a[aG].name:Y(a,aK)?void 0:a[ah.Symbol.IsAlias]?a[ah.Symbol.Name]:a[ah.Symbol.BaseName]}function bZ(a,b){return{name:"string"==typeof a&&a.length>0?a:"",config:"object"==typeof a?a:b}}let b$="u"<typeof TextDecoder?null:new TextDecoder;class b_ extends bS{static [X]="SQLiteBigIntBuilder";constructor(a){super(a,"bigint","SQLiteBigInt")}build(a){return new b0(a,this.config)}}class b0 extends bT{static [X]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(a){return"u">typeof Buffer&&Buffer.from?BigInt((Buffer.isBuffer(a)?a:a instanceof ArrayBuffer?Buffer.from(a):a.buffer?Buffer.from(a.buffer,a.byteOffset,a.byteLength):Buffer.from(a)).toString("utf8")):BigInt(b$.decode(a))}mapToDriverValue(a){return Buffer.from(a.toString())}}class b1 extends bS{static [X]="SQLiteBlobJsonBuilder";constructor(a){super(a,"json","SQLiteBlobJson")}build(a){return new b2(a,this.config)}}class b2 extends bT{static [X]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(a){return"u">typeof Buffer&&Buffer.from?JSON.parse((Buffer.isBuffer(a)?a:a instanceof ArrayBuffer?Buffer.from(a):a.buffer?Buffer.from(a.buffer,a.byteOffset,a.byteLength):Buffer.from(a)).toString("utf8")):JSON.parse(b$.decode(a))}mapToDriverValue(a){return Buffer.from(JSON.stringify(a))}}class b3 extends bS{static [X]="SQLiteBlobBufferBuilder";constructor(a){super(a,"buffer","SQLiteBlobBuffer")}build(a){return new b4(a,this.config)}}class b4 extends bT{static [X]="SQLiteBlobBuffer";mapFromDriverValue(a){return Buffer.isBuffer(a)?a:Buffer.from(a)}getSQLType(){return"blob"}}function b5(a,b){let{name:c,config:d}=bZ(a,b);return d?.mode==="json"?new b1(c):d?.mode==="bigint"?new b_(c):new b3(c)}class b6 extends bS{static [X]="SQLiteCustomColumnBuilder";constructor(a,b,c){super(a,"custom","SQLiteCustomColumn"),this.config.fieldConfig=b,this.config.customTypeParams=c}build(a){return new b7(a,this.config)}}class b7 extends bT{static [X]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(a,b){super(a,b),this.sqlName=b.customTypeParams.dataType(b.fieldConfig),this.mapTo=b.customTypeParams.toDriver,this.mapFrom=b.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(a){return"function"==typeof this.mapFrom?this.mapFrom(a):a}mapToDriverValue(a){return"function"==typeof this.mapTo?this.mapTo(a):a}}function b8(a){return(b,c)=>{let{name:d,config:e}=bZ(b,c);return new b6(d,e,a)}}class b9 extends bS{static [X]="SQLiteBaseIntegerBuilder";constructor(a,b,c){super(a,b,c),this.config.autoIncrement=!1}primaryKey(a){return a?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}}class ca extends bT{static [X]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class cb extends b9{static [X]="SQLiteIntegerBuilder";constructor(a){super(a,"number","SQLiteInteger")}build(a){return new cc(a,this.config)}}class cc extends ca{static [X]="SQLiteInteger"}class cd extends b9{static [X]="SQLiteTimestampBuilder";constructor(a,b){super(a,"date","SQLiteTimestamp"),this.config.mode=b}defaultNow(){return this.default(aP`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(a){return new ce(a,this.config)}}class ce extends ca{static [X]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(a){return new Date("timestamp"===this.config.mode?1e3*a:a)}mapToDriverValue(a){let b=a.getTime();return"timestamp"===this.config.mode?Math.floor(b/1e3):b}}class cf extends b9{static [X]="SQLiteBooleanBuilder";constructor(a,b){super(a,"boolean","SQLiteBoolean"),this.config.mode=b}build(a){return new cg(a,this.config)}}class cg extends ca{static [X]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(a){return 1===Number(a)}mapToDriverValue(a){return+!!a}}function ch(a,b){let{name:c,config:d}=bZ(a,b);return d?.mode==="timestamp"||d?.mode==="timestamp_ms"?new cd(c,d.mode):d?.mode==="boolean"?new cf(c,d.mode):new cb(c)}class ci extends bS{static [X]="SQLiteNumericBuilder";constructor(a){super(a,"string","SQLiteNumeric")}build(a){return new cj(a,this.config)}}class cj extends bT{static [X]="SQLiteNumeric";mapFromDriverValue(a){return"string"==typeof a?a:String(a)}getSQLType(){return"numeric"}}class ck extends bS{static [X]="SQLiteNumericNumberBuilder";constructor(a){super(a,"number","SQLiteNumericNumber")}build(a){return new cl(a,this.config)}}class cl extends bT{static [X]="SQLiteNumericNumber";mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}mapToDriverValue=String;getSQLType(){return"numeric"}}class cm extends bS{static [X]="SQLiteNumericBigIntBuilder";constructor(a){super(a,"bigint","SQLiteNumericBigInt")}build(a){return new cn(a,this.config)}}class cn extends bT{static [X]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function co(a,b){let{name:c,config:d}=bZ(a,b),e=d?.mode;return"number"===e?new ck(c):"bigint"===e?new cm(c):new ci(c)}class cp extends bS{static [X]="SQLiteRealBuilder";constructor(a){super(a,"number","SQLiteReal")}build(a){return new cq(a,this.config)}}class cq extends bT{static [X]="SQLiteReal";getSQLType(){return"real"}}function cr(a){return new cp(a??"")}class cs extends bS{static [X]="SQLiteTextBuilder";constructor(a,b){super(a,"string","SQLiteText"),this.config.enumValues=b.enum,this.config.length=b.length}build(a){return new ct(a,this.config)}}class ct extends bT{static [X]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(a,b){super(a,b)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class cu extends bS{static [X]="SQLiteTextJsonBuilder";constructor(a){super(a,"json","SQLiteTextJson")}build(a){return new cv(a,this.config)}}class cv extends bT{static [X]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(a){return JSON.parse(a)}mapToDriverValue(a){return JSON.stringify(a)}}function cw(a,b={}){let{name:c,config:d}=bZ(a,b);return"json"===d.mode?new cu(c):new cs(c,d)}let cx=Symbol.for("drizzle:SQLiteInlineForeignKeys");class cy extends ah{static [X]="SQLiteTable";static Symbol=Object.assign({},ah.Symbol,{InlineForeignKeys:cx});[ah.Symbol.Columns];[cx]=[];[ah.Symbol.ExtraConfigBuilder]=void 0}let cz=(a,b,c)=>(function(a,b,c,d=a){let e=new cy(a,void 0,d),f=Object.fromEntries(Object.entries("function"==typeof b?b({blob:b5,customType:b8,integer:ch,numeric:co,real:cr,text:cw}):b).map(([a,b])=>{b.setName(a);let c=b.build(e);return e[cx].push(...b.buildForeignKeys(c,e)),[a,c]})),g=Object.assign(e,f);return g[ah.Symbol.Columns]=f,g[ah.Symbol.ExtraConfigColumns]=f,c&&(g[cy.Symbol.ExtraConfigBuilder]=c),g})(a,b,c);class cA extends aV{static [X]="SQLiteViewBase"}class cB{static [X]="SQLiteDialect";casing;constructor(a){this.casing=new bI(a?.casing)}escapeName(a){return`"${a.replace(/"/g,'""')}"`}escapeParam(a){return"?"}escapeString(a){return`'${a.replace(/'/g,"''")}'`}buildWithCTE(a){if(!a?.length)return;let b=[aP`with `];for(let[c,d]of a.entries())b.push(aP`${aP.identifier(d._.alias)} as (${d._.sql})`),c<a.length-1&&b.push(aP`, `);return b.push(aP` `),aP.join(b)}buildDeleteQuery({table:a,where:b,returning:c,withList:d,limit:e,orderBy:f}){let g=this.buildWithCTE(d),h=c?aP` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,i=b?aP` where ${b}`:void 0,j=this.buildOrderBy(f),k=this.buildLimit(e);return aP`${g}delete from ${a}${i}${h}${j}${k}`}buildUpdateSet(a,b){let c=a[ah.Symbol.Columns],d=Object.keys(c).filter(a=>void 0!==b[a]||c[a]?.onUpdateFn!==void 0),e=d.length;return aP.join(d.flatMap((a,d)=>{let f=c[a],g=f.onUpdateFn?.(),h=b[a]??(Y(g,aK)?g:aP.param(g,f)),i=aP`${aP.identifier(this.casing.getColumnCasing(f))} = ${h}`;return d<e-1?[i,aP.raw(", ")]:[i]}))}buildUpdateQuery({table:a,set:b,where:c,returning:d,withList:e,joins:f,from:g,limit:h,orderBy:i}){let j=this.buildWithCTE(e),k=this.buildUpdateSet(a,b),l=g&&aP.join([aP.raw(" from "),this.buildFromTable(g)]),m=this.buildJoins(f),n=d?aP` returning ${this.buildSelection(d,{isSingleTable:!0})}`:void 0,o=c?aP` where ${c}`:void 0,p=this.buildOrderBy(i),q=this.buildLimit(h);return aP`${j}update ${a} set ${k}${l}${m}${o}${n}${p}${q}`}buildSelection(a,{isSingleTable:b=!1}={}){let c=a.length,d=a.flatMap(({field:a},d)=>{let e=[];if(Y(a,aK.Aliased)&&a.isSelectionField)e.push(aP.identifier(a.fieldAlias));else if(Y(a,aK.Aliased)||Y(a,aK)){let c=Y(a,aK.Aliased)?a.sql:a;b?e.push(new aK(c.queryChunks.map(a=>Y(a,Z)?aP.identifier(this.casing.getColumnCasing(a)):a))):e.push(c),Y(a,aK.Aliased)&&e.push(aP` as ${aP.identifier(a.fieldAlias)}`)}else if(Y(a,Z)){let c=a.table[ah.Symbol.Name];"SQLiteNumericBigInt"===a.columnType?b?e.push(aP`cast(${aP.identifier(this.casing.getColumnCasing(a))} as text)`):e.push(aP`cast(${aP.identifier(c)}.${aP.identifier(this.casing.getColumnCasing(a))} as text)`):b?e.push(aP.identifier(this.casing.getColumnCasing(a))):e.push(aP`${aP.identifier(c)}.${aP.identifier(this.casing.getColumnCasing(a))}`)}else if(Y(a,aD)){let b=Object.entries(a._.selectedFields);if(1===b.length){let c=b[0][1],d=Y(c,aK)?c.decoder:Y(c,Z)?{mapFromDriverValue:a=>c.mapFromDriverValue(a)}:c.sql.decoder;d&&(a._.sql.decoder=d)}e.push(a)}return d<c-1&&e.push(aP`, `),e});return aP.join(d)}buildJoins(a){if(!a||0===a.length)return;let b=[];if(a)for(let[c,d]of a.entries()){0===c&&b.push(aP` `);let e=d.table,f=d.on?aP` on ${d.on}`:void 0;if(Y(e,cy)){let a=e[cy.Symbol.Name],c=e[cy.Symbol.Schema],g=e[cy.Symbol.OriginalName],h=a===g?void 0:d.alias;b.push(aP`${aP.raw(d.joinType)} join ${c?aP`${aP.identifier(c)}.`:void 0}${aP.identifier(g)}${h&&aP` ${aP.identifier(h)}`}${f}`)}else b.push(aP`${aP.raw(d.joinType)} join ${e}${f}`);c<a.length-1&&b.push(aP` `)}return aP.join(b)}buildLimit(a){return"object"==typeof a||"number"==typeof a&&a>=0?aP` limit ${a}`:void 0}buildOrderBy(a){let b=[];if(a)for(let[c,d]of a.entries())b.push(d),c<a.length-1&&b.push(aP`, `);return b.length>0?aP` order by ${aP.join(b)}`:void 0}buildFromTable(a){return Y(a,ah)&&a[ah.Symbol.IsAlias]?aP`${aP`${aP.identifier(a[ah.Symbol.Schema]??"")}.`.if(a[ah.Symbol.Schema])}${aP.identifier(a[ah.Symbol.OriginalName])} ${aP.identifier(a[ah.Symbol.Name])}`:a}buildSelectQuery({withList:a,fields:b,fieldsFlat:c,where:d,having:e,table:f,joins:g,orderBy:h,groupBy:i,limit:j,offset:k,distinct:l,setOperators:m}){let n=c??bV(b);for(let a of n){let b;if(Y(a.field,Z)&&a.field.table[$]!==(Y(f,aD)?f._.alias:Y(f,cA)?f[aG].name:Y(f,aK)?void 0:f[$])&&(b=a.field.table,!g?.some(({alias:a})=>a===(b[ah.Symbol.IsAlias]?b[$]:b[ah.Symbol.BaseName])))){let b=a.field.table[$];throw Error(`Your "${a.path.join("->")}" field references a column "${b}"."${a.field.name}", but the table "${b}" is not part of the query! Did you forget to join it?`)}}let o=!g||0===g.length,p=this.buildWithCTE(a),q=l?aP` distinct`:void 0,r=this.buildSelection(n,{isSingleTable:o}),s=this.buildFromTable(f),t=this.buildJoins(g),u=d?aP` where ${d}`:void 0,v=e?aP` having ${e}`:void 0,w=[];if(i)for(let[a,b]of i.entries())w.push(b),a<i.length-1&&w.push(aP`, `);let x=w.length>0?aP` group by ${aP.join(w)}`:void 0,y=this.buildOrderBy(h),z=this.buildLimit(j),A=k?aP` offset ${k}`:void 0,B=aP`${p}select${q} ${r} from ${s}${t}${u}${x}${v}${y}${z}${A}`;return m.length>0?this.buildSetOperations(B,m):B}buildSetOperations(a,b){let[c,...d]=b;if(!c)throw Error("Cannot pass undefined values to any set operator");return 0===d.length?this.buildSetOperationQuery({leftSelect:a,setOperator:c}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:a,setOperator:c}),d)}buildSetOperationQuery({leftSelect:a,setOperator:{type:b,isAll:c,rightSelect:d,limit:e,orderBy:f,offset:g}}){let h,i=aP`${a.getSQL()} `,j=aP`${d.getSQL()}`;if(f&&f.length>0){let a=[];for(let b of f)if(Y(b,bT))a.push(aP.identifier(b.name));else if(Y(b,aK)){for(let a=0;a<b.queryChunks.length;a++){let c=b.queryChunks[a];Y(c,bT)&&(b.queryChunks[a]=aP.identifier(this.casing.getColumnCasing(c)))}a.push(aP`${b}`)}else a.push(aP`${b}`);h=aP` order by ${aP.join(a,aP`, `)}`}let k="object"==typeof e||"number"==typeof e&&e>=0?aP` limit ${e}`:void 0,l=aP.raw(`${b} ${c?"all ":""}`),m=g?aP` offset ${g}`:void 0;return aP`${i}${l}${j}${h}${k}${m}`}buildInsertQuery({table:a,values:b,onConflict:c,returning:d,withList:e,select:f}){let g=[],h=Object.entries(a[ah.Symbol.Columns]).filter(([a,b])=>!b.shouldDisableInsert()),i=h.map(([,a])=>aP.identifier(this.casing.getColumnCasing(a)));if(f)Y(b,aK)?g.push(b):g.push(b.getSQL());else for(let[a,c]of(g.push(aP.raw("values ")),b.entries())){let d=[];for(let[a,b]of h){let e=c[a];if(void 0===e||Y(e,aO)&&void 0===e.value){let a;if(null!==b.default&&void 0!==b.default)a=Y(b.default,aK)?b.default:aP.param(b.default,b);else if(void 0!==b.defaultFn){let c=b.defaultFn();a=Y(c,aK)?c:aP.param(c,b)}else if(b.default||void 0===b.onUpdateFn)a=aP`null`;else{let c=b.onUpdateFn();a=Y(c,aK)?c:aP.param(c,b)}d.push(a)}else d.push(e)}g.push(d),a<b.length-1&&g.push(aP`, `)}let j=this.buildWithCTE(e),k=aP.join(g),l=d?aP` returning ${this.buildSelection(d,{isSingleTable:!0})}`:void 0,m=c?.length?aP.join(c):void 0;return aP`${j}insert into ${a} ${i} ${k}${m}${l}`}sqlToQuery(a,b){return a.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:b})}buildRelationalQuery({fullSchema:a,schema:b,tableNamesMap:c,table:d,tableConfig:e,queryConfig:f,tableAlias:g,nestedQueryRelation:h,joinOn:i}){let j,k=[],l,m,n=[],o,p=[];if(!0===f)k=Object.entries(e.columns).map(([a,b])=>({dbKey:b.name,tsKey:a,field:bB(b,g),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let d=Object.fromEntries(Object.entries(e.columns).map(([a,b])=>[a,bB(b,g)]));if(f.where){let a="function"==typeof f.where?f.where(d,{and:aZ,between:ba,eq:aX,exists:a8,gt:a0,gte:a1,ilike:be,inArray:a4,isNull:a6,isNotNull:a7,like:bc,lt:a2,lte:a3,ne:aY,not:a_,notBetween:bb,notExists:a9,notLike:bd,notIlike:bf,notInArray:a5,or:a$,sql:aP}):f.where;o=a&&bD(a,g)}let h=[],i=[];if(f.columns){let a=!1;for(let[b,c]of Object.entries(f.columns))void 0!==c&&b in e.columns&&(a||!0!==c||(a=!0),i.push(b));i.length>0&&(i=a?i.filter(a=>f.columns?.[a]===!0):Object.keys(e.columns).filter(a=>!i.includes(a)))}else i=Object.keys(e.columns);for(let a of i){let b=e.columns[a];h.push({tsKey:a,value:b})}let j=[];if(f.with&&(j=Object.entries(f.with).filter(a=>!!a[1]).map(([a,b])=>({tsKey:a,queryConfig:b,relation:e.relations[a]}))),f.extras)for(let[a,b]of Object.entries("function"==typeof f.extras?f.extras(d,{sql:aP}):f.extras))h.push({tsKey:a,value:bC(b,g)});for(let{tsKey:a,value:b}of h)k.push({dbKey:Y(b,aK.Aliased)?b.fieldAlias:e.columns[a].name,tsKey:a,field:Y(b,Z)?bB(b,g):b,relationTableTsKey:void 0,isJson:!1,selection:[]});let p="function"==typeof f.orderBy?f.orderBy(d,{sql:aP,asc:bq,desc:br}):f.orderBy??[];for(let{tsKey:d,queryConfig:e,relation:h}of(Array.isArray(p)||(p=[p]),n=p.map(a=>Y(a,Z)?bB(a,g):bD(a,g)),l=f.limit,m=f.offset,j)){let f=function(a,b,c){if(Y(c,bu)&&c.config)return{fields:c.config.fields,references:c.config.references};let d=b[ai(c.referencedTable)];if(!d)throw Error(`Table "${c.referencedTable[ah.Symbol.Name]}" not found in schema`);let e=a[d];if(!e)throw Error(`Table "${d}" not found in schema`);let f=c.sourceTable,g=b[ai(f)];if(!g)throw Error(`Table "${f[ah.Symbol.Name]}" not found in schema`);let h=[];for(let a of Object.values(e.relations))(c.relationName&&c!==a&&a.relationName===c.relationName||!c.relationName&&a.referencedTable===c.sourceTable)&&h.push(a);if(h.length>1)throw c.relationName?Error(`There are multiple relations with name "${c.relationName}" in table "${d}"`):Error(`There are multiple relations between "${d}" and "${c.sourceTable[ah.Symbol.Name]}". Please specify relation name`);if(h[0]&&Y(h[0],bu)&&h[0].config)return{fields:h[0].config.references,references:h[0].config.fields};throw Error(`There is not enough information to infer relation "${g}.${c.fieldName}"`)}(b,c,h),i=c[ai(h.referencedTable)],j=`${g}_${d}`,l=aZ(...f.fields.map((a,b)=>aX(bB(f.references[b],j),bB(a,g)))),m=this.buildRelationalQuery({fullSchema:a,schema:b,tableNamesMap:c,table:a[i],tableConfig:b[i],queryConfig:Y(h,bu)?!0===e?{limit:1}:{...e,limit:1}:e,tableAlias:j,joinOn:l,nestedQueryRelation:h}),n=aP`(${m.sql})`.as(d);k.push({dbKey:d,tsKey:d,field:n,relationTableTsKey:i,isJson:!0,selection:m.selection})}}if(0===k.length)throw new bJ({message:`No fields selected for table "${e.tsName}" ("${g}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});if(o=aZ(i,o),h){let a=aP`json_array(${aP.join(k.map(({field:a})=>Y(a,bT)?aP.identifier(this.casing.getColumnCasing(a)):Y(a,aK.Aliased)?a.sql:a),aP`, `)})`;Y(h,bv)&&(a=aP`coalesce(json_group_array(${a}), json_array())`);let b=[{dbKey:"data",tsKey:"data",field:a.as("data"),isJson:!0,relationTableTsKey:e.tsName,selection:k}];void 0!==l||void 0!==m||n.length>0?(j=this.buildSelectQuery({table:bA(d,g),fields:{},fieldsFlat:[{path:[],field:aP.raw("*")}],where:o,limit:l,offset:m,orderBy:n,setOperators:[]}),o=void 0,l=void 0,m=void 0,n=void 0):j=bA(d,g),j=this.buildSelectQuery({table:Y(j,cy)?j:new aD(j,{},g),fields:{},fieldsFlat:b.map(({field:a})=>({path:[],field:Y(a,Z)?bB(a,g):a})),joins:p,where:o,limit:l,offset:m,orderBy:n,setOperators:[]})}else j=this.buildSelectQuery({table:bA(d,g),fields:{},fieldsFlat:k.map(({field:a})=>({path:[],field:Y(a,Z)?bB(a,g):a})),joins:p,where:o,limit:l,offset:m,orderBy:n,setOperators:[]});return{tableTsKey:e.tsName,sql:j,selection:k}}}class cC extends cB{static [X]="SQLiteSyncDialect";migrate(a,b,c){let d=void 0===c||"string"==typeof c?"__drizzle_migrations":c.migrationsTable??"__drizzle_migrations",e=aP`
|
|
17
|
+
CREATE TABLE IF NOT EXISTS ${aP.identifier(d)} (
|
|
18
|
+
id SERIAL PRIMARY KEY,
|
|
19
|
+
hash text NOT NULL,
|
|
20
|
+
created_at numeric
|
|
21
|
+
)
|
|
22
|
+
`;b.run(e);let f=b.values(aP`SELECT id, hash, created_at FROM ${aP.identifier(d)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;b.run(aP`BEGIN`);try{for(let c of a)if(!f||Number(f[2])<c.folderMillis){for(let a of c.sql)b.run(aP.raw(a));b.run(aP`INSERT INTO ${aP.identifier(d)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}b.run(aP`COMMIT`)}catch(a){throw b.run(aP`ROLLBACK`),a}}}class cD extends null{static [X]=null;async migrate(a,b,c){let d=void 0===c||"string"==typeof c?"__drizzle_migrations":c.migrationsTable??"__drizzle_migrations",e=sql`
|
|
23
|
+
CREATE TABLE IF NOT EXISTS ${sql.identifier(d)} (
|
|
24
|
+
id SERIAL PRIMARY KEY,
|
|
25
|
+
hash text NOT NULL,
|
|
26
|
+
created_at numeric
|
|
27
|
+
)
|
|
28
|
+
`;await b.run(e);let f=(await b.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(d)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await b.transaction(async b=>{for(let c of a)if(!f||Number(f[2])<c.folderMillis){for(let a of c.sql)await b.run(sql.raw(a));await b.run(sql`INSERT INTO ${sql.identifier(d)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}class cE{static [X]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class cF{static [X]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(a){return this.then(void 0,a)}finally(a){return this.then(b=>(a?.(),b),b=>{throw a?.(),b})}then(a,b){return this.execute().then(a,b)}}function cG(a){return Y(a,cy)?[`${a[ah.Symbol.BaseName]}`]:Y(a,aD)?a._.usedTables??[]:Y(a,aK)?a.usedTables??[]:[]}class cH{static [X]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(a){this.fields=a.fields,this.session=a.session,this.dialect=a.dialect,this.withList=a.withList,this.distinct=a.distinct}from(a){let b,c=!!this.fields;return b=this.fields?this.fields:Y(a,aD)?Object.fromEntries(Object.keys(a._.selectedFields).map(b=>[b,a[b]])):Y(a,cA)?a[aG].selectedFields:Y(a,aK)?{}:a[ah.Symbol.Columns],new cJ({table:a,fields:b,isPartialSelect:c,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class cI extends cE{static [X]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:a,fields:b,isPartialSelect:c,session:d,dialect:e,withList:f,distinct:g}){for(const h of(super(),this.config={withList:f,table:a,fields:{...b},distinct:g,setOperators:[]},this.isPartialSelect=c,this.session=d,this.dialect=e,this._={selectedFields:b,config:this.config},this.tableName=bY(a),this.joinsNotNullableMap="string"==typeof this.tableName?{[this.tableName]:!0}:{},cG(a)))this.usedTables.add(h)}getUsedTables(){return[...this.usedTables]}createJoin(a){return(b,c)=>{let d=this.tableName,e=bY(b);for(let a of cG(b))this.usedTables.add(a);if("string"==typeof e&&this.config.joins?.some(a=>a.alias===e))throw Error(`Alias "${e}" is already used in this query`);if(!this.isPartialSelect&&(1===Object.keys(this.joinsNotNullableMap).length&&"string"==typeof d&&(this.config.fields={[d]:this.config.fields}),"string"==typeof e&&!Y(b,aK))){let a=Y(b,aD)?b._.selectedFields:Y(b,aV)?b[aG].selectedFields:b[ah.Symbol.Columns];this.config.fields[e]=a}if("function"==typeof c&&(c=c(new Proxy(this.config.fields,new bE({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:c,table:b,joinType:a,alias:e}),"string"==typeof e)switch(a){case"left":this.joinsNotNullableMap[e]=!1;break;case"right":this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[e]=!0;break;case"cross":case"inner":this.joinsNotNullableMap[e]=!0;break;case"full":this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[e]=!1}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(a,b){return c=>{let d="function"==typeof c?c(cL()):c;if(!bW(this.getSelectedFields(),d.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:a,isAll:b,rightSelect:d}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(a){return this.config.setOperators.push(...a),this}where(a){return"function"==typeof a&&(a=a(new Proxy(this.config.fields,new bE({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=a,this}having(a){return"function"==typeof a&&(a=a(new Proxy(this.config.fields,new bE({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=a,this}groupBy(...a){if("function"==typeof a[0]){let b=a[0](new Proxy(this.config.fields,new bE({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(b)?b:[b]}else this.config.groupBy=a;return this}orderBy(...a){if("function"==typeof a[0]){let b=a[0](new Proxy(this.config.fields,new bE({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),c=Array.isArray(b)?b:[b];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=c:this.config.orderBy=c}else this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=a:this.config.orderBy=a;return this}limit(a){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=a:this.config.limit=a,this}offset(a){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=a:this.config.offset=a,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:a,...b}=this.dialect.sqlToQuery(this.getSQL());return b}as(a){let b=[];if(b.push(...cG(this.config.table)),this.config.joins)for(let a of this.config.joins)b.push(...cG(a.table));return new Proxy(new aD(this.getSQL(),this.config.fields,a,!1,[...new Set(b)]),new bE({alias:a,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bE({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class cJ extends cI{static [X]="SQLiteSelect";_prepare(a=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let b=bV(this.config.fields),c=this.session[a?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),b,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return c.joinsNotNullableMap=this.joinsNotNullableMap,c}$withCache(a){return this.cacheConfig=void 0===a?{config:{},enable:!0,autoInvalidate:!0}:!1===a?{enable:!1}:{enable:!0,autoInvalidate:!0,...a},this}prepare(){return this._prepare(!1)}run=a=>this._prepare().run(a);all=a=>this._prepare().all(a);get=a=>this._prepare().get(a);values=a=>this._prepare().values(a);async execute(){return this.all()}}for(let a of[cF])for(let b of Object.getOwnPropertyNames(a.prototype))"constructor"!==b&&Object.defineProperty(cJ.prototype,b,Object.getOwnPropertyDescriptor(a.prototype,b)||Object.create(null));function cK(a,b){return(c,d,...e)=>{let f=[d,...e].map(c=>({type:a,isAll:b,rightSelect:c}));for(let a of f)if(!bW(c.getSelectedFields(),a.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return c.addSetOperators(f)}}let cL=()=>({union:cM,unionAll:cN,intersect:cO,except:cP}),cM=cK("union",!1),cN=cK("union",!0),cO=cK("intersect",!1),cP=cK("except",!1);class cQ{static [X]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(a){this.dialect=Y(a,cB)?a:void 0,this.dialectConfig=Y(a,cB)?void 0:a}$with=(a,b)=>{let c=this;return{as:d=>("function"==typeof d&&(d=d(c)),new Proxy(new aE(d.getSQL(),b??("getSelectedFields"in d?d.getSelectedFields()??{}:{}),a,!0),new bE({alias:a,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...a){let b=this;return{select:function(c){return new cH({fields:c??void 0,session:void 0,dialect:b.getDialect(),withList:a})},selectDistinct:function(c){return new cH({fields:c??void 0,session:void 0,dialect:b.getDialect(),withList:a,distinct:!0})}}}select(a){return new cH({fields:a??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(a){return new cH({fields:a??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new cC(this.dialectConfig)),this.dialect}}class cR{constructor(a,b,c,d){this.table=a,this.session=b,this.dialect=c,this.withList=d}static [X]="SQLiteUpdateBuilder";set(a){return new cS(this.table,bX(this.table,a),this.session,this.dialect,this.withList)}}class cS extends cF{constructor(a,b,c,d,e){super(),this.session=c,this.dialect=d,this.config={set:b,table:a,withList:e,joins:[]}}static [X]="SQLiteUpdate";config;from(a){return this.config.from=a,this}createJoin(a){return(b,c)=>{let d=bY(b);if("string"==typeof d&&this.config.joins.some(a=>a.alias===d))throw Error(`Alias "${d}" is already used in this query`);if("function"==typeof c){let a=this.config.from?Y(b,cy)?b[ah.Symbol.Columns]:Y(b,aD)?b._.selectedFields:Y(b,cA)?b[aG].selectedFields:void 0:void 0;c=c(new Proxy(this.config.table[ah.Symbol.Columns],new bE({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),a&&new Proxy(a,new bE({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:c,table:b,joinType:a,alias:d}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(a){return this.config.where=a,this}orderBy(...a){if("function"==typeof a[0]){let b=a[0](new Proxy(this.config.table[ah.Symbol.Columns],new bE({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),c=Array.isArray(b)?b:[b];this.config.orderBy=c}else this.config.orderBy=a;return this}limit(a){return this.config.limit=a,this}returning(a=this.config.table[cy.Symbol.Columns]){return this.config.returning=bV(a),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:a,...b}=this.dialect.sqlToQuery(this.getSQL());return b}_prepare(a=!0){return this.session[a?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:cG(this.config.table)})}prepare(){return this._prepare(!1)}run=a=>this._prepare().run(a);all=a=>this._prepare().all(a);get=a=>this._prepare().get(a);values=a=>this._prepare().values(a);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class cT{constructor(a,b,c,d){this.table=a,this.session=b,this.dialect=c,this.withList=d}static [X]="SQLiteInsertBuilder";values(a){if(0===(a=Array.isArray(a)?a:[a]).length)throw Error("values() must be called with at least one value");let b=a.map(a=>{let b={},c=this.table[ah.Symbol.Columns];for(let d of Object.keys(a)){let e=a[d];b[d]=Y(e,aK)?e:new aO(e,c[d])}return b});return new cU(this.table,b,this.session,this.dialect,this.withList)}select(a){let b="function"==typeof a?a(new cQ):a;if(!Y(b,aK)&&!bW(this.table[aa],b._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new cU(this.table,b,this.session,this.dialect,this.withList,!0)}}class cU extends cF{constructor(a,b,c,d,e,f){super(),this.session=c,this.dialect=d,this.config={table:a,values:b,withList:e,select:f}}static [X]="SQLiteInsert";config;returning(a=this.config.table[cy.Symbol.Columns]){return this.config.returning=bV(a),this}onConflictDoNothing(a={}){if(this.config.onConflict||(this.config.onConflict=[]),void 0===a.target)this.config.onConflict.push(aP` on conflict do nothing`);else{let b=Array.isArray(a.target)?aP`${a.target}`:aP`${[a.target]}`,c=a.where?aP` where ${a.where}`:aP``;this.config.onConflict.push(aP` on conflict ${b} do nothing${c}`)}return this}onConflictDoUpdate(a){if(a.where&&(a.targetWhere||a.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);let b=a.where?aP` where ${a.where}`:void 0,c=a.targetWhere?aP` where ${a.targetWhere}`:void 0,d=a.setWhere?aP` where ${a.setWhere}`:void 0,e=Array.isArray(a.target)?aP`${a.target}`:aP`${[a.target]}`,f=this.dialect.buildUpdateSet(this.config.table,bX(this.config.table,a.set));return this.config.onConflict.push(aP` on conflict ${e}${c} do update set ${f}${b}${d}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:a,...b}=this.dialect.sqlToQuery(this.getSQL());return b}_prepare(a=!0){return this.session[a?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:cG(this.config.table)})}prepare(){return this._prepare(!1)}run=a=>this._prepare().run(a);all=a=>this._prepare().all(a);get=a=>this._prepare().get(a);values=a=>this._prepare().values(a);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class cV extends cF{constructor(a,b,c,d){super(),this.table=a,this.session=b,this.dialect=c,this.config={table:a,withList:d}}static [X]="SQLiteDelete";config;where(a){return this.config.where=a,this}orderBy(...a){if("function"==typeof a[0]){let b=a[0](new Proxy(this.config.table[ah.Symbol.Columns],new bE({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),c=Array.isArray(b)?b:[b];this.config.orderBy=c}else this.config.orderBy=a;return this}limit(a){return this.config.limit=a,this}returning(a=this.table[cy.Symbol.Columns]){return this.config.returning=bV(a),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:a,...b}=this.dialect.sqlToQuery(this.getSQL());return b}_prepare(a=!0){return this.session[a?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:cG(this.config.table)})}prepare(){return this._prepare(!1)}run=a=>this._prepare().run(a);all=a=>this._prepare().all(a);get=a=>this._prepare().get(a);values=a=>this._prepare().values(a);async execute(a){return this._prepare().execute(a)}$dynamic(){return this}}class cW extends aK{constructor(a){super(cW.buildEmbeddedCount(a.source,a.filters).queryChunks),this.params=a,this.session=a.session,this.sql=cW.buildCount(a.source,a.filters)}sql;static [X]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(a,b){return aP`(select count(*) from ${a}${aP.raw(" where ").if(b)}${b})`}static buildCount(a,b){return aP`select count(*) from ${a}${aP.raw(" where ").if(b)}${b}`}then(a,b){return Promise.resolve(this.session.count(this.sql)).then(a,b)}catch(a){return this.then(void 0,a)}finally(a){return this.then(b=>(a?.(),b),b=>{throw a?.(),b})}}class cX{constructor(a,b,c,d,e,f,g,h){this.mode=a,this.fullSchema=b,this.schema=c,this.tableNamesMap=d,this.table=e,this.tableConfig=f,this.dialect=g,this.session=h}static [X]="SQLiteAsyncRelationalQueryBuilder";findMany(a){return"sync"===this.mode?new cZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,a||{},"many"):new cY(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,a||{},"many")}findFirst(a){return"sync"===this.mode?new cZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,a?{...a,limit:1}:{limit:1},"first"):new cY(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,a?{...a,limit:1}:{limit:1},"first")}}class cY extends cF{constructor(a,b,c,d,e,f,g,h,i){super(),this.fullSchema=a,this.schema=b,this.tableNamesMap=c,this.table=d,this.tableConfig=e,this.dialect=f,this.session=g,this.config=h,this.mode=i}static [X]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(a=!1){let{query:b,builtQuery:c}=this._toSQL();return this.session[a?"prepareOneTimeQuery":"prepareQuery"](c,void 0,"first"===this.mode?"get":"all",!0,(a,c)=>{let d=a.map(a=>(function a(b,c,d,e,f=a=>a){let g={};for(let[h,i]of e.entries())if(i.isJson){let e=c.relations[i.tsKey],j=d[h],k="string"==typeof j?JSON.parse(j):j;g[i.tsKey]=Y(e,bu)?k&&a(b,b[i.relationTableTsKey],k,i.selection,f):k.map(c=>a(b,b[i.relationTableTsKey],c,i.selection,f))}else{let a,b=f(d[h]),c=i.field;a=Y(c,Z)?c:Y(c,aK)?c.decoder:c.sql.decoder,g[i.tsKey]=null===b?null:a.mapFromDriverValue(b)}return g})(this.schema,this.tableConfig,a,b.selection,c));return"first"===this.mode?d[0]:d})}prepare(){return this._prepare(!1)}_toSQL(){let a=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),b=this.dialect.sqlToQuery(a.sql);return{query:a,builtQuery:b}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return"first"===this.mode?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}}class cZ extends cY{static [X]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class c$ extends cF{constructor(a,b,c,d,e){super(),this.execute=a,this.getSQL=b,this.dialect=d,this.mapBatchResult=e,this.config={action:c}}static [X]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(a,b){return b?this.mapBatchResult(a):a}_prepare(){return this}isResponseInArrayMode(){return!1}}class c_{constructor(a,b,c,d){this.resultKind=a,this.dialect=b,this.session=c,this._=d?{schema:d.schema,fullSchema:d.fullSchema,tableNamesMap:d.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};const e=this.query;if(this._.schema)for(const[f,g]of Object.entries(this._.schema))e[f]=new cX(a,d.fullSchema,this._.schema,this._.tableNamesMap,d.fullSchema[f],g,b,c);this.$cache={invalidate:async a=>{}}}static [X]="BaseSQLiteDatabase";query;$with=(a,b)=>{let c=this;return{as:d=>("function"==typeof d&&(d=d(new cQ(c.dialect))),new Proxy(new aE(d.getSQL(),b??("getSelectedFields"in d?d.getSelectedFields()??{}:{}),a,!0),new bE({alias:a,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(a,b){return new cW({source:a,filters:b,session:this.session})}with(...a){let b=this;return{select:function(c){return new cH({fields:c??void 0,session:b.session,dialect:b.dialect,withList:a})},selectDistinct:function(c){return new cH({fields:c??void 0,session:b.session,dialect:b.dialect,withList:a,distinct:!0})},update:function(c){return new cR(c,b.session,b.dialect,a)},insert:function(c){return new cT(c,b.session,b.dialect,a)},delete:function(c){return new cV(c,b.session,b.dialect,a)}}}select(a){return new cH({fields:a??void 0,session:this.session,dialect:this.dialect})}selectDistinct(a){return new cH({fields:a??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(a){return new cR(a,this.session,this.dialect)}$cache;insert(a){return new cT(a,this.session,this.dialect)}delete(a){return new cV(a,this.session,this.dialect)}run(a){let b="string"==typeof a?aP.raw(a):a.getSQL();return"async"===this.resultKind?new c$(async()=>this.session.run(b),()=>b,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(b)}all(a){let b="string"==typeof a?aP.raw(a):a.getSQL();return"async"===this.resultKind?new c$(async()=>this.session.all(b),()=>b,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(b)}get(a){let b="string"==typeof a?aP.raw(a):a.getSQL();return"async"===this.resultKind?new c$(async()=>this.session.get(b),()=>b,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(b)}values(a){let b="string"==typeof a?aP.raw(a):a.getSQL();return"async"===this.resultKind?new c$(async()=>this.session.values(b),()=>b,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(b)}transaction(a,b){return this.session.transaction(a,b)}}class c0{static [X]="Cache"}class c1 extends c0{strategy(){return"all"}static [X]="NoopCache";async get(a){}async put(a,b,c,d){}async onMutate(a){}}async function c2(a,b){let c=`${a}-${JSON.stringify(b)}`,d=new TextEncoder().encode(c);return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(a=>a.toString(16).padStart(2,"0")).join("")}class c3 extends cF{constructor(a){super(),this.resultCb=a}static [X]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class c4{constructor(a,b,c,d,e,f){this.mode=a,this.executeMethod=b,this.query=c,this.cache=d,this.queryMetadata=e,this.cacheConfig=f,d&&"all"===d.strategy()&&void 0===f&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static [X]="PreparedQuery";joinsNotNullableMap;async queryWithCache(a,b,c){if(void 0===this.cache||Y(this.cache,c1)||void 0===this.queryMetadata||this.cacheConfig&&!this.cacheConfig.enable)try{return await c()}catch(c){throw new bK(a,b,c)}if(("insert"===this.queryMetadata.type||"update"===this.queryMetadata.type||"delete"===this.queryMetadata.type)&&this.queryMetadata.tables.length>0)try{let[a]=await Promise.all([c(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return a}catch(c){throw new bK(a,b,c)}if(!this.cacheConfig)try{return await c()}catch(c){throw new bK(a,b,c)}if("select"===this.queryMetadata.type){let d=await this.cache.get(this.cacheConfig.tag??await c2(a,b),this.queryMetadata.tables,void 0!==this.cacheConfig.tag,this.cacheConfig.autoInvalidate);if(void 0===d){let d;try{d=await c()}catch(c){throw new bK(a,b,c)}return await this.cache.put(this.cacheConfig.tag??await c2(a,b),d,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],void 0!==this.cacheConfig.tag,this.cacheConfig.config),d}return d}try{return await c()}catch(c){throw new bK(a,b,c)}}getQuery(){return this.query}mapRunResult(a,b){return a}mapAllResult(a,b){throw Error("Not implemented")}mapGetResult(a,b){throw Error("Not implemented")}execute(a){return"async"===this.mode?this[this.executeMethod](a):new c3(()=>this[this.executeMethod](a))}mapResult(a,b){switch(this.executeMethod){case"run":return this.mapRunResult(a,b);case"all":return this.mapAllResult(a,b);case"get":return this.mapGetResult(a,b)}}}class c5{constructor(a){this.dialect=a}static [X]="SQLiteSession";prepareOneTimeQuery(a,b,c,d,e,f,g){return this.prepareQuery(a,b,c,d,e,f,g)}run(a){let b=this.dialect.sqlToQuery(a);try{return this.prepareOneTimeQuery(b,void 0,"run",!1).run()}catch(a){throw new bJ({cause:a,message:`Failed to run the query '${b.sql}'`})}}extractRawRunValueFromBatchResult(a){return a}all(a){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(a),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(a){throw Error("Not implemented")}get(a){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(a),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(a){throw Error("Not implemented")}values(a){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(a),void 0,"run",!1).values()}async count(a){return(await this.values(a))[0][0]}extractRawValuesValueFromBatchResult(a){throw Error("Not implemented")}}class c6 extends c_{constructor(a,b,c,d,e=0){super(a,b,c,d),this.schema=d,this.nestedIndex=e}static [X]="SQLiteTransaction";rollback(){throw new bL}}class c7 extends c5{constructor(a,b,c,d={}){super(b),this.client=a,this.schema=c,this.logger=d.logger??new bk,this.cache=d.cache??new c1}static [X]="BetterSQLiteSession";logger;cache;prepareQuery(a,b,c,d,e,f,g){return new c9(this.client.prepare(a.sql),a,this.logger,this.cache,f,g,b,c,d,e)}transaction(a,b={}){let c=new c8("sync",this.dialect,this,this.schema);return this.client.transaction(a)[b.behavior??"deferred"](c)}}class c8 extends c6{static [X]="BetterSQLiteTransaction";transaction(a){let b=`sp${this.nestedIndex}`,c=new c8("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(aP.raw(`savepoint ${b}`));try{let d=a(c);return this.session.run(aP.raw(`release savepoint ${b}`)),d}catch(a){throw this.session.run(aP.raw(`rollback to savepoint ${b}`)),a}}}class c9 extends c4{constructor(a,b,c,d,e,f,g,h,i,j){super("sync",h,b,d,e,f),this.stmt=a,this.logger=c,this.fields=g,this._isResponseInArrayMode=i,this.customResultMapper=j}static [X]="BetterSQLitePreparedQuery";run(a){let b=aT(this.query.params,a??{});return this.logger.logQuery(this.query.sql,b),this.stmt.run(...b)}all(a){let{fields:b,joinsNotNullableMap:c,query:d,logger:e,stmt:f,customResultMapper:g}=this;if(!b&&!g){let b=aT(d.params,a??{});return e.logQuery(d.sql,b),f.all(...b)}let h=this.values(a);return g?g(h):h.map(a=>bU(b,a,c))}get(a){let b=aT(this.query.params,a??{});this.logger.logQuery(this.query.sql,b);let{fields:c,stmt:d,joinsNotNullableMap:e,customResultMapper:f}=this;if(!c&&!f)return d.get(...b);let g=d.raw().get(...b);if(g)return f?f([g]):bU(c,g,e)}values(a){let b=aT(this.query.params,a??{});return this.logger.logQuery(this.query.sql,b),this.stmt.raw().all(...b)}isResponseInArrayMode(){return this._isResponseInArrayMode}}class da extends c_{static [X]="BetterSQLite3Database"}function db(a,b={}){let c,d,e=new cC({casing:b.casing});if(!0===b.logger?c=new bj:!1!==b.logger&&(c=b.logger),b.schema){let a=function(a,b){1===Object.keys(a).length&&"default"in a&&!Y(a.default,ah)&&(a=a.default);let c={},d={},e={};for(let[f,g]of Object.entries(a))if(Y(g,ah)){let a=ai(g),b=d[a];for(let d of(c[a]=f,e[f]={tsName:f,dbName:g[ah.Symbol.Name],schema:g[ah.Symbol.Schema],columns:g[ah.Symbol.Columns],relations:b?.relations??{},primaryKey:b?.primaryKey??[]},Object.values(g[ah.Symbol.Columns])))d.primary&&e[f].primaryKey.push(d);let h=g[ah.Symbol.ExtraConfigBuilder]?.(g[ah.Symbol.ExtraConfigColumns]);if(h)for(let a of Object.values(h))Y(a,bo)&&e[f].primaryKey.push(...a.columns)}else if(Y(g,bt)){let a,f=ai(g.table),h=c[f];for(let[c,i]of Object.entries(g.config(b(g.table))))if(h){let b=e[h];b.relations[c]=i,a&&b.primaryKey.push(...a)}else f in d||(d[f]={relations:{},primaryKey:a}),d[f].relations[c]=i}return{tables:e,tableNamesMap:c}}(b.schema,bw);d={fullSchema:b.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let f=new c7(a,e,d,{logger:c}),g=new da("sync",e,f,d);return g.$client=a,g}function dc(...a){if(void 0===a[0]||"string"==typeof a[0])return db(void 0===a[0]?new bg:new bg(a[0]),a[1]);if(function(a){if("object"!=typeof a||null===a||"Object"!==a.constructor.name)return!1;if("logger"in a){let b=typeof a.logger;return"boolean"===b||"object"===b&&"function"==typeof a.logger.logQuery||"undefined"===b}if("schema"in a){let b=typeof a.schema;return"object"===b||"undefined"===b}if("casing"in a){let b=typeof a.casing;return"string"===b||"undefined"===b}if("mode"in a)return"default"===a.mode&&"planetscale"===a.mode&&void 0===a.mode;if("connection"in a){let b=typeof a.connection;return"string"===b||"object"===b||"undefined"===b}if("client"in a){let b=typeof a.client;return"object"===b||"function"===b||"undefined"===b}return 0===Object.keys(a).length}(a[0])){let{connection:b,client:c,...d}=a[0];if(c)return db(c,d);if("object"==typeof b){let{source:a,...c}=b;return db(new bg(a,c),d)}return db(new bg(b),d)}return db(a[0],a[1])}(dc||(dc={})).mock=function(a){return db({},a)};var dd=c(73024),de=c(76760);class df{constructor(a,b){this.name=a,this.unique=b}static [X]="SQLiteIndexBuilderOn";on(...a){return new dg(this.name,a,this.unique)}}class dg{static [X]="SQLiteIndexBuilder";config;constructor(a,b,c){this.config={name:a,columns:b,unique:c,where:void 0}}where(a){return this.config.where=a,this}build(a){return new dh(this.config,a)}}class dh{static [X]="SQLiteIndex";config;constructor(a,b){this.config={...a,table:b}}}function di(a){return new df(a,!1)}function dj(...a){return a[0].columns?new dk(a[0].columns,a[0].name):new dk(a)}class dk{static [X]="SQLitePrimaryKeyBuilder";columns;name;constructor(a,b){this.columns=a,this.name=b}build(a){return new dl(a,this.columns,this.name)}}class dl{constructor(a,b,c){this.table=a,this.columns=b,this.name=c}static [X]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[cy.Symbol.Name]}_${this.columns.map(a=>a.name).join("_")}_pk`}}let dm=cz("user",{id:cw("id").primaryKey(),name:cw("name").notNull(),email:cw("email").notNull().unique(),emailVerified:ch("email_verified",{mode:"boolean"}).notNull().default(!1),image:cw("image"),twoFactorEnabled:ch("two_factor_enabled",{mode:"boolean"}).notNull().default(!1),addressAs:cw("address_as").notNull().default(""),lang:cw("lang").notNull().default("English (US)"),tz:cw("tz").notNull().default("UTC"),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),dn=cz("session",{id:cw("id").primaryKey(),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),token:cw("token").notNull().unique(),expiresAt:ch("expires_at",{mode:"timestamp"}).notNull(),ipAddress:cw("ip_address"),userAgent:cw("user_agent"),activeOrgId:cw("active_org_id"),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),dp=cz("account",{id:cw("id").primaryKey(),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),accountId:cw("account_id").notNull(),providerId:cw("provider_id").notNull(),accessToken:cw("access_token"),refreshToken:cw("refresh_token"),password:cw("password"),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),dq=cz("verification",{id:cw("id").primaryKey(),identifier:cw("identifier").notNull(),value:cw("value").notNull(),expiresAt:ch("expires_at",{mode:"timestamp"}).notNull(),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),dr=cz("organization",{id:cw("id").primaryKey(),name:cw("name").notNull(),ownerId:cw("owner_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),runMode:cw("run_mode",{enum:["start","auth","vps","portable"]}).notNull().default("start"),archived:ch("archived",{mode:"boolean"}).notNull().default(!1),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),ds=cz("member",{id:cw("id").primaryKey(),orgId:cw("org_id").notNull().references(()=>dr.id,{onDelete:"cascade"}),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),role:cw("role",{enum:["owner","admin","member"]}).notNull().default("owner")}),dt=cz("workspace",{id:cw("id").primaryKey(),orgId:cw("org_id").notNull().references(()=>dr.id,{onDelete:"cascade"}),slug:cw("slug").notNull().unique(),name:cw("name").notNull(),mission:cw("mission").notNull().default(""),objective:cw("objective").notNull().default(""),stack:cw("stack",{mode:"json"}).$type().notNull().default({}),runMode:cw("run_mode",{enum:["off","start","auth","vps","portable"]}).notNull().default("start"),bootstrap:cw("bootstrap",{enum:["pending","template-only","enriching","done"]}).notNull().default("template-only"),settings:cw("settings",{mode:"json"}).$type(),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),du=cz("agent",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),handle:cw("handle").notNull(),name:cw("name").notNull(),role:cw("role").notNull(),color:cw("color").notNull().default("#e0a44e"),image:cw("image"),adapter:cw("adapter").notNull().default("cli_claude_code"),model:cw("model").notNull().default("sonnet"),temperature:cr("temperature").notNull().default(.4),dailyCapUsd:cr("daily_cap_usd").notNull().default(25),tierFloor:cw("tier_floor",{enum:["light","heavy","critical"]}).notNull().default("heavy"),reportsTo:cw("reports_to"),status:cw("status",{enum:["idle","working","review","blocked"]}).notNull().default("idle"),health:cw("health",{enum:["alive","stale","down"]}).notNull().default("alive"),lastPulse:ch("last_pulse",{mode:"timestamp"}),persona:cw("persona",{mode:"json"}).$type(),rag:cw("rag",{mode:"json"}).$type(),orgX:cr("org_x"),orgY:cr("org_y")},a=>({wsIdx:di("agent_ws_idx").on(a.workspaceId)})),dv=cz("pulse",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),agentId:cw("agent_id").notNull().references(()=>du.id,{onDelete:"cascade"}),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),ok:ch("ok",{mode:"boolean"}).notNull().default(!0),latencyMs:ch("latency_ms").notNull().default(0),note:cw("note").notNull().default("")},a=>({agentIdx:di("pulse_agent_idx").on(a.agentId)})),dw=cz("skill",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),name:cw("name").notNull(),summary:cw("summary").notNull().default(""),instructions:cw("instructions").notNull().default(""),trigger:cw("trigger").notNull().default(""),native:ch("native",{mode:"boolean"}).notNull().default(!1),provisional:ch("provisional",{mode:"boolean"}).notNull().default(!1),indexed:cw("indexed",{enum:["pending","indexed"]}).notNull().default("pending"),proposedRole:cw("proposed_role")},a=>({wsIdx:di("skill_ws_idx").on(a.workspaceId)})),dx=cz("agent_skill",{agentId:cw("agent_id").notNull().references(()=>du.id,{onDelete:"cascade"}),skillId:cw("skill_id").notNull().references(()=>dw.id,{onDelete:"cascade"}),auto:ch("auto",{mode:"boolean"}).notNull().default(!0)},a=>({pk:dj({columns:[a.agentId,a.skillId]})})),dy=cz("provider",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),catalogId:cw("catalog_id").notNull(),adapter:cw("adapter").notNull(),kind:cw("kind",{enum:["cloud","cli","local"]}).notNull().default("cloud"),auth:cw("auth",{enum:["api_key","oauth","cli","local","none"]}).notNull().default("api_key"),status:cw("status",{enum:["connected","needs_sync","error"]}).notNull().default("needs_sync"),syncStatus:cw("sync_status",{enum:["implemented","manual","not_implemented"]}).notNull().default("not_implemented"),modelCount:ch("model_count").notNull().default(0),lastSync:ch("last_sync",{mode:"timestamp"}),cliVersion:cw("cli_version"),defaultModel:cw("default_model"),authState:cw("auth_state")},a=>({wsIdx:di("provider_ws_idx").on(a.workspaceId)})),dz=cz("vault",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),providerId:cw("provider_id").references(()=>dy.id,{onDelete:"cascade"}),ref:cw("ref").notNull(),ciphertext:cw("ciphertext").notNull(),iv:cw("iv").notNull()}),dA=cz("provider_model",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),providerId:cw("provider_id").notNull().references(()=>dy.id,{onDelete:"cascade"}),catalogId:cw("catalog_id").notNull(),modelId:cw("model_id").notNull(),name:cw("name").notNull().default(""),context:ch("context").notNull().default(0),outputLimit:ch("output_limit").notNull().default(0),inputCost:cr("input_cost").notNull().default(0),outputCost:cr("output_cost").notNull().default(0),caps:cw("caps",{mode:"json"}).$type(),released:cw("released").notNull().default(""),isDefault:ch("is_default",{mode:"boolean"}).notNull().default(!1),lastSeen:ch("last_seen",{mode:"timestamp"}).$defaultFn(()=>new Date)},a=>({provIdx:di("provider_model_prov_idx").on(a.providerId)})),dB=cz("local_model",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),name:cw("name").notNull(),file:cw("file").notNull(),quant:cw("quant").notNull().default("Q4_K_M"),params:cw("params").notNull().default(""),sizeBytes:ch("size_bytes").notNull().default(0),sha256:cw("sha256").notNull().default(""),bind:cw("bind").notNull().default("127.0.0.1:8080"),loaded:ch("loaded",{mode:"boolean"}).notNull().default(!1)}),dC=cz("goal",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),title:cw("title").notNull(),description:cw("description").notNull().default(""),ownerId:cw("owner_id").references(()=>du.id),progress:ch("progress").notNull().default(0),parentId:cw("parent_id"),status:cw("status",{enum:["active","cancelled","archived","done"]}).notNull().default("active"),specId:cw("spec_id"),archivePath:cw("archive_path").notNull().default(""),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date),doneAt:ch("done_at",{mode:"timestamp"}),cancelledAt:ch("cancelled_at",{mode:"timestamp"}),archivedAt:ch("archived_at",{mode:"timestamp"}),reopenedAt:ch("reopened_at",{mode:"timestamp"})},a=>({wsIdx:di("goal_ws_idx").on(a.workspaceId)})),dD=cz("goal_file",{workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),goalId:cw("goal_id").notNull(),path:cw("path").notNull(),op:cw("op").notNull().default("edit"),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({pk:dj({columns:[a.goalId,a.path]})})),dE=cz("task",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),key:cw("key").notNull(),title:cw("title").notNull(),description:cw("description").notNull().default(""),col:cw("col",{enum:["triage","todo","doing","blocked","review","done"]}).notNull().default("triage"),prio:cw("prio",{enum:["low","med","high"]}).notNull().default("med"),assigneeId:cw("assignee_id").references(()=>du.id),goalId:cw("goal_id").references(()=>dC.id),issueId:cw("issue_id").references(()=>dH.id),createdBy:cw("created_by",{enum:["operator","agent"]}).notNull().default("operator"),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date)},a=>({wsIdx:di("task_ws_idx").on(a.workspaceId)})),dF=cz("task_step",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),taskId:cw("task_id").notNull().references(()=>dE.id,{onDelete:"cascade"}),text:cw("text").notNull(),done:ch("done",{mode:"boolean"}).notNull().default(!1),active:ch("active",{mode:"boolean"}).notNull().default(!1),ord:ch("ord").notNull().default(0),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date)},a=>({taskIdx:di("task_step_idx").on(a.taskId)})),dG=cz("spec",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),key:cw("key").notNull(),title:cw("title").notNull(),summary:cw("summary").notNull().default(""),authorId:cw("author_id").references(()=>du.id),body:cw("body").notNull().default(""),approved:ch("approved",{mode:"boolean"}).notNull().default(!1),goalId:cw("goal_id"),status:cw("status",{enum:["active","cancelled","archived"]}).notNull().default("active"),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date)}),dH=cz("issue",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),specId:cw("spec_id").references(()=>dG.id,{onDelete:"cascade"}),goalId:cw("goal_id"),key:cw("key").notNull(),title:cw("title").notNull(),prio:cw("prio",{enum:["low","med","high"]}).notNull().default("med"),col:cw("col",{enum:["todo","doing","blocked","review","done"]}).notNull().default("todo"),moscow:cw("moscow",{enum:["Must","Should","Could","Won't"]}),points:ch("points").notNull().default(0),assigneeId:cw("assignee_id").references(()=>du.id),approved:ch("approved",{mode:"boolean"}).notNull().default(!1),status:cw("status",{enum:["active","cancelled","archived"]}).notNull().default("active"),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date)}),dI=cz("plan",{workspaceId:cw("workspace_id").primaryKey().references(()=>dt.id,{onDelete:"cascade"}),approved:ch("approved",{mode:"boolean"}).notNull().default(!1),auto247:ch("auto_247",{mode:"boolean"}).notNull().default(!1),stage:ch("stage").notNull().default(4),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date),updatedAt:ch("updated_at",{mode:"timestamp"}).$defaultFn(()=>new Date).$onUpdateFn(()=>new Date)}),dJ=cz("report",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),title:cw("title").notNull(),type:cw("type").notNull().default("Report"),authorId:cw("author_id").references(()=>du.id),body:cw("body").notNull().default(""),goalId:cw("goal_id"),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)}),dK=cz("notification",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),kind:cw("kind").notNull().default("info"),text:cw("text").notNull(),detail:cw("detail").notNull().default(""),agentId:cw("agent_id").references(()=>du.id),messageId:cw("message_id"),channel:cw("channel").notNull().default(""),read:ch("read",{mode:"boolean"}).notNull().default(!1),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("notif_ws_idx").on(a.workspaceId)})),dL=cz("channel_read",{workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),channel:cw("channel").notNull(),lastReadAt:ch("last_read_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({pk:dj({columns:[a.workspaceId,a.channel]})})),dM=cz("budget",{workspaceId:cw("workspace_id").primaryKey().references(()=>dt.id,{onDelete:"cascade"}),monthlyCapUsd:cr("monthly_cap_usd").notNull().default(400),monthlySpentUsd:cr("monthly_spent_usd").notNull().default(0)}),dN=cz("cost_entry",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),agentId:cw("agent_id").references(()=>du.id),provider:cw("provider"),model:cw("model"),usd:cr("usd").notNull().default(0),tokens:ch("tokens").notNull().default(0),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("cost_ws_idx").on(a.workspaceId)})),dO=cz("message",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),channel:cw("channel").notNull().default("room"),fromKind:cw("from_kind",{enum:["operator","agent"]}).notNull(),fromHandle:cw("from_handle"),text:cw("text").notNull(),sources:cw("sources",{mode:"json"}).$type(),attachments:cw("attachments",{mode:"json"}).$type(),sessionId:cw("session_id"),taskId:cw("task_id"),kind:cw("kind"),blocks:cw("blocks",{mode:"json"}).$type(),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsChanIdx:di("msg_ws_chan_idx").on(a.workspaceId,a.channel)})),dP=cz("chat_session",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),channel:cw("channel").notNull(),title:cw("title").notNull().default("Session"),active:ch("active",{mode:"boolean"}).notNull().default(!1),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date)},a=>({wsChanIdx:di("chat_session_ws_chan_idx").on(a.workspaceId,a.channel)})),dQ=cz("event",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),runId:cw("run_id").notNull(),channel:cw("channel").notNull().default("room"),agentId:cw("agent_id").references(()=>du.id),seq:ch("seq").notNull(),kind:cw("kind").notNull(),target:cw("target").notNull().default(""),detail:cw("detail").notNull().default(""),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({chanIdx:di("event_chan_seq_idx").on(a.workspaceId,a.channel,a.seq),runIdx:di("event_run_idx").on(a.runId)})),dR=cz("deploy_run",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),status:cw("status").notNull().default("idle"),runId:cw("run_id").notNull().default(""),steps:cw("steps").notNull().default("[]"),summary:cw("summary").notNull().default(""),buildLog:cw("build_log").notNull().default(""),checklist:cw("checklist").notNull().default("[]"),lastExport:cw("last_export"),startedAt:ch("started_at",{mode:"timestamp"}),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("deploy_run_ws_idx").on(a.workspaceId)})),dS=cz("message_summary",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),channel:cw("channel").notNull(),sessionId:cw("session_id"),summary:cw("summary").notNull().default(""),throughId:cw("through_id").notNull().default(""),msgCount:ch("msg_count").notNull().default(0),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsChanIdx:di("msgsum_ws_chan_idx").on(a.workspaceId,a.channel)})),dT=cz("decision",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),goalId:cw("goal_id"),text:cw("text").notNull(),rationale:cw("rationale").notNull().default(""),by:cw("by").notNull().default(""),source:cw("source").notNull().default(""),refKey:cw("ref_key").notNull().default(""),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("decision_ws_idx").on(a.workspaceId,a.createdAt)})),dU=cz("file",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),path:cw("path").notNull(),lang:cw("lang").notNull().default("ts"),content:cw("content").notNull().default(""),gitStatus:cw("git_status",{enum:["","M","A","U","D"]}).notNull().default("")},a=>({wsPathIdx:di("file_ws_path_idx").on(a.workspaceId,a.path)})),dV=cz("routine",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),name:cw("name").notNull(),agentId:cw("agent_id").references(()=>du.id),cmd:cw("cmd").notNull().default(""),freq:cw("freq").notNull().default("Daily"),enabled:ch("enabled",{mode:"boolean"}).notNull().default(!0)}),dW=cz("cron_job",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),task:cw("task").notNull(),agentId:cw("agent_id").references(()=>du.id),at:cw("at").notNull().default("00:00")}),dX=cz("cron_run",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),task:cw("task").notNull(),agentId:cw("agent_id").references(()=>du.id),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),ok:ch("ok",{mode:"boolean"}).notNull().default(!0)}),dY=cz("finding",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),sev:cw("sev",{enum:["high","med","low"]}).notNull().default("med"),title:cw("title").notNull(),file:cw("file").notNull().default(""),suggestion:cw("suggestion").notNull().default(""),status:cw("status",{enum:["open","fixed"]}).notNull().default("open")}),dZ=cz("inbox_item",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),kind:cw("kind",{enum:["approval","budget","question","review","block","validation"]}).notNull().default("approval"),title:cw("title").notNull(),detail:cw("detail").notNull().default(""),fromAgentId:cw("from_agent_id").references(()=>du.id),resolved:ch("resolved",{mode:"boolean"}).notNull().default(!1),refType:cw("ref_type"),refId:cw("ref_id"),goalId:cw("goal_id"),channel:cw("channel"),messageId:cw("message_id"),createdAt:ch("created_at",{mode:"timestamp"}).$defaultFn(()=>new Date)}),d$=cz("plugin",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),name:cw("name").notNull(),description:cw("description").notNull().default(""),enabled:ch("enabled",{mode:"boolean"}).notNull().default(!1),native:ch("native",{mode:"boolean"}).notNull().default(!1)}),d_=cz("test_run",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),goalId:cw("goal_id"),issueId:cw("issue_id"),status:cw("status",{enum:["running","pass","fail","inconclusive"]}).notNull().default("running"),summary:cw("summary").notNull().default(""),findings:cw("findings").notNull().default("[]"),by:cw("by",{enum:["operator","agent"]}).notNull().default("operator"),startedAt:ch("started_at",{mode:"timestamp"}).$defaultFn(()=>new Date),finishedAt:ch("finished_at",{mode:"timestamp"})},a=>({wsIdx:di("test_run_ws_idx").on(a.workspaceId)})),d0=cz("activity",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),agentId:cw("agent_id").references(()=>du.id),action:cw("action").notNull(),target:cw("target").notNull().default(""),at:ch("at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("activity_ws_idx").on(a.workspaceId)})),d1=cz("backlog_item",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),title:cw("title").notNull(),moscow:cw("moscow",{enum:["Must","Should","Could","Won't"]}).notNull().default("Should"),points:ch("points").notNull().default(0),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("backlog_ws_idx").on(a.workspaceId)})),d2=cz("rag_chunk",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),path:cw("path").notNull(),chunk:cw("chunk").notNull(),vector:cw("vector"),kbEntryId:cw("kb_entry_id"),obsolete:ch("obsolete",{mode:"boolean"}).notNull().default(!1),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("rag_ws_idx").on(a.workspaceId,a.path)})),d3=cz("doc_index",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),kind:cw("kind",{enum:["docs","po"]}).notNull(),path:cw("path").notNull(),title:cw("title").notNull().default(""),summary:cw("summary").notNull().default(""),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("docidx_ws_path_idx").on(a.workspaceId,a.path)})),d4=cz("kb_entry",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),type:cw("type").notNull().default("note"),title:cw("title").notNull(),summary:cw("summary").notNull().default(""),body:cw("body").notNull().default(""),status:cw("status",{enum:["active","superseded","obsolete","archived"]}).notNull().default("active"),goalId:cw("goal_id"),specId:cw("spec_id"),issueId:cw("issue_id"),taskId:cw("task_id"),module:cw("module").notNull().default(""),paths:cw("paths",{mode:"json"}).$type(),agentHandle:cw("agent_handle").notNull().default(""),sourceKind:cw("source_kind").notNull().default(""),sourceRef:cw("source_ref").notNull().default(""),supersedesId:cw("supersedes_id"),hash:cw("hash").notNull().default(""),confidence:ch("confidence").notNull().default(70),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsTypeIdx:di("kb_ws_type_idx").on(a.workspaceId,a.type),wsGoalIdx:di("kb_ws_goal_idx").on(a.workspaceId,a.goalId)})),d5=cz("file_lock",{workspaceId:cw("workspace_id").notNull(),path:cw("path").notNull(),taskId:cw("task_id").notNull().default(""),agentId:cw("agent_id").notNull().default(""),agentHandle:cw("agent_handle").notNull().default(""),acquiredAt:ch("acquired_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),heartbeatAt:ch("heartbeat_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({pk:dj({columns:[a.workspaceId,a.path]})})),d6=cz("kb_query_log",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),agentHandle:cw("agent_handle").notNull().default(""),query:cw("query").notNull().default(""),hits:ch("hits").notNull().default(0),mode:cw("mode").notNull().default(""),refs:cw("refs",{mode:"json"}).$type(),answeredAt:ch("answered_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({wsIdx:di("kb_query_ws_idx").on(a.workspaceId,a.answeredAt)})),d7=cz("synced_block",{workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),slug:cw("slug").notNull(),kind:cw("kind").notNull().default("note"),title:cw("title").notNull().default(""),body:cw("body").notNull().default(""),version:ch("version").notNull().default(1),updatedBy:cw("updated_by").notNull().default(""),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),updatedAt:ch("updated_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({pk:dj({columns:[a.workspaceId,a.slug]})})),d8=cz("block_proposal",{id:cw("id").primaryKey(),workspaceId:cw("workspace_id").notNull().references(()=>dt.id,{onDelete:"cascade"}),slug:cw("slug").notNull(),kind:cw("kind").notNull().default("note"),title:cw("title").notNull().default(""),body:cw("body").notNull().default(""),byAgentHandle:cw("by_agent_handle").notNull().default(""),status:cw("status",{enum:["pending","merged","rejected"]}).notNull().default("pending"),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`),decidedAt:ch("decided_at",{mode:"timestamp"}),decidedBy:cw("decided_by").notNull().default("")},a=>({wsIdx:di("block_prop_ws_idx").on(a.workspaceId,a.status)})),d9=cz("notification_pref",{userId:cw("user_id").primaryKey().references(()=>dm.id,{onDelete:"cascade"}),email:ch("email",{mode:"boolean"}).notNull().default(!0),telegram:ch("telegram",{mode:"boolean"}).notNull().default(!0),inapp:ch("inapp",{mode:"boolean"}).notNull().default(!0),weekly:ch("weekly",{mode:"boolean"}).notNull().default(!1),reducedMotion:ch("reduced_motion",{mode:"boolean"}).notNull().default(!1)}),ea=cz("personal_access_token",{id:cw("id").primaryKey(),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),name:cw("name").notNull(),scope:cw("scope").notNull().default("read"),tokenHash:cw("token_hash").notNull(),prefix:cw("prefix").notNull(),lastUsedAt:ch("last_used_at",{mode:"timestamp"}),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({userIdx:di("pat_user_idx").on(a.userId)})),eb=cz("two_factor",{id:cw("id").primaryKey(),secret:cw("secret").notNull(),backupCodes:cw("backup_codes").notNull(),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"})},a=>({userIdx:di("twofactor_user_idx").on(a.userId)})),ec=cz("passkey",{id:cw("id").primaryKey(),userId:cw("user_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),name:cw("name").notNull().default("Passkey"),credentialId:cw("credential_id").notNull().unique(),publicKey:cw("public_key").notNull(),counter:ch("counter").notNull().default(0),deviceType:cw("device_type").notNull().default(""),backedUp:ch("backed_up",{mode:"boolean"}).notNull().default(!1),transports:cw("transports").notNull().default(""),createdAt:ch("created_at",{mode:"timestamp"}).notNull().default(aP`(unixepoch())`)},a=>({userIdx:di("passkey_user_idx").on(a.userId)})),ed=!1;function ee(){let a=process.cwd();return!process.env.INIT_CWD&&!ed&&/[\\/]\.next[\\/]standalone/.test(a)&&(ed=!0,console.warn("[runtime-root] INIT_CWD unset and cwd is inside .next/standalone — relative DATABASE_URL/CONSTELLA_HOME will resolve UNDER the standalone dir (separate DB!). Set absolute paths or launch via `pnpm start` (which sets INIT_CWD).")),process.env.INIT_CWD||a}function ef(a){return(0,de.isAbsolute)(a)?a:(0,de.resolve)(ee(),a)}let eg=ef((process.env.DATABASE_URL??"file:./.constella/constella.db").replace(/^file:/,""));(0,dd.mkdirSync)((0,de.dirname)(eg),{recursive:!0});let eh=new(bh())(eg);eh.pragma("journal_mode = WAL"),eh.pragma("foreign_keys = ON");let ei=dc(eh,{schema:W});var ej=c(22817),ek=c(15214);async function el(a,b){let d;if(a.database)d="function"==typeof a.database?a.database(a):await b(a);else{let b=Object.keys((0,ej.y)(a)).reduce((a,b)=>(a[b]=[],a),{}),{memoryAdapter:e}=await c.e(2599).then(c.bind(c,62599));d=e(b)(a)}return d.transaction||(ek.vF.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),d.transaction=async a=>a(d)),d}var em=c(9853);async function en(a){return el(a,async a=>{let{createKyselyAdapter:b}=await c.e(2549).then(c.bind(c,42549)),{kysely:d,databaseType:e,transaction:f}=await b(a);if(!d)throw new em.$l("Failed to initialize database adapter");let{kyselyAdapter:g}=await c.e(2549).then(c.bind(c,42549));return g(d,{type:e||"sqlite",debugLogs:!!a.database&&"debugLogs"in a.database&&a.database.debugLogs,transaction:f})(a)})}var eo=c(46404),ep=c(66351),eq=c(43876),er=c(80185);let es={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 et(a){try{let b=await (0,er.l)`SHOW search_path`.execute(a),c=b.rows[0]?.search_path??b.rows[0]?.searchPath;if(c)return c.split(",").map(a=>a.trim()).map(a=>a.replace(/^["']|["']$/g,"")).filter(a=>!a.startsWith("$")&&!a.startsWith("\\$"))[0]||"public"}catch{}return"public"}async function eu(a){let b=function(a){let b=(0,ej.y)(a),c={};for(let a in b){let d=b[a],e=d.fields,f={};if(Object.entries(e).forEach(([a,c])=>{if(f[c.fieldName||a]=c,c.references){let d=b[c.references.model];d&&(f[c.fieldName||a].references={...c.references,model:d.modelName,field:c.references.field})}}),c[d.modelName]){c[d.modelName].fields={...c[d.modelName].fields,...f};continue}c[d.modelName]={fields:f,order:d.order||1/0}}return c}(a),c=(0,ek.h)(a.logger),{kysely:d,databaseType:e}=await (0,eo.xA)(a);e||(c.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),e="sqlite"),d||(c.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 f="public";if("postgres"===e){f=await et(d),c.debug(`PostgreSQL migration: Using schema '${f}' (from search_path)`);try{let a=await (0,er.l)`
|
|
29
|
+
SELECT schema_name
|
|
30
|
+
FROM information_schema.schemata
|
|
31
|
+
WHERE schema_name = ${f}
|
|
32
|
+
`.execute(d);(a.rows[0]?.schema_name??a.rows[0]?.schemaName)||c.warn(`Schema '${f}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`)}catch(a){c.debug(`Could not verify schema existence: ${a instanceof Error?a.message:String(a)}`)}}let g=await d.introspection.getTables(),h=g;if("postgres"===e)try{let a=await (0,er.l)`
|
|
33
|
+
SELECT table_name
|
|
34
|
+
FROM information_schema.tables
|
|
35
|
+
WHERE table_schema = ${f}
|
|
36
|
+
AND table_type = 'BASE TABLE'
|
|
37
|
+
`.execute(d),b=new Set(a.rows.map(a=>a.table_name??a.tableName));h=g.filter(a=>a.schema===f&&b.has(a.name)),c.debug(`Found ${h.length} table(s) in schema '${f}': ${h.map(a=>a.name).join(", ")||"(none)"}`)}catch(a){c.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${a instanceof Error?a.message:String(a)}`)}let i=[],j=[];for(let[a,d]of Object.entries(b)){let b=h.find(b=>b.name===a);if(!b){let b=i.findIndex(b=>b.table===a),c={table:a,fields:d.fields,order:d.order||1/0},e=i.findIndex(a=>(a.order||1/0)>c.order);-1===e?-1===b?i.push(c):i[b].fields={...i[b].fields,...d.fields}:i.splice(e,0,c);continue}let f={};for(let[g,h]of Object.entries(d.fields)){let d=b.columns.find(a=>a.name===g);if(!d){f[g]=h;continue}!function(a,b,c){if("string[]"===b||"number[]"===b)return a.toLowerCase().includes("json");let d=es[c];return(Array.isArray(b)?d.string.map(a=>a.toLowerCase()):d[b].map(a=>a.toLowerCase())).includes(a.toLowerCase().split("(")[0].trim())}(d.dataType,h.type,e)&&c.warn(`Field ${g} in table ${a} has a different type in the database. Expected ${h.type} but got ${d.dataType}.`)}Object.keys(f).length>0&&j.push({table:a,fields:f,order:d.order||1/0})}let k=[],l=a.advanced?.database?.generateId==="uuid",m=a.advanced?.database?.generateId==="serial";function n(a,b){let c=a.type,d=e||"sqlite",f={string:{sqlite:"text",postgres:"text",mysql:a.unique?"varchar(255)":a.references?"varchar(36)":a.sortable||a.index?"varchar(255)":"text",mssql:a.unique||a.sortable?"varchar(255)":a.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:a.bigint?"bigint":"integer",postgres:a.bigint?"bigint":"integer",mysql:a.bigint?"bigint":"integer",mssql:a.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:(0,er.l)`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:m?(0,er.l)`integer GENERATED BY DEFAULT AS IDENTITY`:l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},foreignKeyId:{postgres:m?"integer":l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===b||a.references?.field==="id")return"id"===b?f.id[d]:f.foreignKeyId[d];if(Array.isArray(c))return"text";if(!(c in f))throw Error(`Unsupported field type '${String(c)}' for field '${b}'. 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 f[c][d]}let o=(0,ep.j)({schema:(0,ej.y)(a),usePlural:!1}),p=(0,eq.y)({schema:(0,ej.y)(a),usePlural:!1});function q(a,b){try{return`${o(a)}.${p({model:a,field:b})}`}catch{return`${a}.${b}`}}let r=[];if(j.length)for(let a of j)for(let[b,c]of Object.entries(a.fields)){let f=n(c,b),g=d.schema.alterTable(a.table);if(c.index){let e=`${a.table}_${b}_${c.unique?"uidx":"idx"}`,f=d.schema.createIndex(e).on(a.table).columns([b]);r.push(c.unique?f.unique():f)}let h=g.addColumn(b,f,a=>(a=!1!==c.required?a.notNull():a,c.references&&(a=a.references(q(c.references.model,c.references.field)).onDelete(c.references.onDelete||"cascade")),c.unique&&(a=a.unique()),"date"===c.type&&"function"==typeof c.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,er.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,er.l)`CURRENT_TIMESTAMP`)),a));k.push(h)}if(i.length)for(let a of i){let b=n({type:m?"number":"string"},"id"),c=d.schema.createTable(a.table).addColumn("id",b,a=>{if(m)return"postgres"===e?a.primaryKey().notNull():"sqlite"===e?a.primaryKey().notNull():"mssql"===e?a.identity().primaryKey().notNull():a.autoIncrement().primaryKey().notNull();return l&&"postgres"===e?a.primaryKey().defaultTo((0,er.l)`pg_catalog.gen_random_uuid()`).notNull():a.primaryKey().notNull()});for(let[b,f]of Object.entries(a.fields)){let g=n(f,b);if(c=c.addColumn(b,g,a=>(a=!1!==f.required?a.notNull():a,f.references&&(a=a.references(q(f.references.model,f.references.field)).onDelete(f.references.onDelete||"cascade")),f.unique&&(a=a.unique()),"date"===f.type&&"function"==typeof f.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,er.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,er.l)`CURRENT_TIMESTAMP`)),a)),f.index){let c=d.schema.createIndex(`${a.table}_${b}_${f.unique?"uidx":"idx"}`).on(a.table).columns([b]);r.push(f.unique?c.unique():c)}}k.push(c)}for(let a of r)k.push(a);return{toBeCreated:i,toBeAdded:j,runMigrations:async function(){for(let a of k)await a.execute()},compileMigrations:async function(){return k.map(a=>a.compile().sql).join(";\n\n")+";"}}}function ev(a){return"-"===a||"^"===a||"$"===a||"+"===a||"."===a||"("===a||")"===a||"|"===a||"["===a||"]"===a||"{"===a||"}"===a||"*"===a||"?"===a||"\\"===a?`\\${a}`:a}function ew(a,b){if("string"!=typeof b)throw TypeError(`Sample must be a string, but ${typeof b} given`);return a.test(b)}function ex(a,b){if("string"!=typeof a&&!Array.isArray(a))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof a} given`);if(("string"==typeof b||"boolean"==typeof b)&&(b={separator:b}),2==arguments.length&&!(void 0===b||"object"==typeof b&&null!==b&&!Array.isArray(b)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof b} given`);if("\\"===(b=b||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let c=function a(b,c=!0){if(Array.isArray(b))return`(?:${b.map(b=>`^${a(b,c)}$`).join("|")})`;let d="",e="",f=".";!0===c?(d="/",e="[/\\\\]",f="[^/\\\\]"):c&&((e=function(a){let b="";for(let c=0;c<a.length;c++)b+=ev(a[c]);return b}(d=c)).length>1?(e=`(?:${e})`,f=`((?!${e}).)`):f=`[^${e}]`);let g=c?`${e}+?`:"",h=c?`${e}*?`:"",i=c?b.split(d):[b],j="";for(let a=0;a<i.length;a++){let b=i[a],d=i[a+1],e="";if(b||!(a>0)){if(c&&(e=a===i.length-1?h:"**"!==d?g:""),c&&"**"===b){e&&(j+=0===a?"":e,j+=`(?:${f}*?${e})*?`);continue}for(let a=0;a<b.length;a++){let c=b[a];"\\"===c?a<b.length-1&&(j+=ev(b[a+1]),a++):"?"===c?j+=f:"*"===c?j+=`${f}*?`:j+=ev(c)}j+=e}}return j}(a,b.separator),d=RegExp(`^${c}$`,b.flags),e=ew.bind(null,d);return e.options=b,e.pattern=a,e.regexp=d,e}var ey=c(59310);function ez(a){let b=a.length;for(;b>0&&47===a.charCodeAt(b-1);)b--;return b===a.length?a:a.slice(0,b)}function eA(a,b="/api/auth"){try{let b=new URL(a);if("http:"!==b.protocol&&"https:"!==b.protocol)throw new em.$l(`Invalid base URL: ${a}. URL must include 'http://' or 'https://'`)}catch(b){if(b instanceof em.$l)throw b;throw new em.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`,{cause:b})}if(function(a){try{return"/"!==(ez(new URL(a).pathname)||"/")}catch{throw new em.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`)}}(a))return a;let c=ez(a);return b&&"/"!==b?(b=b.startsWith("/")?b:`/${b}`,`${c}${b}`):c}function eB(a,b){return!!a&&""!==a.trim()&&("proto"===b?"http"===a||"https"===a:"host"===b&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(b=>b.test(a))&&(/^[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(a)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(a)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(a)||/^localhost(:[0-9]{1,5})?$/i.test(a)))}function eC(a,b,c,d,e){if(a)return eA(a,b);if(!1!==d){let a=ey._K.BETTER_AUTH_URL||ey._K.NEXT_PUBLIC_BETTER_AUTH_URL||ey._K.PUBLIC_BETTER_AUTH_URL||ey._K.NUXT_PUBLIC_BETTER_AUTH_URL||ey._K.NUXT_PUBLIC_AUTH_URL||("/"!==ey._K.BASE_URL?ey._K.BASE_URL:void 0);if(a)return eA(a,b)}let f=c?.headers.get("x-forwarded-host"),g=c?.headers.get("x-forwarded-proto");if(f&&g&&e&&eB(g,"proto")&&eB(f,"host"))try{return eA(`${g}://${f}`,b)}catch(a){}if(c){let a=eD(c.url);if(!a)throw new em.$l("Could not get origin from request. Please provide a valid base URL.");return eA(a,b)}if("u">typeof window&&window.location)return eA(window.location.origin,b)}function eD(a){try{let b=new URL(a);return"null"===b.origin?null:b.origin}catch{return null}}function eE(a){return"object"==typeof a&&null!==a&&"allowedHosts"in a&&Array.isArray(a.allowedHosts)}function eF(a){return a instanceof Request||"object"==typeof a&&null!==a&&"[object Request]"===Object.prototype.toString.call(a)&&"string"==typeof a.url&&"object"==typeof a.headers&&null!==a.headers&&"function"==typeof a.headers.get}function eG(a,b){let c=eF(a)?a.headers:a;if(b){let a=c.get("x-forwarded-host");if(a&&eB(a,"host"))return a}let d=c.get("host");if(d&&eB(d,"host"))return d;if(eF(a))try{return new URL(a.url).host}catch{}return null}let eH=(a,b,c)=>{if(a.startsWith("/"))return!!c?.allowRelativePaths&&a.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(a);if(b.includes("*")||b.includes("?")){if(b.includes("://"))return ex(b)(eD(a)||a);let c=function(a){try{return new URL(a).host}catch{return null}}(a);return!!c&&ex(b)(c)}let d=function(a){try{return new URL(a).protocol}catch{return null}}(a);return"http:"!==d&&"https:"!==d&&d?a.startsWith(b):b===eD(a)};function eI(a){return!!a.database||!!a.secondaryStorage}function eJ(a){return!!a.database}function eK(a){return!!a&&("object"==typeof a||"function"==typeof a)&&"function"==typeof a.then}var eL=c(77598);function eM(a,b){return new Promise((c,d)=>{(0,eL.scrypt)(a.normalize("NFKC"),b,64,{N:16384,r:16,p:1,maxmem:0x4000000},(a,b)=>{a?d(a):c(b)})})}async function eN(a){let b=(0,eL.randomBytes)(16).toString("hex"),c=await eM(a,b);return`${b}:${c.toString("hex")}`}async function eO(a,b){let[c,d]=a.split(":");if(!c||!d)throw Error("Invalid password hash");return(await eM(b,c)).toString("hex")===d}let eP=async({hash:a,password:b})=>eO(a,b);function eQ(a,b=""){if("number"!=typeof a){let c=b&&`"${b}" `;throw TypeError(`${c}expected number, got ${typeof a}`)}if(!Number.isSafeInteger(a)||a<0){let c=b&&`"${b}" `;throw RangeError(`${c}expected integer >= 0, got ${a}`)}}function eR(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function eS(a){if("function"!=typeof a||"function"!=typeof a.create)throw TypeError("Hash must wrapped by utils.createHasher");if(eQ(a.outputLen),eQ(a.blockLen),a.outputLen<1)throw Error('"outputLen" must be >= 1');if(a.blockLen<1)throw Error('"blockLen" must be >= 1')}function eT(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function eU(a,b){eR(a,void 0,"digestInto() output");let c=b.outputLen;if(a.length<c)throw RangeError('"digestInto() output" expected to be of length >='+c)}function eV(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}function eW(a){return new DataView(a.buffer,a.byteOffset,a.byteLength)}function eX(a,b){return a<<32-b|a>>>b}class eY{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(a,b){if(eS(a),eR(b,void 0,"key"),this.iHash=a.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 c=this.blockLen,d=new Uint8Array(c);d.set(b.length>c?a.create().update(b).digest():b);for(let a=0;a<d.length;a++)d[a]^=54;this.iHash.update(d),this.oHash=a.create();for(let a=0;a<d.length;a++)d[a]^=106;this.oHash.update(d),eV(d)}update(a){return eT(this),this.iHash.update(a),this}digestInto(a){eT(this),eU(a,this),this.finished=!0;let b=a.subarray(0,this.outputLen);this.iHash.digestInto(b),this.oHash.update(b),this.oHash.digestInto(b),this.destroy()}digest(){let a=new Uint8Array(this.oHash.outputLen);return this.digestInto(a),a}_cloneInto(a){a||=Object.create(Object.getPrototypeOf(this),{});let{oHash:b,iHash:c,finished:d,destroyed:e,blockLen:f,outputLen:g}=this;return a.finished=d,a.destroyed=e,a.blockLen=f,a.outputLen=g,a.oHash=b._cloneInto(a.oHash),a.iHash=c._cloneInto(a.iHash),a}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let eZ=((k=(a,b,c)=>new eY(a,b).update(c).digest()).create=(a,b)=>new eY(a,b),k),e$=Uint8Array.of(0),e_=Uint8Array.of();class e0{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(a,b,c,d){this.blockLen=a,this.outputLen=b,this.padOffset=c,this.isLE=d,this.buffer=new Uint8Array(a),this.view=eW(this.buffer)}update(a){eT(this),eR(a);let{view:b,buffer:c,blockLen:d}=this,e=a.length;for(let f=0;f<e;){let g=Math.min(d-this.pos,e-f);if(g===d){let b=eW(a);for(;d<=e-f;f+=d)this.process(b,f);continue}c.set(a.subarray(f,f+g),this.pos),this.pos+=g,f+=g,this.pos===d&&(this.process(b,0),this.pos=0)}return this.length+=a.length,this.roundClean(),this}digestInto(a){eT(this),eU(a,this),this.finished=!0;let{buffer:b,view:c,blockLen:d,isLE:e}=this,{pos:f}=this;b[f++]=128,eV(this.buffer.subarray(f)),this.padOffset>d-f&&(this.process(c,0),f=0);for(let a=f;a<d;a++)b[a]=0;c.setBigUint64(d-8,BigInt(8*this.length),e),this.process(c,0);let g=eW(a),h=this.outputLen;if(h%4)throw Error("_sha2: outputLen must be aligned to 32bit");let i=h/4,j=this.get();if(i>j.length)throw Error("_sha2: outputLen bigger than state");for(let a=0;a<i;a++)g.setUint32(4*a,j[a],e)}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}_cloneInto(a){(a||=new this.constructor).set(...this.get());let{blockLen:b,buffer:c,length:d,finished:e,destroyed:f,pos:g}=this;return a.destroyed=f,a.finished=e,a.length=d,a.pos=g,d%b&&a.buffer.set(c),a}clone(){return this._cloneInto()}}let e1=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),e2=BigInt(0x100000000-1),e3=BigInt(32),e4=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]),e5=new Uint32Array(64);class e6 extends e0{constructor(a){super(64,a,8,!1)}get(){let{A:a,B:b,C:c,D:d,E:e,F:f,G:g,H:h}=this;return[a,b,c,d,e,f,g,h]}set(a,b,c,d,e,f,g,h){this.A=0|a,this.B=0|b,this.C=0|c,this.D=0|d,this.E=0|e,this.F=0|f,this.G=0|g,this.H=0|h}process(a,b){for(let c=0;c<16;c++,b+=4)e5[c]=a.getUint32(b,!1);for(let a=16;a<64;a++){let b=e5[a-15],c=e5[a-2],d=eX(b,7)^eX(b,18)^b>>>3,e=eX(c,17)^eX(c,19)^c>>>10;e5[a]=e+e5[a-7]+d+e5[a-16]|0}let{A:c,B:d,C:e,D:f,E:g,F:h,G:i,H:j}=this;for(let a=0;a<64;a++){var k,l,m,n;let b=j+(eX(g,6)^eX(g,11)^eX(g,25))+((k=g)&h^~k&i)+e4[a]+e5[a]|0,o=(eX(c,2)^eX(c,13)^eX(c,22))+((l=c)&(m=d)^l&(n=e)^m&n)|0;j=i,i=h,h=g,g=f+b|0,f=e,e=d,d=c,c=b+o|0}c=c+this.A|0,d=d+this.B|0,e=e+this.C|0,f=f+this.D|0,g=g+this.E|0,h=h+this.F|0,i=i+this.G|0,j=j+this.H|0,this.set(c,d,e,f,g,h,i,j)}roundClean(){eV(e5)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),eV(this.buffer)}}class e7 extends e6{A=0|e1[0];B=0|e1[1];C=0|e1[2];D=0|e1[3];E=0|e1[4];F=0|e1[5];G=0|e1[6];H=0|e1[7];constructor(){super(32)}}let e8=function(a,b=!1){let c=a.length,d=new Uint32Array(c),e=new Uint32Array(c);for(let f=0;f<c;f++){let{h:c,l:g}=function(a,b=!1){return b?{h:Number(a&e2),l:Number(a>>e3&e2)}:{h:0|Number(a>>e3&e2),l:0|Number(a&e2)}}(a[f],b);[d[f],e[f]]=[c,g]}return[d,e]}(["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(a=>BigInt(a))),e9=e8[0],fa=e8[1],fb=new Uint32Array(80),fc=new Uint32Array(80),fd=function(a,b={}){let c=(b,c)=>a(c).update(b).digest(),d=a(void 0);return c.outputLen=d.outputLen,c.blockLen=d.blockLen,c.canXOF=d.canXOF,c.create=b=>a(b),Object.assign(c,b),Object.freeze(c)}(()=>new e7,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),fe=new TextEncoder,ff=new TextDecoder;function fg(...a){let b=new Uint8Array(a.reduce((a,{length:b})=>a+b,0)),c=0;for(let d of a)b.set(d,c),c+=d.length;return b}function fh(a,b,c){if(b<0||b>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${b}`);a.set([b>>>24,b>>>16,b>>>8,255&b],c)}function fi(a){let b=Math.floor(a/0x100000000),c=new Uint8Array(8);return fh(c,b,0),fh(c,a%0x100000000,4),c}function fj(a){let b=new Uint8Array(4);return fh(b,a),b}function fk(a){let b=new Uint8Array(a.length);for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>127)throw TypeError("non-ASCII string encountered in encode()");b[c]=d}return b}function fl(a){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof a?a:ff.decode(a),{alphabet:"base64url"});let b=a;b instanceof Uint8Array&&(b=ff.decode(b)),b=b.replace(/-/g,"+").replace(/_/g,"/");try{var c=b;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(c);let a=atob(c),d=new Uint8Array(a.length);for(let b=0;b<a.length;b++)d[b]=a.charCodeAt(b);return d}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function fm(a){let b=a;return("string"==typeof b&&(b=fe.encode(b)),Uint8Array.prototype.toBase64)?b.toBase64({alphabet:"base64url",omitPadding:!0}):(function(a){if(Uint8Array.prototype.toBase64)return a.toBase64();let b=[];for(let c=0;c<a.length;c+=32768)b.push(String.fromCharCode.apply(null,a.subarray(c,c+32768)));return btoa(b.join(""))})(b).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class fn extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(a,b){super(a,b),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class fo extends fn{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class fp extends fn{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class fq extends fn{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class fr extends fn{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class fs extends fn{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(a="decryption operation failed",b){super(a,b)}}class ft extends fn{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class fu extends fn{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class fv extends fn{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class fw extends fn{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class fx extends fn{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class fy extends fn{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(a="no applicable key found in the JSON Web Key Set",b){super(a,b)}}class fz extends fn{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(a="multiple matching keys found in the JSON Web Key Set",b){super(a,b)}}class fA extends fn{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(a="request timed out",b){super(a,b)}}class fB extends fn{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(a="signature verification failed",b){super(a,b)}}let fC=(a,b="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${b} must be ${a}`);function fD(a,b){if(parseInt(a.hash.name.slice(4),10)!==b)throw fC(`SHA-${b}`,"algorithm.hash")}function fE(a,b){if(b&&!a.usages.includes(b))throw TypeError(`CryptoKey does not support this operation, its usages must include ${b}.`)}function fF(a,b,c){switch(b){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==a.algorithm.name)throw fC("AES-GCM");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw fC(c,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==a.algorithm.name)throw fC("AES-KW");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw fC(c,"algorithm.length");break}case"ECDH":switch(a.algorithm.name){case"ECDH":case"X25519":break;default:throw fC("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==a.algorithm.name)throw fC("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==a.algorithm.name)throw fC("RSA-OAEP");fD(a.algorithm,parseInt(b.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}fE(a,c)}function fG(a,b,...c){if((c=c.filter(Boolean)).length>2){let b=c.pop();a+=`one of type ${c.join(", ")}, or ${b}.`}else 2===c.length?a+=`one of type ${c[0]} or ${c[1]}.`:a+=`of type ${c[0]}.`;return null==b?a+=` Received ${b}`:"function"==typeof b&&b.name?a+=` Received function ${b.name}`:"object"==typeof b&&null!=b&&b.constructor?.name&&(a+=` Received an instance of ${b.constructor.name}`),a}let fH=(a,...b)=>fG("Key must be ",a,...b),fI=(a,b,...c)=>fG(`Key for the ${a} algorithm must be `,b,...c);function fJ(a,b){if(a.startsWith("RS")||a.startsWith("PS")){let{modulusLength:c}=b.algorithm;if("number"!=typeof c||c<2048)throw TypeError(`${a} requires key modulusLength to be 2048 bits or larger`)}}function fK(a,b){let c=`SHA-${a.slice(-3)}`;switch(a){case"HS256":case"HS384":case"HS512":return{hash:c,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:c,name:"RSA-PSS",saltLength:parseInt(a.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:c,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:c,name:"ECDSA",namedCurve:b.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:a};default:throw new fr(`alg ${a} is not supported either by JOSE or your javascript runtime`)}}async function fL(a,b,c){if(b instanceof Uint8Array){if(!a.startsWith("HS"))throw TypeError(fH(b,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",b,{hash:`SHA-${a.slice(-3)}`,name:"HMAC"},!1,[c])}switch(a){case"HS256":case"HS384":case"HS512":if("HMAC"!==b.algorithm.name)throw fC("HMAC");fD(b.algorithm,parseInt(a.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==b.algorithm.name)throw fC("RSASSA-PKCS1-v1_5");fD(b.algorithm,parseInt(a.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==b.algorithm.name)throw fC("RSA-PSS");fD(b.algorithm,parseInt(a.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==b.algorithm.name)throw fC("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let d;if(d=b.algorithm,d.name!==a)throw fC(a);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==b.algorithm.name)throw fC("ECDSA");let c=function(a){switch(a){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(a);if(b.algorithm.namedCurve!==c)throw fC(c,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return fE(b,c),b}async function fM(a,b,c){let d=await fL(a,b,"sign");return fJ(a,d),new Uint8Array(await crypto.subtle.sign(fK(a,d.algorithm),d,c))}async function fN(a,b,c,d){let e=await fL(a,b,"verify");fJ(a,e);let f=fK(a,e.algorithm);try{return await crypto.subtle.verify(f,e,c,d)}catch{return!1}}function fO(a){if("object"!=typeof a||null===a||"[object Object]"!==Object.prototype.toString.call(a))return!1;if(null===Object.getPrototypeOf(a))return!0;let b=a;for(;null!==Object.getPrototypeOf(b);)b=Object.getPrototypeOf(b);return Object.getPrototypeOf(a)===b}function fP(...a){let b,c=a.filter(Boolean);if(0===c.length||1===c.length)return!0;for(let a of c){let c=Object.keys(a);if(!b||0===b.size){b=new Set(c);continue}for(let a of c){if(b.has(a))return!1;b.add(a)}}return!0}let fQ=a=>fO(a)&&"string"==typeof a.kty;function fR(a){if(!fS(a))throw Error("CryptoKey instance expected")}let fS=a=>{if(a?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return a instanceof CryptoKey}catch{return!1}},fT=a=>a?.[Symbol.toStringTag]==="KeyObject",fU=a=>fS(a)||fT(a),fV=a=>a?.[Symbol.toStringTag],fW=(a,b,c)=>{if(void 0!==b.use){let a;switch(c){case"sign":case"verify":a="sig";break;case"encrypt":case"decrypt":a="enc"}if(b.use!==a)throw TypeError(`Invalid key for this operation, its "use" must be "${a}" when present`)}if(void 0!==b.alg&&b.alg!==a)throw TypeError(`Invalid key for this operation, its "alg" must be "${a}" when present`);if(Array.isArray(b.key_ops)){let d;switch(!0){case"sign"===c||"verify"===c:case"dir"===a:case a.includes("CBC-HS"):d=c;break;case a.startsWith("PBES2"):d="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(a):d=!a.includes("GCM")&&a.endsWith("KW")?"encrypt"===c?"wrapKey":"unwrapKey":c;break;case"encrypt"===c&&a.startsWith("RSA"):d="wrapKey";break;case"decrypt"===c:d=a.startsWith("RSA")?"unwrapKey":"deriveBits"}if(d&&b.key_ops?.includes?.(d)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${d}" when present`)}return!0};function fX(a,b,c){switch(a.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((a,b,c)=>{if(!(b instanceof Uint8Array)){if(fQ(b)){if("oct"===b.kty&&"string"==typeof b.k&&fW(a,b,c))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(!fU(b))throw TypeError(fI(a,b,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==b.type)throw TypeError(`${fV(b)} instances for symmetric algorithms must be of type "secret"`)}})(a,b,c);break;default:((a,b,c)=>{if(fQ(b))switch(c){case"decrypt":case"sign":if("oct"!==b.kty&&("AKP"===b.kty&&"string"==typeof b.priv||"string"==typeof b.d)&&fW(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==b.kty&&void 0===b.d&&void 0===b.priv&&fW(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!fU(b))throw TypeError(fI(a,b,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===b.type)throw TypeError(`${fV(b)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===b.type)switch(c){case"sign":throw TypeError(`${fV(b)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${fV(b)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===b.type)switch(c){case"verify":throw TypeError(`${fV(b)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${fV(b)} instances for asymmetric algorithm encryption must be of type "public"`)}})(a,b,c)}}function fY(a,b,c,d,e){let f;if(void 0!==e.crit&&d?.crit===void 0)throw new a('"crit" (Critical) Header Parameter MUST be integrity protected');if(!d||void 0===d.crit)return new Set;if(!Array.isArray(d.crit)||0===d.crit.length||d.crit.some(a=>"string"!=typeof a||0===a.length))throw new a('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let g of(f=void 0!==c?new Map([...Object.entries(c),...b.entries()]):b,d.crit)){if(!f.has(g))throw new fr(`Extension Header Parameter "${g}" is not recognized`);if(void 0===e[g])throw new a(`Extension Header Parameter "${g}" is missing`);if(f.get(g)&&void 0===d[g])throw new a(`Extension Header Parameter "${g}" MUST be integrity protected`)}return new Set(d.crit)}let fZ='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function f$(a){if(!a.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:b,keyUsages:c}=function(a){let b,c;switch(a.kty){case"AKP":switch(a.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":b={name:a.alg},c=a.priv?["sign"]:["verify"];break;default:throw new fr(fZ)}break;case"RSA":switch(a.alg){case"PS256":case"PS384":case"PS512":b={name:"RSA-PSS",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":b={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":b={name:"RSA-OAEP",hash:`SHA-${parseInt(a.alg.slice(-3),10)||1}`},c=a.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new fr(fZ)}break;case"EC":switch(a.alg){case"ES256":case"ES384":case"ES512":b={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[a.alg]},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:"ECDH",namedCurve:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new fr(fZ)}break;case"OKP":switch(a.alg){case"Ed25519":case"EdDSA":b={name:"Ed25519"},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new fr(fZ)}break;default:throw new fr('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:b,keyUsages:c}}(a),d={...a};return"AKP"!==d.kty&&delete d.alg,delete d.use,crypto.subtle.importKey("jwk",d,b,a.ext??(!a.d&&!a.priv),a.key_ops??c)}let f_="given KeyObject instance cannot be used for this algorithm",f0=async(a,b,c,d=!1)=>{let e=(f||=new WeakMap).get(a);if(e?.[c])return e[c];let g=await f$({...b,alg:c});return d&&Object.freeze(a),e?e[c]=g:f.set(a,{[c]:g}),g};async function f1(a,b){if(a instanceof Uint8Array||fS(a))return a;if(fT(a)){if("secret"===a.type)return a.export();if("toCryptoKey"in a&&"function"==typeof a.toCryptoKey)try{return((a,b)=>{let c,d=(f||=new WeakMap).get(a);if(d?.[b])return d[b];let e="public"===a.type,g=!!e;if("x25519"===a.asymmetricKeyType){switch(b){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(f_)}c=a.toCryptoKey(a.asymmetricKeyType,g,e?[]:["deriveBits"])}if("ed25519"===a.asymmetricKeyType){if("EdDSA"!==b&&"Ed25519"!==b)throw TypeError(f_);c=a.toCryptoKey(a.asymmetricKeyType,g,[e?"verify":"sign"])}switch(a.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(b!==a.asymmetricKeyType.toUpperCase())throw TypeError(f_);c=a.toCryptoKey(a.asymmetricKeyType,g,[e?"verify":"sign"])}if("rsa"===a.asymmetricKeyType){let d;switch(b){case"RSA-OAEP":d="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":d="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":d="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":d="SHA-512";break;default:throw TypeError(f_)}if(b.startsWith("RSA-OAEP"))return a.toCryptoKey({name:"RSA-OAEP",hash:d},g,e?["encrypt"]:["decrypt"]);c=a.toCryptoKey({name:b.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:d},g,[e?"verify":"sign"])}if("ec"===a.asymmetricKeyType){let d=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(a.asymmetricKeyDetails?.namedCurve);if(!d)throw TypeError(f_);let f={ES256:"P-256",ES384:"P-384",ES512:"P-521"};f[b]&&d===f[b]&&(c=a.toCryptoKey({name:"ECDSA",namedCurve:d},g,[e?"verify":"sign"])),b.startsWith("ECDH-ES")&&(c=a.toCryptoKey({name:"ECDH",namedCurve:d},g,e?[]:["deriveBits"]))}if(!c)throw TypeError(f_);return d?d[b]=c:f.set(a,{[b]:c}),c})(a,b)}catch(a){if(a instanceof TypeError)throw a}let c=a.export({format:"jwk"});return f0(a,c,b)}if(fQ(a))return a.k?fl(a.k):f0(a,a,b,!0);throw Error("unreachable")}let f2=Symbol();function f3(a,b){if(a)throw TypeError(`${b} can only be called once`)}function f4(a,b,c){try{return fl(a)}catch{throw new c(`Failed to base64url decode the ${b}`)}}async function f5(a,b){let c=`SHA-${a.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(c,b))}class f6{#av;#aw;#ax;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#av=a}setProtectedHeader(a){return f3(this.#aw,"setProtectedHeader"),this.#aw=a,this}setUnprotectedHeader(a){return f3(this.#ax,"setUnprotectedHeader"),this.#ax=a,this}async sign(a,b){let c,d,e,f;if(!this.#aw&&!this.#ax)throw new fu("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!fP(this.#aw,this.#ax))throw new fu("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let g={...this.#aw,...this.#ax},h=fY(fu,new Map([["b64",!0]]),b?.crit,this.#aw,g),i=!0;if(h.has("b64")&&"boolean"!=typeof(i=this.#aw.b64))throw new fu('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:j}=g;if("string"!=typeof j||!j)throw new fu('JWS "alg" (Algorithm) Header Parameter missing or invalid');fX(j,a,"sign"),i?d=fk(c=fm(this.#av)):(d=this.#av,c=""),this.#aw?f=fk(e=fm(JSON.stringify(this.#aw))):(e="",f=new Uint8Array);let k=fg(f,fk("."),d),l=await f1(a,j),m={signature:fm(await fM(j,l,k)),payload:c};return this.#ax&&(m.header=this.#ax),this.#aw&&(m.protected=e),m}}class f7{#ay;constructor(a){this.#ay=new f6(a)}setProtectedHeader(a){return this.#ay.setProtectedHeader(a),this}async sign(a,b){let c=await this.#ay.sign(a,b);if(void 0===c.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${c.protected}.${c.payload}.${c.signature}`}}let f8=a=>Math.floor(a.getTime()/1e3),f9=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ga(a){let b,c=f9.exec(a);if(!c||c[4]&&c[1])throw TypeError("Invalid time period format");let d=parseFloat(c[2]);switch(c[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":b=Math.round(d);break;case"minute":case"minutes":case"min":case"mins":case"m":b=Math.round(60*d);break;case"hour":case"hours":case"hr":case"hrs":case"h":b=Math.round(3600*d);break;case"day":case"days":case"d":b=Math.round(86400*d);break;case"week":case"weeks":case"w":b=Math.round(604800*d);break;default:b=Math.round(0x1e187e0*d)}return"-"===c[1]||"ago"===c[4]?-b:b}function gb(a,b){if(!Number.isFinite(b))throw TypeError(`Invalid ${a} input`);return b}let gc=a=>a.includes("/")?a.toLowerCase():`application/${a.toLowerCase()}`;function gd(a,b,c={}){var d,e;let f,g;try{f=JSON.parse(ff.decode(b))}catch{}if(!fO(f))throw new fv("JWT Claims Set must be a top-level JSON object");let{typ:h}=c;if(h&&("string"!=typeof a.typ||gc(a.typ)!==gc(h)))throw new fo('unexpected "typ" JWT header value',f,"typ","check_failed");let{requiredClaims:i=[],issuer:j,subject:k,audience:l,maxTokenAge:m}=c,n=[...i];for(let a of(void 0!==m&&n.push("iat"),void 0!==l&&n.push("aud"),void 0!==k&&n.push("sub"),void 0!==j&&n.push("iss"),new Set(n.reverse())))if(!(a in f))throw new fo(`missing required "${a}" claim`,f,a,"missing");if(j&&!(Array.isArray(j)?j:[j]).includes(f.iss))throw new fo('unexpected "iss" claim value',f,"iss","check_failed");if(k&&f.sub!==k)throw new fo('unexpected "sub" claim value',f,"sub","check_failed");if(l&&(d=f.aud,e="string"==typeof l?[l]:l,"string"==typeof d?!e.includes(d):!(Array.isArray(d)&&e.some(Set.prototype.has.bind(new Set(d))))))throw new fo('unexpected "aud" claim value',f,"aud","check_failed");switch(typeof c.clockTolerance){case"string":g=ga(c.clockTolerance);break;case"number":g=c.clockTolerance;break;case"undefined":g=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:o}=c,p=f8(o||new Date);if((void 0!==f.iat||m)&&"number"!=typeof f.iat)throw new fo('"iat" claim must be a number',f,"iat","invalid");if(void 0!==f.nbf){if("number"!=typeof f.nbf)throw new fo('"nbf" claim must be a number',f,"nbf","invalid");if(f.nbf>p+g)throw new fo('"nbf" claim timestamp check failed',f,"nbf","check_failed")}if(void 0!==f.exp){if("number"!=typeof f.exp)throw new fo('"exp" claim must be a number',f,"exp","invalid");if(f.exp<=p-g)throw new fp('"exp" claim timestamp check failed',f,"exp","check_failed")}if(m){let a=p-f.iat;if(a-g>("number"==typeof m?m:ga(m)))throw new fp('"iat" claim timestamp check failed (too far in the past)',f,"iat","check_failed");if(a<0-g)throw new fo('"iat" claim timestamp check failed (it should be in the past)',f,"iat","check_failed")}return f}class ge{#av;constructor(a){if(!fO(a))throw TypeError("JWT Claims Set MUST be an object");this.#av=structuredClone(a)}data(){return fe.encode(JSON.stringify(this.#av))}get iss(){return this.#av.iss}set iss(a){this.#av.iss=a}get sub(){return this.#av.sub}set sub(a){this.#av.sub=a}get aud(){return this.#av.aud}set aud(a){this.#av.aud=a}set jti(a){this.#av.jti=a}set nbf(a){"number"==typeof a?this.#av.nbf=gb("setNotBefore",a):a instanceof Date?this.#av.nbf=gb("setNotBefore",f8(a)):this.#av.nbf=f8(new Date)+ga(a)}set exp(a){"number"==typeof a?this.#av.exp=gb("setExpirationTime",a):a instanceof Date?this.#av.exp=gb("setExpirationTime",f8(a)):this.#av.exp=f8(new Date)+ga(a)}set iat(a){void 0===a?this.#av.iat=f8(new Date):a instanceof Date?this.#av.iat=gb("setIssuedAt",f8(a)):"string"==typeof a?this.#av.iat=gb("setIssuedAt",f8(new Date)+ga(a)):this.#av.iat=gb("setIssuedAt",a)}}class gf{#aw;#az;constructor(a={}){this.#az=new ge(a)}setIssuer(a){return this.#az.iss=a,this}setSubject(a){return this.#az.sub=a,this}setAudience(a){return this.#az.aud=a,this}setJti(a){return this.#az.jti=a,this}setNotBefore(a){return this.#az.nbf=a,this}setExpirationTime(a){return this.#az.exp=a,this}setIssuedAt(a){return this.#az.iat=a,this}setProtectedHeader(a){return this.#aw=a,this}async sign(a,b){let c=new f7(this.#az.data());if(c.setProtectedHeader(this.#aw),Array.isArray(this.#aw?.crit)&&this.#aw.crit.includes("b64")&&!1===this.#aw.b64)throw new fv("JWTs MUST NOT use unencoded payload");return c.sign(a,b)}}function gg(a,b){if(void 0!==b&&(!Array.isArray(b)||b.some(a=>"string"!=typeof a)))throw TypeError(`"${a}" option must be an array of strings`);if(b)return new Set(b)}async function gh(a,b,c){if(!fO(a))throw new fu("Flattened JWS must be an object");if(void 0===a.protected&&void 0===a.header)throw new fu('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==a.protected&&"string"!=typeof a.protected)throw new fu("JWS Protected Header incorrect type");if(void 0===a.payload)throw new fu("JWS Payload missing");if("string"!=typeof a.signature)throw new fu("JWS Signature missing or incorrect type");if(void 0!==a.header&&!fO(a.header))throw new fu("JWS Unprotected Header incorrect type");let d={};if(a.protected)try{let b=fl(a.protected);d=JSON.parse(ff.decode(b))}catch{throw new fu("JWS Protected Header is invalid")}if(!fP(d,a.header))throw new fu("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let e={...d,...a.header},f=fY(fu,new Map([["b64",!0]]),c?.crit,d,e),g=!0;if(f.has("b64")&&"boolean"!=typeof(g=d.b64))throw new fu('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:h}=e;if("string"!=typeof h||!h)throw new fu('JWS "alg" (Algorithm) Header Parameter missing or invalid');let i=c&&gg("algorithms",c.algorithms);if(i&&!i.has(h))throw new fq('"alg" (Algorithm) Header Parameter value not allowed');if(g){if("string"!=typeof a.payload)throw new fu("JWS Payload must be a string")}else if("string"!=typeof a.payload&&!(a.payload instanceof Uint8Array))throw new fu("JWS Payload must be a string or an Uint8Array instance");let j=!1;"function"==typeof b&&(b=await b(d,a),j=!0),fX(h,b,"verify");let k=fg(void 0!==a.protected?fk(a.protected):new Uint8Array,fk("."),"string"==typeof a.payload?g?fk(a.payload):fe.encode(a.payload):a.payload),l=f4(a.signature,"signature",fu),m=await f1(b,h);if(!await fN(h,m,l,k))throw new fB;let n={payload:g?f4(a.payload,"payload",fu):"string"==typeof a.payload?fe.encode(a.payload):a.payload};return(void 0!==a.protected&&(n.protectedHeader=d),void 0!==a.header&&(n.unprotectedHeader=a.header),j)?{...n,key:m}:n}async function gi(a,b,c){if(a instanceof Uint8Array&&(a=ff.decode(a)),"string"!=typeof a)throw new fu("Compact JWS must be a string or Uint8Array");let{0:d,1:e,2:f,length:g}=a.split(".");if(3!==g)throw new fu("Invalid Compact JWS");let h=await gh({payload:e,protected:d,signature:f},b,c),i={payload:h.payload,protectedHeader:h.protectedHeader};return"function"==typeof b?{...i,key:h.key}:i}async function gj(a,b,c){let d=await gi(a,b,c);if(d.protectedHeader.crit?.includes("b64")&&!1===d.protectedHeader.b64)throw new fv("JWTs MUST NOT use unencoded payload");let e={payload:gd(d.protectedHeader,d.payload,c),protectedHeader:d.protectedHeader};return"function"==typeof b?{...e,key:d.key}:e}async function gk(a){if(fT(a))if("secret"!==a.type)return a.export({format:"jwk"});else a=a.export();if(a instanceof Uint8Array)return{kty:"oct",k:fm(a)};if(!fS(a))throw TypeError(fH(a,"CryptoKey","KeyObject","Uint8Array"));if(!a.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:b,key_ops:c,alg:d,use:e,...f}=await crypto.subtle.exportKey("jwk",a);return"AKP"===f.kty&&(f.alg=d),f}async function gl(a){return gk(a)}let gm=(a,b)=>{if("string"!=typeof a||!a)throw new fw(`${b} missing or invalid`)};async function gn(a,b){let c,d;if(fQ(a))c=a;else if(fU(a))c=await gl(a);else throw TypeError(fH(a,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(b??="sha256")&&"sha384"!==b&&"sha512"!==b)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(c.kty){case"AKP":gm(c.alg,'"alg" (Algorithm) Parameter'),gm(c.pub,'"pub" (Public key) Parameter'),d={alg:c.alg,kty:c.kty,pub:c.pub};break;case"EC":gm(c.crv,'"crv" (Curve) Parameter'),gm(c.x,'"x" (X Coordinate) Parameter'),gm(c.y,'"y" (Y Coordinate) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x,y:c.y};break;case"OKP":gm(c.crv,'"crv" (Subtype of Key Pair) Parameter'),gm(c.x,'"x" (Public Key) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x};break;case"RSA":gm(c.e,'"e" (Exponent) Parameter'),gm(c.n,'"n" (Modulus) Parameter'),d={e:c.e,kty:c.kty,n:c.n};break;case"oct":gm(c.k,'"k" (Key Value) Parameter'),d={k:c.k,kty:c.kty};break;default:throw new fr('"kty" (Key Type) Parameter missing or unsupported')}let e=fk(JSON.stringify(d));return fm(await f5(b,e))}function go(a){switch(a){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 fr(`Unsupported JWE Algorithm: ${a}`)}}let gp=a=>crypto.getRandomValues(new Uint8Array(go(a)>>3));function gq(a,b){let c=a.byteLength<<3;if(c!==b)throw new ft(`Invalid Content Encryption Key length. Expected ${b} bits, got ${c} bits`)}function gr(a){switch(a){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 fr(`Unsupported JWE Algorithm: ${a}`)}}function gs(a,b){if(b.length<<3!==gr(a))throw new ft("Invalid Initialization Vector length")}async function gt(a,b,c){if(!(b instanceof Uint8Array))throw TypeError(fH(b,"Uint8Array"));let d=parseInt(a.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",b.subarray(d>>3),"AES-CBC",!1,[c]),macKey:await crypto.subtle.importKey("raw",b.subarray(0,d>>3),{hash:`SHA-${d<<1}`,name:"HMAC"},!1,["sign"]),keySize:d}}async function gu(a,b,c){return new Uint8Array((await crypto.subtle.sign("HMAC",a,b)).slice(0,c>>3))}async function gv(a,b,c,d,e){let{encKey:f,macKey:g,keySize:h}=await gt(a,c,"encrypt"),i=new Uint8Array(await crypto.subtle.encrypt({iv:d,name:"AES-CBC"},f,b)),j=fg(e,d,i,fi(e.length<<3));return{ciphertext:i,tag:await gu(g,j,h),iv:d}}async function gw(a,b){if(!(a instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(b instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let c={name:"HMAC",hash:"SHA-256"},d=await crypto.subtle.generateKey(c,!1,["sign"]),e=new Uint8Array(await crypto.subtle.sign(c,d,a)),f=new Uint8Array(await crypto.subtle.sign(c,d,b)),g=0,h=-1;for(;++h<32;)g|=e[h]^f[h];return 0===g}async function gx(a,b,c,d,e,f){let g,h,{encKey:i,macKey:j,keySize:k}=await gt(a,b,"decrypt"),l=fg(f,d,c,fi(f.length<<3)),m=await gu(j,l,k);try{g=await gw(e,m)}catch{}if(!g)throw new fs;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:d,name:"AES-CBC"},i,c))}catch{}if(!h)throw new fs;return h}async function gy(a,b,c,d,e){let f;c instanceof Uint8Array?f=await crypto.subtle.importKey("raw",c,"AES-GCM",!1,["encrypt"]):(fF(c,a,"encrypt"),f=c);let g=new Uint8Array(await crypto.subtle.encrypt({additionalData:e,iv:d,name:"AES-GCM",tagLength:128},f,b)),h=g.slice(-16);return{ciphertext:g.slice(0,-16),tag:h,iv:d}}async function gz(a,b,c,d,e,f){let g;b instanceof Uint8Array?g=await crypto.subtle.importKey("raw",b,"AES-GCM",!1,["decrypt"]):(fF(b,a,"decrypt"),g=b);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:f,iv:d,name:"AES-GCM",tagLength:128},g,fg(c,e)))}catch{throw new fs}}let gA="Unsupported JWE Content Encryption Algorithm";async function gB(a,b,c,d,e){if(!fS(c)&&!(c instanceof Uint8Array))throw TypeError(fH(c,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(d)gs(a,d);else d=crypto.getRandomValues(new Uint8Array(gr(a)>>3));switch(a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return c instanceof Uint8Array&&gq(c,parseInt(a.slice(-3),10)),gv(a,b,c,d,e);case"A128GCM":case"A192GCM":case"A256GCM":return c instanceof Uint8Array&&gq(c,parseInt(a.slice(1,4),10)),gy(a,b,c,d,e);default:throw new fr(gA)}}async function gC(a,b,c,d,e,f){if(!fS(b)&&!(b instanceof Uint8Array))throw TypeError(fH(b,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!d)throw new ft("JWE Initialization Vector missing");if(!e)throw new ft("JWE Authentication Tag missing");switch(gs(a,d),a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return b instanceof Uint8Array&&gq(b,parseInt(a.slice(-3),10)),gx(a,b,c,d,e,f);case"A128GCM":case"A192GCM":case"A256GCM":return b instanceof Uint8Array&&gq(b,parseInt(a.slice(1,4),10)),gz(a,b,c,d,e,f);default:throw new fr(gA)}}function gD(a,b){if(a.algorithm.length!==parseInt(b.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${b}`)}function gE(a,b,c){return a instanceof Uint8Array?crypto.subtle.importKey("raw",a,"AES-KW",!0,[c]):(fF(a,b,c),a)}async function gF(a,b,c){let d=await gE(b,a,"wrapKey");gD(d,a);let e=await crypto.subtle.importKey("raw",c,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",e,d,"AES-KW"))}async function gG(a,b,c){let d=await gE(b,a,"unwrapKey");gD(d,a);let e=await crypto.subtle.unwrapKey("raw",c,d,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",e))}function gH(a){return fg(fj(a.length),a)}async function gI(a,b,c){let d=b>>3,e=Math.ceil(d/32),f=new Uint8Array(32*e);for(let b=1;b<=e;b++){let d=new Uint8Array(4+a.length+c.length);d.set(fj(b),0),d.set(a,4),d.set(c,4+a.length);let e=await f5("sha256",d);f.set(e,(b-1)*32)}return f.slice(0,d)}async function gJ(a,b,c,d,e=new Uint8Array,f=new Uint8Array){var g;fF(a,"ECDH"),fF(b,"ECDH","deriveBits");let h=fg(gH(fk(c)),gH(e),gH(f),fj(d),new Uint8Array);return gI(new Uint8Array(await crypto.subtle.deriveBits({name:a.algorithm.name,public:a},b,"X25519"===(g=a).algorithm.name?256:Math.ceil(parseInt(g.algorithm.namedCurve.slice(-3),10)/8)<<3)),d,h)}function gK(a){switch(a.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===a.algorithm.name}}async function gL(a,b,c,d){if(!(a instanceof Uint8Array)||a.length<8)throw new ft("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(c)||1!==Math.sign(c))throw new ft("PBES2 Count Input must be a positive integer");let e=fg(fk(b),Uint8Array.of(0),a),f=parseInt(b.slice(13,16),10),g={hash:`SHA-${b.slice(8,11)}`,iterations:c,name:"PBKDF2",salt:e},h=await (d instanceof Uint8Array?crypto.subtle.importKey("raw",d,"PBKDF2",!1,["deriveBits"]):(fF(d,b,"deriveBits"),d));return new Uint8Array(await crypto.subtle.deriveBits(g,h,f))}async function gM(a,b,c,d=2048,e=crypto.getRandomValues(new Uint8Array(16))){let f=await gL(e,a,d,b);return{encryptedKey:await gF(a.slice(-6),f,c),p2c:d,p2s:fm(e)}}async function gN(a,b,c,d,e){let f=await gL(e,a,d,b);return gG(a.slice(-6),f,c)}let gO=a=>{switch(a){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new fr(`alg ${a} is not supported either by JOSE or your javascript runtime`)}};async function gP(a,b,c){return fF(b,a,"encrypt"),fJ(a,b),new Uint8Array(await crypto.subtle.encrypt(gO(a),b,c))}async function gQ(a,b,c){return fF(b,a,"decrypt"),fJ(a,b),new Uint8Array(await crypto.subtle.decrypt(gO(a),b,c))}async function gR(a,b,c){let d;if(!fO(a))throw TypeError("JWK must be an object");switch(b??=a.alg,d??=c?.extractable??a.ext,a.kty){case"oct":if("string"!=typeof a.k||!a.k)throw TypeError('missing "k" (Key Value) Parameter value');return fl(a.k);case"RSA":if("oth"in a&&void 0!==a.oth)throw new fr('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return f$({...a,alg:b,ext:d});case"AKP":if("string"!=typeof a.alg||!a.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==b&&b!==a.alg)throw TypeError("JWK alg and alg option value mismatch");return f$({...a,ext:d});case"EC":case"OKP":return f$({...a,alg:b,ext:d});default:throw new fr('Unsupported "kty" (Key Type) Parameter value')}}async function gS(a,b,c,d){let e=a.slice(0,7),f=await gB(e,c,b,d,new Uint8Array);return{encryptedKey:f.ciphertext,iv:fm(f.iv),tag:fm(f.tag)}}async function gT(a,b,c,d,e){return gC(a.slice(0,7),b,c,d,e,new Uint8Array)}let gU='Invalid or unsupported "alg" (JWE Algorithm) header value';function gV(a){if(void 0===a)throw new ft("JWE Encrypted Key missing")}async function gW(a,b,c,d,e){switch(a){case"dir":if(void 0!==c)throw new ft("Encountered unexpected JWE Encrypted Key");return b;case"ECDH-ES":if(void 0!==c)throw new ft("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e,f;if(!fO(d.epk))throw new ft('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(fR(b),!gK(b))throw new fr("ECDH with the provided key is not allowed or not supported by your javascript runtime");let g=await gR(d.epk,a);if(fR(g),void 0!==d.apu){if("string"!=typeof d.apu)throw new ft('JOSE Header "apu" (Agreement PartyUInfo) invalid');e=f4(d.apu,"apu",ft)}if(void 0!==d.apv){if("string"!=typeof d.apv)throw new ft('JOSE Header "apv" (Agreement PartyVInfo) invalid');f=f4(d.apv,"apv",ft)}let h=await gJ(g,b,"ECDH-ES"===a?d.enc:a,"ECDH-ES"===a?go(d.enc):parseInt(a.slice(-5,-2),10),e,f);if("ECDH-ES"===a)return h;return gV(c),gG(a.slice(-6),h,c)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return gV(c),fR(b),gQ(a,b,c);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let f;if(gV(c),"number"!=typeof d.p2c)throw new ft('JOSE Header "p2c" (PBES2 Count) missing or invalid');let g=e?.maxPBES2Count||1e4;if(d.p2c>g)throw new ft('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof d.p2s)throw new ft('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return f=f4(d.p2s,"p2s",ft),gN(a,b,c,d.p2c,f)}case"A128KW":case"A192KW":case"A256KW":return gV(c),gG(a,b,c);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(gV(c),"string"!=typeof d.iv)throw new ft('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof d.tag)throw new ft('JOSE Header "tag" (Authentication Tag) missing or invalid');return gT(a,b,c,f4(d.iv,"iv",ft),f4(d.tag,"tag",ft));default:throw new fr(gU)}}async function gX(a,b,c,d,e={}){let f,g,h;switch(a){case"dir":h=c;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i;if(fR(c),!gK(c))throw new fr("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:j,apv:k}=e;i=e.epk?await f1(e.epk,a):(await crypto.subtle.generateKey(c.algorithm,!0,["deriveBits"])).privateKey;let{x:l,y:m,crv:n,kty:o}=await gl(i),p=await gJ(c,i,"ECDH-ES"===a?b:a,"ECDH-ES"===a?go(b):parseInt(a.slice(-5,-2),10),j,k);if(g={epk:{x:l,crv:n,kty:o}},"EC"===o&&(g.epk.y=m),j&&(g.apu=fm(j)),k&&(g.apv=fm(k)),"ECDH-ES"===a){h=p;break}h=d||gp(b);let q=a.slice(-6);f=await gF(q,p,h);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":h=d||gp(b),fR(c),f=await gP(a,c,h);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{h=d||gp(b);let{p2c:i,p2s:j}=e;({encryptedKey:f,...g}=await gM(a,c,h,i,j));break}case"A128KW":case"A192KW":case"A256KW":h=d||gp(b),f=await gF(a,c,h);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{h=d||gp(b);let{iv:i}=e;({encryptedKey:f,...g}=await gS(a,c,h,i));break}default:throw new fr(gU)}return{cek:h,encryptedKey:f,parameters:g}}function gY(a){if(void 0===globalThis[a])throw new fr(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${a} API.`)}async function gZ(a){gY("CompressionStream");let b=new CompressionStream("deflate-raw"),c=b.writable.getWriter();c.write(a).catch(()=>{}),c.close().catch(()=>{});let d=[],e=b.readable.getReader();for(;;){let{value:a,done:b}=await e.read();if(b)break;d.push(a)}return fg(...d)}async function g$(a,b){gY("DecompressionStream");let c=new DecompressionStream("deflate-raw"),d=c.writable.getWriter();d.write(a).catch(()=>{}),d.close().catch(()=>{});let e=[],f=0,g=c.readable.getReader();for(;;){let{value:a,done:c}=await g.read();if(c)break;if(e.push(a),f+=a.byteLength,b!==1/0&&f>b)throw new ft("Decompressed plaintext exceeded the configured limit")}return fg(...e)}class g_{#aA;#aw;#aB;#ax;#aC;#aD;#aE;#aF;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#aA=a}setKeyManagementParameters(a){return f3(this.#aF,"setKeyManagementParameters"),this.#aF=a,this}setProtectedHeader(a){return f3(this.#aw,"setProtectedHeader"),this.#aw=a,this}setSharedUnprotectedHeader(a){return f3(this.#aB,"setSharedUnprotectedHeader"),this.#aB=a,this}setUnprotectedHeader(a){return f3(this.#ax,"setUnprotectedHeader"),this.#ax=a,this}setAdditionalAuthenticatedData(a){return this.#aC=a,this}setContentEncryptionKey(a){return f3(this.#aD,"setContentEncryptionKey"),this.#aD=a,this}setInitializationVector(a){return f3(this.#aE,"setInitializationVector"),this.#aE=a,this}async encrypt(a,b){let c,d,e,f,g,h;if(!this.#aw&&!this.#ax&&!this.#aB)throw new ft("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!fP(this.#aw,this.#ax,this.#aB))throw new ft("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let i={...this.#aw,...this.#ax,...this.#aB};if(fY(ft,new Map,b?.crit,this.#aw,i),void 0!==i.zip&&"DEF"!==i.zip)throw new fr('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==i.zip&&!this.#aw?.zip)throw new ft('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:j,enc:k}=i;if("string"!=typeof j||!j)throw new ft('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof k||!k)throw new ft('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#aD&&("dir"===j||"ECDH-ES"===j))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${j}`);fX("dir"===j?k:j,a,"encrypt");{let e,f=await f1(a,j);({cek:d,encryptedKey:c,parameters:e}=await gX(j,k,f,this.#aD,this.#aF)),e&&(b&&f2 in b?this.#ax?this.#ax={...this.#ax,...e}:this.setUnprotectedHeader(e):this.#aw?this.#aw={...this.#aw,...e}:this.setProtectedHeader(e))}if(this.#aw?g=fk(f=fm(JSON.stringify(this.#aw))):(f="",g=new Uint8Array),this.#aC){let a=fk(h=fm(this.#aC));e=fg(g,fk("."),a)}else e=g;let l=this.#aA;"DEF"===i.zip&&(l=await gZ(l).catch(a=>{throw new ft("Failed to compress plaintext",{cause:a})}));let{ciphertext:m,tag:n,iv:o}=await gB(k,l,d,this.#aE,e),p={ciphertext:fm(m)};return o&&(p.iv=fm(o)),n&&(p.tag=fm(n)),c&&(p.encrypted_key=fm(c)),h&&(p.aad=h),this.#aw&&(p.protected=f),this.#aB&&(p.unprotected=this.#aB),this.#ax&&(p.header=this.#ax),p}}class g0{#ay;constructor(a){this.#ay=new g_(a)}setContentEncryptionKey(a){return this.#ay.setContentEncryptionKey(a),this}setInitializationVector(a){return this.#ay.setInitializationVector(a),this}setProtectedHeader(a){return this.#ay.setProtectedHeader(a),this}setKeyManagementParameters(a){return this.#ay.setKeyManagementParameters(a),this}async encrypt(a,b){let c=await this.#ay.encrypt(a,b);return[c.protected,c.encrypted_key,c.iv,c.ciphertext,c.tag].join(".")}}class g1{#aD;#aE;#aF;#aw;#aG;#aH;#aI;#az;constructor(a={}){this.#az=new ge(a)}setIssuer(a){return this.#az.iss=a,this}setSubject(a){return this.#az.sub=a,this}setAudience(a){return this.#az.aud=a,this}setJti(a){return this.#az.jti=a,this}setNotBefore(a){return this.#az.nbf=a,this}setExpirationTime(a){return this.#az.exp=a,this}setIssuedAt(a){return this.#az.iat=a,this}setProtectedHeader(a){return f3(this.#aw,"setProtectedHeader"),this.#aw=a,this}setKeyManagementParameters(a){return f3(this.#aF,"setKeyManagementParameters"),this.#aF=a,this}setContentEncryptionKey(a){return f3(this.#aD,"setContentEncryptionKey"),this.#aD=a,this}setInitializationVector(a){return f3(this.#aE,"setInitializationVector"),this.#aE=a,this}replicateIssuerAsHeader(){return this.#aG=!0,this}replicateSubjectAsHeader(){return this.#aH=!0,this}replicateAudienceAsHeader(){return this.#aI=!0,this}async encrypt(a,b){let c=new g0(this.#az.data());return this.#aw&&(this.#aG||this.#aH||this.#aI)&&(this.#aw={...this.#aw,iss:this.#aG?this.#az.iss:void 0,sub:this.#aH?this.#az.sub:void 0,aud:this.#aI?this.#az.aud:void 0}),c.setProtectedHeader(this.#aw),this.#aE&&c.setInitializationVector(this.#aE),this.#aD&&c.setContentEncryptionKey(this.#aD),this.#aF&&c.setKeyManagementParameters(this.#aF),c.encrypt(a,b)}}function g2(a){let b;if("string"==typeof a){let c=a.split(".");(3===c.length||5===c.length)&&([b]=c)}else if("object"==typeof a&&a)if("protected"in a)b=a.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof b||!b)throw Error();let a=JSON.parse(ff.decode(fl(b)));if(!fO(a))throw Error();return a}catch{throw TypeError("Invalid Token or Protected Header formatting")}}async function g3(a,b,c){let d,e,f,g,h,i;if(!fO(a))throw new ft("Flattened JWE must be an object");if(void 0===a.protected&&void 0===a.header&&void 0===a.unprotected)throw new ft("JOSE Header missing");if(void 0!==a.iv&&"string"!=typeof a.iv)throw new ft("JWE Initialization Vector incorrect type");if("string"!=typeof a.ciphertext)throw new ft("JWE Ciphertext missing or incorrect type");if(void 0!==a.tag&&"string"!=typeof a.tag)throw new ft("JWE Authentication Tag incorrect type");if(void 0!==a.protected&&"string"!=typeof a.protected)throw new ft("JWE Protected Header incorrect type");if(void 0!==a.encrypted_key&&"string"!=typeof a.encrypted_key)throw new ft("JWE Encrypted Key incorrect type");if(void 0!==a.aad&&"string"!=typeof a.aad)throw new ft("JWE AAD incorrect type");if(void 0!==a.header&&!fO(a.header))throw new ft("JWE Shared Unprotected Header incorrect type");if(void 0!==a.unprotected&&!fO(a.unprotected))throw new ft("JWE Per-Recipient Unprotected Header incorrect type");if(a.protected)try{let b=fl(a.protected);d=JSON.parse(ff.decode(b))}catch{throw new ft("JWE Protected Header is invalid")}if(!fP(d,a.header,a.unprotected))throw new ft("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let j={...d,...a.header,...a.unprotected};if(fY(ft,new Map,c?.crit,d,j),void 0!==j.zip&&"DEF"!==j.zip)throw new fr('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==j.zip&&!d?.zip)throw new ft('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:k,enc:l}=j;if("string"!=typeof k||!k)throw new ft("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof l||!l)throw new ft("missing JWE Encryption Algorithm (enc) in JWE Header");let m=c&&gg("keyManagementAlgorithms",c.keyManagementAlgorithms),n=c&&gg("contentEncryptionAlgorithms",c.contentEncryptionAlgorithms);if(m&&!m.has(k)||!m&&k.startsWith("PBES2"))throw new fq('"alg" (Algorithm) Header Parameter value not allowed');if(n&&!n.has(l))throw new fq('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==a.encrypted_key&&(e=f4(a.encrypted_key,"encrypted_key",ft));let o=!1;"function"==typeof b&&(b=await b(d,a),o=!0),fX("dir"===k?l:k,b,"decrypt");let p=await f1(b,k);try{f=await gW(k,p,e,j,c)}catch(a){if(a instanceof TypeError||a instanceof ft||a instanceof fr)throw a;f=gp(l)}void 0!==a.iv&&(g=f4(a.iv,"iv",ft)),void 0!==a.tag&&(h=f4(a.tag,"tag",ft));let q=void 0!==a.protected?fk(a.protected):new Uint8Array;i=void 0!==a.aad?fg(q,fk("."),fk(a.aad)):q;let r=f4(a.ciphertext,"ciphertext",ft),s=await gC(l,f,r,g,h,i),t={plaintext:s};if("DEF"===j.zip){let a=c?.maxDecompressedLength??25e4;if(0===a)throw new fr('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(a!==1/0&&(!Number.isSafeInteger(a)||a<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");t.plaintext=await g$(s,a).catch(a=>{if(a instanceof ft)throw a;throw new ft("Failed to decompress plaintext",{cause:a})})}return(void 0!==a.protected&&(t.protectedHeader=d),void 0!==a.aad&&(t.additionalAuthenticatedData=f4(a.aad,"aad",ft)),void 0!==a.unprotected&&(t.sharedUnprotectedHeader=a.unprotected),void 0!==a.header&&(t.unprotectedHeader=a.header),o)?{...t,key:p}:t}async function g4(a,b,c){if(a instanceof Uint8Array&&(a=ff.decode(a)),"string"!=typeof a)throw new ft("Compact JWE must be a string or Uint8Array");let{0:d,1:e,2:f,3:g,4:h,length:i}=a.split(".");if(5!==i)throw new ft("Invalid Compact JWE");let j=await g3({ciphertext:g,iv:f||void 0,protected:d,tag:h||void 0,encrypted_key:e||void 0},b,c),k={plaintext:j.plaintext,protectedHeader:j.protectedHeader};return"function"==typeof b?{...k,key:j.key}:k}async function g5(a,b,c){let d=await g4(a,b,c),e=gd(d.protectedHeader,d.plaintext,c),{protectedHeader:f}=d;if(void 0!==f.iss&&f.iss!==e.iss)throw new fo('replicated "iss" claim header parameter mismatch',e,"iss","mismatch");if(void 0!==f.sub&&f.sub!==e.sub)throw new fo('replicated "sub" claim header parameter mismatch',e,"sub","mismatch");if(void 0!==f.aud&&JSON.stringify(f.aud)!==JSON.stringify(e.aud))throw new fo('replicated "aud" claim header parameter mismatch',e,"aud","mismatch");let g={payload:e,protectedHeader:f};return"function"==typeof b?{...g,key:d.key}:g}async function g6(a,b,c=3600){return await new gf(a).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+c).sign(new TextEncoder().encode(b))}async function g7(a,b){try{return(await gj(a,new TextEncoder().encode(b))).payload}catch{return null}}let g8=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]),g9="A256CBC-HS512";function ha(a,b){var c,d,e;return c=new TextEncoder().encode(a),d=new TextEncoder().encode(b),function(a,b,c,d=32){eS(a),eQ(d,"length"),eR(b,void 0,"prk");let e=a.outputLen;if(b.length<e)throw Error('"prk" must be at least HashLen octets');if(d>255*e)throw Error("Length must be <= 255*HashLen");let f=Math.ceil(d/e);void 0===c?c=e_:eR(c,void 0,"info");let g=new Uint8Array(f*e),h=eZ.create(a,b),i=h._cloneInto(),j=new Uint8Array(h.outputLen);for(let a=0;a<f;a++)e$[0]=a+1,i.update(0===a?e_:j).update(c).update(e$).digestInto(j),g.set(j,e*a),h._cloneInto(i);return h.destroy(),i.destroy(),eV(j,e$),g.slice(0,d)}(fd,(e=d,eS(fd),void 0===e&&(e=new Uint8Array(fd.outputLen)),eZ(fd,e,c)),g8,64)}function hb(a){if("string"==typeof a)return[{version:0,value:a}];let b=[];for(let[c,d]of a.keys)b.push({version:c,value:d});return a.legacySecret&&!b.some(b=>b.value===a.legacySecret)&&b.push({version:-1,value:a.legacySecret}),b}async function hc(a,b,c,d=3600){let e=ha(function(a){if("string"==typeof a)return a;let b=a.keys.get(a.currentVersion);if(!b)throw Error(`Secret version ${a.currentVersion} not found in keys`);return b}(b),c),f=await gn({kty:"oct",k:fm(e)},"sha256");return await new g1(a).setProtectedHeader({alg:"dir",enc:g9,kid:f}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+d).setJti(crypto.randomUUID()).encrypt(e)}let hd={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[g9,"A256GCM"]};async function he(a,b,c){if(!a)return null;let d=!1;try{d=void 0!==g2(a).kid}catch{return null}try{let d=hb(b),{payload:e}=await g5(a,async a=>{let b=a.kid;if(void 0!==b){for(let a of d){let d=ha(a.value,c);if(b===await gn({kty:"oct",k:fm(d)},"sha256"))return d}throw Error("no matching decryption secret")}return d.length,ha(d[0].value,c)},hd);return e}catch{if(d)return null;let e=hb(b);if(e.length<=1)return null;for(let b=1;b<e.length;b++)try{let d=e[b],{payload:f}=await g5(a,ha(d.value,c),hd);return f}catch{continue}return null}}function hf(a){return Object.fromEntries(Object.entries(a).map(([a,b])=>[a,{code:a,message:b,toString:()=>a}]))}let hg=hf({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CHANGE_EMAIL_DISABLED:"Change email is disabled",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"});function hh(a,b){if(!a||!b)return a;let c=Object.entries(b).filter(([,{returned:a}])=>!1===a).map(([a])=>a);return Object.entries(structuredClone(a)).filter(([a])=>!c.includes(a)).reduce((a,[b,c])=>({...a,[b]:c}),{})}let hi=new WeakMap;function hj(a,b,c){let d=`${b}:${c}`;hi.has(a)||hi.set(a,new Map);let e=hi.get(a);if(e.has(d))return e.get(d);let f="output"===c?(0,ej.y)(a)[b]?.fields??{}:{},g="user"===b||"session"===b||"account"===b?a[b]?.additionalFields:void 0,h={...f,...g??{}};for(let c of a.plugins||[])c.schema&&c.schema[b]&&(h={...h,...c.schema[b].fields});return e.set(d,h),h}function hk(a,b){return hh(b,hj(a,"user","output"))}function hl(a,b){let c=hj(a,"user","output"),d={};for(let a in c){let e=c[a];!1!==e.returned&&(a in b&&void 0!==b[a]?d[a]=b[a]:void 0!==e.defaultValue?d[a]="function"==typeof e.defaultValue?e.defaultValue():e.defaultValue:e.required||(d[a]=null))}return"id"in b&&(d.id=b.id),d}function hm(a,b){return hh(b,hj(a,"session","output"))}function hn(a,b){let c=b.action||"create",d=b.fields,e=Object.create(null);for(let b in d){if(b in a){if(!1===d[b].input){if(void 0!==d[b].defaultValue&&"update"!==c){e[b]=d[b].defaultValue;continue}if(a[b])throw em.LG.from("BAD_REQUEST",{...hg.FIELD_NOT_ALLOWED,message:`${b} is not allowed to be set`});continue}if(d[b].validator?.input&&void 0!==a[b]){let c=d[b].validator.input["~standard"].validate(a[b]);if(c instanceof Promise)throw em.LG.from("INTERNAL_SERVER_ERROR",hg.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in c&&c.issues)throw em.LG.from("BAD_REQUEST",{...hg.VALIDATION_ERROR,message:c.issues[0]?.message||"Validation Error"});e[b]=c.value;continue}if(d[b].transform?.input&&void 0!==a[b]){e[b]=d[b].transform?.input(a[b]);continue}e[b]=a[b];continue}if(void 0!==d[b].defaultValue&&"create"===c){if("function"==typeof d[b].defaultValue){e[b]=d[b].defaultValue();continue}e[b]=d[b].defaultValue;continue}if(d[b].required&&"create"===c)throw em.LG.from("BAD_REQUEST",{...hg.MISSING_FIELD,message:`${b} is required`})}return e}function ho(a,b={},c){return hn(b,{fields:hj(a,"user","input"),action:c})}let hp=(a,b="ms")=>new Date(Date.now()+("sec"===b?1e3*a:a)),hq=/^(\+|\-)? ?(\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;function hr(a){if(-1===a.indexOf("%"))return a;try{return decodeURIComponent(a)}catch{return a}}function hs(a){if(!a)return[];let b=[],c=0,d=0;for(;d<a.length;){if(","===a[d]){let e=d+1;for(;e<a.length&&" "===a[e];)e++;for(;e<a.length&&"="!==a[e]&&";"!==a[e]&&","!==a[e];)e++;if(e<a.length&&"="===a[e]){let e=a.slice(c,d).trim();for(e&&b.push(e),c=d+1;c<a.length&&" "===a[c];)c++;d=c;continue}}d++}let e=a.slice(c).trim();return e&&b.push(e),b}let ht=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,hu=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function hv(a){return!(a.length<2)&&a.startsWith('"')&&a.endsWith('"')?a.slice(1,-1):a}function hw(a){let b=0,c=a.length;for(;b<c;){let c=a.charCodeAt(b);if(32!==c&&9!==c)break;b++}for(;c>b;){let b=a.charCodeAt(c-1);if(32!==b&&9!==b)break;c--}return 0===b&&c===a.length?a:a.slice(b,c)}function hx(a){let b=new Map;if(a.length<2)return b;for(let c of a.split(";")){let a=c.indexOf("=");if(-1===a)continue;let d=hw(c.slice(0,a)),e=hv(hw(c.slice(a+1)));ht.test(d)&&hu.test(e)&&b.set(d,hr(e))}return b}var hy=c(1434),hz=c(61793);let hA=/^application\/([a-z0-9.+-]*\+)?json/i;async function hB(a,b){let c=a.headers.get("content-type")||"",d=c.toLowerCase();if(a.body){if(b&&b.length>0&&!b.some(a=>{let b=d.split(";")[0].trim(),c=a.toLowerCase().trim();return b===c||b.includes(c)})){if(!d)throw new hz.LG(415,{message:`Content-Type is required. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new hz.LG(415,{message:`Content-Type "${c}" is not allowed. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(hA.test(d))try{return await a.json()}catch(a){if(a instanceof SyntaxError)throw new hz.LG(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw a}if(d.includes("application/x-www-form-urlencoded")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a.toString()}),c}if(d.includes("multipart/form-data")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a}),c}return d.includes("text/plain")?await a.text():d.includes("application/octet-stream")?await a.arrayBuffer():d.includes("application/pdf")||d.includes("image/")||d.includes("video/")?await a.blob():d.includes("application/stream")||a.body instanceof ReadableStream?a.body:await a.text()}}function hC(a){return a instanceof hz.LG||a?.name==="APIError"}async function hD(a){try{return{data:await a,error:null}}catch(a){return{data:null,error:a}}}function hE(a){return a instanceof Request||"[object Request]"===Object.prototype.toString.call(a)}let hF=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 hG(a){for(let b of hF)a.delete(b)}function hH(a,b){if(b)for(let[c,d]of new Headers(b).entries())"set-cookie"===c.toLowerCase()?a.append(c,d):a.set(c,d)}function hI(a,b){if(a instanceof Response){if(b?.headers){let c=new Headers(b.headers);hG(c),hH(a.headers,c)}return a}if(a&&"object"==typeof a&&"_flag"in a&&"json"===a._flag){let c=a.body,d=a.routerResponse;if(d instanceof Response)return d;let e=new Headers;if(hH(e,d?.headers),hH(e,a.headers),b?.headers){let a=new Headers(b.headers);hG(a),hH(e,a)}return e.set("Content-Type","application/json"),new Response(JSON.stringify(c),{...d,headers:e,status:a.status??b?.status??d?.status,statusText:b?.statusText??d?.statusText})}if(hC(a))return hI(a.body,{status:b?.status??a.statusCode,statusText:a.status.toString(),headers:b?.headers||a.headers});let c=a,d=new Headers(b?.headers);if(hG(d),a){if("string"==typeof a)c=a,d.set("Content-Type","text/plain");else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))c=a,d.set("Content-Type","application/octet-stream");else if(a instanceof Blob)c=a,d.set("Content-Type",a.type||"application/octet-stream");else if(a instanceof FormData)c=a;else if(a instanceof URLSearchParams)c=a,d.set("Content-Type","application/x-www-form-urlencoded");else if(a instanceof ReadableStream)c=a,d.set("Content-Type","application/octet-stream");else if(function(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}(a)){let b,e,f;b=new WeakMap,e=new WeakMap,f=0,c=JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("object"==typeof c&&null!==c){if(((a,c)=>{let d=c;for(;d;){if(d===a)return!0;d=b.get(d)}return!1})(c,this))return`[Circular ref-${e.get(c)}]`;b.set(c,this),e.has(c)||e.set(c,f++)}return c}),d.set("Content-Type","application/json")}}else null===a&&(c=JSON.stringify(null)),d.set("content-type","application/json");return new Response(c,{...b,headers:d})}function hJ(){let a="u">typeof globalThis&&globalThis.crypto;if(a&&"object"==typeof a.subtle&&null!=a.subtle)return a.subtle;throw Error("crypto.subtle must be defined")}let hK={name:"HMAC",hash:"SHA-256"},hL=async a=>{let b="string"==typeof a?new TextEncoder().encode(a):a;return await hJ().importKey("raw",b,hK,!1,["sign","verify"])},hM=async(a,b,c)=>{try{let d=atob(a),e=new Uint8Array(d.length);for(let a=0,b=d.length;a<b;a++)e[a]=d.charCodeAt(a);return await hJ().verify(hK,c,e,new TextEncoder().encode(b))}catch(a){return!1}},hN=async(a,b)=>{let c=await hL(b);return btoa(String.fromCharCode(...new Uint8Array(await hJ().sign(hK.name,c,new TextEncoder().encode(a)))))},hO=async(a,b)=>{let c=await hN(a,b);return encodeURIComponent(a=`${a}.${c}`)},hP=(a,b)=>{let c=a;if(b)if("secure"===b)c="__Secure-"+a;else{if("host"!==b)return;c="__Host-"+a}return c},hQ=(a,b,c={})=>{let d;if(d=c?.prefix==="secure"?`__Secure-${a}=${b}`:c?.prefix==="host"?`__Host-${a}=${b}`:`${a}=${b}`,a.startsWith("__Secure-")&&!c.secure&&(c.secure=!0),a.startsWith("__Host-")&&(c.secure||(c.secure=!0),"/"!==c.path&&(c.path="/"),c.domain&&(c.domain=void 0)),c&&"number"==typeof c.maxAge&&c.maxAge>=0){if(c.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");d+=`; Max-Age=${Math.floor(c.maxAge)}`}if(c.domain&&"host"!==c.prefix&&(d+=`; Domain=${c.domain}`),c.path&&(d+=`; Path=${c.path}`),c.expires){if(c.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");d+=`; Expires=${c.expires.toUTCString()}`}return c.httpOnly&&(d+="; HttpOnly"),c.secure&&(d+="; Secure"),c.sameSite&&(d+=`; SameSite=${c.sameSite.charAt(0).toUpperCase()+c.sameSite.slice(1)}`),c.partitioned&&(c.secure||(c.secure=!0),d+="; Partitioned"),d},hR=(a,b,c)=>hQ(a,b=encodeURIComponent(b),c),hS=async(a,b,c,d)=>hQ(a,b=await hO(b,c),d);async function hT(a,b={}){let c={body:b.body,query:b.query};if(a.body){let d=await a.body["~standard"].validate(b.body);if(d.issues)return{data:null,error:hU(d.issues,"body")};c.body=d.value}if(a.query){let d=await a.query["~standard"].validate(b.query);if(d.issues)return{data:null,error:hU(d.issues,"query")};c.query=d.value}return a.requireHeaders&&!b.headers?{data:null,error:{message:"Headers is required",issues:[]}}:a.requireRequest&&!b.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:c,error:null}}function hU(a,b){return{message:a.map(a=>`[${a.path?.length?`${b}.`+a.path.map(a=>"object"==typeof a?a.key:a).join("."):b}] ${a.message}`).join("; "),issues:a}}let hV=async(a,{options:b,path:c})=>{let d,e=new Headers,{data:f,error:g}=await hT(b,a);if(g)throw new hz.yI(g.message,g.issues);let h="headers"in a?a.headers instanceof Headers?a.headers:new Headers(a.headers):"request"in a&&hE(a.request)?a.request.headers:null,i=h?.get("cookie"),j=i?function(a){if("string"!=typeof a)throw TypeError("argument str must be a string");let b=new Map,c=0;for(;c<a.length;){let d=a.indexOf("=",c);if(-1===d)break;let e=a.indexOf(";",c);if(-1===e)e=a.length;else if(e<d){c=a.lastIndexOf(";",d-1)+1;continue}let f=a.slice(c,d).trim();if(!b.has(f)){let c=a.slice(d+1,e).trim();34===c.codePointAt(0)&&(c=c.slice(1,-1)),b.set(f,function(a){try{return a.includes("%")?decodeURIComponent(a):a}catch{return a}}(c))}c=e+1}return b}(i):void 0,k={...a,body:f.body,query:f.query,path:a.path||c||"virtual:",context:"context"in a&&a.context?a.context:{},returned:void 0,headers:a?.headers,request:a?.request,params:"params"in a?a.params:void 0,method:a.method??(Array.isArray(b.method)?b.method[0]:"*"===b.method?"GET":b.method),setHeader:(a,b)=>{e.set(a,b)},getHeader:a=>h?h.get(a):null,getCookie:(a,b)=>{let c=hP(a,b);return c&&j?.get(c)||null},getSignedCookie:async(a,b,c)=>{let d=hP(a,c);if(!d)return null;let e=j?.get(d);if(!e)return null;let f=e.lastIndexOf(".");if(f<1)return null;let g=e.substring(0,f),h=e.substring(f+1);return 44===h.length&&h.endsWith("=")?!!await hM(h,g,await hL(b))&&g:null},setCookie:(a,b,c)=>{let d=hR(a,b,c);return e.append("set-cookie",d),d},setSignedCookie:async(a,b,c,d)=>{let f=await hS(a,b,c,d);return e.append("set-cookie",f),f},redirect:a=>(e.set("location",a),new hz.LG("FOUND",void 0,e)),error:(a,b,c)=>new hz.LG(a,b,c),setStatus:a=>{d=a},json:(b,c)=>a.asResponse?{body:c?.body||b,routerResponse:c,_flag:"json"}:b,responseHeaders:e,get responseStatus(){return d}};for(let a of b.use||[]){let b=await a({...k,returnHeaders:!0,asResponse:!1});b.response&&Object.assign(k.context,b.response),b.headers&&b.headers.forEach((a,b)=>{k.responseHeaders.set(b,a)})}return k};function hW(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c;if(("GET"===e.method||"HEAD"===e.method)&&e.body)throw new hz.xH("Body is not allowed with GET or HEAD methods");if(d&&/\/{2,}/.test(d))throw new hz.xH("Path cannot contain consecutive slashes");let g=async(...a)=>{let b=a[0]||{},{data:c,error:g}=await hD(hV(b,{options:e,path:d}));if(g){if(!(g instanceof hz.yI))throw g;throw e.onValidationError&&await e.onValidationError({message:g.message,issues:g.issues}),new hz.LG(400,{message:g.message,code:"VALIDATION_ERROR"})}let h=await f(c).catch(async a=>{if(hC(a)){let c=e.onAPIError;if(c&&await c(a),b.asResponse)return a}throw a}),i=c.responseHeaders,j=c.responseStatus;return b.asResponse?hI(h,{headers:i,status:j}):b.returnHeaders?b.returnStatus?{headers:i,response:h,status:j}:{headers:i,response:h}:b.returnStatus?{response:h,status:j}:h};return g.options=e,g.path=d,g}function hX(a,b){let c=async c=>{let d="function"==typeof a?a:b,e=await hV(c,{options:"function"==typeof a?{}:a,path:"/"});if(!d)throw Error("handler must be defined");try{let a=await d(e),b=e.responseHeaders;return c.returnHeaders?{headers:b,response:a}:a}catch(a){throw hC(a)&&Object.defineProperty(a,hz.Ri,{enumerable:!1,configurable:!0,get:()=>e.responseHeaders}),a}};return c.options="function"==typeof a?{}:a,c}function hY(a,b,c){function d(c,d){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:d,constr:g,traits:new Set},enumerable:!1}),c._zod.traits.has(a))return;c._zod.traits.add(a),b(c,d);let e=g.prototype,f=Object.keys(e);for(let a=0;a<f.length;a++){let b=f[a];b in c||(c[b]=e[b].bind(c))}}let e=c?.Parent??Object;class f extends e{}function g(a){var b;let e=c?.Parent?new f:this;for(let c of(d(e,a),(b=e._zod).deferred??(b.deferred=[]),e._zod.deferred))c();return e}return Object.defineProperty(f,"name",{value:a}),Object.defineProperty(g,"init",{value:d}),Object.defineProperty(g,Symbol.hasInstance,{value:b=>!!c?.Parent&&b instanceof c.Parent||b?._zod?.traits?.has(a)}),Object.defineProperty(g,"name",{value:a}),g}hW.create=a=>(b,c,d)=>hW(b,{...c,use:[...c?.use||[],...a?.use||[]]},d),hX.create=a=>function(b,c){if("function"==typeof b)return hX({use:a?.use},b);if(!c)throw Error("Middleware handler is required");return hX({...b,method:"*",use:[...a?.use||[],...b.use||[]]},c)},Symbol("zod_brand");class hZ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class h$ extends Error{constructor(a){super(`Encountered unidirectional transform during encode: ${a}`),this.name="ZodEncodeError"}}(U=globalThis).__zod_globalConfig??(U.__zod_globalConfig={});let h_=globalThis.__zod_globalConfig;function h0(a){return a&&Object.assign(h_,a),h_}let h1=/^[cC][0-9a-z]{6,}$/,h2=/^[0-9a-z]+$/,h3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,h4=/^[0-9a-vA-V]{20}$/,h5=/^[A-Za-z0-9]{27}$/,h6=/^[a-zA-Z0-9_-]{21}$/,h7=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,h8=/^([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})$/,h9=a=>a?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${a}[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)$/,ia=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ib=/^(?:(?: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])$/,ic=/^(([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}|:))$/,id=/^((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])$/,ie=/^(([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])$/,ig=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ih=/^[A-Za-z0-9_-]*$/,ii=/^https?$/,ij=/^\+[1-9]\d{6,14}$/,ik="(?:(?:\\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])))",il=RegExp(`^${ik}$`);function im(a){let b="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof a.precision?-1===a.precision?`${b}`:0===a.precision?`${b}:[0-5]\\d`:`${b}:[0-5]\\d\\.\\d{${a.precision}}`:`${b}(?::[0-5]\\d(?:\\.\\d+)?)?`}let io=/^-?\d+$/,ip=/^-?\d+(?:\.\d+)?$/,iq=/^(?:true|false)$/i,ir=/^[^A-Z]*$/,is=/^[^a-z]*$/;function it(a){let b=Object.values(a).filter(a=>"number"==typeof a);return Object.entries(a).filter(([a,c])=>-1===b.indexOf(+a)).map(([a,b])=>b)}function iu(a,b){return"bigint"==typeof b?b.toString():b}function iv(a){return{get value(){{let b=a();return Object.defineProperty(this,"value",{value:b}),b}}}}function iw(a){let b=+!!a.startsWith("^"),c=a.endsWith("$")?a.length-1:a.length;return a.slice(b,c)}let ix=Symbol("evaluating");function iy(a,b,c){let d;Object.defineProperty(a,b,{get(){if(d!==ix)return void 0===d&&(d=ix,d=c()),d},set(c){Object.defineProperty(a,b,{value:c})},configurable:!0})}function iz(a,b,c){Object.defineProperty(a,b,{value:c,writable:!0,enumerable:!0,configurable:!0})}function iA(...a){let b={};for(let c of a)Object.assign(b,Object.getOwnPropertyDescriptors(c));return Object.defineProperties({},b)}function iB(a){return JSON.stringify(a)}let iC="captureStackTrace"in Error?Error.captureStackTrace:(...a)=>{};function iD(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}let iE=iv(()=>{if(h_.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(a){return!1}});function iF(a){if(!1===iD(a))return!1;let b=a.constructor;if(void 0===b||"function"!=typeof b)return!0;let c=b.prototype;return!1!==iD(c)&&!1!==Object.prototype.hasOwnProperty.call(c,"isPrototypeOf")}function iG(a){return iF(a)?{...a}:Array.isArray(a)?[...a]:a instanceof Map?new Map(a):a instanceof Set?new Set(a):a}let iH=new Set(["string","number","symbol"]);function iI(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iJ(a,b,c){let d=new a._zod.constr(b??a._zod.def);return(!b||c?.parent)&&(d._zod.parent=a),d}function iK(a){if(!a)return{};if("string"==typeof a)return{error:()=>a};if(a?.message!==void 0){if(a?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");a.error=a.message}return(delete a.message,"string"==typeof a.error)?{...a,error:()=>a.error}:a}let iL={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]};function iM(a,b=0){if(!0===a.aborted)return!0;for(let c=b;c<a.issues.length;c++)if(a.issues[c]?.continue!==!0)return!0;return!1}function iN(a,b){return b.map(b=>(b.path??(b.path=[]),b.path.unshift(a),b))}function iO(a){return"string"==typeof a?a:a?.message}function iP(a,b,c){let d=a.message?a.message:iO(a.inst?._zod.def?.error?.(a))??iO(b?.error?.(a))??iO(c.customError?.(a))??iO(c.localeError?.(a))??"Invalid input",{inst:e,continue:f,input:g,...h}=a;return h.path??(h.path=[]),h.message=d,b?.reportInput&&(h.input=g),h}function iQ(a){return Array.isArray(a)?"array":"string"==typeof a?"string":"unknown"}function iR(...a){let[b,c,d]=a;return"string"==typeof b?{message:b,code:"custom",input:c,inst:d}:{...b}}let iS=hY("$ZodCheck",(a,b)=>{var c;a._zod??(a._zod={}),a._zod.def=b,(c=a._zod).onattach??(c.onattach=[])}),iT={number:"number",bigint:"bigint",object:"date"},iU=hY("$ZodCheckLessThan",(a,b)=>{iS.init(a,b);let c=iT[typeof b.value];a._zod.onattach.push(a=>{let c=a._zod.bag,d=(b.inclusive?c.maximum:c.exclusiveMaximum)??1/0;b.value<d&&(b.inclusive?c.maximum=b.value:c.exclusiveMaximum=b.value)}),a._zod.check=d=>{(b.inclusive?d.value<=b.value:d.value<b.value)||d.issues.push({origin:c,code:"too_big",maximum:"object"==typeof b.value?b.value.getTime():b.value,input:d.value,inclusive:b.inclusive,inst:a,continue:!b.abort})}}),iV=hY("$ZodCheckGreaterThan",(a,b)=>{iS.init(a,b);let c=iT[typeof b.value];a._zod.onattach.push(a=>{let c=a._zod.bag,d=(b.inclusive?c.minimum:c.exclusiveMinimum)??-1/0;b.value>d&&(b.inclusive?c.minimum=b.value:c.exclusiveMinimum=b.value)}),a._zod.check=d=>{(b.inclusive?d.value>=b.value:d.value>b.value)||d.issues.push({origin:c,code:"too_small",minimum:"object"==typeof b.value?b.value.getTime():b.value,input:d.value,inclusive:b.inclusive,inst:a,continue:!b.abort})}}),iW=hY("$ZodCheckMultipleOf",(a,b)=>{iS.init(a,b),a._zod.onattach.push(a=>{var c;(c=a._zod.bag).multipleOf??(c.multipleOf=b.value)}),a._zod.check=c=>{let d,e,f;if(typeof c.value!=typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof c.value?c.value%b.value===BigInt(0):0==(e=Math.round(d=c.value/b.value),f=Number.EPSILON*Math.max(Math.abs(d),1),Math.abs(d-e)<f?0:d-e))||c.issues.push({origin:typeof c.value,code:"not_multiple_of",divisor:b.value,input:c.value,inst:a,continue:!b.abort})}}),iX=hY("$ZodCheckNumberFormat",(a,b)=>{iS.init(a,b),b.format=b.format||"float64";let c=b.format?.includes("int"),d=c?"int":"number",[e,f]=iL[b.format];a._zod.onattach.push(a=>{let d=a._zod.bag;d.format=b.format,d.minimum=e,d.maximum=f,c&&(d.pattern=io)}),a._zod.check=g=>{let h=g.value;if(c){if(!Number.isInteger(h))return void g.issues.push({expected:d,format:b.format,code:"invalid_type",continue:!1,input:h,inst:a});if(!Number.isSafeInteger(h))return void(h>0?g.issues.push({input:h,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:a,origin:d,inclusive:!0,continue:!b.abort}):g.issues.push({input:h,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:a,origin:d,inclusive:!0,continue:!b.abort}))}h<e&&g.issues.push({origin:"number",input:h,code:"too_small",minimum:e,inclusive:!0,inst:a,continue:!b.abort}),h>f&&g.issues.push({origin:"number",input:h,code:"too_big",maximum:f,inclusive:!0,inst:a,continue:!b.abort})}}),iY=hY("$ZodCheckMaxLength",(a,b)=>{var c;iS.init(a,b),(c=a._zod.def).when??(c.when=a=>{let b=a.value;return null!=b&&void 0!==b.length}),a._zod.onattach.push(a=>{let c=a._zod.bag.maximum??1/0;b.maximum<c&&(a._zod.bag.maximum=b.maximum)}),a._zod.check=c=>{let d=c.value;if(d.length<=b.maximum)return;let e=iQ(d);c.issues.push({origin:e,code:"too_big",maximum:b.maximum,inclusive:!0,input:d,inst:a,continue:!b.abort})}}),iZ=hY("$ZodCheckMinLength",(a,b)=>{var c;iS.init(a,b),(c=a._zod.def).when??(c.when=a=>{let b=a.value;return null!=b&&void 0!==b.length}),a._zod.onattach.push(a=>{let c=a._zod.bag.minimum??-1/0;b.minimum>c&&(a._zod.bag.minimum=b.minimum)}),a._zod.check=c=>{let d=c.value;if(d.length>=b.minimum)return;let e=iQ(d);c.issues.push({origin:e,code:"too_small",minimum:b.minimum,inclusive:!0,input:d,inst:a,continue:!b.abort})}}),i$=hY("$ZodCheckLengthEquals",(a,b)=>{var c;iS.init(a,b),(c=a._zod.def).when??(c.when=a=>{let b=a.value;return null!=b&&void 0!==b.length}),a._zod.onattach.push(a=>{let c=a._zod.bag;c.minimum=b.length,c.maximum=b.length,c.length=b.length}),a._zod.check=c=>{let d=c.value,e=d.length;if(e===b.length)return;let f=iQ(d),g=e>b.length;c.issues.push({origin:f,...g?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:c.value,inst:a,continue:!b.abort})}}),i_=hY("$ZodCheckStringFormat",(a,b)=>{var c,d;iS.init(a,b),a._zod.onattach.push(a=>{let c=a._zod.bag;c.format=b.format,b.pattern&&(c.patterns??(c.patterns=new Set),c.patterns.add(b.pattern))}),b.pattern?(c=a._zod).check??(c.check=c=>{b.pattern.lastIndex=0,b.pattern.test(c.value)||c.issues.push({origin:"string",code:"invalid_format",format:b.format,input:c.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:a,continue:!b.abort})}):(d=a._zod).check??(d.check=()=>{})}),i0=hY("$ZodCheckRegex",(a,b)=>{i_.init(a,b),a._zod.check=c=>{b.pattern.lastIndex=0,b.pattern.test(c.value)||c.issues.push({origin:"string",code:"invalid_format",format:"regex",input:c.value,pattern:b.pattern.toString(),inst:a,continue:!b.abort})}}),i1=hY("$ZodCheckLowerCase",(a,b)=>{b.pattern??(b.pattern=ir),i_.init(a,b)}),i2=hY("$ZodCheckUpperCase",(a,b)=>{b.pattern??(b.pattern=is),i_.init(a,b)}),i3=hY("$ZodCheckIncludes",(a,b)=>{iS.init(a,b);let c=iI(b.includes),d=new RegExp("number"==typeof b.position?`^.{${b.position}}${c}`:c);b.pattern=d,a._zod.onattach.push(a=>{let b=a._zod.bag;b.patterns??(b.patterns=new Set),b.patterns.add(d)}),a._zod.check=c=>{c.value.includes(b.includes,b.position)||c.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:c.value,inst:a,continue:!b.abort})}}),i4=hY("$ZodCheckStartsWith",(a,b)=>{iS.init(a,b);let c=RegExp(`^${iI(b.prefix)}.*`);b.pattern??(b.pattern=c),a._zod.onattach.push(a=>{let b=a._zod.bag;b.patterns??(b.patterns=new Set),b.patterns.add(c)}),a._zod.check=c=>{c.value.startsWith(b.prefix)||c.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:c.value,inst:a,continue:!b.abort})}}),i5=hY("$ZodCheckEndsWith",(a,b)=>{iS.init(a,b);let c=RegExp(`.*${iI(b.suffix)}$`);b.pattern??(b.pattern=c),a._zod.onattach.push(a=>{let b=a._zod.bag;b.patterns??(b.patterns=new Set),b.patterns.add(c)}),a._zod.check=c=>{c.value.endsWith(b.suffix)||c.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:c.value,inst:a,continue:!b.abort})}}),i6=hY("$ZodCheckOverwrite",(a,b)=>{iS.init(a,b),a._zod.check=a=>{a.value=b.tx(a.value)}});class i7{constructor(a=[]){this.content=[],this.indent=0,this&&(this.args=a)}indented(a){this.indent+=1,a(this),this.indent-=1}write(a){if("function"==typeof a){a(this,{execution:"sync"}),a(this,{execution:"async"});return}let b=a.split("\n").filter(a=>a),c=Math.min(...b.map(a=>a.length-a.trimStart().length));for(let a of b.map(a=>a.slice(c)).map(a=>" ".repeat(2*this.indent)+a))this.content.push(a)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(a=>` ${a}`)].join("\n"))}}let i8=(a,b)=>{a.name="$ZodError",Object.defineProperty(a,"_zod",{value:a._zod,enumerable:!1}),Object.defineProperty(a,"issues",{value:b,enumerable:!1}),a.message=JSON.stringify(b,iu,2),Object.defineProperty(a,"toString",{value:()=>a.message,enumerable:!1})},i9=hY("$ZodError",i8),ja=hY("$ZodError",i8,{Parent:Error}),jb=a=>(b,c,d,e)=>{let f=d?{...d,async:!1}:{async:!1},g=b._zod.run({value:c,issues:[]},f);if(g instanceof Promise)throw new hZ;if(g.issues.length){let b=new(e?.Err??a)(g.issues.map(a=>iP(a,f,h0())));throw iC(b,e?.callee),b}return g.value},jc=a=>async(b,c,d,e)=>{let f=d?{...d,async:!0}:{async:!0},g=b._zod.run({value:c,issues:[]},f);if(g instanceof Promise&&(g=await g),g.issues.length){let b=new(e?.Err??a)(g.issues.map(a=>iP(a,f,h0())));throw iC(b,e?.callee),b}return g.value},jd=a=>(b,c,d)=>{let e=d?{...d,async:!1}:{async:!1},f=b._zod.run({value:c,issues:[]},e);if(f instanceof Promise)throw new hZ;return f.issues.length?{success:!1,error:new(a??i9)(f.issues.map(a=>iP(a,e,h0())))}:{success:!0,data:f.value}},je=jd(ja),jf=a=>async(b,c,d)=>{let e=d?{...d,async:!0}:{async:!0},f=b._zod.run({value:c,issues:[]},e);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new a(f.issues.map(a=>iP(a,e,h0())))}:{success:!0,data:f.value}},jg=jf(ja),jh={major:4,minor:4,patch:3},ji=hY("$ZodType",(a,b)=>{var c;a??(a={}),a._zod.def=b,a._zod.bag=a._zod.bag||{},a._zod.version=jh;let d=[...a._zod.def.checks??[]];for(let b of(a._zod.traits.has("$ZodCheck")&&d.unshift(a),d))for(let c of b._zod.onattach)c(a);if(0===d.length)(c=a._zod).deferred??(c.deferred=[]),a._zod.deferred?.push(()=>{a._zod.run=a._zod.parse});else{let b=(a,b,c)=>{let d,e=iM(a);for(let f of b){if(f._zod.def.when){if(function(a,b=0){if(!0===a.aborted)return!0;for(let c=b;c<a.issues.length;c++)if(a.issues[c]?.continue===!1)return!0;return!1}(a)||!f._zod.def.when(a))continue}else if(e)continue;let b=a.issues.length,g=f._zod.check(a);if(g instanceof Promise&&c?.async===!1)throw new hZ;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await g,a.issues.length!==b&&(e||(e=iM(a,b)))});else{if(a.issues.length===b)continue;e||(e=iM(a,b))}}return d?d.then(()=>a):a},c=(c,e,f)=>{if(iM(c))return c.aborted=!0,c;let g=b(e,d,f);if(g instanceof Promise){if(!1===f.async)throw new hZ;return g.then(b=>a._zod.parse(b,f))}return a._zod.parse(g,f)};a._zod.run=(e,f)=>{if(f.skipChecks)return a._zod.parse(e,f);if("backward"===f.direction){let b=a._zod.parse({value:e.value,issues:[]},{...f,skipChecks:!0});return b instanceof Promise?b.then(a=>c(a,e,f)):c(b,e,f)}let g=a._zod.parse(e,f);if(g instanceof Promise){if(!1===f.async)throw new hZ;return g.then(a=>b(a,d,f))}return b(g,d,f)}}iy(a,"~standard",()=>({validate:b=>{try{let c=je(a,b);return c.success?{value:c.data}:{issues:c.error?.issues}}catch(c){return jg(a,b).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),jj=hY("$ZodString",(a,b)=>{var c;let d;ji.init(a,b),a._zod.pattern=[...a?._zod.bag?.patterns??[]].pop()??(d=(c=a._zod.bag)?`[\\s\\S]{${c?.minimum??0},${c?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${d}$`)),a._zod.parse=(c,d)=>{if(b.coerce)try{c.value=String(c.value)}catch(a){}return"string"==typeof c.value||c.issues.push({expected:"string",code:"invalid_type",input:c.value,inst:a}),c}}),jk=hY("$ZodStringFormat",(a,b)=>{i_.init(a,b),jj.init(a,b)}),jl=hY("$ZodGUID",(a,b)=>{b.pattern??(b.pattern=h8),jk.init(a,b)}),jm=hY("$ZodUUID",(a,b)=>{if(b.version){let a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(void 0===a)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=h9(a))}else b.pattern??(b.pattern=h9());jk.init(a,b)}),jn=hY("$ZodEmail",(a,b)=>{b.pattern??(b.pattern=ia),jk.init(a,b)}),jo=hY("$ZodURL",(a,b)=>{jk.init(a,b),a._zod.check=c=>{try{let d=c.value.trim();if(!b.normalize&&b.protocol?.source===ii.source&&!/^https?:\/\//i.test(d))return void c.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:c.value,inst:a,continue:!b.abort});let e=new URL(d);b.hostname&&(b.hostname.lastIndex=0,b.hostname.test(e.hostname)||c.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:b.hostname.source,input:c.value,inst:a,continue:!b.abort})),b.protocol&&(b.protocol.lastIndex=0,b.protocol.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)||c.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:c.value,inst:a,continue:!b.abort})),b.normalize?c.value=e.href:c.value=d;return}catch(d){c.issues.push({code:"invalid_format",format:"url",input:c.value,inst:a,continue:!b.abort})}}}),jp=hY("$ZodEmoji",(a,b)=>{b.pattern??(b.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),jk.init(a,b)}),jq=hY("$ZodNanoID",(a,b)=>{b.pattern??(b.pattern=h6),jk.init(a,b)}),jr=hY("$ZodCUID",(a,b)=>{b.pattern??(b.pattern=h1),jk.init(a,b)}),js=hY("$ZodCUID2",(a,b)=>{b.pattern??(b.pattern=h2),jk.init(a,b)}),jt=hY("$ZodULID",(a,b)=>{b.pattern??(b.pattern=h3),jk.init(a,b)}),ju=hY("$ZodXID",(a,b)=>{b.pattern??(b.pattern=h4),jk.init(a,b)}),jv=hY("$ZodKSUID",(a,b)=>{b.pattern??(b.pattern=h5),jk.init(a,b)}),jw=hY("$ZodISODateTime",(a,b)=>{let c,d,e;b.pattern??(c=im({precision:b.precision}),d=["Z"],b.local&&d.push(""),b.offset&&d.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),e=`${c}(?:${d.join("|")})`,b.pattern=RegExp(`^${ik}T(?:${e})$`)),jk.init(a,b)}),jx=hY("$ZodISODate",(a,b)=>{b.pattern??(b.pattern=il),jk.init(a,b)}),jy=hY("$ZodISOTime",(a,b)=>{b.pattern??(b.pattern=RegExp(`^${im(b)}$`)),jk.init(a,b)}),jz=hY("$ZodISODuration",(a,b)=>{b.pattern??(b.pattern=h7),jk.init(a,b)}),jA=hY("$ZodIPv4",(a,b)=>{b.pattern??(b.pattern=ib),jk.init(a,b),a._zod.bag.format="ipv4"}),jB=hY("$ZodIPv6",(a,b)=>{b.pattern??(b.pattern=ic),jk.init(a,b),a._zod.bag.format="ipv6",a._zod.check=c=>{try{new URL(`http://[${c.value}]`)}catch{c.issues.push({code:"invalid_format",format:"ipv6",input:c.value,inst:a,continue:!b.abort})}}}),jC=hY("$ZodCIDRv4",(a,b)=>{b.pattern??(b.pattern=id),jk.init(a,b)}),jD=hY("$ZodCIDRv6",(a,b)=>{b.pattern??(b.pattern=ie),jk.init(a,b),a._zod.check=c=>{let d=c.value.split("/");try{if(2!==d.length)throw Error();let[a,b]=d;if(!b)throw Error();let c=Number(b);if(`${c}`!==b||c<0||c>128)throw Error();new URL(`http://[${a}]`)}catch{c.issues.push({code:"invalid_format",format:"cidrv6",input:c.value,inst:a,continue:!b.abort})}}});function jE(a){if(""===a)return!0;if(/\s/.test(a)||a.length%4!=0)return!1;try{return atob(a),!0}catch{return!1}}let jF=hY("$ZodBase64",(a,b)=>{b.pattern??(b.pattern=ig),jk.init(a,b),a._zod.bag.contentEncoding="base64",a._zod.check=c=>{jE(c.value)||c.issues.push({code:"invalid_format",format:"base64",input:c.value,inst:a,continue:!b.abort})}}),jG=hY("$ZodBase64URL",(a,b)=>{b.pattern??(b.pattern=ih),jk.init(a,b),a._zod.bag.contentEncoding="base64url",a._zod.check=c=>{!function(a){if(!ih.test(a))return!1;let b=a.replace(/[-_]/g,a=>"-"===a?"+":"/");return jE(b.padEnd(4*Math.ceil(b.length/4),"="))}(c.value)&&c.issues.push({code:"invalid_format",format:"base64url",input:c.value,inst:a,continue:!b.abort})}}),jH=hY("$ZodE164",(a,b)=>{b.pattern??(b.pattern=ij),jk.init(a,b)}),jI=hY("$ZodJWT",(a,b)=>{jk.init(a,b),a._zod.check=c=>{!function(a,b=null){try{let c=a.split(".");if(3!==c.length)return!1;let[d]=c;if(!d)return!1;let e=JSON.parse(atob(d));if("typ"in e&&e?.typ!=="JWT"||!e.alg||b&&(!("alg"in e)||e.alg!==b))return!1;return!0}catch{return!1}}(c.value,b.alg)&&c.issues.push({code:"invalid_format",format:"jwt",input:c.value,inst:a,continue:!b.abort})}}),jJ=hY("$ZodNumber",(a,b)=>{ji.init(a,b),a._zod.pattern=a._zod.bag.pattern??ip,a._zod.parse=(c,d)=>{if(b.coerce)try{c.value=Number(c.value)}catch(a){}let e=c.value;if("number"==typeof e&&!Number.isNaN(e)&&Number.isFinite(e))return c;let f="number"==typeof e?Number.isNaN(e)?"NaN":Number.isFinite(e)?void 0:"Infinity":void 0;return c.issues.push({expected:"number",code:"invalid_type",input:e,inst:a,...f?{received:f}:{}}),c}}),jK=hY("$ZodNumberFormat",(a,b)=>{iX.init(a,b),jJ.init(a,b)}),jL=hY("$ZodBoolean",(a,b)=>{ji.init(a,b),a._zod.pattern=iq,a._zod.parse=(c,d)=>{if(b.coerce)try{c.value=!!c.value}catch(a){}let e=c.value;return"boolean"==typeof e||c.issues.push({expected:"boolean",code:"invalid_type",input:e,inst:a}),c}}),jM=hY("$ZodAny",(a,b)=>{ji.init(a,b),a._zod.parse=a=>a}),jN=hY("$ZodUnknown",(a,b)=>{ji.init(a,b),a._zod.parse=a=>a}),jO=hY("$ZodNever",(a,b)=>{ji.init(a,b),a._zod.parse=(b,c)=>(b.issues.push({expected:"never",code:"invalid_type",input:b.value,inst:a}),b)});function jP(a,b,c){a.issues.length&&b.issues.push(...iN(c,a.issues)),b.value[c]=a.value}let jQ=hY("$ZodArray",(a,b)=>{ji.init(a,b),a._zod.parse=(c,d)=>{let e=c.value;if(!Array.isArray(e))return c.issues.push({expected:"array",code:"invalid_type",input:e,inst:a}),c;c.value=Array(e.length);let f=[];for(let a=0;a<e.length;a++){let g=e[a],h=b.element._zod.run({value:g,issues:[]},d);h instanceof Promise?f.push(h.then(b=>jP(b,c,a))):jP(h,c,a)}return f.length?Promise.all(f).then(()=>c):c}});function jR(a,b,c,d,e,f){let g=c in d;if(a.issues.length){if(e&&f&&!g)return;b.issues.push(...iN(c,a.issues))}if(!g&&!e){a.issues.length||b.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[c]});return}void 0===a.value?g&&(b.value[c]=void 0):b.value[c]=a.value}function jS(a){var b;let c=Object.keys(a.shape);for(let b of c)if(!a.shape?.[b]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${b}": expected a Zod schema`);let d=Object.keys(b=a.shape).filter(a=>"optional"===b[a]._zod.optin&&"optional"===b[a]._zod.optout);return{...a,keys:c,keySet:new Set(c),numKeys:c.length,optionalKeys:new Set(d)}}function jT(a,b,c,d,e,f){let g=[],h=e.keySet,i=e.catchall._zod,j=i.def.type,k="optional"===i.optin,l="optional"===i.optout;for(let e in b){if("__proto__"===e||h.has(e))continue;if("never"===j){g.push(e);continue}let f=i.run({value:b[e],issues:[]},d);f instanceof Promise?a.push(f.then(a=>jR(a,c,e,b,k,l))):jR(f,c,e,b,k,l)}return(g.length&&c.issues.push({code:"unrecognized_keys",keys:g,input:b,inst:f}),a.length)?Promise.all(a).then(()=>c):c}let jU=hY("$ZodObject",(a,b)=>{let c;ji.init(a,b);let d=Object.getOwnPropertyDescriptor(b,"shape");if(!d?.get){let a=b.shape;Object.defineProperty(b,"shape",{get:()=>{let c={...a};return Object.defineProperty(b,"shape",{value:c}),c}})}let e=iv(()=>jS(b));iy(a._zod,"propValues",()=>{let a=b.shape,c={};for(let b in a){let d=a[b]._zod;if(d.values)for(let a of(c[b]??(c[b]=new Set),d.values))c[b].add(a)}return c});let f=b.catchall;a._zod.parse=(b,d)=>{c??(c=e.value);let g=b.value;if(!iD(g))return b.issues.push({expected:"object",code:"invalid_type",input:g,inst:a}),b;b.value={};let h=[],i=c.shape;for(let a of c.keys){let c=i[a],e="optional"===c._zod.optin,f="optional"===c._zod.optout,j=c._zod.run({value:g[a],issues:[]},d);j instanceof Promise?h.push(j.then(c=>jR(c,b,a,g,e,f))):jR(j,b,a,g,e,f)}return f?jT(h,g,b,d,e.value,a):h.length?Promise.all(h).then(()=>b):b}}),jV=hY("$ZodObjectJIT",(a,b)=>{let c,d;jU.init(a,b);let e=a._zod.parse,f=iv(()=>jS(b)),g=!h_.jitless,h=g&&iE.value,i=b.catchall;a._zod.parse=(j,k)=>{d??(d=f.value);let l=j.value;return iD(l)?g&&h&&k?.async===!1&&!0!==k.jitless?(c||(c=(a=>{let b=new i7(["shape","payload","ctx"]),c=f.value,d=a=>{let b=iB(a);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};b.write("const input = payload.value;");let e=Object.create(null),g=0;for(let a of c.keys)e[a]=`key_${g++}`;for(let f of(b.write("const newResult = {};"),c.keys)){let c=e[f],g=iB(f),h=a[f],i=h?._zod?.optin==="optional",j=h?._zod?.optout==="optional";b.write(`const ${c} = ${d(f)};`),i&&j?b.write(`
|
|
38
|
+
if (${c}.issues.length) {
|
|
39
|
+
if (${g} in input) {
|
|
40
|
+
payload.issues = payload.issues.concat(${c}.issues.map(iss => ({
|
|
41
|
+
...iss,
|
|
42
|
+
path: iss.path ? [${g}, ...iss.path] : [${g}]
|
|
43
|
+
})));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (${c}.value === undefined) {
|
|
48
|
+
if (${g} in input) {
|
|
49
|
+
newResult[${g}] = undefined;
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
newResult[${g}] = ${c}.value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
`):i?b.write(`
|
|
56
|
+
if (${c}.issues.length) {
|
|
57
|
+
payload.issues = payload.issues.concat(${c}.issues.map(iss => ({
|
|
58
|
+
...iss,
|
|
59
|
+
path: iss.path ? [${g}, ...iss.path] : [${g}]
|
|
60
|
+
})));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (${c}.value === undefined) {
|
|
64
|
+
if (${g} in input) {
|
|
65
|
+
newResult[${g}] = undefined;
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
newResult[${g}] = ${c}.value;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
`):b.write(`
|
|
72
|
+
const ${c}_present = ${g} in input;
|
|
73
|
+
if (${c}.issues.length) {
|
|
74
|
+
payload.issues = payload.issues.concat(${c}.issues.map(iss => ({
|
|
75
|
+
...iss,
|
|
76
|
+
path: iss.path ? [${g}, ...iss.path] : [${g}]
|
|
77
|
+
})));
|
|
78
|
+
}
|
|
79
|
+
if (!${c}_present && !${c}.issues.length) {
|
|
80
|
+
payload.issues.push({
|
|
81
|
+
code: "invalid_type",
|
|
82
|
+
expected: "nonoptional",
|
|
83
|
+
input: undefined,
|
|
84
|
+
path: [${g}]
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (${c}_present) {
|
|
89
|
+
if (${c}.value === undefined) {
|
|
90
|
+
newResult[${g}] = undefined;
|
|
91
|
+
} else {
|
|
92
|
+
newResult[${g}] = ${c}.value;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
`)}b.write("payload.value = newResult;"),b.write("return payload;");let h=b.compile();return(b,c)=>h(a,b,c)})(b.shape)),j=c(j,k),i)?jT([],l,j,k,d,a):j:e(j,k):(j.issues.push({expected:"object",code:"invalid_type",input:l,inst:a}),j)}});function jW(a,b,c,d){for(let c of a)if(0===c.issues.length)return b.value=c.value,b;let e=a.filter(a=>!iM(a));return 1===e.length?(b.value=e[0].value,e[0]):(b.issues.push({code:"invalid_union",input:b.value,inst:c,errors:a.map(a=>a.issues.map(a=>iP(a,d,h0())))}),b)}let jX=hY("$ZodUnion",(a,b)=>{ji.init(a,b),iy(a._zod,"optin",()=>b.options.some(a=>"optional"===a._zod.optin)?"optional":void 0),iy(a._zod,"optout",()=>b.options.some(a=>"optional"===a._zod.optout)?"optional":void 0),iy(a._zod,"values",()=>{if(b.options.every(a=>a._zod.values))return new Set(b.options.flatMap(a=>Array.from(a._zod.values)))}),iy(a._zod,"pattern",()=>{if(b.options.every(a=>a._zod.pattern)){let a=b.options.map(a=>a._zod.pattern);return RegExp(`^(${a.map(a=>iw(a.source)).join("|")})$`)}});let c=1===b.options.length?b.options[0]._zod.run:null;a._zod.parse=(d,e)=>{if(c)return c(d,e);let f=!1,g=[];for(let a of b.options){let b=a._zod.run({value:d.value,issues:[]},e);if(b instanceof Promise)g.push(b),f=!0;else{if(0===b.issues.length)return b;g.push(b)}}return f?Promise.all(g).then(b=>jW(b,d,a,e)):jW(g,d,a,e)}}),jY=hY("$ZodIntersection",(a,b)=>{ji.init(a,b),a._zod.parse=(a,c)=>{let d=a.value,e=b.left._zod.run({value:d,issues:[]},c),f=b.right._zod.run({value:d,issues:[]},c);return e instanceof Promise||f instanceof Promise?Promise.all([e,f]).then(([b,c])=>jZ(a,b,c)):jZ(a,e,f)}});function jZ(a,b,c){let d,e=new Map;for(let c of b.issues)if("unrecognized_keys"===c.code)for(let a of(d??(d=c),c.keys))e.has(a)||e.set(a,{}),e.get(a).l=!0;else a.issues.push(c);for(let b of c.issues)if("unrecognized_keys"===b.code)for(let a of b.keys)e.has(a)||e.set(a,{}),e.get(a).r=!0;else a.issues.push(b);let f=[...e].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(f.length&&d&&a.issues.push({...d,keys:f}),iM(a))return a;let g=function a(b,c){if(b===c||b instanceof Date&&c instanceof Date&&+b==+c)return{valid:!0,data:b};if(iF(b)&&iF(c)){let d=Object.keys(c),e=Object.keys(b).filter(a=>-1!==d.indexOf(a)),f={...b,...c};for(let d of e){let e=a(b[d],c[d]);if(!e.valid)return{valid:!1,mergeErrorPath:[d,...e.mergeErrorPath]};f[d]=e.data}return{valid:!0,data:f}}if(Array.isArray(b)&&Array.isArray(c)){if(b.length!==c.length)return{valid:!1,mergeErrorPath:[]};let d=[];for(let e=0;e<b.length;e++){let f=a(b[e],c[e]);if(!f.valid)return{valid:!1,mergeErrorPath:[e,...f.mergeErrorPath]};d.push(f.data)}return{valid:!0,data:d}}return{valid:!1,mergeErrorPath:[]}}(b.value,c.value);if(!g.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(g.mergeErrorPath)}`);return a.value=g.data,a}let j$=hY("$ZodRecord",(a,b)=>{ji.init(a,b),a._zod.parse=(c,d)=>{let e=c.value;if(!iF(e))return c.issues.push({expected:"record",code:"invalid_type",input:e,inst:a}),c;let f=[],g=b.keyType._zod.values;if(g){let h;c.value={};let i=new Set;for(let h of g)if("string"==typeof h||"number"==typeof h||"symbol"==typeof h){i.add("number"==typeof h?h.toString():h);let g=b.keyType._zod.run({value:h,issues:[]},d);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(g.issues.length){c.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map(a=>iP(a,d,h0())),input:h,path:[h],inst:a});continue}let j=g.value,k=b.valueType._zod.run({value:e[h],issues:[]},d);k instanceof Promise?f.push(k.then(a=>{a.issues.length&&c.issues.push(...iN(h,a.issues)),c.value[j]=a.value})):(k.issues.length&&c.issues.push(...iN(h,k.issues)),c.value[j]=k.value)}for(let a in e)i.has(a)||(h=h??[]).push(a);h&&h.length>0&&c.issues.push({code:"unrecognized_keys",input:e,inst:a,keys:h})}else for(let g of(c.value={},Reflect.ownKeys(e))){if("__proto__"===g||!Object.prototype.propertyIsEnumerable.call(e,g))continue;let h=b.keyType._zod.run({value:g,issues:[]},d);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof g&&ip.test(g)&&h.issues.length){let a=b.keyType._zod.run({value:Number(g),issues:[]},d);if(a instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===a.issues.length&&(h=a)}if(h.issues.length){"loose"===b.mode?c.value[g]=e[g]:c.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(a=>iP(a,d,h0())),input:g,path:[g],inst:a});continue}let i=b.valueType._zod.run({value:e[g],issues:[]},d);i instanceof Promise?f.push(i.then(a=>{a.issues.length&&c.issues.push(...iN(g,a.issues)),c.value[h.value]=a.value})):(i.issues.length&&c.issues.push(...iN(g,i.issues)),c.value[h.value]=i.value)}return f.length?Promise.all(f).then(()=>c):c}}),j_=hY("$ZodEnum",(a,b)=>{ji.init(a,b);let c=it(b.entries),d=new Set(c);a._zod.values=d,a._zod.pattern=RegExp(`^(${c.filter(a=>iH.has(typeof a)).map(a=>"string"==typeof a?iI(a):a.toString()).join("|")})$`),a._zod.parse=(b,e)=>{let f=b.value;return d.has(f)||b.issues.push({code:"invalid_value",values:c,input:f,inst:a}),b}}),j0=hY("$ZodTransform",(a,b)=>{ji.init(a,b),a._zod.optin="optional",a._zod.parse=(c,d)=>{if("backward"===d.direction)throw new h$(a.constructor.name);let e=b.transform(c.value,c);if(d.async)return(e instanceof Promise?e:Promise.resolve(e)).then(a=>(c.value=a,c.fallback=!0,c));if(e instanceof Promise)throw new hZ;return c.value=e,c.fallback=!0,c}});function j1(a,b){return void 0===b&&(a.issues.length||a.fallback)?{issues:[],value:void 0}:a}let j2=hY("$ZodOptional",(a,b)=>{ji.init(a,b),a._zod.optin="optional",a._zod.optout="optional",iy(a._zod,"values",()=>b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0),iy(a._zod,"pattern",()=>{let a=b.innerType._zod.pattern;return a?RegExp(`^(${iw(a.source)})?$`):void 0}),a._zod.parse=(a,c)=>{if("optional"===b.innerType._zod.optin){let d=a.value,e=b.innerType._zod.run(a,c);return e instanceof Promise?e.then(a=>j1(a,d)):j1(e,d)}return void 0===a.value?a:b.innerType._zod.run(a,c)}}),j3=hY("$ZodExactOptional",(a,b)=>{j2.init(a,b),iy(a._zod,"values",()=>b.innerType._zod.values),iy(a._zod,"pattern",()=>b.innerType._zod.pattern),a._zod.parse=(a,c)=>b.innerType._zod.run(a,c)}),j4=hY("$ZodNullable",(a,b)=>{ji.init(a,b),iy(a._zod,"optin",()=>b.innerType._zod.optin),iy(a._zod,"optout",()=>b.innerType._zod.optout),iy(a._zod,"pattern",()=>{let a=b.innerType._zod.pattern;return a?RegExp(`^(${iw(a.source)}|null)$`):void 0}),iy(a._zod,"values",()=>b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0),a._zod.parse=(a,c)=>null===a.value?a:b.innerType._zod.run(a,c)}),j5=hY("$ZodDefault",(a,b)=>{ji.init(a,b),a._zod.optin="optional",iy(a._zod,"values",()=>b.innerType._zod.values),a._zod.parse=(a,c)=>{if("backward"===c.direction)return b.innerType._zod.run(a,c);if(void 0===a.value)return a.value=b.defaultValue,a;let d=b.innerType._zod.run(a,c);return d instanceof Promise?d.then(a=>j6(a,b)):j6(d,b)}});function j6(a,b){return void 0===a.value&&(a.value=b.defaultValue),a}let j7=hY("$ZodPrefault",(a,b)=>{ji.init(a,b),a._zod.optin="optional",iy(a._zod,"values",()=>b.innerType._zod.values),a._zod.parse=(a,c)=>("backward"===c.direction||void 0===a.value&&(a.value=b.defaultValue),b.innerType._zod.run(a,c))}),j8=hY("$ZodNonOptional",(a,b)=>{ji.init(a,b),iy(a._zod,"values",()=>{let a=b.innerType._zod.values;return a?new Set([...a].filter(a=>void 0!==a)):void 0}),a._zod.parse=(c,d)=>{let e=b.innerType._zod.run(c,d);return e instanceof Promise?e.then(b=>j9(b,a)):j9(e,a)}});function j9(a,b){return a.issues.length||void 0!==a.value||a.issues.push({code:"invalid_type",expected:"nonoptional",input:a.value,inst:b}),a}let ka=hY("$ZodCatch",(a,b)=>{ji.init(a,b),a._zod.optin="optional",iy(a._zod,"optout",()=>b.innerType._zod.optout),iy(a._zod,"values",()=>b.innerType._zod.values),a._zod.parse=(a,c)=>{if("backward"===c.direction)return b.innerType._zod.run(a,c);let d=b.innerType._zod.run(a,c);return d instanceof Promise?d.then(d=>(a.value=d.value,d.issues.length&&(a.value=b.catchValue({...a,error:{issues:d.issues.map(a=>iP(a,c,h0()))},input:a.value}),a.issues=[],a.fallback=!0),a)):(a.value=d.value,d.issues.length&&(a.value=b.catchValue({...a,error:{issues:d.issues.map(a=>iP(a,c,h0()))},input:a.value}),a.issues=[],a.fallback=!0),a)}}),kb=hY("$ZodPipe",(a,b)=>{ji.init(a,b),iy(a._zod,"values",()=>b.in._zod.values),iy(a._zod,"optin",()=>b.in._zod.optin),iy(a._zod,"optout",()=>b.out._zod.optout),iy(a._zod,"propValues",()=>b.in._zod.propValues),a._zod.parse=(a,c)=>{if("backward"===c.direction){let d=b.out._zod.run(a,c);return d instanceof Promise?d.then(a=>kc(a,b.in,c)):kc(d,b.in,c)}let d=b.in._zod.run(a,c);return d instanceof Promise?d.then(a=>kc(a,b.out,c)):kc(d,b.out,c)}});function kc(a,b,c){return a.issues.length?(a.aborted=!0,a):b._zod.run({value:a.value,issues:a.issues,fallback:a.fallback},c)}let kd=hY("$ZodReadonly",(a,b)=>{ji.init(a,b),iy(a._zod,"propValues",()=>b.innerType._zod.propValues),iy(a._zod,"values",()=>b.innerType._zod.values),iy(a._zod,"optin",()=>b.innerType?._zod?.optin),iy(a._zod,"optout",()=>b.innerType?._zod?.optout),a._zod.parse=(a,c)=>{if("backward"===c.direction)return b.innerType._zod.run(a,c);let d=b.innerType._zod.run(a,c);return d instanceof Promise?d.then(ke):ke(d)}});function ke(a){return a.value=Object.freeze(a.value),a}let kf=hY("$ZodCustom",(a,b)=>{iS.init(a,b),ji.init(a,b),a._zod.parse=(a,b)=>a,a._zod.check=c=>{let d=c.value,e=b.fn(d);if(e instanceof Promise)return e.then(b=>kg(b,c,d,a));kg(e,c,d,a)}});function kg(a,b,c,d){if(!a){let a={code:"custom",input:c,inst:d,path:[...d._zod.def.path??[]],continue:!d._zod.def.abort};d._zod.def.params&&(a.params=d._zod.def.params),b.issues.push(iR(a))}}Symbol("ZodOutput"),Symbol("ZodInput");class kh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(a,...b){let c=b[0];return this._map.set(a,c),c&&"object"==typeof c&&"id"in c&&this._idmap.set(c.id,a),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(a){let b=this._map.get(a);return b&&"object"==typeof b&&"id"in b&&this._idmap.delete(b.id),this._map.delete(a),this}get(a){let b=a._zod.parent;if(b){let c={...this.get(b)??{}};delete c.id;let d={...c,...this._map.get(a)};return Object.keys(d).length?d:void 0}return this._map.get(a)}has(a){return this._map.has(a)}}(V=globalThis).__zod_globalRegistry??(V.__zod_globalRegistry=new kh);let ki=globalThis.__zod_globalRegistry;function kj(a,b){return new a({type:"string",format:"email",check:"string_format",abort:!1,...iK(b)})}function kk(a,b){return new a({type:"string",format:"guid",check:"string_format",abort:!1,...iK(b)})}function kl(a,b){return new a({type:"string",format:"ipv4",check:"string_format",abort:!1,...iK(b)})}function km(a,b){return new a({type:"string",format:"ipv6",check:"string_format",abort:!1,...iK(b)})}function kn(a,b){return new iU({check:"less_than",...iK(b),value:a,inclusive:!1})}function ko(a,b){return new iU({check:"less_than",...iK(b),value:a,inclusive:!0})}function kp(a,b){return new iV({check:"greater_than",...iK(b),value:a,inclusive:!1})}function kq(a,b){return new iV({check:"greater_than",...iK(b),value:a,inclusive:!0})}function kr(a,b){return new iW({check:"multiple_of",...iK(b),value:a})}function ks(a,b){return new iY({check:"max_length",...iK(b),maximum:a})}function kt(a,b){return new iZ({check:"min_length",...iK(b),minimum:a})}function ku(a,b){return new i$({check:"length_equals",...iK(b),length:a})}function kv(a){return new i6({check:"overwrite",tx:a})}function kw(a){let b=a?.target??"draft-2020-12";return"draft-4"===b&&(b="draft-04"),"draft-7"===b&&(b="draft-07"),{processors:a.processors??{},metadataRegistry:a?.metadata??ki,target:b,unrepresentable:a?.unrepresentable??"throw",override:a?.override??(()=>{}),io:a?.io??"output",counter:0,seen:new Map,cycles:a?.cycles??"ref",reused:a?.reused??"inline",external:a?.external??void 0}}function kx(a,b,c={path:[],schemaPath:[]}){var d;let e=a._zod.def,f=b.seen.get(a);if(f)return f.count++,c.schemaPath.includes(a)&&(f.cycle=c.path),f.schema;let g={schema:{},count:1,cycle:void 0,path:c.path};b.seen.set(a,g);let h=a._zod.toJSONSchema?.();if(h)g.schema=h;else{let d={...c,schemaPath:[...c.schemaPath,a],path:c.path};if(a._zod.processJSONSchema)a._zod.processJSONSchema(b,g.schema,d);else{let c=g.schema,f=b.processors[e.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${e.type}`);f(a,b,c,d)}let f=a._zod.parent;f&&(g.ref||(g.ref=f),kx(f,b,d),b.seen.get(f).isParent=!0)}let i=b.metadataRegistry.get(a);return i&&Object.assign(g.schema,i),"input"===b.io&&function a(b,c){let d=c??{seen:new Set};if(d.seen.has(b))return!1;d.seen.add(b);let e=b._zod.def;if("transform"===e.type)return!0;if("array"===e.type)return a(e.element,d);if("set"===e.type)return a(e.valueType,d);if("lazy"===e.type)return a(e.getter(),d);if("promise"===e.type||"optional"===e.type||"nonoptional"===e.type||"nullable"===e.type||"readonly"===e.type||"default"===e.type||"prefault"===e.type)return a(e.innerType,d);if("intersection"===e.type)return a(e.left,d)||a(e.right,d);if("record"===e.type||"map"===e.type)return a(e.keyType,d)||a(e.valueType,d);if("pipe"===e.type)return!!b._zod.traits.has("$ZodCodec")||a(e.in,d)||a(e.out,d);if("object"===e.type){for(let b in e.shape)if(a(e.shape[b],d))return!0;return!1}if("union"===e.type){for(let b of e.options)if(a(b,d))return!0;return!1}if("tuple"===e.type){for(let b of e.items)if(a(b,d))return!0;if(e.rest&&a(e.rest,d))return!0}return!1}(a)&&(delete g.schema.examples,delete g.schema.default),"input"===b.io&&"_prefault"in g.schema&&((d=g.schema).default??(d.default=g.schema._prefault)),delete g.schema._prefault,b.seen.get(a).schema}function ky(a,b){let c=a.seen.get(b);if(!c)throw Error("Unprocessed schema. This is a bug in Zod.");let d=new Map;for(let b of a.seen.entries()){let c=a.metadataRegistry.get(b[0])?.id;if(c){let a=d.get(c);if(a&&a!==b[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);d.set(c,b[0])}}let e=b=>{if(b[1].schema.$ref)return;let d=b[1],{ref:e,defId:f}=(b=>{let d="draft-2020-12"===a.target?"$defs":"definitions";if(a.external){let c=a.external.registry.get(b[0])?.id,e=a.external.uri??(a=>a);if(c)return{ref:e(c)};let f=b[1].defId??b[1].schema.id??`schema${a.counter++}`;return b[1].defId=f,{defId:f,ref:`${e("__shared")}#/${d}/${f}`}}if(b[1]===c)return{ref:"#"};let e=`#/${d}/`,f=b[1].schema.id??`__schema${a.counter++}`;return{defId:f,ref:e+f}})(b);d.def={...d.schema},f&&(d.defId=f);let g=d.schema;for(let a in g)delete g[a];g.$ref=e};if("throw"===a.cycles)for(let b of a.seen.entries()){let a=b[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
97
|
+
|
|
98
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let c of a.seen.entries()){let d=c[1];if(b===c[0]){e(c);continue}if(a.external){let d=a.external.registry.get(c[0])?.id;if(b!==c[0]&&d){e(c);continue}}if(a.metadataRegistry.get(c[0])?.id||d.cycle||d.count>1&&"ref"===a.reused){e(c);continue}}}function kz(a,b){let c=a.seen.get(b);if(!c)throw Error("Unprocessed schema. This is a bug in Zod.");let d=b=>{let c=a.seen.get(b);if(null===c.ref)return;let e=c.def??c.schema,f={...e},g=c.ref;if(c.ref=null,g){d(g);let c=a.seen.get(g),h=c.schema;if(h.$ref&&("draft-07"===a.target||"draft-04"===a.target||"openapi-3.0"===a.target)?(e.allOf=e.allOf??[],e.allOf.push(h)):Object.assign(e,h),Object.assign(e,f),b._zod.parent===g)for(let a in e)"$ref"!==a&&"allOf"!==a&&(a in f||delete e[a]);if(h.$ref&&c.def)for(let a in e)"$ref"!==a&&"allOf"!==a&&a in c.def&&JSON.stringify(e[a])===JSON.stringify(c.def[a])&&delete e[a]}let h=b._zod.parent;if(h&&h!==g){d(h);let b=a.seen.get(h);if(b?.schema.$ref&&(e.$ref=b.schema.$ref,b.def))for(let a in e)"$ref"!==a&&"allOf"!==a&&a in b.def&&JSON.stringify(e[a])===JSON.stringify(b.def[a])&&delete e[a]}a.override({zodSchema:b,jsonSchema:e,path:c.path??[]})};for(let b of[...a.seen.entries()].reverse())d(b[0]);let e={};if("draft-2020-12"===a.target?e.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===a.target?e.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===a.target?e.$schema="http://json-schema.org/draft-04/schema#":a.target,a.external?.uri){let c=a.external.registry.get(b)?.id;if(!c)throw Error("Schema is missing an `id` property");e.$id=a.external.uri(c)}Object.assign(e,c.def??c.schema);let f=a.metadataRegistry.get(b)?.id;void 0!==f&&e.id===f&&delete e.id;let g=a.external?.defs??{};for(let b of a.seen.entries()){let a=b[1];a.def&&a.defId&&(a.def.id===a.defId&&delete a.def.id,g[a.defId]=a.def)}a.external||Object.keys(g).length>0&&("draft-2020-12"===a.target?e.$defs=g:e.definitions=g);try{let c=JSON.parse(JSON.stringify(e));return Object.defineProperty(c,"~standard",{value:{...b["~standard"],jsonSchema:{input:kA(b,"input",a.processors),output:kA(b,"output",a.processors)}},enumerable:!1,writable:!1}),c}catch(a){throw Error("Error converting schema to JSON.")}}let kA=(a,b,c={})=>d=>{let{libraryOptions:e,target:f}=d??{},g=kw({...e??{},target:f,io:b,processors:c});return kx(a,g),ky(g,a),kz(g,a)},kB={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},kC=(a,b,c,d)=>{let e=a._zod.def;kx(e.innerType,b,d),b.seen.get(a).ref=e.innerType},kD=hY("ZodISODateTime",(a,b)=>{jw.init(a,b),k$.init(a,b)}),kE=hY("ZodISODate",(a,b)=>{jx.init(a,b),k$.init(a,b)}),kF=hY("ZodISOTime",(a,b)=>{jy.init(a,b),k$.init(a,b)}),kG=hY("ZodISODuration",(a,b)=>{jz.init(a,b),k$.init(a,b)}),kH=hY("ZodError",(a,b)=>{i9.init(a,b),a.name="ZodError",Object.defineProperties(a,{format:{value:b=>(function(a,b=a=>a.message){let c={_errors:[]},d=(a,e=[])=>{for(let f of a.issues)if("invalid_union"===f.code&&f.errors.length)f.errors.map(a=>d({issues:a},[...e,...f.path]));else if("invalid_key"===f.code)d({issues:f.issues},[...e,...f.path]);else if("invalid_element"===f.code)d({issues:f.issues},[...e,...f.path]);else{let a=[...e,...f.path];if(0===a.length)c._errors.push(b(f));else{let d=c,e=0;for(;e<a.length;){let c=a[e];e===a.length-1?(d[c]=d[c]||{_errors:[]},d[c]._errors.push(b(f))):d[c]=d[c]||{_errors:[]},d=d[c],e++}}}};return d(a),c})(a,b)},flatten:{value:b=>(function(a,b=a=>a.message){let c={},d=[];for(let e of a.issues)e.path.length>0?(c[e.path[0]]=c[e.path[0]]||[],c[e.path[0]].push(b(e))):d.push(b(e));return{formErrors:d,fieldErrors:c}})(a,b)},addIssue:{value:b=>{a.issues.push(b),a.message=JSON.stringify(a.issues,iu,2)}},addIssues:{value:b=>{a.issues.push(...b),a.message=JSON.stringify(a.issues,iu,2)}},isEmpty:{get:()=>0===a.issues.length}})},{Parent:Error}),kI=jb(kH),kJ=jc(kH),kK=jd(kH),kL=jf(kH),kM=(a,b,c)=>{let d=c?{...c,direction:"backward"}:{direction:"backward"};return jb(kH)(a,b,d)},kN=(a,b,c)=>jb(kH)(a,b,c),kO=async(a,b,c)=>{let d=c?{...c,direction:"backward"}:{direction:"backward"};return jc(kH)(a,b,d)},kP=async(a,b,c)=>jc(kH)(a,b,c),kQ=(a,b,c)=>{let d=c?{...c,direction:"backward"}:{direction:"backward"};return jd(kH)(a,b,d)},kR=(a,b,c)=>jd(kH)(a,b,c),kS=async(a,b,c)=>{let d=c?{...c,direction:"backward"}:{direction:"backward"};return jf(kH)(a,b,d)},kT=async(a,b,c)=>jf(kH)(a,b,c),kU=new WeakMap;function kV(a,b,c){let d=Object.getPrototypeOf(a),e=kU.get(d);if(e||(e=new Set,kU.set(d,e)),!e.has(b))for(let a in e.add(b),c){let b=c[a];Object.defineProperty(d,a,{configurable:!0,enumerable:!1,get(){let c=b.bind(this);return Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(b){Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:b})}})}}let kW=hY("ZodType",(a,b)=>(ji.init(a,b),Object.assign(a["~standard"],{jsonSchema:{input:kA(a,"input"),output:kA(a,"output")}}),a.toJSONSchema=((a,b={})=>c=>{let d=kw({...c,processors:b});return kx(a,d),ky(d,a),kz(d,a)})(a,{}),a.def=b,a.type=b.type,Object.defineProperty(a,"_def",{value:b}),a.parse=(b,c)=>kI(a,b,c,{callee:a.parse}),a.safeParse=(b,c)=>kK(a,b,c),a.parseAsync=async(b,c)=>kJ(a,b,c,{callee:a.parseAsync}),a.safeParseAsync=async(b,c)=>kL(a,b,c),a.spa=a.safeParseAsync,a.encode=(b,c)=>kM(a,b,c),a.decode=(b,c)=>kN(a,b,c),a.encodeAsync=async(b,c)=>kO(a,b,c),a.decodeAsync=async(b,c)=>kP(a,b,c),a.safeEncode=(b,c)=>kQ(a,b,c),a.safeDecode=(b,c)=>kR(a,b,c),a.safeEncodeAsync=async(b,c)=>kS(a,b,c),a.safeDecodeAsync=async(b,c)=>kT(a,b,c),kV(a,"ZodType",{check(...a){let b=this.def;return this.clone(iA(b,{checks:[...b.checks??[],...a.map(a=>"function"==typeof a?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...a){return this.check(...a)},clone(a,b){return iJ(this,a,b)},brand(){return this},register(a,b){return a.add(this,b),this},refine(a,b){return this.check(function(a,b={}){return new lQ({type:"custom",check:"custom",fn:a,...iK(b)})}(a,b))},superRefine(a,b){return this.check(function(a,b){var c;let d,e;return c=b=>(b.addIssue=a=>{"string"==typeof a?b.issues.push(iR(a,b.value,d._zod.def)):(a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=b.value),a.inst??(a.inst=d),a.continue??(a.continue=!d._zod.def.abort),b.issues.push(iR(a)))},a(b.value,b)),(e=new iS({check:"custom",...iK(b)}))._zod.check=c,d=e}(a,b))},overwrite(a){return this.check(kv(a))},optional(){return lF(this)},exactOptional(){var a;return a=this,new lG({type:"optional",innerType:a})},nullable(){return lI(this)},nullish(){return lF(lI(this))},nonoptional(a){var b;return b=this,new lL({type:"nonoptional",innerType:b,...iK(a)})},array(){return lu(this)},or(a){return new lx({type:"union",options:[this,a],...iK(void 0)})},and(a){var b;return b=this,new ly({type:"intersection",left:b,right:a})},transform(a){return lO(this,new lD({type:"transform",transform:a}))},default(a){var b,c;return b=this,c=a,new lJ({type:"default",innerType:b,get defaultValue(){return"function"==typeof c?c():iG(c)}})},prefault(a){var b,c;return b=this,c=a,new lK({type:"prefault",innerType:b,get defaultValue(){return"function"==typeof c?c():iG(c)}})},catch(a){var b,c;return b=this,new lM({type:"catch",innerType:b,catchValue:"function"==typeof(c=a)?c:()=>c})},pipe(a){return lO(this,a)},readonly(){var a;return a=this,new lP({type:"readonly",innerType:a})},describe(a){let b=this.clone();return ki.add(b,{description:a}),b},meta(...a){if(0===a.length)return ki.get(this);let b=this.clone();return ki.add(b,a[0]),b},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(a){return a(this)}}),Object.defineProperty(a,"description",{get:()=>ki.get(a)?.description,configurable:!0}),a)),kX=hY("_ZodString",(a,b)=>{jj.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{c.type="string";let{minimum:e,maximum:f,format:g,patterns:h,contentEncoding:i}=a._zod.bag;if("number"==typeof e&&(c.minLength=e),"number"==typeof f&&(c.maxLength=f),g&&(c.format=kB[g]??g,""===c.format&&delete c.format,"time"===g&&delete c.format),i&&(c.contentEncoding=i),h&&h.size>0){let a=[...h];1===a.length?c.pattern=a[0].source:a.length>1&&(c.allOf=[...a.map(a=>({..."draft-07"===b.target||"draft-04"===b.target||"openapi-3.0"===b.target?{type:"string"}:{},pattern:a.source}))])}})(a,b,c,0);let c=a._zod.bag;a.format=c.format??null,a.minLength=c.minimum??null,a.maxLength=c.maximum??null,kV(a,"_ZodString",{regex(...a){return this.check(function(a,b){return new i0({check:"string_format",format:"regex",...iK(b),pattern:a})}(...a))},includes(...a){return this.check(function(a,b){return new i3({check:"string_format",format:"includes",...iK(b),includes:a})}(...a))},startsWith(...a){return this.check(function(a,b){return new i4({check:"string_format",format:"starts_with",...iK(b),prefix:a})}(...a))},endsWith(...a){return this.check(function(a,b){return new i5({check:"string_format",format:"ends_with",...iK(b),suffix:a})}(...a))},min(...a){return this.check(kt(...a))},max(...a){return this.check(ks(...a))},length(...a){return this.check(ku(...a))},nonempty(...a){return this.check(kt(1,...a))},lowercase(a){return this.check(new i1({check:"string_format",format:"lowercase",...iK(a)}))},uppercase(a){return this.check(new i2({check:"string_format",format:"uppercase",...iK(a)}))},trim(){return this.check(kv(a=>a.trim()))},normalize(...a){return this.check(function(a){return kv(b=>b.normalize(a))}(...a))},toLowerCase(){return this.check(kv(a=>a.toLowerCase()))},toUpperCase(){return this.check(kv(a=>a.toUpperCase()))},slugify(){return this.check(kv(a=>a.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")))}})}),kY=hY("ZodString",(a,b)=>{jj.init(a,b),kX.init(a,b),a.email=b=>a.check(kj(k_,b)),a.url=b=>a.check(new k2({type:"string",format:"url",check:"string_format",abort:!1,...iK(b)})),a.jwt=b=>a.check(new lh({type:"string",format:"jwt",check:"string_format",abort:!1,...iK(b)})),a.emoji=b=>a.check(new k3({type:"string",format:"emoji",check:"string_format",abort:!1,...iK(b)})),a.guid=b=>a.check(kk(k0,b)),a.uuid=b=>a.check(new k1({type:"string",format:"uuid",check:"string_format",abort:!1,...iK(b)})),a.uuidv4=b=>a.check(new k1({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...iK(b)})),a.uuidv6=b=>a.check(new k1({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...iK(b)})),a.uuidv7=b=>a.check(new k1({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...iK(b)})),a.nanoid=b=>a.check(new k4({type:"string",format:"nanoid",check:"string_format",abort:!1,...iK(b)})),a.guid=b=>a.check(kk(k0,b)),a.cuid=b=>a.check(new k5({type:"string",format:"cuid",check:"string_format",abort:!1,...iK(b)})),a.cuid2=b=>a.check(new k6({type:"string",format:"cuid2",check:"string_format",abort:!1,...iK(b)})),a.ulid=b=>a.check(new k7({type:"string",format:"ulid",check:"string_format",abort:!1,...iK(b)})),a.base64=b=>a.check(new le({type:"string",format:"base64",check:"string_format",abort:!1,...iK(b)})),a.base64url=b=>a.check(new lf({type:"string",format:"base64url",check:"string_format",abort:!1,...iK(b)})),a.xid=b=>a.check(new k8({type:"string",format:"xid",check:"string_format",abort:!1,...iK(b)})),a.ksuid=b=>a.check(new k9({type:"string",format:"ksuid",check:"string_format",abort:!1,...iK(b)})),a.ipv4=b=>a.check(kl(la,b)),a.ipv6=b=>a.check(km(lb,b)),a.cidrv4=b=>a.check(new lc({type:"string",format:"cidrv4",check:"string_format",abort:!1,...iK(b)})),a.cidrv6=b=>a.check(new ld({type:"string",format:"cidrv6",check:"string_format",abort:!1,...iK(b)})),a.e164=b=>a.check(new lg({type:"string",format:"e164",check:"string_format",abort:!1,...iK(b)})),a.datetime=b=>a.check(new kD({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...iK(b)})),a.date=b=>a.check(new kE({type:"string",format:"date",check:"string_format",...iK(b)})),a.time=b=>a.check(new kF({type:"string",format:"time",check:"string_format",precision:null,...iK(b)})),a.duration=b=>a.check(new kG({type:"string",format:"duration",check:"string_format",...iK(b)}))});function kZ(a){return new kY({type:"string",...iK(a)})}let k$=hY("ZodStringFormat",(a,b)=>{jk.init(a,b),kX.init(a,b)}),k_=hY("ZodEmail",(a,b)=>{jn.init(a,b),k$.init(a,b)}),k0=hY("ZodGUID",(a,b)=>{jl.init(a,b),k$.init(a,b)}),k1=hY("ZodUUID",(a,b)=>{jm.init(a,b),k$.init(a,b)}),k2=hY("ZodURL",(a,b)=>{jo.init(a,b),k$.init(a,b)}),k3=hY("ZodEmoji",(a,b)=>{jp.init(a,b),k$.init(a,b)}),k4=hY("ZodNanoID",(a,b)=>{jq.init(a,b),k$.init(a,b)}),k5=hY("ZodCUID",(a,b)=>{jr.init(a,b),k$.init(a,b)}),k6=hY("ZodCUID2",(a,b)=>{js.init(a,b),k$.init(a,b)}),k7=hY("ZodULID",(a,b)=>{jt.init(a,b),k$.init(a,b)}),k8=hY("ZodXID",(a,b)=>{ju.init(a,b),k$.init(a,b)}),k9=hY("ZodKSUID",(a,b)=>{jv.init(a,b),k$.init(a,b)}),la=hY("ZodIPv4",(a,b)=>{jA.init(a,b),k$.init(a,b)}),lb=hY("ZodIPv6",(a,b)=>{jB.init(a,b),k$.init(a,b)}),lc=hY("ZodCIDRv4",(a,b)=>{jC.init(a,b),k$.init(a,b)}),ld=hY("ZodCIDRv6",(a,b)=>{jD.init(a,b),k$.init(a,b)}),le=hY("ZodBase64",(a,b)=>{jF.init(a,b),k$.init(a,b)}),lf=hY("ZodBase64URL",(a,b)=>{jG.init(a,b),k$.init(a,b)}),lg=hY("ZodE164",(a,b)=>{jH.init(a,b),k$.init(a,b)}),lh=hY("ZodJWT",(a,b)=>{jI.init(a,b),k$.init(a,b)}),li=hY("ZodNumber",(a,b)=>{jJ.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{let{minimum:e,maximum:f,format:g,multipleOf:h,exclusiveMaximum:i,exclusiveMinimum:j}=a._zod.bag;"string"==typeof g&&g.includes("int")?c.type="integer":c.type="number";let k="number"==typeof j&&j>=(e??-1/0),l="number"==typeof i&&i<=(f??1/0),m="draft-04"===b.target||"openapi-3.0"===b.target;k?m?(c.minimum=j,c.exclusiveMinimum=!0):c.exclusiveMinimum=j:"number"==typeof e&&(c.minimum=e),l?m?(c.maximum=i,c.exclusiveMaximum=!0):c.exclusiveMaximum=i:"number"==typeof f&&(c.maximum=f),"number"==typeof h&&(c.multipleOf=h)})(a,b,c,0),kV(a,"ZodNumber",{gt(a,b){return this.check(kp(a,b))},gte(a,b){return this.check(kq(a,b))},min(a,b){return this.check(kq(a,b))},lt(a,b){return this.check(kn(a,b))},lte(a,b){return this.check(ko(a,b))},max(a,b){return this.check(ko(a,b))},int(a){return this.check(ll(a))},safe(a){return this.check(ll(a))},positive(a){return this.check(kp(0,a))},nonnegative(a){return this.check(kq(0,a))},negative(a){return this.check(kn(0,a))},nonpositive(a){return this.check(ko(0,a))},multipleOf(a,b){return this.check(kr(a,b))},step(a,b){return this.check(kr(a,b))},finite(){return this}});let c=a._zod.bag;a.minValue=Math.max(c.minimum??-1/0,c.exclusiveMinimum??-1/0)??null,a.maxValue=Math.min(c.maximum??1/0,c.exclusiveMaximum??1/0)??null,a.isInt=(c.format??"").includes("int")||Number.isSafeInteger(c.multipleOf??.5),a.isFinite=!0,a.format=c.format??null});function lj(a){return new li({type:"number",checks:[],...iK(a)})}let lk=hY("ZodNumberFormat",(a,b)=>{jK.init(a,b),li.init(a,b)});function ll(a){return new lk({type:"number",check:"number_format",abort:!1,format:"safeint",...iK(a)})}let lm=hY("ZodBoolean",(a,b)=>{jL.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>{b.type="boolean"}});function ln(a){return new lm({type:"boolean",...iK(a)})}let lo=hY("ZodAny",(a,b)=>{jM.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>{}});function lp(){return new lo({type:"any"})}let lq=hY("ZodUnknown",(a,b)=>{jN.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>{}});function lr(){return new lq({type:"unknown"})}let ls=hY("ZodNever",(a,b)=>{jO.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>{b.not={}}}),lt=hY("ZodArray",(a,b)=>{jQ.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{let e=a._zod.def,{minimum:f,maximum:g}=a._zod.bag;"number"==typeof f&&(c.minItems=f),"number"==typeof g&&(c.maxItems=g),c.type="array",c.items=kx(e.element,b,{...d,path:[...d.path,"items"]})})(a,b,c,d),a.element=b.element,kV(a,"ZodArray",{min(a,b){return this.check(kt(a,b))},nonempty(a){return this.check(kt(1,a))},max(a,b){return this.check(ks(a,b))},length(a,b){return this.check(ku(a,b))},unwrap(){return this.element}})});function lu(a,b){return new lt({type:"array",element:a,...iK(b)})}let lv=hY("ZodObject",(a,b)=>{jV.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{let e=a._zod.def;c.type="object",c.properties={};let f=e.shape;for(let a in f)c.properties[a]=kx(f[a],b,{...d,path:[...d.path,"properties",a]});let g=new Set([...new Set(Object.keys(f))].filter(a=>{let c=e.shape[a]._zod;return"input"===b.io?void 0===c.optin:void 0===c.optout}));g.size>0&&(c.required=Array.from(g)),e.catchall?._zod.def.type==="never"?c.additionalProperties=!1:e.catchall?e.catchall&&(c.additionalProperties=kx(e.catchall,b,{...d,path:[...d.path,"additionalProperties"]})):"output"===b.io&&(c.additionalProperties=!1)})(a,b,c,d),iy(a,"shape",()=>b.shape),kV(a,"ZodObject",{keyof(){return lC(Object.keys(this._zod.def.shape))},catchall(a){return this.clone({...this._zod.def,catchall:a})},passthrough(){return this.clone({...this._zod.def,catchall:lr()})},loose(){return this.clone({...this._zod.def,catchall:lr()})},strict(){return this.clone({...this._zod.def,catchall:new ls({type:"never",...iK(void 0)})})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(a){return function(a,b){if(!iF(b))throw Error("Invalid input to extend: expected a plain object");let c=a._zod.def.checks;if(c&&c.length>0){let c=a._zod.def.shape;for(let a in b)if(void 0!==Object.getOwnPropertyDescriptor(c,a))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let d=iA(a._zod.def,{get shape(){let c={...a._zod.def.shape,...b};return iz(this,"shape",c),c}});return iJ(a,d)}(this,a)},safeExtend(a){var b=this;if(!iF(a))throw Error("Invalid input to safeExtend: expected a plain object");let c=iA(b._zod.def,{get shape(){let c={...b._zod.def.shape,...a};return iz(this,"shape",c),c}});return iJ(b,c)},merge(a){var b=this;if(b._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let c=iA(b._zod.def,{get shape(){let c={...b._zod.def.shape,...a._zod.def.shape};return iz(this,"shape",c),c},get catchall(){return a._zod.def.catchall},checks:a._zod.def.checks??[]});return iJ(b,c)},pick(a){return function(a,b){let c=a._zod.def,d=c.checks;if(d&&d.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let e=iA(a._zod.def,{get shape(){let a={};for(let d in b){if(!(d in c.shape))throw Error(`Unrecognized key: "${d}"`);b[d]&&(a[d]=c.shape[d])}return iz(this,"shape",a),a},checks:[]});return iJ(a,e)}(this,a)},omit(a){return function(a,b){let c=a._zod.def,d=c.checks;if(d&&d.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let e=iA(a._zod.def,{get shape(){let d={...a._zod.def.shape};for(let a in b){if(!(a in c.shape))throw Error(`Unrecognized key: "${a}"`);b[a]&&delete d[a]}return iz(this,"shape",d),d},checks:[]});return iJ(a,e)}(this,a)},partial(...a){return function(a,b,c){let d=b._zod.def.checks;if(d&&d.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let e=iA(b._zod.def,{get shape(){let d=b._zod.def.shape,e={...d};if(c)for(let b in c){if(!(b in d))throw Error(`Unrecognized key: "${b}"`);c[b]&&(e[b]=a?new a({type:"optional",innerType:d[b]}):d[b])}else for(let b in d)e[b]=a?new a({type:"optional",innerType:d[b]}):d[b];return iz(this,"shape",e),e},checks:[]});return iJ(b,e)}(lE,this,a[0])},required(...a){var b,c;let d;return b=this,c=a[0],d=iA(b._zod.def,{get shape(){let a=b._zod.def.shape,d={...a};if(c)for(let b in c){if(!(b in d))throw Error(`Unrecognized key: "${b}"`);c[b]&&(d[b]=new lL({type:"nonoptional",innerType:a[b]}))}else for(let b in a)d[b]=new lL({type:"nonoptional",innerType:a[b]});return iz(this,"shape",d),d}}),iJ(b,d)}})});function lw(a,b){return new lv({type:"object",shape:a??{},...iK(b)})}let lx=hY("ZodUnion",(a,b)=>{jX.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e,f,g;return f=!1===(e=a._zod.def).inclusive,g=e.options.map((a,c)=>kx(a,b,{...d,path:[...d.path,f?"oneOf":"anyOf",c]})),void(f?c.oneOf=g:c.anyOf=g)},a.options=b.options}),ly=hY("ZodIntersection",(a,b)=>{jY.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e,f,g,h;return f=kx((e=a._zod.def).left,b,{...d,path:[...d.path,"allOf",0]}),g=kx(e.right,b,{...d,path:[...d.path,"allOf",1]}),void(c.allOf=[...(h=a=>"allOf"in a&&1===Object.keys(a).length)(f)?f.allOf:[f],...h(g)?g.allOf:[g]])}}),lz=hY("ZodRecord",(a,b)=>{j$.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{let e=a._zod.def;c.type="object";let f=e.keyType,g=f._zod.bag,h=g?.patterns;if("loose"===e.mode&&h&&h.size>0){let a=kx(e.valueType,b,{...d,path:[...d.path,"patternProperties","*"]});for(let b of(c.patternProperties={},h))c.patternProperties[b.source]=a}else("draft-07"===b.target||"draft-2020-12"===b.target)&&(c.propertyNames=kx(e.keyType,b,{...d,path:[...d.path,"propertyNames"]})),c.additionalProperties=kx(e.valueType,b,{...d,path:[...d.path,"additionalProperties"]});let i=f._zod.values;if(i){let a=[...i].filter(a=>"string"==typeof a||"number"==typeof a);a.length>0&&(c.required=a)}})(a,b,c,d),a.keyType=b.keyType,a.valueType=b.valueType});function lA(a,b,c){return new lz(b&&b._zod?{type:"record",keyType:a,valueType:b,...iK(c)}:{type:"record",keyType:kZ(),valueType:a,...iK(b)})}let lB=hY("ZodEnum",(a,b)=>{j_.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e;(e=it(a._zod.def.entries)).every(a=>"number"==typeof a)&&(c.type="number"),e.every(a=>"string"==typeof a)&&(c.type="string"),c.enum=e},a.enum=b.entries,a.options=Object.values(b.entries);let c=new Set(Object.keys(b.entries));a.extract=(a,d)=>{let e={};for(let d of a)if(c.has(d))e[d]=b.entries[d];else throw Error(`Key ${d} not found in enum`);return new lB({...b,checks:[],...iK(d),entries:e})},a.exclude=(a,d)=>{let e={...b.entries};for(let b of a)if(c.has(b))delete e[b];else throw Error(`Key ${b} not found in enum`);return new lB({...b,checks:[],...iK(d),entries:e})}});function lC(a,b){return new lB({type:"enum",entries:Array.isArray(a)?Object.fromEntries(a.map(a=>[a,a])):a,...iK(b)})}let lD=hY("ZodTransform",(a,b)=>{j0.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>((a,b,c,d)=>{if("throw"===b.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")})(0,a,0,0),a._zod.parse=(c,d)=>{if("backward"===d.direction)throw new h$(a.constructor.name);c.addIssue=d=>{"string"==typeof d?c.issues.push(iR(d,c.value,b)):(d.fatal&&(d.continue=!1),d.code??(d.code="custom"),d.input??(d.input=c.value),d.inst??(d.inst=a),c.issues.push(iR(d)))};let e=b.transform(c.value,c);return e instanceof Promise?e.then(a=>(c.value=a,c.fallback=!0,c)):(c.value=e,c.fallback=!0,c)}}),lE=hY("ZodOptional",(a,b)=>{j2.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>kC(a,b,c,d),a.unwrap=()=>a._zod.def.innerType});function lF(a){return new lE({type:"optional",innerType:a})}let lG=hY("ZodExactOptional",(a,b)=>{j3.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>kC(a,b,c,d),a.unwrap=()=>a._zod.def.innerType}),lH=hY("ZodNullable",(a,b)=>{j4.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e,f,g;return f=kx((e=a._zod.def).innerType,b,d),g=b.seen.get(a),void("openapi-3.0"===b.target?(g.ref=e.innerType,c.nullable=!0):c.anyOf=[f,{type:"null"}])},a.unwrap=()=>a._zod.def.innerType});function lI(a){return new lH({type:"nullable",innerType:a})}let lJ=hY("ZodDefault",(a,b)=>{j5.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e;kx((e=a._zod.def).innerType,b,d),b.seen.get(a).ref=e.innerType,c.default=JSON.parse(JSON.stringify(e.defaultValue))},a.unwrap=()=>a._zod.def.innerType,a.removeDefault=a.unwrap}),lK=hY("ZodPrefault",(a,b)=>{j7.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e;kx((e=a._zod.def).innerType,b,d),b.seen.get(a).ref=e.innerType,"input"===b.io&&(c._prefault=JSON.parse(JSON.stringify(e.defaultValue)))},a.unwrap=()=>a._zod.def.innerType}),lL=hY("ZodNonOptional",(a,b)=>{j8.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e;kx((e=a._zod.def).innerType,b,d),b.seen.get(a).ref=e.innerType},a.unwrap=()=>a._zod.def.innerType}),lM=hY("ZodCatch",(a,b)=>{ka.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>((a,b,c,d)=>{let e,f=a._zod.def;kx(f.innerType,b,d),b.seen.get(a).ref=f.innerType;try{e=f.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}c.default=e})(a,b,c,d),a.unwrap=()=>a._zod.def.innerType,a.removeCatch=a.unwrap}),lN=hY("ZodPipe",(a,b)=>{kb.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e,f,g;return f=(e=a._zod.def).in._zod.traits.has("$ZodTransform"),void(kx(g="input"===b.io?f?e.out:e.in:e.out,b,d),b.seen.get(a).ref=g)},a.in=b.in,a.out=b.out});function lO(a,b){return new lN({type:"pipe",in:a,out:b})}let lP=hY("ZodReadonly",(a,b)=>{kd.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(b,c,d)=>{let e;kx((e=a._zod.def).innerType,b,d),b.seen.get(a).ref=e.innerType,c.readOnly=!0},a.unwrap=()=>a._zod.def.innerType}),lQ=hY("ZodCustom",(a,b)=>{kf.init(a,b),kW.init(a,b),a._zod.processJSONSchema=(a,b,c)=>((a,b,c,d)=>{if("throw"===b.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")})(0,a,0,0)}),lR={};function lS(a){switch(a.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function lT(a){let b=[];return a.metadata?.openapi?.parameters?b.push(...a.metadata.openapi.parameters):a.query instanceof lv&&Object.entries(a.query.shape).forEach(([a,c])=>{c instanceof lv&&b.push({name:a,in:"query",schema:{type:lS(c),..."minLength"in c&&c.minLength?{minLength:c.minLength}:{},description:c.description}})}),b}function lU(a){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."},...a}}async function lV(a,b){return Object.entries(a).forEach(([a,b])=>{let c=b.options;if(!(!b.path||c.metadata?.SERVER_ONLY)&&("GET"===c.method&&(lR[b.path]={get:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:lT(c),responses:lU(c.metadata?.openapi?.responses)}}),"POST"===c.method)){let a=function(a){if(a.metadata?.openapi?.requestBody)return a.metadata.openapi.requestBody;if(a.body&&(a.body instanceof lv||a.body instanceof lE)){let b=a.body.shape;if(!b)return;let c={},d=[];return Object.entries(b).forEach(([a,b])=>{b instanceof lv&&(c[a]={type:lS(b),description:b.description},b instanceof lE||d.push(a))}),{required:!(a.body instanceof lE)&&!!a.body,content:{"application/json":{schema:{type:"object",properties:c,required:d}}}}}}(c);lR[b.path]={post:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:lT(c),...a?{requestBody:a}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:lU(c.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:b?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:lR}}let lW=((l=function(){}).prototype=Object.create(null),Object.freeze(l.prototype),l);function lX(){return{root:{key:""},static:new lW}}function lY(a){let[b,...c]=a.split("/");return""===c[c.length-1]?c.slice(0,-1):c}function lZ(a,b){let c=new lW;for(let[d,e]of b){let b=d<0?a.slice(-(d+1)).join("/"):a[d];if("string"==typeof e)c[e]=b;else{let a=b.match(e);if(a)for(let b in a.groups)c[b]=a.groups[b]}}return c}function l$(a,b="",c,d){b=b.toUpperCase(),47!==c.charCodeAt(0)&&(c=`/${c}`);let e=lY(c=c.replace(/\\:/g,"%3A")),f=a.root,g=0,h=[],i=[];for(let a=0;a<e.length;a++){let b=e[a];if(b.startsWith("**")){f.wildcard||(f.wildcard={key:"**"}),f=f.wildcard,h.push([-(a+1),b.split(":")[1]||"_",2===b.length]);break}if("*"===b||b.includes(":")){if(f.param||(f.param={key:"*"}),f=f.param,"*"===b)h.push([a,`_${g++}`,!0]);else if(b.includes(":",1)){let c=function(a){let b=a.replace(/:(\w+)/g,(a,b)=>`(?<${b}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${b}$`)}(b);i[a]=c,f.hasRegexParam=!0,h.push([a,c,!1])}else h.push([a,b.slice(1),!1]);continue}"\\*"===b?b=e[a]="*":"\\*\\*"===b&&(b=e[a]="**");let c=f.static?.[b];if(c)f=c;else{let a={key:b};f.static||(f.static=new lW),f.static[b]=a,f=a}}let j=h.length>0;f.methods||(f.methods=new lW),f.methods[b]??=[],f.methods[b].push({data:d||null,paramsRegexp:i,paramsMap:j?h:void 0}),j||(a.static["/"+e.join("/")]=f)}function l_(a){return new kY({type:"string",coerce:!0,...iK(a)})}function l0(a){return new lm({type:"boolean",coerce:!0,...iK(a)})}let l1=a=>(b,c,d)=>{let e=function(a,b){let c={};for(let[d,e]of hx(b.headers?.get("cookie")||""))d.startsWith(a)&&(c[d]=e);return c}(b,d),f=d.context.logger,g=()=>{let a=function(a,b){let c={};for(let d in a)c[d]={name:d,value:"",attributes:{...b,maxAge:0}};return c}(e,c);for(let a in e)delete e[a];return a};return{chunk(d,h){let i=g();for(let g of function(a,b,c,d){let e=4050-hR(`${b.name}.99`,"",{...b.attributes}).length,f=e>0?Math.ceil(b.value.length/e):1/0;if(f<=1)return c[b.name]=b.value,[b];if(f>100)return d.warn(`${a} cookie is too large to store even after chunking, so the cache was skipped. Reduce the cached data or use a database session.`),[];let g=[];for(let a=0;a<f;a++){let d=`${b.name}.${a}`,f=a*e,h=b.value.substring(f,f+e);g.push({...b,name:d,value:h}),c[d]=h}return d.debug(`CHUNKING_${a.toUpperCase()}_COOKIE`,{message:`${a} cookie exceeds the 4050 byte limit and was split into ${f} chunks.`,valueSize:b.value.length,chunkCount:f,chunkSizes:g.map(a=>a.value.length)}),g}(a,{name:b,value:d,attributes:{...c,...h}},e,f))i[g.name]=g;return Object.values(i)},clean:()=>Object.values(g()),setCookies(a){for(let b of a)d.setCookie(b.name,b.value,b.attributes)}}},l2=l1("Session"),l3=l1("Account");function l4(a,b){let c=a.getCookie(b);if(c)return c;let d=[],e=a.headers?.get("cookie");if(!e)return null;for(let[a,c]of hx(e))if(a.startsWith(b+".")){let b=parseInt(a.split(".").at(-1)||"0",10);isNaN(b)||d.push({index:b,value:c})}return d.length>0?(d.sort((a,b)=>a.index-b.index),d.map(a=>a.value).join("")):null}async function l5(a,b){let c=a.context.authCookies.accountData,d={maxAge:300,...c.attributes},e=await hc(b,a.context.secretConfig,"better-auth-account",d.maxAge),f=l3(c.name,d,a);f.setCookies(f.chunk(e,d))}async function l6(a){let b=l4(a,a.context.authCookies.accountData.name);if(b){let c=(0,hy.$)(await he(b,a.context.secretConfig,"better-auth-account"));if(c)return c}return null}let l7=lF(lw({disableCookieCache:l0().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:l0().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function l8(a){return a?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function l9(a,b,c){let d="",e=0,f=0;for(let c of a)for(e=e<<8|c,f+=8;f>=6;)f-=6,d+=b[e>>f&63];if(f>0&&(d+=b[e<<6-f&63]),c){let a=(4-d.length%4)%4;d+="=".repeat(a)}return d}function ma(a,b){let c=new Map;for(let a=0;a<b.length;a++)c.set(b[a],a);let d=[],e=0,f=0;for(let b of a){if("="===b)break;let a=c.get(b);if(void 0===a)throw Error(`Invalid Base64 character: ${b}`);e=e<<6|a,(f+=6)>=8&&(f-=8,d.push(e>>f&255))}return Uint8Array.from(d)}let mb={encode(a,b={}){let c=l8(!1);return l9("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){"string"!=typeof a&&(a=new TextDecoder().decode(a));let b=l8(a.includes("-")||a.includes("_"));return ma(a,b)}},mc={encode(a,b={}){let c=l8(!0);return l9("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){let b=l8(a.includes("-")||a.includes("_"));return ma(a,b)}},md=new Map,me={decode:(a,b="utf-8")=>(md.has(b)||md.set(b,new TextDecoder(b)),md.get(b).decode(a)),encode:new TextEncoder().encode},mf=(a="SHA-256",b="none")=>{let c={importKey:async(b,c)=>hJ().importKey("raw","string"==typeof b?new TextEncoder().encode(b):b,{name:"HMAC",hash:{name:a}},!1,[c]),sign:async(a,d)=>{"string"==typeof a&&(a=await c.importKey(a,"sign"));let e=await hJ().sign("HMAC",a,"string"==typeof d?new TextEncoder().encode(d):d);return"hex"===b?(a=>{if("string"==typeof a&&(a=new TextEncoder().encode(a)),0===a.byteLength)return"";let b=new Uint8Array(a),c="";for(let a of b)c+=a.toString(16).padStart(2,"0");return c})(e):"base64"===b||"base64url"===b||"base64urlnopad"===b?mc.encode(e,{padding:"base64urlnopad"!==b}):e},verify:async(a,d,e)=>("string"==typeof a&&(a=await c.importKey(a,"verify")),"hex"===b&&(e=(a=>{if(!a)return"";if("string"==typeof a){if(a.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(a))throw Error("Invalid hexadecimal string");let b=new Uint8Array(a.length/2);for(let c=0;c<a.length;c+=2)b[c/2]=parseInt(a.slice(c,c+2),16);return new TextDecoder().decode(b)}return new TextDecoder().decode(a)})(e)),("base64"===b||"base64url"===b||"base64urlnopad"===b)&&(e=await mb.decode(e)),hJ().verify("HMAC",a,"string"==typeof e?new TextEncoder().encode(e):e,"string"==typeof d?new TextEncoder().encode(d):d))};return c};function mg(a){let b="string"==typeof a.baseURL?a.baseURL:void 0,c="object"==typeof a.baseURL&&null!==a.baseURL?a.baseURL.protocol:void 0,d=(a.advanced?.useSecureCookies!==void 0?a.advanced?.useSecureCookies:"https"===c||"http"!==c&&(b?b.startsWith("https://"):ey.KV))?"__Secure-":"",e=!!a.advanced?.crossSubDomainCookies?.enabled,f=e?a.advanced?.crossSubDomainCookies?.domain||(b?new URL(b).hostname:void 0):void 0;if(e&&!f&&!eE(a.baseURL))throw new em.$l("baseURL is required when crossSubdomainCookies are enabled.");return function(b,c={}){let g=a.advanced?.cookiePrefix||"better-auth",h=a.advanced?.cookies?.[b]?.name||`${g}.${b}`,i=a.advanced?.cookies?.[b]?.attributes??{};return{name:`${d}${h}`,attributes:{secure:!!d,sameSite:"lax",path:"/",httpOnly:!0,...e?{domain:f}:{},...a.advanced?.defaultCookieAttributes,...c,...i}}}}function mh(a){let b=mg(a),c=b("session_token",{maxAge:a.session?.expiresIn||Math.round(function(){let a,b=hq.exec("7d");if(!b||b[4]&&b[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let c=parseFloat(b[2]),d=b[3].toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":a=315576e5*c;break;case"months":case"month":case"mo":a=2592e6*c;break;case"weeks":case"week":case"w":a=6048e5*c;break;case"days":case"day":case"d":a=864e5*c;break;case"hours":case"hour":case"hrs":case"hr":case"h":a=36e5*c;break;case"minutes":case"minute":case"mins":case"min":case"m":a=6e4*c;break;case"seconds":case"second":case"secs":case"sec":case"s":a=1e3*c;break;default:throw TypeError(`Unknown time unit: "${d}"`)}return"-"===b[1]||"ago"===b[4]?-a:a}()/1e3)}),d=b("session_data",{maxAge:a.session?.cookieCache?.maxAge||300}),e=b("account_data",{maxAge:a.session?.cookieCache?.maxAge||300}),f=b("dont_remember");return{sessionToken:{name:c.name,attributes:c.attributes},sessionData:{name:d.name,attributes:d.attributes},dontRememberToken:{name:f.name,attributes:f.attributes},accountData:{name:e.name,attributes:e.attributes}}}async function mi(a,b,c){let d;if(!a.context.options.session?.cookieCache?.enabled)return;let e=hh(b.session,a.context.options.session?.additionalFields),f=hk(a.context.options,b.user),g=a.context.options.session?.cookieCache?.version,h="1";if(g){if("string"==typeof g)h=g;else if("function"==typeof g){let a=g(b.session,b.user);h=eK(a)?await a:a}}let i={session:e,user:f,updatedAt:Date.now(),version:h},j={...a.context.authCookies.sessionData.attributes,maxAge:c?void 0:a.context.authCookies.sessionData.attributes.maxAge},k=hp(j.maxAge||60,"sec").getTime(),l=a.context.options.session?.cookieCache?.strategy||"compact";d="jwe"===l?await hc(i,a.context.secretConfig,"better-auth-session",j.maxAge||300):"jwt"===l?await g6(i,a.context.secret,j.maxAge||300):mc.encode(JSON.stringify({session:i,expiresAt:k,signature:await mf("SHA-256","base64urlnopad").sign(a.context.secret,JSON.stringify({...i,expiresAt:k}))}),{padding:!1});let m=l2(a.context.authCookies.sessionData.name,j,a);if(m.setCookies(m.chunk(d,j)),a.context.options.account?.storeAccountCookie&&!function(a,b){let c=new Set;a.responseHeaders&&c.add(a.responseHeaders),a.context?.responseHeaders&&c.add(a.context.responseHeaders);let d=`${b}=`,e=`${b}.`;for(let a of c)if(("function"==typeof a.getSetCookie?a.getSetCookie():hs(a.get("set-cookie")||"")).some(a=>a.startsWith(d)||a.startsWith(e)))return!0;return!1}(a,a.context.authCookies.accountData.name)){let c=await l6(a);if(c)if(eJ(a.context.options)&&c.userId!==b.user.id){mk(a,a.context.authCookies.accountData);let b=l3(a.context.authCookies.accountData.name,a.context.authCookies.accountData.attributes,a);b.setCookies(b.clean())}else await l5(a,c)}}async function mj(a,b,c,d){let e=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);c=void 0!==c?c:!!e;let f=a.context.authCookies.sessionToken.attributes,g=c?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...f,maxAge:g,...d}),c&&await a.setSignedCookie(a.context.authCookies.dontRememberToken.name,"true",a.context.secret,a.context.authCookies.dontRememberToken.attributes),await mi(a,b,c),a.context.setNewSession(b)}function mk(a,b){!function(a,b){let c=new Set;a.responseHeaders&&c.add(a.responseHeaders),a.context?.responseHeaders&&c.add(a.context.responseHeaders);let d=`${b}=`,e=`${b}.`;for(let a of c){let b="function"==typeof a.getSetCookie?a.getSetCookie():hs(a.get("set-cookie")||"");if(!b.length)continue;let c=b.filter(a=>!a.startsWith(d)&&!a.startsWith(e));if(c.length!==b.length)for(let b of(a.delete("set-cookie"),c))a.append("set-cookie",b)}}(a,b.name),a.setCookie(b.name,"",{...b.attributes,maxAge:0})}function ml(a,b){if(mk(a,a.context.authCookies.sessionToken),mk(a,a.context.authCookies.sessionData),a.context.options.account?.storeAccountCookie){mk(a,a.context.authCookies.accountData);let b=l3(a.context.authCookies.accountData.name,a.context.authCookies.accountData.attributes,a),c=b.clean();b.setCookies(c)}"cookie"===a.context.oauthConfig.storeStateStrategy&&mk(a,a.context.createAuthCookie("oauth_state"));let c=l2(a.context.authCookies.sessionData.name,a.context.authCookies.sessionData.attributes,a),d=c.clean();c.setCookies(d),b||mk(a,a.context.authCookies.dontRememberToken)}function mm(a){return kl(la,void 0).safeParse(a).success||km(lb,void 0).safeParse(a).success}function mn(a){if(a.includes("::")){let b=a.split("::"),c=b[0]?b[0].split(":"):[],d=b[1]?b[1].split(":"):[],e=Array(8-c.length-d.length).fill("0000");return[...c.map(a=>a.padStart(4,"0")),...e,...d.map(a=>a.padStart(4,"0"))]}return a.split(":").map(a=>a.padStart(4,"0"))}function mo(a,b={}){if(kl(la,void 0).safeParse(a).success||!km(lb,void 0).safeParse(a).success)return a.toLowerCase();let c=function(a){let b=a.toLowerCase();if(b.startsWith("::ffff:")){let a=b.substring(7);if(kl(la,void 0).safeParse(a).success)return a}let c=a.split(":");if(7===c.length&&c[5]?.toLowerCase()==="ffff"){let a=c[6];if(a&&kl(la,void 0).safeParse(a).success)return a}if(b.includes("::ffff:")||b.includes(":ffff:")){let b=mn(a);if(8===b.length&&"0000"===b[0]&&"0000"===b[1]&&"0000"===b[2]&&"0000"===b[3]&&"0000"===b[4]&&"ffff"===b[5]&&b[6]&&b[7])return`${Number.parseInt(b[6].substring(0,2),16)}.${Number.parseInt(b[6].substring(2,4),16)}.${Number.parseInt(b[7].substring(0,2),16)}.${Number.parseInt(b[7].substring(2,4),16)}`}return null}(a);if(c)return c.toLowerCase();var d=b.ipv6Subnet??64;let e=mn(a);if(void 0!==d&&d<128){let a=Math.max(0,Math.floor(d));return e.map(b=>{if(a<=0)return"0000";if(a>=16)return a-=16,b;let c=Number.parseInt(b,16)&(65535<<16-a&65535);return a=0,c.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return e.join(":").toLowerCase()}function mp(a,b){if(b.advanced?.ipAddress?.disableIpTracking)return null;let c="headers"in a?a.headers:a;for(let a of b.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"]){let d="get"in c?c.get(a):c[a];if("string"==typeof d){let a=d.split(",")[0].trim();if(mm(a))return mo(a,{ipv6Subnet:b.advanced?.ipAddress?.ipv6Subnet})}}return(0,ey.Nu)()||(0,ey.yz)()?"127.0.0.1":null}function mq(a,b){return{digest:async c=>{let d=new TextEncoder,e="string"==typeof c?d.encode(c):c,f=await hJ().digest(a,e);return"hex"===b?Array.from(new Uint8Array(f)).map(a=>a.toString(16).padStart(2,"0")).join(""):"base64"===b||"base64url"===b||"base64urlnopad"===b?b.includes("url")?mc.encode(f,{padding:"base64urlnopad"!==b}):mb.encode(f):f}}}let mr=async a=>{let b=await mq("SHA-256").digest(new TextEncoder().encode(a));return mc.encode(new Uint8Array(b),{padding:!1})};async function ms(a,b){return b&&"plain"!==b?"hashed"===b?mr(a):"object"==typeof b&&"hash"in b?b.hash(a):a:a}function mt(a,b){if(b){if("object"==typeof b&&"default"in b){if(b.overrides){for(let[c,d]of Object.entries(b.overrides))if(a.startsWith(c))return d}return b.default}return b}}var mu=c(79953),mv=c(34248);let mw=async()=>{let a=(0,mu.Q)();if(!a.context.endpointContextAsyncStorage){let b=await (0,mv.V)();a.context.endpointContextAsyncStorage=new b}return a.context.endpointContextAsyncStorage};async function mx(){let a=(await mw()).getStore();if(!a)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return a}async function my(a,b){return(await mw()).run(a,b)}var mz=c(6840),mA=c(33583);let mB="better_auth.operation_id",mC="better_auth.hook.type",mD="better_auth.context";var mE=c(64561),mF=c(15793);function mG(a,b=Date.now()){return Math.max(Math.floor((("number"==typeof a?a:a.getTime())-b)/1e3),0)}let mH=(a,b)=>{let c,d=b.logger,e=b.options,f=e.secondaryStorage,g=new Map,h=!1,i=e.session?.expiresIn||604800,{createWithHooks:j,updateWithHooks:k,updateManyWithHooks:l,deleteWithHooks:m,deleteManyWithHooks:n,consumeOneWithHooks:o}=(c=b.hooks,{createWithHooks:async function(b,d,e){let f=await mx().catch(()=>null),g=b;for(let{source:a,hooks:b}of c){let c=b[d]?.create?.before;if(c){let b=await (0,mA.f)(`db create.before ${d}`,{[mC]:"create.before",[mE.qU]:d,[mD]:a},()=>c(g,f));if(!1===b)return null;"object"==typeof b&&"data"in b&&(g={...g,...b.data})}}let h=null;for(let{source:b,hooks:i}of((!e||e.executeMainFn)&&(h=await (await (0,mz.d3)(a)).create({model:d,data:g,forceAllowId:!0})),e?.fn&&(h=await e.fn(h??g)),c)){let a=i[d]?.create?.after;a&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db create.after ${d}`,{[mC]:"create.after",[mE.qU]:d,[mD]:b},()=>a(h,f))})}return h},updateWithHooks:async function(b,d,e,f){let g=await mx().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,mA.f)(`db update.before ${e}`,{[mC]:"update.before",[mE.qU]:e,[mD]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await (0,mz.d3)(a)).update({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db update.after ${e}`,{[mC]:"update.after",[mE.qU]:e,[mD]:a},()=>c(j,g))})}return j},updateManyWithHooks:async function(b,d,e,f){let g=await mx().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,mA.f)(`db updateMany.before ${e}`,{[mC]:"updateMany.before",[mE.qU]:e,[mD]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await (0,mz.d3)(a)).updateMany({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db updateMany.after ${e}`,{[mC]:"updateMany.after",[mE.qU]:e,[mD]:a},()=>c(j,g))})}return j},deleteWithHooks:async function(b,d,e){let f=await mx().catch(()=>null),g=null;try{g=(await (await (0,mz.d3)(a)).findMany({model:d,where:b,limit:1}))[0]||null}catch{}if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.before;if(c&&await (0,mA.f)(`db delete.before ${d}`,{[mC]:"delete.before",[mE.qU]:d,[mD]:a},()=>c(g,f))===!1)return null}let h=e?await e.fn(b):null,i=(!e||e.executeMainFn)&&g?await (await (0,mz.d3)(a)).delete({model:d,where:b}):h;if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.after;c&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db delete.after ${d}`,{[mC]:"delete.after",[mE.qU]:d,[mD]:a},()=>c(g,f))})}return i},deleteManyWithHooks:async function(b,d,e){let f=await mx().catch(()=>null),g=[];try{g=await (await (0,mz.d3)(a)).findMany({model:d,where:b})}catch{}for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.before;if(c&&await (0,mA.f)(`db delete.before ${d}`,{[mC]:"delete.before",[mE.qU]:d,[mD]:b},()=>c(a,f))===!1)return null}let h=e?await e.fn(b):null,i=!e||e.executeMainFn?await (await (0,mz.d3)(a)).deleteMany({model:d,where:b}):h;for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.after;c&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db delete.after ${d}`,{[mC]:"delete.after",[mE.qU]:d,[mD]:b},()=>c(a,f))})}return i},consumeOneWithHooks:async function(b,d,e,f){let g=await mx().catch(()=>null),h=c.flatMap(({source:a,hooks:c})=>{let d=c[b]?.delete?.before;return d?[{source:a,fn:d}]:[]}),i=f??null;if(h.length){if(!i)try{i=(await (await (0,mz.d3)(a)).findMany({model:b,where:d,limit:1}))[0]||null}catch{}if(i){for(let{source:a,fn:c}of h)if(await (0,mA.f)(`db delete.before ${b}`,{[mC]:"delete.before",[mE.qU]:b,[mD]:a},()=>c(i,g))===!1)return null}}let j=await e();if(!j)return null;for(let{source:a,hooks:d}of c){let c=d[b]?.delete?.after;c&&await (0,mz.dS)(async()=>{await (0,mA.f)(`db delete.after ${b}`,{[mC]:"delete.after",[mE.qU]:b,[mD]:a},()=>c(j,g))})}return j}});async function p(a){if(!f)return;let b=await f.get(`active-sessions-${a.id}`);if(!b)return;let c=Date.now(),d=((0,hy.$)(b)||[]).filter(a=>a.expiresAt>c);await Promise.all(d.map(async({token:b})=>{let d=await f.get(b);if(!d)return;let e=(0,hy.$)(d);if(!e)return;let g=mG(e.session.expiresAt,c);await f.set(b,JSON.stringify({session:e.session,user:a}),Math.floor(g))}))}async function q(a,b){let c,d=g.get(a)??Promise.resolve(),e=new Promise(a=>{c=a}),f=d.catch(()=>{}).then(()=>e);g.set(a,f),await d.catch(()=>{});try{return await b()}finally{c(),g.get(a)===f&&g.delete(a)}}return{createOAuthUser:async(b,c)=>(0,mz.iD)(a,async()=>{let a=await j({createdAt:new Date,updatedAt:new Date,...b,email:b.email?.toLowerCase()},"user",void 0);return{user:a,account:await j({...c,userId:a.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async a=>await j({createdAt:new Date,updatedAt:new Date,...a,email:a.email?.toLowerCase()},"user",void 0),createAccount:async a=>await j({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),listSessions:async(c,d)=>{if(f){let a=await f.get(`active-sessions-${c}`);if(!a)return[];let d=(0,hy.$)(a)||[],e=Date.now(),g=new Set,h=[];for(let{token:a,expiresAt:c}of d){if(c<=e||g.has(a))continue;g.add(a);let d=await f.get(a);if(d)try{let a="string"==typeof d?JSON.parse(d):d;if(!a?.session)continue;h.push(hm(b.options,{...a.session,expiresAt:new Date(a.session.expiresAt)}))}catch{continue}}return h}return await (await (0,mz.d3)(a)).findMany({model:"session",where:[{field:"userId",value:c},...d?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(b,c,d,e)=>await (await (0,mz.d3)(a)).findMany({model:"user",limit:b,offset:c,sortBy:d,where:e}),countTotalUsers:async b=>{let c=await (await (0,mz.d3)(a)).count({model:"user",where:b});return"string"==typeof c?parseInt(c):c},deleteUser:async a=>{(!f||e.session?.storeSessionInDatabase)&&await n([{field:"userId",value:a}],"session",void 0),await n([{field:"userId",value:a}],"account",void 0),await m([{field:"id",value:a}],"user",void 0)},createSession:async(c,d,g,h)=>{let k,l=await (async()=>{let a=await mx().catch(()=>null);return a?.headers||a?.request?.headers})(),m=e.session?.storeSessionInDatabase,{id:n,...o}=g||{};if(f&&!m){let a=b.generateId({model:"session"});k=!1!==a?a:(0,mF.$)()}let p=function(a){let b=hj(a,"session","input"),c={};for(let a in b)void 0!==b[a].defaultValue&&(c[a]="function"==typeof b[a].defaultValue?b[a].defaultValue():b[a].defaultValue);return c}(e),q={...k?{id:k}:{},ipAddress:l&&mp(l,e)||"",userAgent:l?.get("user-agent")||"",...o,expiresAt:d?hp(86400,"sec"):hp(i,"sec"),userId:c,token:(0,mF.$)(32),createdAt:new Date,updatedAt:new Date,...p,...h?o:{}};return await j(q,"session",f?{fn:async b=>{let d=await f.get(`active-sessions-${c}`),e=[],g=Date.now();d&&(e=(e=(0,hy.$)(d)||[]).filter(a=>a.expiresAt>g&&a.token!==q.token));let h=[...e,{token:q.token,expiresAt:q.expiresAt.getTime()}].sort((a,b)=>a.expiresAt-b.expiresAt),i=mG(h.at(-1)?.expiresAt??q.expiresAt.getTime(),g);i>0&&await f.set(`active-sessions-${c}`,JSON.stringify(h),i);let j=await (await (0,mz.d3)(a)).findOne({model:"user",where:[{field:"id",value:c}]}),k=mG(q.expiresAt,g);return k>0&&await f.set(q.token,JSON.stringify({session:b,user:j}),k),b},executeMainFn:m}:void 0)},findSession:async c=>{if(f){let a=await f.get(c);if(!a&&(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase))return null;if(a){let c=(0,hy.$)(a);return c?{session:hm(b.options,{...c.session,expiresAt:new Date(c.session.expiresAt),createdAt:new Date(c.session.createdAt),updatedAt:new Date(c.session.updatedAt)}),user:hk(b.options,{...c.user,createdAt:new Date(c.user.createdAt),updatedAt:new Date(c.user.updatedAt)})}:null}}let d=await (await (0,mz.d3)(a)).findOne({model:"session",where:[{value:c,field:"token"}],join:{user:!0}});if(!d)return null;let{user:g,...h}=d;return g?{session:hm(b.options,h),user:hk(b.options,g)}:null},findSessions:async(b,c)=>{if(f){let a=[];for(let d of b){let b=await f.get(d);if(b)try{let d="string"==typeof b?JSON.parse(b):b;if(!d)return[];let e=new Date(d.session.expiresAt);if(c?.onlyActiveSessions&&e<=new Date)continue;let f={session:{...d.session,expiresAt:new Date(d.session.expiresAt)},user:{...d.user,createdAt:new Date(d.user.createdAt),updatedAt:new Date(d.user.updatedAt)}};a.push(f)}catch{continue}}return a}let d=await (await (0,mz.d3)(a)).findMany({model:"session",where:[{field:"token",value:b,operator:"in"},...c?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!d.length||d.some(a=>!a.user)?[]:d.map(a=>{let{user:b,...c}=a;return{session:c,user:b}})},updateSession:async(a,c)=>await k(c,[{field:"token",value:a}],"session",f?{async fn(c){let d=await f.get(a);if(!d)return null;let e=(0,hy.$)(d);if(!e)return null;let g={...e.session,...c,expiresAt:new Date(c.expiresAt??e.session.expiresAt),createdAt:new Date(e.session.createdAt),updatedAt:new Date(c.updatedAt??e.session.updatedAt)},h=hm(b.options,g),i=Date.now(),j=new Date(h.expiresAt).getTime(),k=mG(j,i);if(k>0){await f.set(a,JSON.stringify({session:h,user:e.user}),k);let b=`active-sessions-${h.userId}`,c=await f.get(b),d=(c&&(0,hy.$)(c)||[]).filter(b=>b.token!==a&&b.expiresAt>i).concat([{token:a,expiresAt:j}]).sort((a,b)=>a.expiresAt-b.expiresAt),g=d.at(-1)?.expiresAt;g&&g>i?await f.set(b,JSON.stringify(d),mG(g,i)):await f.delete(b)}return h},executeMainFn:e.session?.storeSessionInDatabase}:void 0),deleteSession:async a=>{if(f){let c=await f.get(a);if(c){let{session:b}=(0,hy.$)(c)??{};if(!b)return void d.error("Session not found in secondary storage");let e=b.userId,g=await f.get(`active-sessions-${e}`);if(g){let b=(0,hy.$)(g)||[],c=Date.now(),d=b.filter(b=>b.expiresAt>c&&b.token!==a),h=d.sort((a,b)=>a.expiresAt-b.expiresAt).at(-1)?.expiresAt;d.length>0&&h&&h>Date.now()?await f.set(`active-sessions-${e}`,JSON.stringify(d),mG(h,c)):await f.delete(`active-sessions-${e}`)}else d.error("Active sessions list not found in secondary storage")}if(await f.delete(a),!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await m([{field:"token",value:a}],"session",void 0)},deleteAccounts:async a=>{await n([{field:"userId",value:a}],"account",void 0)},deleteAccount:async a=>{await m([{field:"id",value:a}],"account",void 0)},deleteUserSessions:async a=>{if(f){let c=await f.get(`active-sessions-${a}`),d=c?(0,hy.$)(c):[];if(!d)return;for(let a of d)await f.delete(a.token);if(await f.delete(`active-sessions-${a}`),!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await n([{field:"userId",value:a}],"session",void 0)},deleteSessions:async a=>{if(f){for(let b of a)await f.get(b)&&await f.delete(b);if(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await n([{field:"token",value:a,operator:"in"}],"session",void 0)},findOAuthUser:async(b,c,d)=>{let e=await (await (0,mz.d3)(a)).findOne({model:"account",where:[{value:c,field:"accountId"},{value:d,field:"providerId"}],join:{user:!0}});if(e)if(e.user)return{user:e.user,linkedAccount:e,accounts:[e]};else{let c=await (await (0,mz.d3)(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:e,accounts:[e]}:null}{let c=await (await (0,mz.d3)(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:null,accounts:await (await (0,mz.d3)(a)).findMany({model:"account",where:[{value:c.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(b,c)=>{let d=await (await (0,mz.d3)(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}],join:{...c?.includeAccounts?{account:!0}:{}}});if(!d)return null;let{account:e,...f}=d;return{user:f,accounts:e??[]}},findUserById:async b=>b?await (await (0,mz.d3)(a)).findOne({model:"user",where:[{field:"id",value:b}]}):null,linkAccount:async a=>await j({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),updateUser:async(a,b)=>{let c=await k({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"id",value:a}],"user",void 0);return await p(c),c},updateUserByEmail:async(a,b)=>{let c=await k({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"email",value:a.toLowerCase()}],"user",void 0);return await p(c),c},updatePassword:async(a,b)=>{await l({password:b},[{field:"userId",value:a},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async b=>await (await (0,mz.d3)(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),findAccountByProviderId:async(b,c)=>await (await (0,mz.d3)(a)).findOne({model:"account",where:[{field:"accountId",value:b},{field:"providerId",value:c}]}),findAccountByUserId:async b=>await (await (0,mz.d3)(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),updateAccount:async(a,b)=>await k(b,[{field:"id",value:a}],"account",void 0),createVerificationValue:async a=>{let b=mt(a.identifier,e.verification?.storeIdentifier),c=await ms(a.identifier,b);return await j({createdAt:new Date,updatedAt:new Date,...a,identifier:c},"verification",f?{async fn(a){let b=mG(a.expiresAt);return b>0&&await f.set(`verification:${c}`,JSON.stringify(a),b),a},executeMainFn:e.verification?.storeInDatabase}:void 0)},findVerificationValue:async b=>{let c=mt(b,e.verification?.storeIdentifier),d=await ms(b,c);if(f){let a=await f.get(`verification:${d}`);if(a){let b=(0,hy.$)(a);if(b)return b}if(c&&"plain"!==c){let a=await f.get(`verification:${b}`);if(a){let b=(0,hy.$)(a);if(b)return b}}if(!e.verification?.storeInDatabase)return null}let g=await (0,mz.d3)(a);async function h(a){return g.findMany({model:"verification",where:[{field:"identifier",value:a}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let i=await h(d);return!i.length&&c&&"plain"!==c&&(i=await h(b)),e.verification?.disableCleanup||await n([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),i[0]||null},deleteVerificationByIdentifier:async a=>{let b=await ms(a,mt(a,e.verification?.storeIdentifier));f&&await f.delete(`verification:${b}`),(!f||e.verification?.storeInDatabase)&&await m([{field:"identifier",value:b}],"verification",void 0)},consumeVerificationValue:async b=>{let c=mt(b,e.verification?.storeIdentifier),g=await ms(b,c),i=c&&"plain"!==c?[g,b]:[g],j=a=>{if(!a)return null;let b="string"==typeof a?(0,hy.$)(a):"object"==typeof a?a:null;if(!b)return null;let c=new Date(b.expiresAt);return Number.isFinite(c.getTime())?{...b,expiresAt:c}:null},k=null;if(f&&!e.verification?.storeInDatabase){let a=async a=>f.getAndDelete?j(await f.getAndDelete(a)):(h||(h=!0,d.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.")),q(a,async()=>{let b=j(await f.get(a));return b?(await f.delete(a),b):null}));for(let b of i){let c=await a(`verification:${b}`);if(c){await Promise.all(i.filter(a=>a!==b).map(a=>f.delete(`verification:${a}`))),k=c;break}}}else{let b=async b=>q(`verification:${b}`,()=>(0,mz.iD)(a,async()=>{let c=await (0,mz.d3)(a),d=[{field:"identifier",value:b}],e=(await c.findMany({model:"verification",where:d,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return e?o("verification",[{field:"id",value:e.id}],async()=>{let a=await c.consumeOne({model:"verification",where:[{field:"id",value:e.id}]});return a?(await c.deleteMany({model:"verification",where:d}),a):null},e):null}));for(let a of i)if(k=await b(a))break;k&&f&&await Promise.all(i.map(a=>f.delete(`verification:${a}`)))}return!k||k.expiresAt<new Date?null:k},reserveVerificationValue:async b=>{let c=mc.encode(new Uint8Array(await mq("SHA-256").digest(new TextEncoder().encode("reserve:"+b.identifier))),{padding:!1}),d=mt(b.identifier,e.verification?.storeIdentifier),g=await ms(b.identifier,d);if(f&&!e.verification?.storeInDatabase){let a=`verification:${g}`;return!await f.get(a)&&(await f.set(a,JSON.stringify({id:c,identifier:g,value:b.value,expiresAt:b.expiresAt}),mG(b.expiresAt)),!0)}try{await a.create({model:"verification",data:{id:c,identifier:g,value:b.value,expiresAt:b.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(b){if(await a.findOne({model:"verification",where:[{field:"id",value:c}]}))return!1;throw b}if(f){let a=mG(b.expiresAt);a>0&&await f.set(`verification:${g}`,JSON.stringify({id:c,identifier:g,value:b.value,expiresAt:b.expiresAt}),a)}return!0},updateVerificationByIdentifier:async(a,b)=>{let c=await ms(a,mt(a,e.verification?.storeIdentifier));if(f){let a=await f.get(`verification:${c}`);if(a){let d=(0,hy.$)(a);if(d){let a={...d,...b},g=a.expiresAt??d.expiresAt,h=mG(g instanceof Date?g:new Date(g));if(h>0&&await f.set(`verification:${c}`,JSON.stringify(a),h),!e.verification?.storeInDatabase)return a}}}return!f||e.verification?.storeInDatabase?await k(b,[{field:"identifier",value:c}],"verification",void 0):b},refreshUserSessions:p}};function mI(a){if(null===a||"object"!=typeof a)return!1;let b=Object.getPrototypeOf(a);return(null===b||b===Object.prototype||null===Object.getPrototypeOf(b))&&!(Symbol.iterator in a)&&(!(Symbol.toStringTag in a)||"[object Module]"===Object.prototype.toString.call(a))}function mJ(a){return(...b)=>b.reduce((b,c)=>(function a(b,c,d=".",e){if(!mI(c))return a(b,{},d,e);let f={...c};for(let c of Object.keys(b)){if("__proto__"===c||"constructor"===c)continue;let g=b[c];null!=g&&(e&&e(f,c,g,d)||(Array.isArray(g)&&Array.isArray(f[c])?f[c]=[...g,...f[c]]:mI(g)&&mI(f[c])?f[c]=a(g,f[c],(d?`${d}.`:"")+c.toString(),e):f[c]=g))}return f})(b,c,"",a),{})}let mK=mJ();mJ((a,b,c)=>{if(void 0!==a[b]&&"function"==typeof c)return a[b]=c(a[b]),!0}),mJ((a,b,c)=>{if(Array.isArray(a[b])&&"function"==typeof c)return a[b]=c(a[b]),!0});let mL=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function mM(a){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a)}function mN(a){let b=a.split(".");return(Number(b[0])<<24|Number(b[1])<<16|Number(b[2])<<8|Number(b[3]))>>>0}function mO(a,b,c){if(0===c)return!0;let d=32===c?0xffffffff:-1<<32-c>>>0;return(a&d)==(b&d)}function mP(a){if("0.0.0.0"===a)return"unspecified";if("255.255.255.255"===a)return"broadcast";let b=mN(a);return mO(b,mN("127.0.0.0"),8)?"loopback":mO(b,mN("10.0.0.0"),8)||mO(b,mN("172.16.0.0"),12)||mO(b,mN("192.168.0.0"),16)?"private":mO(b,mN("169.254.0.0"),16)?"linkLocal":mO(b,mN("100.64.0.0"),10)?"sharedAddressSpace":mO(b,mN("192.0.2.0"),24)||mO(b,mN("198.51.100.0"),24)||mO(b,mN("203.0.113.0"),24)?"documentation":mO(b,mN("198.18.0.0"),15)?"benchmarking":mO(b,mN("224.0.0.0"),4)?"multicast":mO(b,mN("0.0.0.0"),8)||mO(b,mN("192.0.0.0"),24)||mO(b,mN("240.0.0.0"),4)?"reserved":"public"}function mQ(a,b,c={}){let d=5*b,e=Number.parseInt(a.slice(d,d+4),16),f=Number.parseInt(a.slice(d+5,d+9),16);if(!Number.isFinite(e)||!Number.isFinite(f))return null;let g=(e<<16|f)>>>0;return c.xor&&(g=(0xffffffff^g)>>>0),`${g>>>24&255}.${g>>>16&255}.${g>>>8&255}.${255&g}`}async function mR(a){let b=a.options,c=b.plugins||[],d=[],e=[];for(let f of c)if(f.init){let c,g=f.init(a);if("object"==typeof(c=eK(g)?await g:g)){if(c.options){let{databaseHooks:a,trustedOrigins:g,...h}=c.options;a&&e.push({source:`plugin:${f.id}`,hooks:a}),g&&d.push(g),b=mK(b,h)}c.context&&Object.assign(a,c.context)}}if(d.length>0){let a=[...b.trustedOrigins?[b.trustedOrigins]:[],...d],c=a.filter(Array.isArray).flat(),e=a.filter(a=>"function"==typeof a);e.length>0?b.trustedOrigins=async a=>[...c,...(await Promise.all(e.map(b=>b(a)))).flat()].filter(a=>"string"==typeof a&&""!==a):b.trustedOrigins=c}b.databaseHooks&&e.push({source:"user",hooks:b.databaseHooks}),a.internalAdapter=mH(a.adapter,{options:b,logger:a.logger,hooks:e,generateId:a.generateId}),a.options=b}async function mS(a,b){let c=[];if(eE(a.baseURL)){let b=a.baseURL.allowedHosts,d=a.baseURL.protocol;for(let a of b)a.includes("://")?c.push(a):(d&&"https"!==d&&"auto"!==d||c.push(`https://${a}`),("http"===d||"auto"===d||function(a){let b=function(a){var b,c;let d,e=(-1===(d=(c=(b=function(a){if(a.startsWith("[")){let b=a.indexOf("]");return -1===b?a:a.slice(0,b+1)}let b=a.indexOf(":");return -1===b||-1!==a.indexOf(":",b+1)?a:a.slice(0,b)}(a.trim())).length>=2&&b.startsWith("[")&&b.endsWith("]")?b.slice(1,-1):b).indexOf("%"))?c:c.slice(0,d)).replace(/\.+$/,"").toLowerCase();if(""===e)return{kind:"reserved",literal:"fqdn",canonical:""};if(!mm(e))return"localhost"===e||e.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:e}:mL.has(e)?{kind:"cloudMetadata",literal:"fqdn",canonical:e}:{kind:"public",literal:"fqdn",canonical:e};if(mM(e))return{kind:mP(e),literal:"ipv4",canonical:e};let f=mo(e,{ipv6Subnet:128});return mM(f)?{kind:mP(f),literal:"ipv4",canonical:f}:{kind:function(a){if("0000:0000:0000:0000:0000:0000:0000:0000"===a)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===a)return"loopback";let b=Number.parseInt(a.slice(0,2),16),c=Number.parseInt(a.slice(2,4),16);if(255===b)return"multicast";if(254===b&&(192&c)==128)return"linkLocal";if((254&b)==252)return"private";if(a.startsWith("2001:0db8:"))return"documentation";if(a.startsWith("2001:0002:0000:"))return"benchmarking";if(a.startsWith("2002:")){let b=mQ(a,1);return b&&"public"!==mP(b)?"reserved":"public"}if(a.startsWith("0064:ff9b:0000:0000:0000:0000:")){let b=mQ(a,6);return b&&mP(b),"reserved"}if(a.startsWith("0064:ff9b:0001:"))return"reserved";if(a.startsWith("2001:0000:")){let b=mQ(a,6,{xor:!0});return b&&mP(b),"reserved"}return a.startsWith("0100:0000:0000:0000:")?"reserved":a.startsWith("3fff:0")?"documentation":a.startsWith("5f00:")?"reserved":"public"}(f),literal:"ipv6",canonical:f}}(a).kind;return"loopback"===b||"localhost"===b}(a))&&c.push(`http://${a}`));if(a.baseURL.fallback)try{c.push(new URL(a.baseURL.fallback).origin)}catch{}}else{let d=eC("string"==typeof a.baseURL?a.baseURL:void 0,a.basePath,b);d&&c.push(new URL(d).origin)}if(a.trustedOrigins&&(Array.isArray(a.trustedOrigins)&&c.push(...a.trustedOrigins),"function"==typeof a.trustedOrigins)){let d=await a.trustedOrigins(b);c.push(...d)}let d=ey._K.BETTER_AUTH_TRUSTED_ORIGINS;return d&&c.push(...d.split(",")),c.filter(a=>!!a)}function mT(a){return a.advanced?.trustedProxyHeaders??!0}async function mU(a,b,c){let d,e=a.options.baseURL,f=function(a,b,c,d,e){if(eE(a)){if(c){let d=eG(c,e);if(!d){if(a.fallback)return eA(a.fallback,b);throw new em.$l("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(a.allowedHosts.some(a=>((a,b)=>{if(!a||!b)return!1;let c=a.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),d=b.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return d.includes("*")||d.includes("?")?ex(d)(c):c.toLowerCase()===d.toLowerCase()})(d,a)))return eA(`${function(a,b,c){let d;if("http"===b||"https"===b)return b;let e=eF(a)?a.headers:a;if(c){let a=e.get("x-forwarded-proto");if(a&&eB(a,"proto"))return a}if(eF(a))try{let b=new URL(a.url);if("http:"===b.protocol||"https:"===b.protocol)return b.protocol.slice(0,-1)}catch{}let f=eG(a,c);return f&&("localhost"===(d=f.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||d.endsWith(".localhost")||"::1"===d||d.startsWith("127."))?"http":"https"}(c,a.protocol,e)}://${d}`,b);if(a.fallback)return eA(a.fallback,b);throw new em.$l(`Host "${d}" is not in the allowed hosts list. Allowed hosts: ${a.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return a.fallback?eA(a.fallback,b):eC(void 0,b,void 0,d,e)}let f=eF(c)?c:void 0;return"string"==typeof a?eC(a,b,f,d,e):eC(void 0,b,f,d,e)}(e,a.options.basePath||"/api/auth",b,void 0,c);if(!f)throw new em.$l("Could not resolve base URL from request. Check your allowedHosts config.");let g=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));g.baseURL=f,g.options={...a.options,baseURL:eD(f)||void 0};let h={...g.options,baseURL:e};return d="function"==typeof a.options.trustedOrigins||"function"==typeof a.options.account?.accountLinking?.trustedProviders?eF(b)?b:b?new Request(f,{headers:b}):void 0:void 0,g.trustedOrigins=await mS(h,d),g.trustedProviders=await mW(g.options,d),a.options.advanced?.crossSubDomainCookies?.enabled&&(g.authCookies=mh(g.options),g.createAuthCookie=mg(g.options)),g}async function mV(a,b){if(a)for(let c of a){let a="function"==typeof c?await c():c;if(a[b.field??"id"]===b.value)return a}}async function mW(a,b){let c=a.account?.accountLinking?.trustedProviders;return c?Array.isArray(c)?c.filter(a=>!!a):(await c(b)??[]).filter(a=>!!a):[]}async function mX(a,b){let c=(await a.context.internalAdapter.findAccounts(b.userId))?.find(a=>"credential"===a.providerId),d=c?.password;return!!c&&!!d&&await a.context.password.verify({hash:d,password:b.password})}async function mY(a,b){let c=(await b.context.internalAdapter.findAccounts(a))?.find(a=>"credential"===a.providerId),d=c?.password,e=b.body.password;if(!c||!d||!e)throw e&&await b.context.password.hash(e),em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);if(!await b.context.password.verify({hash:d,password:e}))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);return!0}async function mZ(a,b,c){return!c||!!(await a.context.internalAdapter.findAccounts(b))?.find(a=>"credential"===a.providerId&&a.password)}function m$(a){return a instanceof hz.LG||a instanceof em.LG||a?.name==="APIError"}function m_(a,b){let c;try{c=new URL(a).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let d=b.replace(/\/+$/,"");return""===d?c:c===d?"/":c.startsWith(d+"/")?c.slice(d.length).replace(/\/+$/,"")||"/":c}let m0=hX(async()=>({})),m1=hX.create({use:[m0,hX(async()=>({}))]}),m2=[m0];function m3(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c,g=async a=>{try{return await my(a,()=>f(a))}catch(c){var b;throw b=a.responseHeaders,m$(c)&&b&&Object.defineProperty(c,hz.Ri,{enumerable:!1,configurable:!0,value:b,writable:!1}),c}};return d?hW(d,{...e,use:[...e?.use||[],...m2]},g):hW({...e,use:[...e?.use||[],...m2]},g)}function m4(a){return!0===a.context.skipOriginCheck&&a.context.options.advanced?.disableCSRFCheck===void 0}function m5(a){let b=a.context.skipOriginCheck;if(!0===b)return!0;if(Array.isArray(b)&&a.request)try{let c=new URL(a.context.baseURL).pathname,d=m_(a.request.url,c);return b.some(a=>{let b=a.replace(/\/+$/,"");return d===b||d.startsWith(`${b}/`)})}catch{}return!1}m3.serverOnly=(a,b)=>m3({...a,metadata:{...a.metadata,SERVER_ONLY:!0}},b);let m6=(O=function(){},m=!1,function(...a){return m||(((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."),m=!0),O.apply(this,a)}),m7=m1(async a=>{if(a.request?.method==="GET"||a.request?.method==="OPTIONS"||a.request?.method==="HEAD"||!a.request||(await m9(a),m5(a)))return;let{body:b,query:c}=a,d=b?.callbackURL||c?.callbackURL,e=b?.redirectTo,f=b?.errorCallbackURL,g=b?.newUserCallbackURL,h=(b,c)=>{if(b){if("string"!=typeof b)throw em.LG.fromStatus("BAD_REQUEST",{message:`Invalid ${c}: expected a string`});if(!a.context.isTrustedOrigin(b,{allowRelativePaths:"origin"!==c})){if(a.context.logger.error(`Invalid ${c}: ${b}`),a.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
|
|
99
|
+
`,`Current list of trustedOrigins: ${a.context.trustedOrigins}`),"origin"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_ORIGIN);if("callbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_CALLBACK_URL);if("redirectURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_REDIRECT_URL);if("errorCallbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_NEW_USER_CALLBACK_URL);throw em.LG.fromStatus("FORBIDDEN",{message:`Invalid ${c}`})}}};d&&h(d,"callbackURL"),e&&h(e,"redirectURL"),f&&h(f,"errorCallbackURL"),g&&h(g,"newUserCallbackURL")}),m8=a=>m1(async b=>{if(!b.request||m5(b))return;let c=a(b),d=(a,c)=>{if(a&&!b.context.isTrustedOrigin(a,{allowRelativePaths:"origin"!==c})){if(b.context.logger.error(`Invalid ${c}: ${a}`),b.context.logger.info(`If it's a valid URL, please add ${a} to trustedOrigins in your auth config
|
|
100
|
+
`,`Current list of trustedOrigins: ${b.context.trustedOrigins}`),"origin"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_ORIGIN);if("callbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_CALLBACK_URL);if("redirectURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_REDIRECT_URL);if("errorCallbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===c)throw em.LG.from("FORBIDDEN",hg.INVALID_NEW_USER_CALLBACK_URL);throw em.LG.fromStatus("FORBIDDEN",{message:`Invalid ${c}`})}};for(let a of Array.isArray(c)?c:[c])d(a,"callbackURL")});async function m9(a,b=!1){let c=a.request?.headers;if(!c||!a.request)return;let d=c.get("origin")||c.get("referer")||"",e=c.has("cookie");if(a.context.skipCSRFCheck)return;if(m4(a)){a.context.options.advanced?.disableOriginCheck===!0&&m6();return}if(m5(a)||!(b||e))return;if(!d||"null"===d)throw em.LG.from("FORBIDDEN",hg.MISSING_OR_NULL_ORIGIN);let f=Array.isArray(a.context.options.trustedOrigins)?a.context.trustedOrigins:[...a.context.trustedOrigins,...(await a.context.options.trustedOrigins?.(a.request))?.filter(a=>!!a)||[]];if(!f.some(a=>eH(d,a)))throw a.context.logger.error(`Invalid origin: ${d}`),a.context.logger.info(`If it's a valid URL, please add ${d} to trustedOrigins in your auth config
|
|
101
|
+
`,`Current list of trustedOrigins: ${f}`),em.LG.from("FORBIDDEN",hg.INVALID_ORIGIN)}let na=m1(async a=>{a.request&&await nb(a)});async function nb(a){let b=a.request;if(!b||a.context.skipCSRFCheck||m4(a))return;let c=b.headers;if(c.has("cookie"))return await m9(a);let d=c.get("Sec-Fetch-Site"),e=c.get("Sec-Fetch-Mode"),f=c.get("Sec-Fetch-Dest");if(d&&d.trim()||e&&e.trim()||f&&f.trim()){if("cross-site"===d&&"navigate"===e)throw a.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:d,secFetchMode:e,secFetchDest:f}),em.LG.from("FORBIDDEN",hg.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await m9(a,!0)}if(c.get("origin")||c.get("referer"))return await m9(a,!0)}let nc=new Map;function nd(a,b,c){let d=1e3*b.window;return a?c-a.lastRequest>d?{next:{...a,count:1,lastRequest:c},update:!0,allowed:!0,retryAfter:null}:a.count>=b.max?{next:a,update:!0,allowed:!1,retryAfter:nf(a.lastRequest,b.window)}:{next:{...a,count:a.count+1,lastRequest:c},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:c},update:!1,allowed:!0,retryAfter:null}}function ne(a){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":a.toString()}})}function nf(a,b){return Math.ceil((a+1e3*b-Date.now())/1e3)}let ng=!1;async function nh(a,b){var c;let d=new URL(b.baseURL).pathname,e=m_(a.url,d),f=b.rateLimit.window,g=b.rateLimit.max,h=mp(a,b.options);if(!h&&b.options.advanced?.ipAddress?.disableIpTracking)return null;h||ng||(b.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 and configure `advanced.ipAddress.ipAddressHeaders` if needed."),ng=!0);let i=(c=h??"no-trusted-ip",`${c}|${e}`),j=nl().find(a=>a.pathMatcher(e));for(let a of(j&&(f=j.window,g=j.max),b.options.plugins||[]))if(a.rateLimit){let b=a.rateLimit.find(a=>a.pathMatcher(e));if(b){f=b.window,g=b.max;break}}if(b.rateLimit.customRules){let c=Object.keys(b.rateLimit.customRules).find(a=>a.includes("*")?ex(a)(e):a===e);if(c){let d=b.rateLimit.customRules[c],e="function"==typeof d?await d(a,{window:f,max:g}):d;if(e&&(f=e.window,g=e.max),!1===e)return null}}return{key:i,currentWindow:f,currentMax:g}}let ni=!1;async function nj(a,b){if(!b.rateLimit.enabled)return;let c=await nh(a,b);if(!c)return;let{key:d,currentWindow:e,currentMax:f}=c,g=function(a,b){let c,d,e,f,g;if(a.options.rateLimit?.customStorage)return a.options.rateLimit.customStorage;let h=a.rateLimit.storage;if("secondary-storage"===h){let c=b=>b??a.options.rateLimit?.window??10;return{get:async b=>{let c=await a.options.secondaryStorage?.get(b);return c?(0,hy.$)(c):null},set:async(d,e,f)=>{await a.options.secondaryStorage?.set?.(d,JSON.stringify(e),c(b.window))},consume:a.options.secondaryStorage?.increment?async(b,d)=>await a.options.secondaryStorage.increment(b,c(d.window))<=d.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:d.window}:void 0}}if("memory"===h){let c=b=>b??a.options.rateLimit?.window??10;return{async get(a){let b=nc.get(a);return b?Date.now()>=b.expiresAt?(nc.delete(a),null):b.data:null},async set(a,d,e){let f=Date.now()+1e3*c(b.window);nc.set(a,{data:d,expiresAt:f})},async consume(a,b){!function(){let a=Date.now();for(let[b,c]of nc)a>=c.expiresAt&&nc.delete(b);if(nc.size<=1e5)return;let b=nc.size-1e5,c=0;for(let a of nc.keys())if(nc.delete(a),++c>=b)break}();let d=Date.now(),e=nc.get(a),f=nd(e&&d<e.expiresAt?e.data:void 0,b,d);return f.allowed&&nc.set(a,{data:{...f.next,key:a},expiresAt:d+1e3*c(b.window)}),{allowed:f.allowed,retryAfter:f.retryAfter}}}}return c="rateLimit",d=a.adapter,e=async a=>{let b=(await d.findMany({model:c,where:[{field:"key",value:a}]}))[0];return"bigint"==typeof b?.lastRequest&&(b.lastRequest=Number(b.lastRequest)),b},f=async(a,b)=>{let h=1e3*b.window,i=await e(a),j=Date.now();if(!i)try{return await d.create({model:c,data:{key:a,count:1,lastRequest:j}}),{allowed:!0,retryAfter:null}}catch(c){if(!await e(a))throw c;return f(a,b)}if(j-i.lastRequest>h)return await d.incrementOne({model:c,where:[{field:"key",value:a},{field:"lastRequest",operator:"lte",value:i.lastRequest}],increment:{},set:{count:1,lastRequest:j}})?(g(j),{allowed:!0,retryAfter:null}):f(a,b);let k=j-h;if(await d.incrementOne({model:c,where:[{field:"key",value:a},{field:"lastRequest",operator:"gt",value:k},{field:"count",operator:"lt",value:b.max}],increment:{count:1},set:{lastRequest:j}}))return{allowed:!0,retryAfter:null};let l=await e(a);return!l||j-l.lastRequest>h?f(a,b):{allowed:!1,retryAfter:nf(l.lastRequest,b.window)}},g=b=>{let e=b-1e3*Math.max(a.rateLimit.window,...nl().map(a=>a.window));a.runInBackground(d.deleteMany({model:c,where:[{field:"lastRequest",operator:"lt",value:e}]}).then(()=>void 0).catch(b=>a.logger.error("Error pruning rate limit rows",b)))},{get:e,set:async(b,e,f)=>{try{f?await d.updateMany({model:c,where:[{field:"key",value:b}],update:{count:e.count,lastRequest:e.lastRequest}}):await d.create({model:c,data:{key:b,count:e.count,lastRequest:e.lastRequest}})}catch(b){a.logger.error("Error setting rate limit",b)}},consume:f}}(b,{window:e}),h={window:e,max:f};if(g.consume){let{allowed:a,retryAfter:b}=await g.consume(d,h);return a?void 0:ne(b??e)}return nk(b,g,d,h)}async function nk(a,b,c,d){ni||(a.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."),ni=!0);let e=nd(await b.get(c),d,Date.now());if(!e.allowed)return ne(e.retryAfter??d.window);await b.set(c,{...e.next,key:c},e.update)}function nl(){return[{pathMatcher:a=>a.startsWith("/sign-in")||a.startsWith("/sign-up")||a.startsWith("/change-password")||a.startsWith("/change-email"),window:10,max:3},{pathMatcher:a=>"/request-password-reset"===a||"/send-verification-email"===a||a.startsWith("/forget-password")||"/email-otp/send-verification-otp"===a||"/email-otp/request-password-reset"===a,window:60,max:3}]}let nm=async()=>{let a=(0,mu.Q)();if(!a.context.requestStateAsyncStorage){let b=await (0,mv.V)();a.context.requestStateAsyncStorage=new b}return a.context.requestStateAsyncStorage};async function nn(){return void 0!==(await nm()).getStore()}async function no(){let a=(await nm()).getStore();if(!a)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return a}async function np(a,b){return(await nm()).run(a,b)}function nq(a){let b=Object.freeze({});return{get ref(){return b},async get(){let c=await no();if(!c.has(b)){let d=await a();return c.set(b,d),d}return c.get(b)},async set(a){(await no()).set(b,a)}}}let{get:nr,set:ns}=nq(()=>!1),nt=()=>m3("/get-session",{method:["GET","POST"],operationId:"getSession",query:l7,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 a=>{let b=a.context.options.session?.deferSessionRefresh,c="POST"===a.method;if(c&&!b)throw em.LG.from("METHOD_NOT_ALLOWED",hg.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let d=await a.getSignedCookie(a.context.authCookies.sessionToken.name,a.context.secret);if(!d)return null;let e=l4(a,a.context.authCookies.sessionData.name),f=null;if(e){let b=a.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===b){let b=await he(e,a.context.secretConfig,"better-auth-session");b&&b.session&&b.user?f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}:mk(a,a.context.authCookies.sessionData)}else if("jwt"===b){let b=await g7(e,a.context.secret);b&&b.session&&b.user?f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}:mk(a,a.context.authCookies.sessionData)}else{let b=(0,hy.$)(me.decode(mc.decode(e)));b&&(await mf("SHA-256","base64urlnopad").verify(a.context.secret,JSON.stringify({...b.session,expiresAt:b.expiresAt}),b.signature)?f=b:mk(a,a.context.authCookies.sessionData))}}let g=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);if(f?.session&&a.context.options.session?.cookieCache?.enabled&&!a.query?.disableCookieCache){let b=f.session,c=a.context.options.session?.cookieCache?.version,d="1";if(c){if("string"==typeof c)d=c;else if("function"==typeof c){let a=c(b.session,b.user);d=a instanceof Promise?await a:a}}if((b.version||"1")!==d)mk(a,a.context.authCookies.sessionData);else{let c=new Date(b.session.expiresAt);if(f.expiresAt<Date.now()||c<new Date)mk(a,a.context.authCookies.sessionData);else{let c=a.context.sessionConfig.cookieRefreshCache;if(!1===c){a.context.session=b;let c=hm(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),d=hk(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.json({session:c,user:d})}let d=f.expiresAt-Date.now(),e=1e3*c.updateAge,h=await nr();if(d<e&&!h){let c={session:{...b.session},user:b.user,updatedAt:Date.now()};await mi(a,c,!1);let d=a.context.authCookies.sessionToken.attributes,e=g?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...d,maxAge:e});let f=hm(a.context.options,{...c.session,expiresAt:new Date(c.session.expiresAt),createdAt:new Date(c.session.createdAt),updatedAt:new Date(c.session.updatedAt)}),h=hk(a.context.options,{...c.user,createdAt:new Date(c.user.createdAt),updatedAt:new Date(c.user.updatedAt)});return a.context.session={session:f,user:h},a.json({session:f,user:h})}let i=hm(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),j=hk(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.context.session={session:i,user:j},a.json({session:i,user:j})}}}let h=await a.context.internalAdapter.findSession(d);if(a.context.session=h,!h||h.session.expiresAt<new Date)return ml(a),h&&(!b||c)&&await a.context.internalAdapter.deleteSession(h.session.token),a.json(null);if(g||a.query?.disableRefresh){let b=hm(a.context.options,h.session),c=hk(a.context.options,h.user);return a.json({session:b,user:c})}let i=a.context.sessionConfig.expiresIn,j=a.context.sessionConfig.updateAge,k=h.session.expiresAt.valueOf()-1e3*i+1e3*j<=Date.now(),l=a.query?.disableRefresh||a.context.options.session?.disableSessionRefresh,m=await nr(),n=k&&!l&&!m;if(b&&!c){await mi(a,h,!!g);let b=hm(a.context.options,h.session),c=hk(a.context.options,h.user);return a.json({session:b,user:c,needsRefresh:n})}if(n){let b=await a.context.internalAdapter.updateSession(h.session.token,{expiresAt:hp(a.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!b)throw ml(a),em.LG.from("UNAUTHORIZED",hg.FAILED_TO_GET_SESSION);let c=(b.expiresAt.valueOf()-Date.now())/1e3;await mj(a,{session:b,user:h.user},!1,{maxAge:c});let d=hm(a.context.options,b),e=hk(a.context.options,h.user);return a.json({session:d,user:e})}await mi(a,h,!!g);let o=hm(a.context.options,h.session),p=hk(a.context.options,h.user);return a.json({session:o,user:p})}catch(b){if(m$(b))throw b;throw a.context.logger.error("INTERNAL_SERVER_ERROR",b),em.LG.from("INTERNAL_SERVER_ERROR",hg.FAILED_TO_GET_SESSION)}}),nu=async(a,b)=>{if(a.context.session)return a.context.session;let c=await nt()({...a,method:"GET",asResponse:!1,headers:a.headers,returnHeaders:!0,returnStatus:!1,query:{...b,...a.query,disableCookieCache:b?.disableCookieCache||a.query?.disableCookieCache,disableRefresh:b?.disableRefresh||a.query?.disableRefresh}}).catch(()=>null);return c?(c.headers&&c.headers.forEach((b,c)=>{a.context.responseHeaders?"set-cookie"===c.toLowerCase()?a.context.responseHeaders.append(c,b):a.context.responseHeaders.set(c,b):a.context.responseHeaders=new Headers({[c]:b})}),a.context.session=c.response,c.response):(a.context.session=null,null)},nv=m1(async a=>{let b=await nu(a);if(!b?.session)throw em.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}}),nw=m1(async a=>{let b=await nu(a,{disableCookieCache:!0});if(!b?.session)throw em.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});m1(async a=>{let b=await nu(a);if(!b?.session&&(a.request||a.headers))throw em.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});let nx=m1(async a=>{let b=await nu(a);if(!b?.session)throw em.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==a.context.sessionConfig.freshAge){let c=new Date(b.session.createdAt).getTime(),d=1e3*a.context.sessionConfig.freshAge;if(Date.now()-c>=d)throw em.LG.from("FORBIDDEN",hg.SESSION_NOT_FRESH)}return{session:b}}),ny=m3("/revoke-session",{method:"POST",body:lw({token:kZ().meta({description:"The token to revoke"})}),use:[nw],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 a=>{let b=a.body.token;if((await a.context.internalAdapter.findSession(b))?.session.userId===a.context.session.user.id)try{await a.context.internalAdapter.deleteSession(b)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),em.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),nz=m3("/revoke-sessions",{method:"POST",use:[nw],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 a=>{try{await a.context.internalAdapter.deleteUserSessions(a.context.session.user.id)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),em.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),nA=m3("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[nw],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 a=>{let b=a.context.session;if(!b.user)throw em.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let c=(await a.context.internalAdapter.listSessions(b.user.id)).filter(a=>a.expiresAt>new Date).filter(b=>b.token!==a.context.session.session.token);return await Promise.all(c.map(b=>a.context.internalAdapter.deleteSession(b.token))),a.json({status:!0})});function nB(a,b,c,d){let e=new URLSearchParams({error:c});d&&e.set("error_description",d);let f=b.includes("?")?"&":"?";throw a.redirect(`${b}${f}${e.toString()}`)}function nC(a,b){return`${b?.source==="generic"?`Generic OAuth provider "${a}"`:`Provider "${a}"`} did not return an email${b?.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`}function nD(a){if("boolean"!=typeof a)throw TypeError(`boolean expected, not ${a}`)}function nE(a){if("number"!=typeof a)throw TypeError("number expected, got "+typeof a);if(!Number.isSafeInteger(a)||a<0)throw RangeError("positive integer expected, got "+a)}function nF(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function nG(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function nH(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function nI(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}let nJ=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],nK=a=>a<<24&0xff000000|a<<8&0xff0000|a>>>8&65280|a>>>24&255,nL=nJ?a=>a:a=>nK(a)>>>0,nM=nJ?a=>a:a=>{for(let b=0;b<a.length;b++)a[b]=nK(a[b]);return a},nN="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,nO=Array.from({length:256},(a,b)=>b.toString(16).padStart(2,"0"));function nP(a){return a>=48&&a<=57?a-48:a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:void 0}function nQ(a,b,c=!0){if(void 0===b)return new Uint8Array(a);if(nF(b,void 0,"output"),b.length!==a)throw Error('"output" expected Uint8Array of length '+a+", got: "+b.length);if(c&&!nR(b))throw Error("invalid output, must be aligned");return b}function nR(a){return a.byteOffset%4==0}function nS(a){return Uint8Array.from(nF(a))}function nT(a=32){nE(a);let b="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof b?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return b.getRandomValues(new Uint8Array(a))}function nU(a,b=nT){let{nonceLength:c}=a;nE(c);let d=(a,b,c)=>{let d=function(...a){let b=0;for(let c=0;c<a.length;c++){let d=a[c];nF(d),b+=d.length}let c=new Uint8Array(b);for(let b=0,d=0;b<a.length;b++){let e=a[b];c.set(e,d),d+=e.length}return c}(a,b);return c.byteLength&&b.byteLength&&c.buffer===b.buffer&&c.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<c.byteOffset+c.byteLength||b.fill(0),d},e=(e,...f)=>({encrypt(g){nF(g);let h=b(c),i=a(e,h,...f).encrypt(g);return i instanceof Promise?i.then(a=>d(h,a,g)):d(h,i,g)},decrypt(b){nF(b);let d=b.subarray(0,c),g=b.subarray(c);return a(e,d,...f).decrypt(g)}});return"blockSize"in a&&(e.blockSize=a.blockSize),"tagLength"in a&&(e.tagLength=a.tagLength),e}let nV=a=>Uint8Array.from(a.split(""),a=>a.charCodeAt(0)),nW=nM(nH(nV("expand 16-byte k"))),nX=nM(nH(nV("expand 32-byte k")));function nY(a,b){return a<<b|a>>>32-b}let nZ=0x100000000-1,n$=Uint32Array.of();function n_(a,b){return 255&a[b++]|(255&a[b++])<<8}class n0{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(a){const b=n_(a=nS(nF(a,32,"key")),0),c=n_(a,2),d=n_(a,4),e=n_(a,6),f=n_(a,8),g=n_(a,10),h=n_(a,12),i=n_(a,14);this.r[0]=8191&b,this.r[1]=(b>>>13|c<<3)&8191,this.r[2]=(c>>>10|d<<6)&7939,this.r[3]=(d>>>7|e<<9)&8191,this.r[4]=(e>>>4|f<<12)&255,this.r[5]=f>>>1&8190,this.r[6]=(f>>>14|g<<2)&8191,this.r[7]=(g>>>11|h<<5)&8065,this.r[8]=(h>>>8|i<<8)&8191,this.r[9]=i>>>5&127;for(let b=0;b<8;b++)this.pad[b]=n_(a,16+2*b)}process(a,b,c=!1){let{h:d,r:e}=this,f=e[0],g=e[1],h=e[2],i=e[3],j=e[4],k=e[5],l=e[6],m=e[7],n=e[8],o=e[9],p=n_(a,b+0),q=n_(a,b+2),r=n_(a,b+4),s=n_(a,b+6),t=n_(a,b+8),u=n_(a,b+10),v=n_(a,b+12),w=n_(a,b+14),x=d[0]+(8191&p),y=d[1]+((p>>>13|q<<3)&8191),z=d[2]+((q>>>10|r<<6)&8191),A=d[3]+((r>>>7|s<<9)&8191),B=d[4]+((s>>>4|t<<12)&8191),C=d[5]+(t>>>1&8191),D=d[6]+((t>>>14|u<<2)&8191),E=d[7]+((u>>>11|v<<5)&8191),F=d[8]+((v>>>8|w<<8)&8191),G=d[9]+(w>>>5|2048*!c),H=0,I=0+x*f+5*o*y+5*n*z+5*m*A+5*l*B;H=I>>>13,I&=8191,I+=5*k*C+5*j*D+5*i*E+5*h*F+5*g*G,H+=I>>>13,I&=8191;let J=H+x*g+y*f+5*o*z+5*n*A+5*m*B;H=J>>>13,J&=8191,J+=5*l*C+5*k*D+5*j*E+5*i*F+5*h*G,H+=J>>>13,J&=8191;let K=H+x*h+y*g+z*f+5*o*A+5*n*B;H=K>>>13,K&=8191,K+=5*m*C+5*l*D+5*k*E+5*j*F+5*i*G,H+=K>>>13,K&=8191;let L=H+x*i+y*h+z*g+A*f+5*o*B;H=L>>>13,L&=8191,L+=5*n*C+5*m*D+5*l*E+5*k*F+5*j*G,H+=L>>>13,L&=8191;let M=H+x*j+y*i+z*h+A*g+B*f;H=M>>>13,M&=8191,M+=5*o*C+5*n*D+5*m*E+5*l*F+5*k*G,H+=M>>>13,M&=8191;let N=H+x*k+y*j+z*i+A*h+B*g;H=N>>>13,N&=8191,N+=C*f+5*o*D+5*n*E+5*m*F+5*l*G,H+=N>>>13,N&=8191;let O=H+x*l+y*k+z*j+A*i+B*h;H=O>>>13,O&=8191,O+=C*g+D*f+5*o*E+5*n*F+5*m*G,H+=O>>>13,O&=8191;let P=H+x*m+y*l+z*k+A*j+B*i;H=P>>>13,P&=8191,P+=C*h+D*g+E*f+5*o*F+5*n*G,H+=P>>>13,P&=8191;let Q=H+x*n+y*m+z*l+A*k+B*j;H=Q>>>13,Q&=8191,Q+=C*i+D*h+E*g+F*f+5*o*G,H+=Q>>>13,Q&=8191;let R=H+x*o+y*n+z*m+A*l+B*k;H=R>>>13,R&=8191,R+=C*j+D*i+E*h+F*g+G*f,H+=R>>>13,R&=8191,I=8191&(H=(H=(H<<2)+H|0)+I|0),H>>>=13,J+=H,d[0]=I,d[1]=J,d[2]=K,d[3]=L,d[4]=M,d[5]=N,d[6]=O,d[7]=P,d[8]=Q,d[9]=R}finalize(){let{h:a,pad:b}=this,c=new Uint16Array(10),d=a[1]>>>13;a[1]&=8191;for(let b=2;b<10;b++)a[b]+=d,d=a[b]>>>13,a[b]&=8191;a[0]+=5*d,d=a[0]>>>13,a[0]&=8191,a[1]+=d,d=a[1]>>>13,a[1]&=8191,a[2]+=d,c[0]=a[0]+5,d=c[0]>>>13,c[0]&=8191;for(let b=1;b<10;b++)c[b]=a[b]+d,d=c[b]>>>13,c[b]&=8191;c[9]-=8192;let e=(1^d)-1;for(let a=0;a<10;a++)c[a]&=e;e=~e;for(let b=0;b<10;b++)a[b]=a[b]&e|c[b];a[0]=(a[0]|a[1]<<13)&65535,a[1]=(a[1]>>>3|a[2]<<10)&65535,a[2]=(a[2]>>>6|a[3]<<7)&65535,a[3]=(a[3]>>>9|a[4]<<4)&65535,a[4]=(a[4]>>>12|a[5]<<1|a[6]<<14)&65535,a[5]=(a[6]>>>2|a[7]<<11)&65535,a[6]=(a[7]>>>5|a[8]<<8)&65535,a[7]=(a[8]>>>8|a[9]<<5)&65535;let f=a[0]+b[0];a[0]=65535&f;for(let c=1;c<8;c++)f=(a[c]+b[c]|0)+(f>>>16)|0,a[c]=65535&f;nI(c)}update(a){nG(this),nF(a);let{buffer:b,blockLen:c}=this,d=(a=nS(a)).length;for(let e=0;e<d;){let f=Math.min(c-this.pos,d-e);if(f===c){for(;c<=d-e;e+=c)this.process(a,e);continue}b.set(a.subarray(e,e+f),this.pos),this.pos+=f,e+=f,this.pos===c&&(this.process(b,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,nI(this.h,this.r,this.buffer,this.pad)}digestInto(a){nG(this),function(a,b,c=!1){nF(a,void 0,"output");let d=b.outputLen;if(a.length<d)throw RangeError("digestInto() expects output buffer of length at least "+d);if(c&&!nR(a))throw Error("invalid output, must be aligned")}(a,this),this.finished=!0;let{buffer:b,h:c}=this,{pos:d}=this;if(d){for(b[d++]=1;d<16;d++)b[d]=0;this.process(b,0,!0)}this.finalize();let e=0;for(let b=0;b<8;b++)a[e++]=c[b]>>>0,a[e++]=c[b]>>>8}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}}let n1=(P=a=>new n0(a),n=()=>[],(o=(a,b)=>P(b,...n(a)).update(a).digest()).outputLen=(p=P(new Uint8Array(32),...n(new Uint8Array(0)))).outputLen,o.blockLen=p.blockLen,o.create=(a,...b)=>P(a,...b),o),n2=function(a,b){let{allowShortKeys:c,extendNonceFn:d,counterLength:e,counterRight:f,rounds:g}=function(a,b){if(null==b||"object"!=typeof b)throw Error("options must be defined");return Object.assign(a,b)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},b);if("function"!=typeof a)throw Error("core must be a function");return nE(e),nE(g),nD(f),nD(c),(b,h,i,j,k=0)=>{let l,m;if(nF(b,void 0,"key"),nF(h,void 0,"nonce"),nF(i,void 0,"data"),j=nQ(i.length,j,!1),nE(k),k<0||k>=nZ)throw Error("arx: counter overflow");let n=[],o=b.length;if(32===o)n.push(l=nS(b)),m=nX;else if(16===o&&c)(l=new Uint8Array(32)).set(b),l.set(b,16),m=nW,n.push(l);else throw nF(b,32,"arx key"),Error("invalid key size");nJ&&nR(h)||n.push(h=nS(h));let p=nH(l);if(d){if(24!==h.length)throw Error("arx: extended nonce must be 24 bytes");let a=h.subarray(0,16);if(nJ)d(m,p,nH(a),p);else{let b=nM(Uint32Array.from(m));d(b,p,nH(a),p),nI(b),nM(p)}h=h.subarray(16)}else nJ||nM(p);let q=16-e;if(q!==h.length)throw Error(`arx: nonce must be ${q} or 16 bytes`);if(12!==q){let a=new Uint8Array(12);a.set(h,f?0:12-h.length),h=a,n.push(h)}let r=nM(nH(h));try{return!function(a,b,c,d,e,f,g,h){let i=e.length,j=new Uint8Array(64),k=nH(j),l=nJ&&nR(e)&&nR(f),m=l?nH(e):n$,n=l?nH(f):n$;if(!nJ){for(let l=0;l<i;g++){if(a(b,c,d,k,g,h),nM(k),g>=nZ)throw Error("arx: counter overflow");let m=Math.min(64,i-l);for(let a=0,b;a<m;a++)f[b=l+a]=e[b]^j[a];l+=m}return}for(let o=0;o<i;g++){if(a(b,c,d,k,g,h),g>=nZ)throw Error("arx: counter overflow");let p=Math.min(64,i-o);if(l&&64===p){let a=o/4;if(o%4!=0)throw Error("arx: invalid block position");for(let b=0,c;b<16;b++)n[c=a+b]=m[c]^k[b];o+=64;continue}for(let a=0,b;a<p;a++)f[b=o+a]=e[b]^j[a];o+=p}}(a,m,p,r,i,j,k,g),j}finally{nI(...n)}}}(function(a,b,c,d,e,f=20){let g=a[0],h=a[1],i=a[2],j=a[3],k=b[0],l=b[1],m=b[2],n=b[3],o=b[4],p=b[5],q=b[6],r=b[7],s=c[0],t=c[1],u=c[2],v=g,w=h,x=i,y=j,z=k,A=l,B=m,C=n,D=o,E=p,F=q,G=r,H=e,I=s,J=t,K=u;for(let a=0;a<f;a+=2)D=D+(H=nY(H^(v=v+z|0),16))|0,v=v+(z=nY(z^D,12))|0,D=D+(H=nY(H^v,8))|0,z=nY(z^D,7),E=E+(I=nY(I^(w=w+A|0),16))|0,w=w+(A=nY(A^E,12))|0,E=E+(I=nY(I^w,8))|0,A=nY(A^E,7),F=F+(J=nY(J^(x=x+B|0),16))|0,x=x+(B=nY(B^F,12))|0,F=F+(J=nY(J^x,8))|0,B=nY(B^F,7),G=G+(K=nY(K^(y=y+C|0),16))|0,y=y+(C=nY(C^G,12))|0,G=G+(K=nY(K^y,8))|0,C=nY(C^G,7),F=F+(K=nY(K^(v=v+A|0),16))|0,v=v+(A=nY(A^F,12))|0,F=F+(K=nY(K^v,8))|0,A=nY(A^F,7),G=G+(H=nY(H^(w=w+B|0),16))|0,w=w+(B=nY(B^G,12))|0,G=G+(H=nY(H^w,8))|0,B=nY(B^G,7),D=D+(I=nY(I^(x=x+C|0),16))|0,x=x+(C=nY(C^D,12))|0,D=D+(I=nY(I^x,8))|0,C=nY(C^D,7),E=E+(J=nY(J^(y=y+z|0),16))|0,y=y+(z=nY(z^E,12))|0,E=E+(J=nY(J^y,8))|0,z=nY(z^E,7);let L=0;d[L++]=g+v|0,d[L++]=h+w|0,d[L++]=i+x|0,d[L++]=j+y|0,d[L++]=k+z|0,d[L++]=l+A|0,d[L++]=m+B|0,d[L++]=n+C|0,d[L++]=o+D|0,d[L++]=p+E|0,d[L++]=q+F|0,d[L++]=r+G|0,d[L++]=e+H|0,d[L++]=s+I|0,d[L++]=t+J|0,d[L++]=u+K|0},{counterRight:!1,counterLength:8,extendNonceFn:function(a,b,c,d){let e=nL(a[0]),f=nL(a[1]),g=nL(a[2]),h=nL(a[3]),i=nL(b[0]),j=nL(b[1]),k=nL(b[2]),l=nL(b[3]),m=nL(b[4]),n=nL(b[5]),o=nL(b[6]),p=nL(b[7]),q=nL(c[0]),r=nL(c[1]),s=nL(c[2]),t=nL(c[3]);for(let a=0;a<20;a+=2)m=m+(q=nY(q^(e=e+i|0),16))|0,e=e+(i=nY(i^m,12))|0,m=m+(q=nY(q^e,8))|0,i=nY(i^m,7),n=n+(r=nY(r^(f=f+j|0),16))|0,f=f+(j=nY(j^n,12))|0,n=n+(r=nY(r^f,8))|0,j=nY(j^n,7),o=o+(s=nY(s^(g=g+k|0),16))|0,g=g+(k=nY(k^o,12))|0,o=o+(s=nY(s^g,8))|0,k=nY(k^o,7),p=p+(t=nY(t^(h=h+l|0),16))|0,h=h+(l=nY(l^p,12))|0,p=p+(t=nY(t^h,8))|0,l=nY(l^p,7),o=o+(t=nY(t^(e=e+j|0),16))|0,e=e+(j=nY(j^o,12))|0,o=o+(t=nY(t^e,8))|0,j=nY(j^o,7),p=p+(q=nY(q^(f=f+k|0),16))|0,f=f+(k=nY(k^p,12))|0,p=p+(q=nY(q^f,8))|0,k=nY(k^p,7),m=m+(r=nY(r^(g=g+l|0),16))|0,g=g+(l=nY(l^m,12))|0,m=m+(r=nY(r^g,8))|0,l=nY(l^m,7),n=n+(s=nY(s^(h=h+i|0),16))|0,h=h+(i=nY(i^n,12))|0,n=n+(s=nY(s^h,8))|0,i=nY(i^n,7);let u=0;d[u++]=e,d[u++]=f,d[u++]=g,d[u++]=h,d[u++]=q,d[u++]=r,d[u++]=s,d[u++]=t,nM(d)},allowShortKeys:!1}),n3=new Uint8Array(16),n4=(a,b)=>{a.update(b);let c=b.length%16;c&&a.update(n3.subarray(c))},n5=new Uint8Array(32);function n6(a,b,c,d,e){var f,g;let h,i;void 0!==e&&nF(e,void 0,"AAD");let j=a(b,c,n5),k=(f=d.length,g=e?e.length:0,nE(f),nE(g),nD(!0),(i=new DataView((h=new Uint8Array(16)).buffer,h.byteOffset,h.byteLength)).setBigUint64(0,BigInt(g),!0),i.setBigUint64(8,BigInt(f),!0),h),l=n1.create(j);e&&n4(l,e),n4(l,d),l.update(k);let m=l.digest();return nI(j,k),m}let n7=((a,b)=>{function c(d,...e){nF(d,void 0,"key"),void 0!==a.nonceLength&&nF(e[0],a.varSizeNonce?void 0:a.nonceLength,"nonce");let f=a.tagLength;f&&void 0!==e[1]&&nF(e[1],void 0,"AAD");let g=b(d,...e),h=(a,b)=>{if(void 0!==b){if(2!==a)throw Error("cipher output not supported");nF(b,void 0,"output")}},i=!1;return{encrypt(a,b){if(i)throw Error("cannot encrypt() twice with same key + nonce");return i=!0,nF(a),h(g.encrypt.length,b),g.encrypt(a,b)},decrypt(a,b){if(nF(a),f&&a.length<f)throw Error('"ciphertext" expected length bigger than tagLength='+f);return h(g.decrypt.length,b),g.decrypt(a,b)}}}return Object.assign(c,a),c})({blockSize:64,nonceLength:24,tagLength:16},(a,b,c)=>({encrypt(d,e){let f=d.length;(e=nQ(f+16,e,!1)).set(d);let g=e.subarray(0,-16);n2(a,b,g,g,1);let h=n6(n2,a,b,g,c);return e.set(h,f),nI(h),e},decrypt(d,e){e=nQ(d.length-16,e,!1);let f=d.subarray(0,-16),g=d.subarray(-16),h=n6(n2,a,b,f,c);if(!function(a,b){if(a.length!==b.length)return!1;let c=0;for(let d=0;d<a.length;d++)c|=a[d]^b[d];return 0===c}(g,h))throw nI(h),Error("invalid tag");return e.set(d.subarray(0,-16)),n2(a,b,e,e,1),nI(h),e}})),n8="$ba$";async function n9(a,b){let c=await mq("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(a))}(b);var e=nU(n7)(new Uint8Array(c)).encrypt(d);if(nF(e),nN)return e.toHex();let f="";for(let a=0;a<e.length;a++)f+=nO[e[a]];return f}async function oa(a,b){let c=await mq("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("hex string expected, got "+typeof a);if(nN)try{return Uint8Array.fromHex(a)}catch(a){if(a instanceof SyntaxError)throw RangeError(a.message);throw a}let b=a.length,c=b/2;if(b%2)throw RangeError("hex string expected, got unpadded hex of length "+b);let d=new Uint8Array(c);for(let b=0,e=0;b<c;b++,e+=2){let c=nP(a.charCodeAt(e)),f=nP(a.charCodeAt(e+1));if(void 0===c||void 0===f)throw RangeError('hex string expected, got non-hex character "'+(a[e]+a[e+1])+'" at index '+e);d[b]=16*c+f}return d}(b),e=nU(n7)(new Uint8Array(c));return new TextDecoder().decode(e.decrypt(d))}let ob=async({key:a,data:b})=>{var c;if("string"==typeof a)return n9(a,b);let d=a.keys.get(a.currentVersion);if(!d)throw Error(`Secret version ${a.currentVersion} not found in keys`);let e=await n9(d,b);return c=a.currentVersion,`${n8}${c}$${e}`},oc=async({key:a,data:b})=>{if("string"==typeof a)return oa(a,b);let c=function(a){if(!a.startsWith(n8))return null;let b=a.indexOf("$",4);if(-1===b)return null;let c=parseInt(a.slice(4,b),10);return!Number.isInteger(c)||c<0?null:{version:c,ciphertext:a.slice(b+1)}}(b);if(c){let b=a.keys.get(c.version);if(!b)throw Error(`Secret version ${c.version} not found in keys (key may have been retired)`);return oa(b,c.ciphertext)}if(a.legacySecret)return oa(a.legacySecret,b);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};function od(a,b){if(!a)return a;if(b.options.account?.encryptOAuthTokens)return a.startsWith("$ba$")||a.length%2==0&&/^[0-9a-f]+$/i.test(a)?oc({key:b.secretConfig,data:a}):a;return a}function oe(a,b){return b.options.account?.encryptOAuthTokens&&a?ob({key:b.secretConfig,data:a}):a}async function of(a,b,c,d=3600,e){return await g6({email:b.toLowerCase(),updateTo:c?.toLowerCase(),...e},a,d)}async function og(a,b){if(!a.context.options.emailVerification?.sendVerificationEmail)throw a.context.logger.error("Verification email isn't enabled."),em.LG.from("BAD_REQUEST",hg.VERIFICATION_EMAIL_NOT_ENABLED);let c=await of(a.context.secret,b.email,void 0,a.context.options.emailVerification?.expiresIn),d=a.body.callbackURL?encodeURIComponent(a.body.callbackURL):encodeURIComponent("/"),e=`${a.context.baseURL}/verify-email?token=${c}&callbackURL=${d}`;await a.context.options.emailVerification.sendVerificationEmail({user:b,url:e,token:c},a.request)}let oh=m3("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:lw({email:kj(k_,void 0).meta({description:"The email to send the verification email to"}),callbackURL:kZ().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 a=>{if(!a.context.options.emailVerification?.sendVerificationEmail)throw a.context.logger.error("Verification email isn't enabled."),em.LG.from("BAD_REQUEST",hg.VERIFICATION_EMAIL_NOT_ENABLED);let{email:b}=a.body,c=await nu(a);if(!c){let c,d=Date.now(),e=await a.context.internalAdapter.findUserByEmail(b);if(!e||e.user.emailVerified)await of(a.context.secret,b,void 0,a.context.options.emailVerification?.expiresIn);else try{await og(a,e.user)}catch(a){c=a}let f=500-(Date.now()-d);if(f>0&&await new Promise(a=>setTimeout(a,f)),c)throw c;return a.json({status:!0})}if(c?.user.email.toLowerCase()!==b.toLowerCase())throw em.LG.from("BAD_REQUEST",hg.EMAIL_MISMATCH);if(c?.user.emailVerified)throw em.LG.from("BAD_REQUEST",hg.EMAIL_ALREADY_VERIFIED);return await og(a,c.user),a.json({status:!0})}),oi=m3("/verify-email",{method:"GET",operationId:"verifyEmail",query:lw({token:kZ().meta({description:"The token to verify the email"}),callbackURL:kZ().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[m8(a=>a.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 a=>{let b;function c(b){if(a.query.callbackURL){if(a.query.callbackURL.includes("?"))throw a.redirect(`${a.query.callbackURL}&error=${b.code}`);throw a.redirect(`${a.query.callbackURL}?error=${b.code}`)}throw em.LG.from("UNAUTHORIZED",b)}let{token:d}=a.query;try{b=await gj(d,new TextEncoder().encode(a.context.secret),{algorithms:["HS256"]})}catch(a){if(a instanceof fp)return c(hg.TOKEN_EXPIRED);return c(hg.INVALID_TOKEN)}let e=lw({email:kj(k_,void 0),updateTo:kZ().optional(),requestType:kZ().optional()}).parse(b.payload),f=await a.context.internalAdapter.findUserByEmail(e.email);if(!f)return c(hg.USER_NOT_FOUND);if(e.updateTo){let b=await nu(a);if(b&&b.user.email!==e.email)return c(hg.INVALID_USER);switch(e.requestType){case"change-email-confirmation":{let b=await of(a.context.secret,e.email,e.updateTo,a.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),c=a.query.callbackURL?encodeURIComponent(a.query.callbackURL):encodeURIComponent("/"),d=`${a.context.baseURL}/verify-email?token=${b}&callbackURL=${c}`;if(a.context.options.emailVerification?.sendVerificationEmail&&await a.context.runInBackgroundOrAwait(a.context.options.emailVerification.sendVerificationEmail({user:{...f.user,email:e.updateTo},url:d,token:b},a.request?.clone())),a.query.callbackURL)throw a.redirect(a.query.callbackURL);return a.json({status:!0})}case"change-email-verification":{let c=b;if(!c){let b=await a.context.internalAdapter.createSession(f.user.id);if(!b)throw em.LG.from("INTERNAL_SERVER_ERROR",hg.FAILED_TO_CREATE_SESSION);c={session:b,user:f.user}}let d=await a.context.internalAdapter.updateUserByEmail(e.email,{email:e.updateTo,emailVerified:!0});if(a.context.options.emailVerification?.afterEmailVerification&&await a.context.options.emailVerification.afterEmailVerification(d,a.request),await mj(a,{session:c.session,user:{...c.user,email:e.updateTo,emailVerified:!0}}),a.query.callbackURL)throw a.redirect(a.query.callbackURL);return a.json({status:!0,user:hk(a.context.options,d)})}default:{let c=b;if(!c){let b=await a.context.internalAdapter.createSession(f.user.id);if(!b)throw em.LG.from("INTERNAL_SERVER_ERROR",hg.FAILED_TO_CREATE_SESSION);c={session:b,user:f.user}}let d=await a.context.internalAdapter.updateUserByEmail(e.email,{email:e.updateTo,emailVerified:!1}),g=await of(a.context.secret,e.updateTo),h=a.query.callbackURL?encodeURIComponent(a.query.callbackURL):encodeURIComponent("/");if(a.context.options.emailVerification?.sendVerificationEmail&&await a.context.runInBackgroundOrAwait(a.context.options.emailVerification.sendVerificationEmail({user:d,url:`${a.context.baseURL}/verify-email?token=${g}&callbackURL=${h}`,token:g},a.request?.clone())),await mj(a,{session:c.session,user:{...c.user,email:e.updateTo,emailVerified:!1}}),a.query.callbackURL)throw a.redirect(a.query.callbackURL);return a.json({status:!0,user:hk(a.context.options,d)})}}}if(f.user.emailVerified){if(a.query.callbackURL)throw a.redirect(a.query.callbackURL);return a.json({status:!0,user:null})}a.context.options.emailVerification?.beforeEmailVerification&&await a.context.options.emailVerification.beforeEmailVerification(f.user,a.request);let g=await a.context.internalAdapter.updateUserByEmail(e.email,{emailVerified:!0});if(a.context.options.emailVerification?.afterEmailVerification&&await a.context.options.emailVerification.afterEmailVerification(g,a.request),a.context.options.emailVerification?.autoSignInAfterVerification){let b=await nu(a);if(b&&b.user.email===e.email)await mj(a,{session:b.session,user:{...b.user,emailVerified:!0}});else{let b=await a.context.internalAdapter.createSession(f.user.id);if(!b)throw em.LG.from("INTERNAL_SERVER_ERROR",hg.FAILED_TO_CREATE_SESSION);await mj(a,{session:b,user:{...f.user,emailVerified:!0}})}}if(a.query.callbackURL)throw a.redirect(a.query.callbackURL);return a.json({status:!0,user:null})});async function oj(a,b){let{userInfo:c,account:d,callbackURL:e,disableSignUp:f,overrideUserInfo:g}=b,h=await a.context.internalAdapter.findOAuthUser(c.email.toLowerCase(),d.accountId,d.providerId).catch(b=>{ek.vF.error("Better auth was unable to query your database.\nError: ",b),nB(a,a.context.options.onAPIError?.errorURL||`${a.context.baseURL}/error`,"internal_server_error")}),i=h?.user,j=!i;if(h){let e=h.linkedAccount??h.accounts.find(a=>a.providerId===d.providerId&&a.accountId===d.accountId);if(e){let b=a.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({idToken:d.idToken,accessToken:await oe(d.accessToken,a.context),refreshToken:await oe(d.refreshToken,a.context),accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:d.refreshTokenExpiresAt,scope:d.scope}).filter(([a,b])=>void 0!==b)):{};a.context.options.account?.storeAccountCookie&&await l5(a,{...e,...b}),Object.keys(b).length>0&&await a.context.internalAdapter.updateAccount(e.id,b),c.emailVerified&&!h.user.emailVerified&&c.email.toLowerCase()===h.user.email&&await a.context.internalAdapter.updateUser(h.user.id,{emailVerified:!0})}else{let e=a.context.options.account?.accountLinking,f=b.isTrustedProvider||!1!==b.trustProviderByName&&a.context.trustedProviders.includes(d.providerId),g=e?.requireLocalEmailVerified??!0;if(!f&&!c.emailVerified||g&&!h.user.emailVerified||e?.enabled===!1||e?.disableImplicitLinking===!0)return(0,ey.yz)()&&ek.vF.warn(`User already exist but account isn't linked to ${d.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 a.context.internalAdapter.linkAccount({providerId:d.providerId,accountId:c.id.toString(),userId:h.user.id,accessToken:await oe(d.accessToken,a.context),refreshToken:await oe(d.refreshToken,a.context),idToken:d.idToken,accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:d.refreshTokenExpiresAt,scope:d.scope})}catch(a){return ek.vF.error("Unable to link account",a),{error:"unable to link account",data:null}}c.emailVerified&&!h.user.emailVerified&&c.email.toLowerCase()===h.user.email&&await a.context.internalAdapter.updateUser(h.user.id,{emailVerified:!0}),i=await ok(a,h.user.id,c)??i}if(g){let{id:b,...d}=c;i=await a.context.internalAdapter.updateUser(h.user.id,{...d,email:c.email.toLowerCase(),emailVerified:c.email.toLowerCase()===h.user.email&&h.user.emailVerified||c.emailVerified})}}else{if(f)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:b,...f}=c,g={accessToken:await oe(d.accessToken,a.context),refreshToken:await oe(d.refreshToken,a.context),idToken:d.idToken,accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:d.refreshTokenExpiresAt,scope:d.scope,providerId:d.providerId,accountId:c.id.toString()},{user:h,account:j}=await a.context.internalAdapter.createOAuthUser({...f,email:c.email.toLowerCase()},g);if(i=h,a.context.options.account?.storeAccountCookie&&await l5(a,j),!c.emailVerified&&i&&a.context.options.emailVerification?.sendOnSignUp&&a.context.options.emailVerification?.sendVerificationEmail){let b=await of(a.context.secret,i.email,void 0,a.context.options.emailVerification?.expiresIn),c=`${a.context.baseURL}/verify-email?token=${b}&callbackURL=${encodeURIComponent(e||"/")}`;await a.context.runInBackgroundOrAwait(a.context.options.emailVerification.sendVerificationEmail({user:i,url:c,token:b},a.request))}}catch(a){if(ek.vF.error(a),m$(a))return{error:a.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let k=await a.context.internalAdapter.createSession(i.id);return k?{data:{session:k,user:i},error:null,isRegister:j}:{error:"unable to create session",data:null,isRegister:!1}}async function ok(a,b,c){if(a.context.options.account?.accountLinking?.updateUserInfoOnLink!==!0)return;let{id:d,email:e,emailVerified:f,...g}=c;try{return await a.context.internalAdapter.updateUser(b,g)}catch(b){a.context.logger.warn("Could not update user info on account link",b);return}}var ol=c(81605);let om=(0,ol.q)("a-z","0-9","A-Z","-_"),{get:on,set:oo}=nq(()=>null),op=new lv({type:"object",shape:{callbackURL:kZ(),codeVerifier:kZ(),errorURL:kZ().optional(),newUserURL:kZ().optional(),expiresAt:lj(),oauthState:kZ().optional(),link:lw({email:kZ(),userId:l_()}).optional(),requestSignUp:ln().optional()},catchall:lr(),...iK(void 0)});Object.keys(op.shape);var oq=class extends em.$l{code;details;errorURL;constructor(a,b){super(a,b),this.code=b.code,this.details=b.details,this.errorURL=b.errorURL}};async function or(a,b,c){let d=om(32);if("cookie"===a.context.oauthConfig.storeStateStrategy){let e={...b,oauthState:d},f=await ob({key:a.context.secretConfig,data:JSON.stringify(e)}),g=a.context.createAuthCookie(c?.cookieName??"oauth_state",{maxAge:600});return a.setCookie(g.name,f,g.attributes),{state:d,codeVerifier:b.codeVerifier}}let e=a.context.createAuthCookie(c?.cookieName??"state",{maxAge:300});await a.setSignedCookie(e.name,d,a.context.secret,e.attributes);let f=new Date;if(f.setMinutes(f.getMinutes()+10),!await a.context.internalAdapter.createVerificationValue({value:JSON.stringify({...b,oauthState:d}),identifier:d,expiresAt:f}))throw new oq("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:d,codeVerifier:b.codeVerifier}}async function os(a,b,c){let d;if(!b)throw new oq("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===a.context.oauthConfig.storeStateStrategy){let e=a.context.createAuthCookie(c?.cookieName??"oauth_state"),f=a.getCookie(e.name);if(!f)throw new oq("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:b}});try{let b=await oc({key:a.context.secretConfig,data:f});d=op.parse(JSON.parse(b))}catch(a){throw new oq("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:b},cause:a})}if(!d.oauthState||d.oauthState!==b)throw new oq("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b},errorURL:d.errorURL});mk(a,e)}else{let e=await a.context.internalAdapter.findVerificationValue(b);if(!e)throw new oq("State mismatch: verification not found",{code:"state_mismatch",details:{state:b}});if(void 0!==(d=op.parse(JSON.parse(e.value))).oauthState&&d.oauthState!==b)throw new oq("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b},errorURL:d.errorURL});let f=a.context.createAuthCookie(c?.cookieName??"state"),g=await a.getSignedCookie(f.name,a.context.secret);if(!(c?.skipStateCookieCheck??a.context.oauthConfig.skipStateCookieCheck)&&(!g||g!==b))throw new oq("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:b},errorURL:d.errorURL});mk(a,f),await a.context.internalAdapter.deleteVerificationByIdentifier(b)}if(d.expiresAt<Date.now())throw new oq("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:d.expiresAt},errorURL:d.errorURL});return d}async function ot(a,b,c){let d=a.body?.callbackURL||a.context.options.baseURL;if(!d)throw em.LG.from("BAD_REQUEST",hg.CALLBACK_URL_REQUIRED);let e=om(128),f={...c||{},callbackURL:d,codeVerifier:e,errorURL:a.body?.errorCallbackURL,newUserURL:a.body?.newUserCallbackURL,link:b,expiresAt:Date.now()+6e5,requestSignUp:a.body?.requestSignUp};await oo(f);try{return or(a,f)}catch(b){throw a.context.logger.error("Failed to create verification",b),new em.LG("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:b})}}async function ou(a){let b,c=a.query.state||a.body?.state,d=a.context.options.onAPIError?.errorURL||`${a.context.baseURL}/error`;try{b=await os(a,c)}catch(e){a.context.logger.error("Failed to parse state",e);let b="internal_server_error",c=d;e instanceof oq&&(b="state_security_mismatch"===e.code?"state_mismatch":e.code,c=e.errorURL??d),nB(a,c,b)}return b.errorURL||(b.errorURL=d),b&&await oo(b),b}function ov(a){let b=a=>new Date(new Date().getTime()+1e3*a);return{tokenType:a.token_type,accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?b(a.expires_in):void 0,refreshTokenExpiresAt:a.refresh_token_expires_in?b(a.refresh_token_expires_in):void 0,scopes:a?.scope?"string"==typeof a.scope?a.scope.split(" "):a.scope:[],idToken:a.id_token,raw:a}}function ow(a){let b=Array.isArray(a)?a[0]:a;return"string"==typeof b&&b.length>0?b:void 0}async function ox(a){let b=new TextEncoder().encode(a),c=await crypto.subtle.digest("SHA-256",b);return mc.encode(new Uint8Array(c),{padding:!1})}async function oy({id:a,options:b,authorizationEndpoint:c,state:d,codeVerifier:e,scopes:f,claims:g,redirectURI:h,duration:i,prompt:j,accessType:k,responseType:l,display:m,loginHint:n,hd:o,responseMode:p,additionalParams:q,scopeJoiner:r}){let s=new URL((b="function"==typeof b?await b():b).authorizationEndpoint||c);s.searchParams.set("response_type",l||"code");let t=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;if(s.searchParams.set("client_id",t),s.searchParams.set("state",d),f&&s.searchParams.set("scope",f.join(r||" ")),s.searchParams.set("redirect_uri",b.redirectURI||h),i&&s.searchParams.set("duration",i),m&&s.searchParams.set("display",m),n&&s.searchParams.set("login_hint",n),j&&s.searchParams.set("prompt",j),o&&s.searchParams.set("hd",o),k&&s.searchParams.set("access_type",k),p&&s.searchParams.set("response_mode",p),e){let a=await ox(e);s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("code_challenge",a)}if(g){let a=g.reduce((a,b)=>(a[b]=null,a),{});s.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...a}}))}return q&&Object.entries(q).forEach(([a,b])=>{s.searchParams.set(a,b)}),s}var oz=Object.defineProperty,oA=Object.defineProperties,oB=Object.getOwnPropertyDescriptors,oC=Object.getOwnPropertySymbols,oD=Object.prototype.hasOwnProperty,oE=Object.prototype.propertyIsEnumerable,oF=(a,b,c)=>b in a?oz(a,b,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[b]=c,oG=(a,b)=>{for(var c in b||(b={}))oD.call(b,c)&&oF(a,c,b[c]);if(oC)for(var c of oC(b))oE.call(b,c)&&oF(a,c,b[c]);return a},oH=(a,b)=>oA(a,oB(b)),oI=class extends Error{constructor(a,b,c){super(b||a.toString(),{cause:c}),this.status=a,this.statusText=b,this.error=c,Error.captureStackTrace(this,this.constructor)}},oJ=async(a,b)=>{var c,d,e,f,g,h;let i=b||{},j={onRequest:[null==b?void 0:b.onRequest],onResponse:[null==b?void 0:b.onResponse],onSuccess:[null==b?void 0:b.onSuccess],onError:[null==b?void 0:b.onError],onRetry:[null==b?void 0:b.onRetry]};if(!b||!(null==b?void 0:b.plugins))return{url:a,options:i,hooks:j};for(let k of(null==b?void 0:b.plugins)||[]){if(k.init){let d=await (null==(c=k.init)?void 0:c.call(k,a.toString(),b));i=d.options||i,a=d.url}j.onRequest.push(null==(d=k.hooks)?void 0:d.onRequest),j.onResponse.push(null==(e=k.hooks)?void 0:e.onResponse),j.onSuccess.push(null==(f=k.hooks)?void 0:f.onSuccess),j.onError.push(null==(g=k.hooks)?void 0:g.onError),j.onRetry.push(null==(h=k.hooks)?void 0:h.onRetry)}return{url:a,options:i,hooks:j}},oK=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(){return this.options.delay}},oL=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(a){return Math.min(this.options.maxDelay,this.options.baseDelay*2**a)}},oM=async a=>{let b={},c=async a=>"function"==typeof a?await a():a;if(null==a?void 0:a.auth){if("Bearer"===a.auth.type){let d=await c(a.auth.token);if(!d)return b;b.authorization=`Bearer ${d}`}else if("Basic"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.username),c(a.auth.password)]);if(!d||!e)return b;b.authorization=`Basic ${btoa(`${d}:${e}`)}`}else if("Custom"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.prefix),c(a.auth.value)]);if(!e)return b;b.authorization=`${null!=d?d:""} ${e}`}}return b},oN=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function oO(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}function oP(a){try{return JSON.parse(a)}catch(b){return a}}function oQ(a){return"function"==typeof a}async function oR(a){let b=new Headers(function(...a){let b={};for(let c of a)if(c)if(c instanceof Headers)c.forEach((a,c)=>{b[c]=a});else for(let[a,d]of Array.isArray(c)?c:Object.entries(c))null!=d&&(b[a]=d);return b}(null==a?void 0:a.headers,await oM(a)));if(!b.has("content-type")){let c=oO(null==a?void 0:a.body)?"application/json":null;c&&b.set("content-type",c)}return b}var oS=class a extends Error{constructor(b,c){super(c||JSON.stringify(b,null,2)),this.issues=b,Object.setPrototypeOf(this,a.prototype)}};async function oT(a,b){let c=await a["~standard"].validate(b);if(c.issues)throw new oS(c.issues);return c.value}var oU=["get","post","put","patch","delete"],oV=async(a,b)=>{var c,d,e,f,g,h,i,j;let k,{hooks:l,url:m,options:n}=await oJ(a,b),o=function(a){if(null==a?void 0:a.customFetchImpl)return a.customFetchImpl;if("u">typeof globalThis&&oQ(globalThis.fetch))return globalThis.fetch;if("u">typeof window&&oQ(window.fetch))return window.fetch;throw Error("No fetch implementation found")}(n),p=new AbortController,q=null!=(c=n.signal)?c:p.signal,r=function(a,b){let{baseURL:c,params:d,query:e}=b||{query:{},params:{},baseURL:""},f=a.startsWith("http")?a.split("/").slice(0,3).join("/"):c||"";if(a.startsWith("@")){let b=a.toString().split("@")[1].split("/")[0];oU.includes(b)&&(a=a.replace(`@${b}/`,"/"))}f.endsWith("/")||(f+="/");let[g,h]=a.replace(f,"").split("?"),i=new URLSearchParams(h);for(let[a,b]of Object.entries(e||{})){let c;if(null!=b){if("string"==typeof b)c=b;else if(Array.isArray(b)){for(let c of b)i.append(a,c);continue}else c=JSON.stringify(b);i.set(a,c)}}let j=new Map;if(d)if(Array.isArray(d))for(let[a,b]of g.split("/").filter(a=>a.startsWith(":")).entries()){let c=d[a];j.set(b,String(c))}else for(let[a,b]of Object.entries(d))j.set(`:${a}`,String(b));g=(g=g.split("/").map(a=>(function(a,b){let c,d=a;for(let[a,c]of b)d=d.replace(a,c);if("."===(c=d)||".."===c)throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(d)})(a,j)).join("/")).replace(/^\/+/,"");let k=i.toString();return(k=k.length>0?`?${k}`.replace(/\+/g,"%20"):"",f.startsWith("http"))?new URL(`${g}${k}`,f):`${f}${g}${k}`}(m,n),s=await oR(n),t=function(a,b){let c,{body:d}=a;return d?oO(d)&&"string"!=typeof d?"application/x-www-form-urlencoded"===((c=b.get("content-type"))?c.split(";")[0].trim().toLowerCase():null)?new URLSearchParams(d).toString():JSON.stringify(d):d:null}(n,s),u=function(a,b){var c;if(null==b?void 0:b.method)return b.method.toUpperCase();if(a.startsWith("@")){let d=null==(c=a.split("@")[1])?void 0:c.split("/")[0];return oU.includes(d)?d.toUpperCase():(null==b?void 0:b.body)?"POST":"GET"}return(null==b?void 0:b.body)?"POST":"GET"}(m,n),v=oH(oG({},n),{url:r,headers:s,body:t,method:u,signal:q});for(let a of l.onRequest)if(a){let b=await a(v);"object"==typeof b&&null!==b&&Object.assign(v,b)}("pipeTo"in v&&"function"==typeof v.pipeTo||"function"==typeof(null==(d=null==b?void 0:b.body)?void 0:d.pipe))&&!("duplex"in v)&&(v.duplex="half");let{clearTimeout:w}=(!(null==n?void 0:n.signal)&&(null==n?void 0:n.timeout)&&(k=setTimeout(()=>null==p?void 0:p.abort(),null==n?void 0:n.timeout)),{abortTimeout:k,clearTimeout:()=>{k&&clearTimeout(k)}}),x=await o(v.url,v);w();let y={response:x,request:v};for(let a of l.onResponse)if(a){let c=await a(oH(oG({},y),{response:(null==(e=null==b?void 0:b.hookOptions)?void 0:e.cloneResponse)?x.clone():x}));c instanceof Response?x=c:"object"==typeof c&&null!==c&&(x=c.response)}if(x.ok){if("HEAD"===v.method)return{data:"",error:null};let a=function(a){let b=a.headers.get("content-type"),c=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!b)return"json";let d=b.split(";").shift()||"";return oN.test(d)?"json":c.has(d)||d.startsWith("text/")?"text":"blob"}(x),c={data:null,response:x,request:v};if("json"===a||"text"===a){let a=await x.text(),b=null!=(f=v.jsonParser)?f:oP;c.data=await b(a)}else c.data=await x[a]();for(let a of((null==v?void 0:v.output)&&v.output&&!v.disableValidation&&(c.data=await oT(v.output,c.data)),l.onSuccess))a&&await a(oH(oG({},c),{response:(null==(g=null==b?void 0:b.hookOptions)?void 0:g.cloneResponse)?x.clone():x}));return(null==b?void 0:b.throw)?c.data:{data:c.data,error:null}}let z=null!=(h=null==b?void 0:b.jsonParser)?h:oP,A=await x.text(),B=function(a){try{return JSON.parse(a),!0}catch(a){return!1}}(A),C=B?await z(A):null,D={response:x,responseText:A,request:v,error:oH(oG({},C),{status:x.status,statusText:x.statusText})};for(let a of l.onError)a&&await a(oH(oG({},D),{response:(null==(i=null==b?void 0:b.hookOptions)?void 0:i.cloneResponse)?x.clone():x}));if(null==b?void 0:b.retry){let c=function(a){if("number"==typeof a)return new oK({type:"linear",attempts:a,delay:1e3});switch(a.type){case"linear":return new oK(a);case"exponential":return new oL(a);default:throw Error("Invalid retry strategy")}}(b.retry),d=null!=(j=b.retryAttempt)?j:0;if(await c.shouldAttemptRetry(d,x)){for(let a of l.onRetry)a&&await a(y);let e=c.getDelay(d);return await new Promise(a=>setTimeout(a,e)),await oV(a,oH(oG({},b),{retryAttempt:d+1}))}}if(null==b?void 0:b.throw)throw new oI(x.status,x.statusText,B?C:A);return{data:null,error:oH(oG({},C),{status:x.status,statusText:x.statusText})}};async function oW({refreshToken:a,options:b,tokenEndpoint:c,authentication:d,extraParams:e}){let{body:f,headers:g}=await function({refreshToken:a,options:b,authentication:c,extraParams:d,resource:e}){let f=new URLSearchParams,g={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(f.set("grant_type","refresh_token"),f.set("refresh_token",a),"basic"===c){let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;a?g.authorization="Basic "+mb.encode(`${a}:${b.clientSecret??""}`):g.authorization="Basic "+mb.encode(`:${b.clientSecret??""}`)}else{let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;f.set("client_id",a),b.clientSecret&&f.set("client_secret",b.clientSecret)}if(e)if("string"==typeof e)f.append("resource",e);else for(let a of e)f.append("resource",a);if(d)for(let[a,b]of Object.entries(d))f.set(a,b);return{body:f,headers:g}}({refreshToken:a,options:b,authentication:d,extraParams:e}),{data:h,error:i}=await oV(c,{method:"POST",body:f,headers:g});if(i)throw i;let j={accessToken:h.access_token,refreshToken:h.refresh_token,tokenType:h.token_type,scopes:h.scope?.split(" "),idToken:h.id_token};return h.expires_in&&(j.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*h.expires_in)),h.refresh_token_expires_in&&(j.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*h.refresh_token_expires_in)),j}async function oX({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){return oY({code:a,codeVerifier:b,redirectURI:c,options:d="function"==typeof d?await d():d,authentication:e,deviceId:f,headers:g,additionalParams:h,resource:i})}function oY({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){let j=new URLSearchParams,k={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...g};if(j.set("grant_type","authorization_code"),j.set("code",a),b&&j.set("code_verifier",b),d.clientKey&&j.set("client_key",d.clientKey),f&&j.set("device_id",f),j.set("redirect_uri",d.redirectURI||c),i)if("string"==typeof i)j.append("resource",i);else for(let a of i)j.append("resource",a);if("basic"===e){let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;k.authorization=`Basic ${mb.encode(`${a}:${d.clientSecret??""}`)}`}else{let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;j.set("client_id",a),d.clientSecret&&j.set("client_secret",d.clientSecret)}for(let[a,b]of Object.entries(h))j.has(a)||j.append(a,b);return{body:j,headers:k}}async function oZ({code:a,codeVerifier:b,redirectURI:c,options:d,tokenEndpoint:e,authentication:f,deviceId:g,headers:h,additionalParams:i={},resource:j}){let{body:k,headers:l}=await oX({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:f,deviceId:g,headers:h,additionalParams:i,resource:j}),{data:m,error:n}=await oV(e,{method:"POST",body:k,headers:l});if(n)throw n;return ov(m)}function o$(a){let b,c;if("string"!=typeof a)throw new fv("JWTs must use Compact JWS serialization, JWT must be a string");let{1:d,length:e}=a.split(".");if(5===e)throw new fv("Only JWTs using Compact JWS serialization can be decoded");if(3!==e)throw new fv("Invalid JWT");if(!d)throw new fv("JWTs must contain a payload");try{b=fl(d)}catch{throw new fv("Failed to base64url decode the payload")}try{c=JSON.parse(ff.decode(b))}catch{throw new fv("Failed to parse the decoded payload as JSON")}if(!fO(c))throw new fv("Invalid JWT Claims Set");return c}async function o_(a){let b=new TextEncoder().encode(a);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",b))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function o0(a,b){return"string"==typeof a&&(a===b||a===await o_(b))}let o1=async a=>{let{data:b}=await oV("https://appleid.apple.com/auth/keys");if(!b?.keys)throw new em.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await gR(c,c.alg)},o2=async(a,b,c)=>{let d=`https://cognito-idp.${b}.amazonaws.com/${c}/.well-known/jwks.json`;try{let{data:b}=await oV(d);if(!b?.keys)throw new em.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await gR(c,c.alg)}catch(a){throw ek.vF.error("Failed to fetch Cognito public key:",a),a}};function o3(a){return fO(a)}class o4{#aJ;#aK=new WeakMap;constructor(a){if(!function(a){return a&&"object"==typeof a&&Array.isArray(a.keys)&&a.keys.every(o3)}(a))throw new fx("JSON Web Key Set malformed");this.#aJ=structuredClone(a)}jwks(){return this.#aJ}async getKey(a,b){let{alg:c,kid:d}={...a,...b?.header},e=function(a){switch("string"==typeof a&&a.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new fr('Unsupported "alg" value for a JSON Web Key Set')}}(c),f=this.#aJ.keys.filter(a=>{let b=e===a.kty;if(b&&"string"==typeof d&&(b=d===a.kid),b&&("string"==typeof a.alg||"AKP"===e)&&(b=c===a.alg),b&&"string"==typeof a.use&&(b="sig"===a.use),b&&Array.isArray(a.key_ops)&&(b=a.key_ops.includes("verify")),b)switch(c){case"ES256":b="P-256"===a.crv;break;case"ES384":b="P-384"===a.crv;break;case"ES512":b="P-521"===a.crv;break;case"Ed25519":case"EdDSA":b="Ed25519"===a.crv}return b}),{0:g,length:h}=f;if(0===h)throw new fy;if(1!==h){let a=new fz,b=this.#aK;throw a[Symbol.asyncIterator]=async function*(){for(let a of f)try{yield await o5(b,a,c)}catch{}},a}return o5(this.#aK,g,c)}}async function o5(a,b,c){let d=a.get(b)||a.set(b,{}).get(b);if(void 0===d[c]){let a=await gR({...b,ext:!0},c);if(a instanceof Uint8Array||"public"!==a.type)throw new fx("JSON Web Key Set members must be public keys");d[c]=a}return d[c]}function o6(a){let b=new o4(a),c=async(a,c)=>b.getKey(a,c);return Object.defineProperties(c,{jwks:{value:()=>structuredClone(b.jwks()),enumerable:!1,configurable:!1,writable:!1}}),c}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(g="jose/v6.2.3");let o7=Symbol();async function o8(a,b,c,d=fetch){let e=await d(a,{method:"GET",signal:c,redirect:"manual",headers:b}).catch(a=>{if("TimeoutError"===a.name)throw new fA;throw a});if(200!==e.status)throw new fn("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await e.json()}catch{throw new fn("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let o9=Symbol();class pa{#aL;#aM;#aN;#aO;#aP;#aQ;#aR;#aS;#aT;#aU;constructor(a,b){if(!(a instanceof URL))throw TypeError("url must be an instance of URL");this.#aL=new URL(a.href),this.#aM="number"==typeof b?.timeoutDuration?b?.timeoutDuration:5e3,this.#aN="number"==typeof b?.cooldownDuration?b?.cooldownDuration:3e4,this.#aO="number"==typeof b?.cacheMaxAge?b?.cacheMaxAge:6e5,this.#aR=new Headers(b?.headers),g&&!this.#aR.has("User-Agent")&&this.#aR.set("User-Agent",g),this.#aR.has("accept")||(this.#aR.set("accept","application/json"),this.#aR.append("accept","application/jwk-set+json")),this.#aS=b?.[o7],b?.[o9]!==void 0&&(this.#aU=b?.[o9],function(a,b){return!("object"!=typeof a||null===a||!("uat"in a)||"number"!=typeof a.uat||Date.now()-a.uat>=b)&&"jwks"in a&&!!fO(a.jwks)&&!!Array.isArray(a.jwks.keys)&&!!Array.prototype.every.call(a.jwks.keys,fO)}(b?.[o9],this.#aO)&&(this.#aP=this.#aU.uat,this.#aT=o6(this.#aU.jwks)))}pendingFetch(){return!!this.#aQ}coolingDown(){return"number"==typeof this.#aP&&Date.now()<this.#aP+this.#aN}fresh(){return"number"==typeof this.#aP&&Date.now()<this.#aP+this.#aO}jwks(){return this.#aT?.jwks()}async getKey(a,b){this.#aT&&this.fresh()||await this.reload();try{return await this.#aT(a,b)}catch(c){if(c instanceof fy&&!1===this.coolingDown())return await this.reload(),this.#aT(a,b);throw c}}async reload(){this.#aQ&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#aQ=void 0),this.#aQ||=o8(this.#aL.href,this.#aR,AbortSignal.timeout(this.#aM),this.#aS).then(a=>{this.#aT=o6(a),this.#aU&&(this.#aU.uat=Date.now(),this.#aU.jwks=a),this.#aP=Date.now(),this.#aQ=void 0}).catch(a=>{throw this.#aQ=void 0,a}),await this.#aQ}}async function pb(a,b){let c=ow(b.clientId);if(!c||!b.clientSecret)return null;let d=Array.isArray(b.clientId)?b.clientId:[b.clientId],{data:e,error:f}=await oV("https://graph.facebook.com/debug_token",{query:{input_token:a,access_token:`${c}|${b.clientSecret}`}});if(f||!e?.data)return null;let{is_valid:g,app_id:h,user_id:i}=e.data;return!0===g&&h&&d.includes(h)&&i?i:null}let pc=(a="")=>a.split("://").map(a=>a.replace(/\/{2,}/g,"/")).join("://"),pd=async a=>{let{data:b}=await oV("https://www.googleapis.com/oauth2/v3/certs");if(!b?.keys)throw new em.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await gR(c,c.alg)},pe="9188040d-6c67-4c5b-b112-36a304b66dad",pf=async(a,b,c)=>{let{data:d}=await oV(`${c}/${b}/discovery/v2.0/keys`);if(!d?.keys)throw new em.LG("BAD_REQUEST",{message:"Keys not found"});let e=d.keys.find(b=>b.kid===a);if(!e)throw Error(`JWK with kid ${a} not found`);return await gR(e,e.alg)},pg=["RS256","HS256"],ph=async(a,b)=>{let{data:c}=await oV(b);if(!c?.keys)throw new em.LG("BAD_REQUEST",{message:"Keys not found"});let d=c.keys.find(b=>b.kid===a);if(!d)throw Error(`JWK with kid ${a} not found`);return await gR(d,d.alg)},pi="https://backboard.railway.com/oauth/token",pj={apple:a=>{let b="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:b,scopes:c,redirectURI:d}){if(!ow(a.clientId)||!a.clientSecret)throw ek.vF.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");let e=a.disableDefaultScope?[]:["email","name"];return a.scope&&e.push(...a.scope),c&&e.push(...c),await oy({id:"apple",options:a,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:e,state:b,redirectURI:d,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=g2(b);if(!d||!e)return!1;let{payload:f}=await gj(b,await o1(d),{algorithms:[e],issuer:"https://appleid.apple.com",audience:a.audience&&a.audience.length?a.audience:a.appBundleIdentifier?a.appBundleIdentifier:a.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(a=>{void 0!==f[a]&&(f[a]=!!f[a])}),c&&!await o0(f.nonce,c))return!1;return!!f}catch{return!1}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:a,tokenEndpoint:b}),async getUserInfo(b){let c;if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let d=o$(b.idToken);if(!d)return null;c=b.user?.name?`${b.user.name.firstName||""} ${b.user.name.lastName||""}`.trim():d.name||"";let e="boolean"==typeof d.email_verified?d.email_verified:"true"===d.email_verified,f={...d,name:c},g=await a.mapProfileToUser?.(f);return{user:{id:d.sub,name:f.name,emailVerified:e,email:d.email,...g},data:f}},options:a}},atlassian:a=>{let b="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw ek.vF.error("Client Id and Secret are required for Atlassian"),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new em.$l("codeVerifier is required for Atlassian");let f=a.disableDefaultScope?[]:["read:jira-user","offline_access"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"atlassian",options:a,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e,additionalParams:{audience:"api.atlassian.com"},prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.accessToken)return null;try{let{data:c}=await oV("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name,email:c.email,image:c.picture,emailVerified:!1,...d},data:c}}catch(a){return ek.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},cognito:a=>{if(!a.domain||!a.region||!a.userPoolId)throw ek.vF.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new em.$l("DOMAIN_AND_REGION_REQUIRED");let b=a.domain.replace(/^https?:\/\//,""),c=`https://${b}/oauth2/authorize`,d=`https://${b}/oauth2/token`,e=`https://${b}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:b,scopes:d,codeVerifier:e,redirectURI:f}){if(!ow(a.clientId))throw ek.vF.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(a.requireClientSecret&&!a.clientSecret)throw ek.vF.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new em.$l("CLIENT_SECRET_REQUIRED");let g=a.disableDefaultScope?[]:["openid","profile","email"];a.scope&&g.push(...a.scope),d&&g.push(...d);let h=await oy({id:"cognito",options:{...a},authorizationEndpoint:c,scopes:g,state:b,codeVerifier:e,redirectURI:f,prompt:a.prompt}),i=h.searchParams.get("scope");if(i){h.searchParams.delete("scope");let a=encodeURIComponent(i),b=h.toString(),c=b.includes("?")?"&":"?";return new URL(`${b}${c}scope=${a}`)}return h},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:e})=>oZ({code:b,codeVerifier:c,redirectURI:e,options:a,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:d}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=g2(b);if(!d||!e)return!1;let f=await o2(d,a.region,a.userPoolId),g=`https://cognito-idp.${a.region}.amazonaws.com/${a.userPoolId}`,{payload:h}=await gj(b,f,{algorithms:[e],issuer:g,audience:a.clientId,maxTokenAge:"1h"});if(c&&h.nonce!==c)return!1;return!0}catch(a){return ek.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken)try{let c=o$(b.idToken);if(!c)return null;let d=c.name||c.given_name||c.username||"",e={...c,name:d},f=await a.mapProfileToUser?.(e);return{user:{id:c.sub,name:e.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...f},data:e}}catch(a){ek.vF.error("Failed to decode ID token:",a)}if(b.accessToken)try{let{data:c}=await oV(e,{headers:{Authorization:`Bearer ${b.accessToken}`}});if(c){let b=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.given_name||c.username||"",email:c.email,image:c.picture,emailVerified:c.email_verified,...b},data:c}}}catch(a){ek.vF.error("Failed to fetch user info from Cognito:",a)}return null},options:a}},discord:a=>{let b="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["identify","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=e.includes("bot")&&void 0!==a.permissions?`&permissions=${a.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${e.join("+")}&response_type=code&client_id=${a.clientId}&redirect_uri=${encodeURIComponent(a.redirectURI||d)}&state=${b}&prompt=${a.prompt||"none"}${f}`)},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;if(null===c.avatar)c.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===c.discriminator?Number(BigInt(c.id)>>BigInt(22))%6:parseInt(c.discriminator)%5}.png`;else{let a=c.avatar.startsWith("a_")?"gif":"png";c.image_url=`https://cdn.discordapp.com/avatars/${c.id}/${c.avatar}.${a}`}let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.global_name||c.username||"",email:c.email,emailVerified:c.verified,image:c.image_url,...e},data:c}},options:a}},facebook:a=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:b,scopes:c,redirectURI:d,loginHint:e}){if(!ow(a.clientId)||!a.clientSecret)throw ek.vF.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");let f=a.disableDefaultScope?[]:["email","public_profile"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await oy({id:"facebook",options:a,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:f,state:b,redirectURI:d,loginHint:e,additionalParams:a.configId?{config_id:a.configId}:{}})},validateAuthorizationCode:async({code:b,redirectURI:c})=>oZ({code:b,redirectURI:c,options:a,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);if(3===b.split(".").length)try{var d;let e,f,{payload:g}=await gj(b,(d=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),e=new pa(d,void 0),f=async(a,b)=>e.getKey(a,b),Object.defineProperties(f,{coolingDown:{get:()=>e.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>e.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>e.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>e.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>e.jwks(),enumerable:!0,configurable:!1,writable:!1}}),f),{algorithms:["RS256"],audience:a.clientId,issuer:"https://www.facebook.com"});if(c&&g.nonce!==c)return!1;return!!g}catch{return!1}return await pb(b,a)!==null},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken&&3===b.idToken.split(".").length){let c=o$(b.idToken),d={id:c.sub,name:c.name,email:c.email,picture:{data:{url:c.picture,height:100,width:100,is_silhouette:!1}}},e=await a.mapProfileToUser?.({...d,email_verified:!1});return{user:{...d,emailVerified:!1,...e},data:c}}let c=b.accessToken;if(!c)return null;let d=await pb(c,a);if(!d)return null;let{data:e,error:f}=await oV("https://graph.facebook.com/me?fields="+["id","name","email","picture",...a?.fields||[]].join(","),{auth:{type:"Bearer",token:c}});if(f||e.id!==d)return null;let g=await a.mapProfileToUser?.(e);return{user:{id:e.id,name:e.name,email:e.email,image:e.picture.data.url,emailVerified:e.email_verified??!1,...g},data:e}},options:a}),figma:a=>{let b="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw ek.vF.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new em.$l("codeVerifier is required for Figma");let f=a.disableDefaultScope?[]:["current_user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await oy({id:"figma",options:a,authorizationEndpoint:"https://www.figma.com/oauth",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b,authentication:"basic"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b,authentication:"basic"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);try{let{data:c}=await oV("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return ek.vF.error("Failed to fetch user from Figma"),null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.handle,email:c.email,image:c.img_url,emailVerified:!1,...d},data:c}}catch(a){return ek.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},github:a=>{let b="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:b,scopes:c,loginHint:d,codeVerifier:e,redirectURI:f}){let g=a.disableDefaultScope?[]:["read:user","user:email"];return a.scope&&g.push(...a.scope),c&&g.push(...c),oy({id:"github",options:a,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:g,state:b,codeVerifier:e,redirectURI:f,loginHint:d,prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>{let{body:f,headers:g}=oY({code:c,codeVerifier:d,redirectURI:e,options:a}),{data:h,error:i}=await oV(b,{method:"POST",body:f,headers:g});return i?(ek.vF.error("GitHub OAuth token exchange failed:",i),null):"error"in h?(ek.vF.error("GitHub OAuth token exchange failed:",h),null):ov(h)},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e}=await oV("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${b.accessToken}`,"User-Agent":"better-auth"}});!c.email&&e&&(c.email=(e.find(a=>a.primary)??e[0])?.email);let f=e?.find(a=>a.email===c.email)?.verified??!1,g=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name||c.login||"",email:c.email,image:c.avatar_url,emailVerified:f,...g},data:c}},options:a}},microsoft:a=>{let b=a.tenantId||"common",c=a.authority||"https://login.microsoftonline.com";for(;c.endsWith("/");)c=c.slice(0,-1);let d=`${c}/${b}/oauth2/v2.0/authorize`,e=`${c}/${b}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(b){if(!ow(a.clientId))throw ek.vF.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),oy({id:"microsoft",options:a,authorizationEndpoint:d,state:b.state,codeVerifier:b.codeVerifier,scopes:c,redirectURI:b.redirectURI,prompt:a.prompt,loginHint:b.loginHint})},validateAuthorizationCode:({code:b,codeVerifier:c,redirectURI:d})=>oZ({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:e}),async verifyIdToken(d,e){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(d,e);try{let{kid:f,alg:g}=g2(d);if(!f||!g)return!1;let h=await pf(f,b,c),i={algorithms:[g],audience:a.clientId,maxTokenAge:"1h"};"common"!==b&&"organizations"!==b&&"consumers"!==b&&(i.issuer=`${c}/${b}/v2.0`);let{payload:j}=await gj(d,h,i);if(e&&j.nonce!==e)return!1;let k=j.tid;if("string"!=typeof k||j.iss!==`${c}/${k}/v2.0`||"organizations"===b&&k===pe||"consumers"===b&&k!==pe)return!1;return!0}catch(a){return ek.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=o$(b.idToken),d=a.profilePhotoSize||48;await oV(`https://graph.microsoft.com/v1.0/me/photos/${d}x${d}/$value`,{headers:{Authorization:`Bearer ${b.accessToken}`},async onResponse(b){if(!a.disableProfilePhoto&&b.response.ok)try{let a=await b.response.clone().arrayBuffer();c.picture=`data:image/jpeg;base64, ${mb.encode(a)}`}catch(a){ek.vF.error(a&&"object"==typeof a&&"name"in a?a.name:"",a)}}});let e=await a.mapProfileToUser?.(c),f=void 0!==c.email_verified?c.email_verified:!!(c.email&&(c.verified_primary_email?.includes(c.email)||c.verified_secondary_email?.includes(c.email)));return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:f,...e},data:c}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>{let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),oW({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},extraParams:{scope:c.join(" ")},tokenEndpoint:e})},options:a}},google:a=>({id:"google",name:"Google",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e,loginHint:f,display:g}){if(!ow(a.clientId)||!a.clientSecret)throw ek.vF.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new em.$l("codeVerifier is required for Google");let h=a.disableDefaultScope?[]:["email","profile","openid"];return a.scope&&h.push(...a.scope),c&&h.push(...c),await oy({id:"google",options:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:h,state:b,codeVerifier:d,redirectURI:e,prompt:a.prompt,accessType:a.accessType,display:g||a.display,loginHint:f,hd:a.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:d})=>oZ({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=g2(b);if(!d||!e)return!1;let{payload:f}=await gj(b,await pd(d),{algorithms:[e],issuer:["https://accounts.google.com","accounts.google.com"],audience:a.clientId,maxTokenAge:"1h"});if(c&&f.nonce!==c||a.hd&&f.hd!==a.hd)return!1;return!0}catch{return!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=o$(b.idToken);if(a.hd&&c.hd!==a.hd)return ek.vF.error(`Google sign-in rejected: id token hosted domain (hd) "${c.hd??"<missing>"}" does not match the configured "hd" option "${a.hd}".`),null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...d},data:c}},options:a}),huggingface:a=>{let b="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["openid","profile","email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"huggingface",options:a,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.preferred_username||"",email:c.email,image:c.picture,emailVerified:c.email_verified??!1,...e},data:c}},options:a}},slack:a=>{let b="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["openid","profile","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=new URL("https://slack.com/openid/connect/authorize");return f.searchParams.set("scope",e.join(" ")),f.searchParams.set("response_type","code"),f.searchParams.set("client_id",a.clientId),f.searchParams.set("redirect_uri",a.redirectURI||d),f.searchParams.set("state",b),f},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c["https://slack.com/user_id"],name:c.name||"",email:c.email,emailVerified:c.email_verified,image:c.picture||c["https://slack.com/user_image_512"],...e},data:c}},options:a}},spotify:a=>{let b="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["user-read-email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"spotify",options:a,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.display_name,email:c.email,image:c.images[0]?.url,emailVerified:!1,...e},data:c}},options:a}},twitch:a=>{let b="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["user:read:email","openid"];return a.scope&&e.push(...a.scope),c&&e.push(...c),oy({id:"twitch",redirectURI:d,options:a,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:e,state:b,claims:a.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let c=b.idToken;if(!c)return ek.vF.error("No idToken found in token"),null;let d=o$(c),e=await a.mapProfileToUser?.(d);return{user:{id:d.sub,name:d.preferred_username,email:d.email,image:d.picture,emailVerified:d.email_verified,...e},data:d}},options:a}},twitter:a=>{let b="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(b){let c=a.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),oy({id:"twitter",options:a,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:c,state:b.state,codeVerifier:b.codeVerifier,redirectURI:b.redirectURI})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,authentication:"basic",redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},authentication:"basic",tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e,error:f}=await oV("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}}),g=!1;!f&&e?.data?.confirmed_email&&(c.data.email=e.data.confirmed_email,g=!0);let h=await a.mapProfileToUser?.(c);return{user:{id:c.data.id,name:c.data.name,email:c.data.email||c.data.username||null,image:c.data.profile_image_url,emailVerified:g,...h},data:c}},options:a}},dropbox:a=>{let b="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:b,scopes:c,codeVerifier:d,redirectURI:e})=>{let f=a.disableDefaultScope?[]:["account_info.read"];a.scope&&f.push(...a.scope),c&&f.push(...c);let g={};return a.accessType&&(g.token_access_type=a.accessType),await oy({id:"dropbox",options:a,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:f,state:b,redirectURI:e,codeVerifier:d,additionalParams:g})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>await oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name?.display_name,email:c.email,emailVerified:c.email_verified||!1,image:c.profile_photo_url,...e},data:c}},options:a}},kick:a=>({id:"kick",name:"Kick",createAuthorizationURL({state:b,scopes:c,redirectURI:d,codeVerifier:e}){let f=a.disableDefaultScope?[]:["user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"kick",redirectURI:d,options:a,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:f,codeVerifier:e,state:b})},validateAuthorizationCode:async({code:b,redirectURI:c,codeVerifier:d})=>oZ({code:b,redirectURI:c,options:a,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=c.data[0],f=await a.mapProfileToUser?.(e);return{user:{id:e.user_id,name:e.name,email:e.email,image:e.profile_picture,emailVerified:!1,...f},data:e}},options:a}),linear:a=>{let b="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:b,scopes:c,loginHint:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"linear",options:a,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:f,state:b,redirectURI:e,loginHint:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b.accessToken}`},body:JSON.stringify({query:`
|
|
102
|
+
query {
|
|
103
|
+
viewer {
|
|
104
|
+
id
|
|
105
|
+
name
|
|
106
|
+
email
|
|
107
|
+
avatarUrl
|
|
108
|
+
active
|
|
109
|
+
createdAt
|
|
110
|
+
updatedAt
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
`})});if(d||!c?.data?.viewer)return null;let e=c.data.viewer,f=await a.mapProfileToUser?.(e);return{user:{id:c.data.viewer.id,name:c.data.viewer.name,email:c.data.viewer.email,image:c.data.viewer.avatarUrl,emailVerified:!1,...f},data:e}},options:a}},linkedin:a=>{let b="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:b,scopes:c,redirectURI:d,loginHint:e})=>{let f=a.disableDefaultScope?[]:["profile","email","openid"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await oy({id:"linkedin",options:a,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:f,state:b,loginHint:e,redirectURI:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>await oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name,email:c.email,emailVerified:c.email_verified??!1,image:c.picture,...e},data:c}},options:a}},gitlab:a=>{let b,{authorizationEndpoint:c,tokenEndpoint:d,userinfoEndpoint:e}=(b=a.issuer||"https://gitlab.com",{authorizationEndpoint:pc(`${b}/oauth/authorize`),tokenEndpoint:pc(`${b}/oauth/token`),userinfoEndpoint:pc(`${b}/api/v4/user`)}),f="gitlab";return{id:f,name:"Gitlab",createAuthorizationURL:async({state:b,scopes:d,codeVerifier:e,loginHint:g,redirectURI:h})=>{let i=a.disableDefaultScope?[]:["read_user"];return a.scope&&i.push(...a.scope),d&&i.push(...d),await oy({id:f,options:a,authorizationEndpoint:c,scopes:i,state:b,redirectURI:h,codeVerifier:e,loginHint:g})},validateAuthorizationCode:async({code:b,redirectURI:c,codeVerifier:e})=>oZ({code:b,redirectURI:c,options:a,codeVerifier:e,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:d}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV(e,{headers:{authorization:`Bearer ${b.accessToken}`}});if(d||"active"!==c.state||c.locked)return null;let f=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name??c.username??"",email:c.email,image:c.avatar_url,emailVerified:c.email_verified??!1,...f},data:c}},options:a}},tiktok:a=>{let b="https://open.tiktokapis.com/v2/oauth/token/";return{id:"tiktok",name:"TikTok",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["user.info.profile"];return a.scope&&e.push(...a.scope),c&&e.push(...c),new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${e.join(",")}&response_type=code&client_key=${a.clientKey}&redirect_uri=${encodeURIComponent(a.redirectURI||d)}&state=${b}`)},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:a.redirectURI||d,options:{clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientSecret:a.clientSecret},tokenEndpoint:b,authentication:"post",extraParams:{client_key:a.clientKey}}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${b.accessToken}`}});return d?null:{user:{email:c.data.user.email||c.data.user.username,id:c.data.user.open_id,name:c.data.user.display_name||c.data.user.username||"",image:c.data.user.avatar_large_url,emailVerified:!1},data:c}},options:a}},reddit:a=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["identity"];return a.scope&&e.push(...a.scope),c&&e.push(...c),oy({id:"reddit",options:a,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:e,state:b,redirectURI:d,duration:a.duration})},validateAuthorizationCode:async({code:b,redirectURI:c})=>{let d=new URLSearchParams({grant_type:"authorization_code",code:b,redirect_uri:a.redirectURI||c}),{data:e,error:f}=await oV("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 ${mb.encode(`${a.clientId}:${a.clientSecret}`)}`},body:d.toString()});if(f)throw f;return ov(e)},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},authentication:"basic",tokenEndpoint:"https://www.reddit.com/api/v1/access_token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${b.accessToken}`,"User-Agent":"better-auth"}});if(d)return null;let e=await a.mapProfileToUser?.(c),f=e?.email||`${c.id}@reddit.invalid`;return{user:{id:c.id,name:c.name,image:c.icon_img?.split("?")[0],...e,email:f,emailVerified:e?.emailVerified??!1},data:c}},options:a}),roblox:a=>{let b="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["openid","profile"];return a.scope&&e.push(...a.scope),c&&e.push(...c),new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${e.join("+")}&response_type=code&client_id=${a.clientId}&redirect_uri=${encodeURIComponent(a.redirectURI||d)}&state=${b}&prompt=${a.prompt||"select_account consent"}`)},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:a.redirectURI||d,options:a,tokenEndpoint:b,authentication:"post"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.nickname||c.preferred_username||"",image:c.picture,email:c.preferred_username||null,emailVerified:!1,...e},data:{...c}}},options:a}},salesforce:a=>{let b=(a.environment??"production")==="sandbox",c=a.loginUrl?`https://${a.loginUrl}/services/oauth2/authorize`:b?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",d=a.loginUrl?`https://${a.loginUrl}/services/oauth2/token`:b?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",e=a.loginUrl?`https://${a.loginUrl}/services/oauth2/userinfo`:b?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",async createAuthorizationURL({state:b,scopes:d,codeVerifier:e,redirectURI:f}){if(!a.clientId||!a.clientSecret)throw ek.vF.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!e)throw new em.$l("codeVerifier is required for Salesforce");let g=a.disableDefaultScope?[]:["openid","email","profile"];return a.scope&&g.push(...a.scope),d&&g.push(...d),oy({id:"salesforce",options:a,authorizationEndpoint:c,scopes:g,state:b,codeVerifier:e,redirectURI:a.redirectURI||f})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:e})=>oZ({code:b,codeVerifier:c,redirectURI:a.redirectURI||e,options:a,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:d}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);try{let{data:c}=await oV(e,{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return ek.vF.error("Failed to fetch user info from Salesforce"),null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.user_id,name:c.name,email:c.email,image:c.photos?.picture||c.photos?.thumbnail,emailVerified:c.email_verified??!1,...d},data:c}}catch(a){return ek.vF.error("Failed to fetch user info from Salesforce:",a),null}},options:a}},vk:a=>{let b="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["email","phone"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"vk",options:a,authorizationEndpoint:"https://id.vk.com/authorize",scopes:f,state:b,redirectURI:e,codeVerifier:d})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e,deviceId:f})=>oZ({code:c,codeVerifier:d,redirectURI:a.redirectURI||e,options:a,deviceId:f,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.accessToken)return null;let c=new URLSearchParams({access_token:b.accessToken,client_id:a.clientId}).toString(),{data:d,error:e}=await oV("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});if(e)return null;let f=await a.mapProfileToUser?.(d);return d.user.email||f?.email?{user:{id:d.user.user_id,first_name:d.user.first_name,last_name:d.user.last_name,email:d.user.email,image:d.user.avatar,emailVerified:!1,birthday:d.user.birthday,sex:d.user.sex,name:`${d.user.first_name} ${d.user.last_name}`,...f},data:d}:null},options:a}},zoom:a=>{let b={pkce:!0,...a};return{id:"zoom",name:"Zoom",createAuthorizationURL:async({state:a,redirectURI:c,codeVerifier:d})=>{let e=new URLSearchParams({response_type:"code",redirect_uri:b.redirectURI?b.redirectURI:c,client_id:b.clientId,state:a});if(b.pkce){let a=await ox(d);e.set("code_challenge_method","S256"),e.set("code_challenge",a)}let f=new URL("https://zoom.us/oauth/authorize");return f.search=e.toString(),f},validateAuthorizationCode:async({code:a,redirectURI:c,codeVerifier:d})=>oZ({code:a,redirectURI:b.redirectURI||c,codeVerifier:d,options:b,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:b.refreshAccessToken?b.refreshAccessToken:async a=>oW({refreshToken:a,options:{clientId:b.clientId,clientKey:b.clientKey,clientSecret:b.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(a){if(b.getUserInfo)return b.getUserInfo(a);let{data:c,error:d}=await oV("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${a.accessToken}`}});if(d)return null;let e=await b.mapProfileToUser?.(c);return{user:{id:c.id,name:c.display_name,image:c.pic_url,email:c.email,emailVerified:!!c.verified,...e},data:{...c}}}}},notion:a=>{let b="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",createAuthorizationURL({state:b,scopes:c,loginHint:d,redirectURI:e}){let f=(a.disableDefaultScope,[]);return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"notion",options:a,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:f,state:b,redirectURI:e,loginHint:d,additionalParams:{owner:"user"}})},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b,authentication:"basic"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${b.accessToken}`,"Notion-Version":"2022-06-28"}});if(d||!c)return null;let e=c.bot?.owner?.user;if(!e)return null;let f=await a.mapProfileToUser?.(e);return{user:{id:e.id,name:e.name||"",email:e.person?.email||null,image:e.avatar_url,emailVerified:!1,...f},data:e}},options:a}},kakao:a=>{let b="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return a.scope&&e.push(...a.scope),c&&e.push(...c),oy({id:"kakao",options:a,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:e,state:b,redirectURI:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(d||!c)return null;let e=await a.mapProfileToUser?.(c),f=c.kakao_account||{},g=f.profile||{};return{user:{id:String(c.id),name:g.nickname||f.name||"",email:f.email,image:g.profile_image_url||g.thumbnail_image_url,emailVerified:!!f.is_email_valid&&!!f.is_email_verified,...e},data:c}},options:a}},naver:a=>{let b="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["profile","email"];return a.scope&&e.push(...a.scope),c&&e.push(...c),oy({id:"naver",options:a,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:e,state:b,redirectURI:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>oZ({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(d||!c||"00"!==c.resultcode)return null;let e=await a.mapProfileToUser?.(c),f=c.response||{};return{user:{id:f.id,name:f.name||f.nickname||"",email:f.email,image:f.profile_image,emailVerified:!1,...e},data:c}},options:a}},line:a=>{let b="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e,loginHint:f}){let g=a.disableDefaultScope?[]:["openid","profile","email"];return a.scope&&g.push(...a.scope),c&&g.push(...c),await oy({id:"line",options:a,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:g,state:b,codeVerifier:d,redirectURI:e,loginHint:f})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:b}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);let d=new URLSearchParams;d.set("id_token",b),d.set("client_id",a.clientId),c&&d.set("nonce",c);let{data:e,error:f}=await oV("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:d});return!f&&!!e&&e.aud===a.clientId&&(!e.nonce||e.nonce===c)},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let c=null;if(b.idToken)try{c=o$(b.idToken)}catch{}if(!c){let{data:a}=await oV("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${b.accessToken}`}});c=a||null}if(!c)return null;let d=await a.mapProfileToUser?.(c),e=c.sub||c.userId,f=c.name||c.displayName||"",g=c.picture||c.pictureUrl||void 0;return{user:{id:e,name:f,email:c.email,image:g,emailVerified:!1,...d},data:c}},options:a}},paybin:a=>{let b=a.issuer||"https://idp.paybin.io",c=`${b}/oauth2/authorize`,d=`${b}/oauth2/token`;return{id:"paybin",name:"Paybin",async createAuthorizationURL({state:b,scopes:d,codeVerifier:e,redirectURI:f,loginHint:g}){if(!a.clientId||!a.clientSecret)throw ek.vF.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!e)throw new em.$l("codeVerifier is required for Paybin");let h=a.disableDefaultScope?[]:["openid","email","profile"];return a.scope&&h.push(...a.scope),d&&h.push(...d),await oy({id:"paybin",options:a,authorizationEndpoint:c,scopes:h,state:b,codeVerifier:e,redirectURI:f,prompt:a.prompt,loginHint:g})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:e})=>oZ({code:b,codeVerifier:c,redirectURI:e,options:a,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:d}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=o$(b.idToken),d=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.preferred_username||"",email:c.email,image:c.picture,emailVerified:c.email_verified||!1,...d},data:c}},options:a}},paypal:a=>{let b="sandbox"===(a.environment||"sandbox"),c=b?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",d=b?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",e=b?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",f=b?"https://www.sandbox.paypal.com":"https://www.paypal.com",g=b?"https://api.sandbox.paypal.com/v1/oauth2/certs":"https://api.paypal.com/v1/oauth2/certs";return{id:"paypal",name:"PayPal",async createAuthorizationURL({state:b,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw ek.vF.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new em.$l("CLIENT_ID_AND_SECRET_REQUIRED");return await oy({id:"paypal",options:a,authorizationEndpoint:c,scopes:[],state:b,codeVerifier:d,redirectURI:e,prompt:a.prompt})},validateAuthorizationCode:async({code:b,redirectURI:c})=>{let e=mb.encode(`${a.clientId}:${a.clientSecret}`);try{let a=await oV(d,{method:"POST",headers:{Authorization:`Basic ${e}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:b,redirect_uri:c}).toString()});if(!a.data)throw new em.$l("FAILED_TO_GET_ACCESS_TOKEN");let f=a.data;return{accessToken:f.access_token,refreshToken:f.refresh_token,accessTokenExpiresAt:f.expires_in?new Date(Date.now()+1e3*f.expires_in):void 0,idToken:f.id_token}}catch(a){throw ek.vF.error("PayPal token exchange failed:",a),new em.$l("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>{let c=mb.encode(`${a.clientId}:${a.clientSecret}`);try{let a=await oV(d,{method:"POST",headers:{Authorization:`Basic ${c}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:b}).toString()});if(!a.data)throw new em.$l("FAILED_TO_REFRESH_ACCESS_TOKEN");let e=a.data;return{accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?new Date(Date.now()+1e3*e.expires_in):void 0}}catch(a){throw ek.vF.error("PayPal token refresh failed:",a),new em.$l("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=g2(b);if(!e||!pg.includes(e))return!1;let h="HS256"===e?new TextEncoder().encode(a.clientSecret):d?await ph(d,g):void 0;if(!h)return!1;let{payload:i}=await gj(b,h,{algorithms:[e],issuer:f,audience:a.clientId,maxTokenAge:"1h"});if(c&&i.nonce!==c)return!1;return!0}catch(a){return ek.vF.error("Failed to verify PayPal ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.accessToken)return ek.vF.error("Access token is required to fetch PayPal user info"),null;try{let c=await oV(`${e}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${b.accessToken}`,Accept:"application/json"}});if(!c.data)return ek.vF.error("Failed to fetch user info from PayPal"),null;let d=c.data,f=await a.mapProfileToUser?.(d);return{user:{id:d.user_id,name:d.name,email:d.email,image:d.picture,emailVerified:d.email_verified,...f},data:d}}catch(a){return ek.vF.error("Failed to fetch user info from PayPal:",a),null}},options:a}},polar:a=>{let b="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["openid","profile","email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"polar",options:a,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e,prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>oZ({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>oW({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.public_name||c.username||"",email:c.email,image:c.avatar_url,emailVerified:c.email_verified??!1,...e},data:c}},options:a}},railway:a=>({id:"railway",name:"Railway",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["openid","email","profile"];return a.scope&&f.push(...a.scope),c&&f.push(...c),oy({id:"railway",options:a,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:d})=>oZ({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:pi,authentication:"basic"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>oW({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:pi,authentication:"basic"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d||!c)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:!1,...e},data:c}},options:a}),vercel:a=>({id:"vercel",name:"Vercel",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f;if(!d)throw new em.$l("codeVerifier is required for Vercel");return(void 0!==a.scope||void 0!==c)&&(f=[],a.scope&&f.push(...a.scope),c&&f.push(...c)),oy({id:"vercel",options:a,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:d})=>oZ({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await oV("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(d||!c)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name??c.preferred_username??"",email:c.email,image:c.picture,emailVerified:c.email_verified??!1,...e},data:c}},options:a}),wechat:a=>({id:"wechat",name:"WeChat",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["snsapi_login"];a.scope&&e.push(...a.scope),c&&e.push(...c);let f=new URL("https://open.weixin.qq.com/connect/qrconnect");return f.searchParams.set("scope",e.join(",")),f.searchParams.set("response_type","code"),f.searchParams.set("appid",a.clientId),f.searchParams.set("redirect_uri",a.redirectURI||d),f.searchParams.set("state",b),f.searchParams.set("lang",a.lang||"cn"),f.hash="wechat_redirect",f},validateAuthorizationCode:async({code:b})=>{let{data:c,error:d}=await oV("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:a.clientId,secret:a.clientSecret,code:b,grant_type:"authorization_code"}).toString(),{method:"GET"});if(d||!c||c.errcode)throw Error(`Failed to validate authorization code: ${c?.errmsg||d?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:c.access_token,refreshToken:c.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*c.expires_in),scopes:c.scope.split(","),openid:c.openid,unionid:c.unionid}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>{let{data:c,error:d}=await oV("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:a.clientId,grant_type:"refresh_token",refresh_token:b}).toString(),{method:"GET"});if(d||!c||c.errcode)throw Error(`Failed to refresh access token: ${c?.errmsg||d?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:c.access_token,refreshToken:c.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*c.expires_in),scopes:c.scope.split(",")}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let c=b.openid;if(!c)return null;let{data:d,error:e}=await oV("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:b.accessToken||"",openid:c,lang:"zh_CN"}).toString(),{method:"GET"});if(e||!d||d.errcode)return null;let f=await a.mapProfileToUser?.(d);return{user:{id:d.unionid||d.openid||c,name:d.nickname,email:d.email||`${d.unionid||d.openid||c}@wechat.invalid`,image:d.headimgurl,emailVerified:!1,...f},data:d}},options:a})},pk=lC(Object.keys(pj)).or(kZ()),pl=m3("/list-accounts",{method:"GET",use:[nv],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 a=>{let b=a.context.session,c=await a.context.internalAdapter.findAccounts(b.user.id);return a.json(c.map(b=>{let{scope:c,...d}=function(a,b){let{accessToken:c,refreshToken:d,idToken:e,accessTokenExpiresAt:f,refreshTokenExpiresAt:g,password:h,...i}=hh(b,hj(a,"account","output"));return i}(a.context.options,b);return{...d,scopes:c?.split(",")||[]}}))}),pm=m3("/link-social",{method:"POST",requireHeaders:!0,body:lw({callbackURL:kZ().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:pk,idToken:lw({token:kZ(),nonce:kZ().optional(),accessToken:kZ().optional(),refreshToken:kZ().optional(),scopes:lu(kZ()).optional()}).optional(),requestSignUp:ln().optional(),scopes:lu(kZ()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:kZ().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:ln().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),additionalData:lA(kZ(),lp()).optional()}),use:[nv],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 a=>{let b=a.context.session,c=await mV(a.context.socialProviders,{value:a.body.provider});if(!c)throw a.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:a.body.provider}),em.LG.from("NOT_FOUND",hg.PROVIDER_NOT_FOUND);if(a.body.idToken){if(!c.verifyIdToken)throw a.context.logger.error("Provider does not support id token verification",{provider:a.body.provider}),em.LG.from("NOT_FOUND",hg.ID_TOKEN_NOT_SUPPORTED);let{token:d,nonce:e}=a.body.idToken;if(!await c.verifyIdToken(d,e))throw a.context.logger.warn("Invalid id token",{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.INVALID_TOKEN);let f=await c.getUserInfo({idToken:d,accessToken:a.body.idToken.accessToken,refreshToken:a.body.idToken.refreshToken});if(!f||!f?.user)throw a.context.logger.error("Failed to get user info",{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.FAILED_TO_GET_USER_INFO);let g=String(f.user.id);if(!f.user.email)throw a.context.logger.error(nC(a.body.provider,{source:"id_token"}),{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.USER_EMAIL_NOT_FOUND);if((await a.context.internalAdapter.findAccounts(b.user.id)).find(a=>a.providerId===c.id&&a.accountId===g))return a.json({url:"",status:!0,redirect:!1});if(!a.context.trustedProviders.includes(c.id)&&!f.user.emailVerified||a.context.options.account?.accountLinking?.enabled===!1)throw em.LG.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(f.user.email?.toLowerCase()!==b.user.email.toLowerCase()&&a.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw em.LG.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await a.context.internalAdapter.createAccount({userId:b.user.id,providerId:c.id,accountId:g,accessToken:a.body.idToken.accessToken,idToken:d,refreshToken:a.body.idToken.refreshToken,scope:a.body.idToken.scopes?.join(",")})}catch(a){throw em.LG.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await ok(a,b.user.id,f.user),a.json({url:"",status:!0,redirect:!1})}let d=await ot(a,{userId:b.user.id,email:b.user.email},a.body.additionalData),e=await c.createAuthorizationURL({state:d.state,codeVerifier:d.codeVerifier,redirectURI:`${a.context.baseURL}/callback/${c.id}`,scopes:a.body.scopes});return a.body.disableRedirect||a.setHeader("Location",e.toString()),a.json({url:e.toString(),redirect:!a.body.disableRedirect})}),pn=m3("/unlink-account",{method:"POST",body:lw({providerId:kZ(),accountId:kZ().optional()}),use:[nx],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{let{providerId:b,accountId:c}=a.body,d=await a.context.internalAdapter.findAccounts(a.context.session.user.id);if(1===d.length&&!a.context.options.account?.accountLinking?.allowUnlinkingAll)throw em.LG.from("BAD_REQUEST",hg.FAILED_TO_UNLINK_LAST_ACCOUNT);let e=d.find(a=>c?a.accountId===c&&a.providerId===b:a.providerId===b);if(!e)throw em.LG.from("BAD_REQUEST",hg.ACCOUNT_NOT_FOUND);return await a.context.internalAdapter.deleteAccount(e.id),a.json({status:!0})});async function po(a,b){let c=await nu(a,{disableCookieCache:eI(a.context.options)});if(!c&&(a.request||a.headers))throw a.error("UNAUTHORIZED");let d=c?.user?.id||b;if(!d)throw em.LG.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return d}function pp(a,b,{resolvedUserId:c,providerId:d,accountId:e}){return(!eJ(a.context.options)||b.userId===c)&&(!d||d===b.providerId)&&(!e||b.accountId===e)}async function pq(a,{resolvedUserId:b,providerId:c,accountId:d,account:e}){let f=await mV(a.context.socialProviders,{value:c});if(!f)throw em.LG.from("BAD_REQUEST",{message:`Provider ${c} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});let g=e;if(!g){let e=await l6(a);g=e&&pp(a,e,{resolvedUserId:b,providerId:c,accountId:d})?e:(await a.context.internalAdapter.findAccounts(b)).find(a=>d?a.accountId===d&&a.providerId===c:a.providerId===c)}if(!g)throw em.LG.from("BAD_REQUEST",hg.ACCOUNT_NOT_FOUND);try{let b=null,c=g.accessTokenExpiresAt&&new Date(g.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(g.refreshToken&&c&&f.refreshAccessToken){let c=await od(g.refreshToken,a.context);b=await f.refreshAccessToken(c);let d={accessToken:await oe(b?.accessToken,a.context),accessTokenExpiresAt:b?.accessTokenExpiresAt,refreshToken:b?.refreshToken?await oe(b.refreshToken,a.context):g.refreshToken,refreshTokenExpiresAt:b?.refreshTokenExpiresAt??g.refreshTokenExpiresAt,idToken:b?.idToken||g.idToken},e=null;g.id&&(e=await a.context.internalAdapter.updateAccount(g.id,d)),a.context.options.account?.storeAccountCookie&&await l5(a,{...g,...e??d})}let d=b?.accessTokenExpiresAt?"string"==typeof b.accessTokenExpiresAt?new Date(b.accessTokenExpiresAt):b.accessTokenExpiresAt:g.accessTokenExpiresAt?"string"==typeof g.accessTokenExpiresAt?new Date(g.accessTokenExpiresAt):g.accessTokenExpiresAt:void 0;return{accessToken:b?.accessToken??await od(g.accessToken??"",a.context),accessTokenExpiresAt:d,scopes:g.scope?.split(",")??[],idToken:b?.idToken??g.idToken??void 0}}catch(a){throw em.LG.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let pr=m3("/get-access-token",{method:"POST",body:lw({providerId:kZ().meta({description:"The provider ID for the OAuth provider"}),accountId:kZ().meta({description:"The account ID associated with the refresh token"}).optional(),userId:kZ().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 a=>{let{providerId:b,accountId:c,userId:d}=a.body||{},e=await pq(a,{resolvedUserId:await po(a,d),providerId:b,accountId:c});return a.json(e)}),ps=m3("/refresh-token",{method:"POST",body:lw({providerId:kZ().meta({description:"The provider ID for the OAuth provider"}),accountId:kZ().meta({description:"The account ID associated with the refresh token"}).optional(),userId:kZ().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 a=>{let b,{providerId:c,accountId:d,userId:e}=a.body,f=await po(a,e),g=await mV(a.context.socialProviders,{value:c});if(!g)throw em.LG.from("BAD_REQUEST",{message:`Provider ${c} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!g.refreshAccessToken)throw em.LG.from("BAD_REQUEST",{message:`Provider ${c} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let h=await l6(a),i=!!h&&pp(a,h,{resolvedUserId:f,providerId:c,accountId:d});if(!(b=i?h:(await a.context.internalAdapter.findAccounts(f)).find(a=>d?a.accountId===d&&a.providerId===c:a.providerId===c)))throw em.LG.from("BAD_REQUEST",hg.ACCOUNT_NOT_FOUND);let j=b.refreshToken??void 0;if(!j)throw em.LG.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let c=await od(j,a.context),d=await g.refreshAccessToken(c),e=d.refreshToken?await oe(d.refreshToken,a.context):j,f=d.refreshTokenExpiresAt??b.refreshTokenExpiresAt;if(b.id){let c={...b||{},accessToken:await oe(d.accessToken,a.context),refreshToken:e,accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:f,scope:d.scopes?.join(",")||b.scope,idToken:d.idToken||b.idToken};await a.context.internalAdapter.updateAccount(b.id,c)}return i&&a.context.options.account?.storeAccountCookie&&await l5(a,{...h,accessToken:await oe(d.accessToken,a.context),refreshToken:e,accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:f,scope:d.scopes?.join(",")||h.scope,idToken:d.idToken||h.idToken}),a.json({accessToken:d.accessToken,refreshToken:d.refreshToken??c,accessTokenExpiresAt:d.accessTokenExpiresAt,refreshTokenExpiresAt:f,scope:d.scopes?.join(",")||b.scope,idToken:d.idToken||b.idToken,providerId:b.providerId,accountId:b.accountId})}catch(a){throw em.LG.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),pt=m3("/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:lF(lw({accountId:kZ().meta({description:"The provider given account id for which to get the account info"}).optional(),providerId:kZ().meta({description:"The provider ID to disambiguate provider-issued account IDs"}).optional(),userId:kZ().meta({description:"The user ID associated with the account"}).optional()}))},async a=>{let b,{accountId:c,providerId:d,userId:e}=a.query||{},f=await po(a,e);if(c){let e=(await a.context.internalAdapter.findAccounts(f)).filter(a=>a.accountId===c&&(!d||a.providerId===d));if(e.length>1)throw em.LG.from("BAD_REQUEST",{message:"Multiple accounts share this account ID. Pass a providerId to disambiguate.",code:"AMBIGUOUS_ACCOUNT"});b=e[0]}else if(a.context.options.account?.storeAccountCookie){let c=await l6(a);c&&pp(a,c,{resolvedUserId:f,providerId:d})&&(b=c)}if(!b||!pp(a,b,{resolvedUserId:f}))throw em.LG.from("BAD_REQUEST",hg.ACCOUNT_NOT_FOUND);let g=await mV(a.context.socialProviders,{value:b.providerId});if(!g)throw em.LG.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let h=await pq(a,{resolvedUserId:f,providerId:b.providerId,accountId:b.accountId,account:b});if(!h.accessToken)throw em.LG.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let i=await g.getUserInfo({...h,accessToken:h.accessToken});return a.json(i)}),pu={scope:"server"},pv=lw({code:kZ().optional(),error:kZ().optional(),device_id:kZ().optional(),error_description:kZ().optional(),state:kZ().optional(),user:kZ().optional()}),pw=m3("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:pv.optional(),query:pv.optional(),metadata:{...pu,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async a=>{let b,c,d,e,f=a.context.options.onAPIError?.errorURL||`${a.context.baseURL}/error`;if("POST"===a.method){let b=a.body?pv.parse(a.body):{},c=a.query?pv.parse(a.query):{},d=pv.parse({...b,...c}),e=new URLSearchParams;for(let[a,b]of Object.entries(d))null!=b&&e.set(a,String(b));let f=`${a.context.baseURL}/callback/${a.params.id}?${e.toString()}`;throw a.redirect(f)}try{if("GET"===a.method)b=pv.parse(a.query);else if("POST"===a.method)b=pv.parse(a.body);else throw Error("Unsupported method")}catch(b){a.context.logger.error("INVALID_CALLBACK_REQUEST",b),nB(a,f,"invalid_callback_request")}let{code:g,error:h,error_description:i,device_id:j,user:k}=b,{codeVerifier:l,callbackURL:m,link:n,errorURL:o,newUserURL:p,requestSignUp:q}=await ou(a),r=o??f;h&&nB(a,r,h,i),g||(a.context.logger.warn("Code not found"),nB(a,r,"no_code"));let s=await mV(a.context.socialProviders,{value:a.params.id});s||(a.context.logger.warn("OAuth provider not found",{providerId:a.params.id}),nB(a,r,"oauth_provider_not_found"));try{c=await s.validateAuthorizationCode({code:g,codeVerifier:l,deviceId:j,redirectURI:`${a.context.baseURL}/callback/${s.id}`})}catch(b){a.context.logger.error("",b),nB(a,r,"invalid_code")}c||nB(a,r,"invalid_code");let t=k?(0,hy.$)(k):null,u=await s.getUserInfo({...c,user:t??void 0}).then(a=>a?.user);u&&void 0!==u.id&&null!==u.id&&""!==u.id||(a.context.logger.error("Unable to get user info"),nB(a,r,"unable_to_get_user_info"));let v=String(u.id);if(m||(a.context.logger.error("No callback URL found"),nB(a,r,"no_callback_url")),n){let b;(a.context.trustedProviders.includes(s.id)||u.emailVerified)&&a.context.options.account?.accountLinking?.enabled!==!1||(a.context.logger.error("Unable to link account - untrusted provider"),nB(a,r,"unable_to_link_account")),u.email?.toLowerCase()!==n.email.toLowerCase()&&a.context.options.account?.accountLinking?.allowDifferentEmails!==!0&&nB(a,r,"email_doesn't_match");let d=await a.context.internalAdapter.findAccountByProviderId(v,s.id);if(d){d.userId.toString()!==n.userId.toString()&&nB(a,r,"account_already_linked_to_different_user");let b=Object.fromEntries(Object.entries({accessToken:await oe(c.accessToken,a.context),refreshToken:await oe(c.refreshToken,a.context),idToken:c.idToken,accessTokenExpiresAt:c.accessTokenExpiresAt,refreshTokenExpiresAt:c.refreshTokenExpiresAt,scope:c.scopes?.join(",")}).filter(([a,b])=>void 0!==b));await a.context.internalAdapter.updateAccount(d.id,b)}else await a.context.internalAdapter.createAccount({userId:n.userId,providerId:s.id,accountId:v,...c,accessToken:await oe(c.accessToken,a.context),refreshToken:await oe(c.refreshToken,a.context),scope:c.scopes?.join(",")})||nB(a,r,"unable_to_link_account");await ok(a,n.userId,u);try{b=m.toString()}catch{b=m}throw a.redirect(b)}u.email||(a.context.logger.error(nC(s.id)),nB(a,r,"email_not_found"));let w={providerId:s.id,accountId:v,...c,scope:c.scopes?.join(",")};try{d=await oj(a,{userInfo:{...u,id:v,email:u.email,name:u.name||""},account:w,callbackURL:m,disableSignUp:s.disableImplicitSignUp&&!q||s.options?.disableSignUp,overrideUserInfo:s.options?.overrideUserInfoOnSignIn})}catch(b){throw m$(b)&&b.body?.code&&nB(a,r,b.body.code,b.body.message),b}d.error&&(a.context.logger.error(d.error.split(" ").join("_")),nB(a,r,d.error.split(" ").join("_")));let{session:x,user:y}=d.data;await mj(a,{session:x,user:y});try{e=(d.isRegister&&p||m).toString()}catch{e=d.isRegister&&p||m}throw a.redirect(e)});function px(a){return a.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&")}let py=m3("/error",{method:"GET",metadata:{...pu,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 a=>{let b=new URL(a.request?.url||""),c=b.searchParams.get("error")||"UNKNOWN",d=b.searchParams.get("error_description")||null,e=/^[\'A-Za-z0-9_-]+$/.test(c||"")?c:"UNKNOWN",f=d?px(d):null,g=new URLSearchParams;g.set("error",e),d&&g.set("error_description",d);let h=a.context.options,i=h.onAPIError?.errorURL;return i?new Response(null,{status:302,headers:{Location:`${i}${i.includes("?")?"&":"?"}${g.toString()}`}}):ey.KV&&!h.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${g.toString()}`}}):new Response(((a,b="Unknown",c=null)=>{let d=a.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
114
|
+
<html lang="en">
|
|
115
|
+
<head>
|
|
116
|
+
<meta charset="UTF-8" />
|
|
117
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
118
|
+
<title>Error</title>
|
|
119
|
+
<style>
|
|
120
|
+
* {
|
|
121
|
+
box-sizing: border-box;
|
|
122
|
+
}
|
|
123
|
+
body {
|
|
124
|
+
font-family: ${d?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
|
|
125
|
+
background: ${d?.colors?.background||"var(--background)"};
|
|
126
|
+
color: var(--foreground);
|
|
127
|
+
margin: 0;
|
|
128
|
+
}
|
|
129
|
+
:root,
|
|
130
|
+
:host {
|
|
131
|
+
--spacing: 0.25rem;
|
|
132
|
+
--container-md: 28rem;
|
|
133
|
+
--text-sm: ${d?.size?.textSm||"0.875rem"};
|
|
134
|
+
--text-sm--line-height: calc(1.25 / 0.875);
|
|
135
|
+
--text-2xl: ${d?.size?.text2xl||"1.5rem"};
|
|
136
|
+
--text-2xl--line-height: calc(2 / 1.5);
|
|
137
|
+
--text-4xl: ${d?.size?.text4xl||"2.25rem"};
|
|
138
|
+
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
139
|
+
--text-6xl: ${d?.size?.text6xl||"3rem"};
|
|
140
|
+
--text-6xl--line-height: 1;
|
|
141
|
+
--font-weight-medium: 500;
|
|
142
|
+
--font-weight-semibold: 600;
|
|
143
|
+
--font-weight-bold: 700;
|
|
144
|
+
--default-transition-duration: 150ms;
|
|
145
|
+
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
146
|
+
--radius: ${d?.size?.radiusSm||"0.625rem"};
|
|
147
|
+
--default-mono-font-family: ${d?.font?.monoFamily||"var(--font-geist-mono)"};
|
|
148
|
+
--primary: ${d?.colors?.primary||"black"};
|
|
149
|
+
--primary-foreground: ${d?.colors?.primaryForeground||"white"};
|
|
150
|
+
--background: ${d?.colors?.background||"white"};
|
|
151
|
+
--foreground: ${d?.colors?.foreground||"oklch(0.271 0 0)"};
|
|
152
|
+
--border: ${d?.colors?.border||"oklch(0.89 0 0)"};
|
|
153
|
+
--destructive: ${d?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
|
|
154
|
+
--muted-foreground: ${d?.colors?.mutedForeground||"oklch(0.545 0 0)"};
|
|
155
|
+
--corner-border: ${d?.colors?.cornerBorder||"#404040"};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
button, .btn {
|
|
159
|
+
cursor: pointer;
|
|
160
|
+
background: none;
|
|
161
|
+
border: none;
|
|
162
|
+
color: inherit;
|
|
163
|
+
font: inherit;
|
|
164
|
+
transition: all var(--default-transition-duration)
|
|
165
|
+
var(--default-transition-timing-function);
|
|
166
|
+
}
|
|
167
|
+
button:hover, .btn:hover {
|
|
168
|
+
opacity: 0.8;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
@media (prefers-color-scheme: dark) {
|
|
172
|
+
:root,
|
|
173
|
+
:host {
|
|
174
|
+
--primary: ${d?.colors?.primary||"white"};
|
|
175
|
+
--primary-foreground: ${d?.colors?.primaryForeground||"black"};
|
|
176
|
+
--background: ${d?.colors?.background||"oklch(0.15 0 0)"};
|
|
177
|
+
--foreground: ${d?.colors?.foreground||"oklch(0.98 0 0)"};
|
|
178
|
+
--border: ${d?.colors?.border||"oklch(0.27 0 0)"};
|
|
179
|
+
--destructive: ${d?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
|
|
180
|
+
--muted-foreground: ${d?.colors?.mutedForeground||"oklch(0.65 0 0)"};
|
|
181
|
+
--corner-border: ${d?.colors?.cornerBorder||"#a0a0a0"};
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
@media (max-width: 640px) {
|
|
185
|
+
:root, :host {
|
|
186
|
+
--text-6xl: 2.5rem;
|
|
187
|
+
--text-2xl: 1.25rem;
|
|
188
|
+
--text-sm: 0.8125rem;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
@media (max-width: 480px) {
|
|
192
|
+
:root, :host {
|
|
193
|
+
--text-6xl: 2rem;
|
|
194
|
+
--text-2xl: 1.125rem;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
</style>
|
|
198
|
+
</head>
|
|
199
|
+
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
200
|
+
<div
|
|
201
|
+
style="
|
|
202
|
+
display: flex;
|
|
203
|
+
flex-direction: column;
|
|
204
|
+
align-items: center;
|
|
205
|
+
justify-content: center;
|
|
206
|
+
gap: 1.5rem;
|
|
207
|
+
position: relative;
|
|
208
|
+
width: 100%;
|
|
209
|
+
min-height: 100vh;
|
|
210
|
+
padding: 1rem;
|
|
211
|
+
"
|
|
212
|
+
>
|
|
213
|
+
${d?.disableBackgroundGrid?"":`
|
|
214
|
+
<div
|
|
215
|
+
style="
|
|
216
|
+
position: absolute;
|
|
217
|
+
inset: 0;
|
|
218
|
+
background-image: linear-gradient(to right, ${d?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
|
|
219
|
+
linear-gradient(to bottom, ${d?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
|
|
220
|
+
background-size: 40px 40px;
|
|
221
|
+
opacity: 0.6;
|
|
222
|
+
pointer-events: none;
|
|
223
|
+
width: 100vw;
|
|
224
|
+
height: 100vh;
|
|
225
|
+
"
|
|
226
|
+
></div>
|
|
227
|
+
<div
|
|
228
|
+
style="
|
|
229
|
+
position: absolute;
|
|
230
|
+
inset: 0;
|
|
231
|
+
display: flex;
|
|
232
|
+
align-items: center;
|
|
233
|
+
justify-content: center;
|
|
234
|
+
background: ${d?.colors?.background||"var(--background)"};
|
|
235
|
+
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
236
|
+
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
237
|
+
pointer-events: none;
|
|
238
|
+
"
|
|
239
|
+
></div>
|
|
240
|
+
`}
|
|
241
|
+
|
|
242
|
+
<div
|
|
243
|
+
style="
|
|
244
|
+
position: relative;
|
|
245
|
+
z-index: 10;
|
|
246
|
+
border: 2px solid var(--border);
|
|
247
|
+
background: ${d?.colors?.cardBackground||"var(--background)"};
|
|
248
|
+
padding: 1.5rem;
|
|
249
|
+
max-width: 42rem;
|
|
250
|
+
width: 100%;
|
|
251
|
+
"
|
|
252
|
+
>
|
|
253
|
+
${d?.disableCornerDecorations?"":`
|
|
254
|
+
<!-- Corner decorations -->
|
|
255
|
+
<div
|
|
256
|
+
style="
|
|
257
|
+
position: absolute;
|
|
258
|
+
top: -2px;
|
|
259
|
+
left: -2px;
|
|
260
|
+
width: 2rem;
|
|
261
|
+
height: 2rem;
|
|
262
|
+
border-top: 4px solid var(--corner-border);
|
|
263
|
+
border-left: 4px solid var(--corner-border);
|
|
264
|
+
"
|
|
265
|
+
></div>
|
|
266
|
+
<div
|
|
267
|
+
style="
|
|
268
|
+
position: absolute;
|
|
269
|
+
top: -2px;
|
|
270
|
+
right: -2px;
|
|
271
|
+
width: 2rem;
|
|
272
|
+
height: 2rem;
|
|
273
|
+
border-top: 4px solid var(--corner-border);
|
|
274
|
+
border-right: 4px solid var(--corner-border);
|
|
275
|
+
"
|
|
276
|
+
></div>
|
|
277
|
+
|
|
278
|
+
<div
|
|
279
|
+
style="
|
|
280
|
+
position: absolute;
|
|
281
|
+
bottom: -2px;
|
|
282
|
+
left: -2px;
|
|
283
|
+
width: 2rem;
|
|
284
|
+
height: 2rem;
|
|
285
|
+
border-bottom: 4px solid var(--corner-border);
|
|
286
|
+
border-left: 4px solid var(--corner-border);
|
|
287
|
+
"
|
|
288
|
+
></div>
|
|
289
|
+
<div
|
|
290
|
+
style="
|
|
291
|
+
position: absolute;
|
|
292
|
+
bottom: -2px;
|
|
293
|
+
right: -2px;
|
|
294
|
+
width: 2rem;
|
|
295
|
+
height: 2rem;
|
|
296
|
+
border-bottom: 4px solid var(--corner-border);
|
|
297
|
+
border-right: 4px solid var(--corner-border);
|
|
298
|
+
"
|
|
299
|
+
></div>`}
|
|
300
|
+
|
|
301
|
+
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
302
|
+
<div style="margin-bottom: 1.5rem;">
|
|
303
|
+
<div
|
|
304
|
+
style="
|
|
305
|
+
display: inline-block;
|
|
306
|
+
border: 2px solid ${d?.disableTitleBorder?"transparent":d?.colors?.titleBorder||"var(--destructive)"};
|
|
307
|
+
padding: 0.375rem 1rem;
|
|
308
|
+
"
|
|
309
|
+
>
|
|
310
|
+
<h1
|
|
311
|
+
style="
|
|
312
|
+
font-size: var(--text-6xl);
|
|
313
|
+
font-weight: var(--font-weight-semibold);
|
|
314
|
+
color: ${d?.colors?.titleColor||"var(--foreground)"};
|
|
315
|
+
letter-spacing: -0.02em;
|
|
316
|
+
margin: 0;
|
|
317
|
+
"
|
|
318
|
+
>
|
|
319
|
+
ERROR
|
|
320
|
+
</h1>
|
|
321
|
+
</div>
|
|
322
|
+
<div
|
|
323
|
+
style="
|
|
324
|
+
height: 2px;
|
|
325
|
+
background-color: var(--border);
|
|
326
|
+
width: calc(100% + 3rem);
|
|
327
|
+
margin-left: -1.5rem;
|
|
328
|
+
margin-top: 1.5rem;
|
|
329
|
+
"
|
|
330
|
+
></div>
|
|
331
|
+
</div>
|
|
332
|
+
|
|
333
|
+
<h2
|
|
334
|
+
style="
|
|
335
|
+
font-size: var(--text-2xl);
|
|
336
|
+
font-weight: var(--font-weight-semibold);
|
|
337
|
+
color: var(--foreground);
|
|
338
|
+
margin: 0 0 1rem;
|
|
339
|
+
"
|
|
340
|
+
>
|
|
341
|
+
Something went wrong
|
|
342
|
+
</h2>
|
|
343
|
+
|
|
344
|
+
<div
|
|
345
|
+
style="
|
|
346
|
+
display: inline-flex;
|
|
347
|
+
align-items: center;
|
|
348
|
+
gap: 0.5rem;
|
|
349
|
+
border: 2px solid var(--border);
|
|
350
|
+
background-color: var(--muted);
|
|
351
|
+
padding: 0.375rem 0.75rem;
|
|
352
|
+
margin: 0 0 1rem;
|
|
353
|
+
flex-wrap: wrap;
|
|
354
|
+
justify-content: center;
|
|
355
|
+
"
|
|
356
|
+
>
|
|
357
|
+
<span
|
|
358
|
+
style="
|
|
359
|
+
font-size: 0.75rem;
|
|
360
|
+
color: var(--muted-foreground);
|
|
361
|
+
font-weight: var(--font-weight-semibold);
|
|
362
|
+
"
|
|
363
|
+
>
|
|
364
|
+
CODE:
|
|
365
|
+
</span>
|
|
366
|
+
<span
|
|
367
|
+
style="
|
|
368
|
+
font-size: var(--text-sm);
|
|
369
|
+
font-family: var(--default-mono-font-family, monospace);
|
|
370
|
+
color: var(--foreground);
|
|
371
|
+
word-break: break-all;
|
|
372
|
+
"
|
|
373
|
+
>
|
|
374
|
+
${px(b)}
|
|
375
|
+
</span>
|
|
376
|
+
</div>
|
|
377
|
+
|
|
378
|
+
<p
|
|
379
|
+
style="
|
|
380
|
+
color: var(--muted-foreground);
|
|
381
|
+
max-width: 28rem;
|
|
382
|
+
margin: 0 auto;
|
|
383
|
+
font-size: var(--text-sm);
|
|
384
|
+
line-height: 1.5;
|
|
385
|
+
text-wrap: pretty;
|
|
386
|
+
"
|
|
387
|
+
>
|
|
388
|
+
${!c?`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(b)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:c}
|
|
389
|
+
</p>
|
|
390
|
+
</div>
|
|
391
|
+
|
|
392
|
+
<div
|
|
393
|
+
style="
|
|
394
|
+
display: flex;
|
|
395
|
+
gap: 0.75rem;
|
|
396
|
+
margin-top: 1.5rem;
|
|
397
|
+
justify-content: center;
|
|
398
|
+
flex-wrap: wrap;
|
|
399
|
+
"
|
|
400
|
+
>
|
|
401
|
+
<a
|
|
402
|
+
href="/"
|
|
403
|
+
style="
|
|
404
|
+
text-decoration: none;
|
|
405
|
+
"
|
|
406
|
+
>
|
|
407
|
+
<div
|
|
408
|
+
style="
|
|
409
|
+
border: 2px solid var(--border);
|
|
410
|
+
background: var(--primary);
|
|
411
|
+
color: var(--primary-foreground);
|
|
412
|
+
padding: 0.5rem 1rem;
|
|
413
|
+
border-radius: 0;
|
|
414
|
+
white-space: nowrap;
|
|
415
|
+
"
|
|
416
|
+
class="btn"
|
|
417
|
+
>
|
|
418
|
+
Go Home
|
|
419
|
+
</div>
|
|
420
|
+
</a>
|
|
421
|
+
<a
|
|
422
|
+
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(b)}?askai=${encodeURIComponent(`What does the error code ${b} mean?`)}"
|
|
423
|
+
target="_blank"
|
|
424
|
+
rel="noopener noreferrer"
|
|
425
|
+
style="
|
|
426
|
+
text-decoration: none;
|
|
427
|
+
"
|
|
428
|
+
>
|
|
429
|
+
<div
|
|
430
|
+
style="
|
|
431
|
+
border: 2px solid var(--border);
|
|
432
|
+
background: transparent;
|
|
433
|
+
color: var(--foreground);
|
|
434
|
+
padding: 0.5rem 1rem;
|
|
435
|
+
border-radius: 0;
|
|
436
|
+
white-space: nowrap;
|
|
437
|
+
"
|
|
438
|
+
class="btn"
|
|
439
|
+
>
|
|
440
|
+
Ask AI
|
|
441
|
+
</div>
|
|
442
|
+
</a>
|
|
443
|
+
</div>
|
|
444
|
+
</div>
|
|
445
|
+
</div>
|
|
446
|
+
</body>
|
|
447
|
+
</html>`})(a.context.options,e,f),{headers:{"Content-Type":"text/html"}})}),pz=m3("/ok",{method:"GET",metadata:{...pu,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 a=>a.json({ok:!0}));function pA(a,b,c){let d=b?new URL(b,a.baseURL):new URL(`${a.baseURL}/error`);return c&&Object.entries(c).forEach(([a,b])=>d.searchParams.set(a,b)),d.href}let pB=m3("/request-password-reset",{method:"POST",body:lw({email:kj(k_,void 0).meta({description:"The email address of the user to send a password reset email to"}),redirectTo:kZ().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:[m8(a=>a.body.redirectTo)]},async a=>{if(!a.context.options.emailAndPassword?.sendResetPassword)throw a.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),em.LG.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:b,redirectTo:c}=a.body,d=await a.context.internalAdapter.findUserByEmail(b,{includeAccounts:!0});if(!d)return(0,mF.$)(24),await a.context.internalAdapter.findVerificationValue("dummy-verification-token"),a.context.logger.warn("Reset Password: User not found"),a.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let e=hp(a.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),f=(0,mF.$)(24);await a.context.internalAdapter.createVerificationValue({value:d.user.id,identifier:`reset-password:${f}`,expiresAt:e});let g=c?encodeURIComponent(c):"",h=`${a.context.baseURL}/reset-password/${f}?callbackURL=${g}`;return await a.context.runInBackgroundOrAwait(a.context.options.emailAndPassword.sendResetPassword({user:d.user,url:h,token:f},a.request)),a.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),pC=m3("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:lw({callbackURL:kZ().meta({description:"The URL to redirect the user to reset their password"})}),use:[m8(a=>a.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 a=>{var b,c;let d,{token:e}=a.params,{callbackURL:f}=a.query;if(!e||!f)throw a.redirect(pA(a.context,f,{error:"INVALID_TOKEN"}));let g=await a.context.internalAdapter.findVerificationValue(`reset-password:${e}`);if(!g||g.expiresAt<new Date)throw a.redirect(pA(a.context,f,{error:"INVALID_TOKEN"}));throw a.redirect((b=a.context,c={token:e},d=new URL(f,b.baseURL),c&&Object.entries(c).forEach(([a,b])=>d.searchParams.set(a,b)),d.href))}),pD=m3("/reset-password",{method:"POST",operationId:"resetPassword",query:lw({token:kZ().optional()}).optional(),body:lw({newPassword:kZ().meta({description:"The new password to set"}),token:kZ().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 a=>{let b=a.body.token||a.query?.token;if(!b)throw em.LG.from("BAD_REQUEST",hg.INVALID_TOKEN);let{newPassword:c}=a.body,d=a.context.password?.config.minPasswordLength,e=a.context.password?.config.maxPasswordLength;if(c.length<d)throw em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_SHORT);if(c.length>e)throw em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_LONG);let f=`reset-password:${b}`,g=await a.context.internalAdapter.consumeVerificationValue(f);if(!g)throw em.LG.from("BAD_REQUEST",hg.INVALID_TOKEN);let h=g.value,i=await a.context.password.hash(c);if((await a.context.internalAdapter.findAccounts(h)).find(a=>"credential"===a.providerId)?await a.context.internalAdapter.updatePassword(h,i):await a.context.internalAdapter.createAccount({userId:h,providerId:"credential",password:i,accountId:h}),a.context.options.emailAndPassword?.onPasswordReset){let b=await a.context.internalAdapter.findUserById(h);b&&await a.context.options.emailAndPassword.onPasswordReset({user:b},a.request)}return a.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await a.context.internalAdapter.deleteUserSessions(h),a.json({status:!0})}),pE=m3("/verify-password",{method:"POST",body:lw({password:kZ().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:[nw]},async a=>{let{password:b}=a.body,c=a.context.session;if(!await mX(a,{password:b,userId:c.user.id}))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);return a.json({status:!0})}),pF=lw({callbackURL:kZ().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:kZ().optional(),errorCallbackURL:kZ().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:pk,disableRedirect:ln().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:lF(lw({token:kZ().meta({description:"ID token from the provider"}),nonce:kZ().meta({description:"Nonce used to generate the token"}).optional(),accessToken:kZ().meta({description:"Access token from the provider"}).optional(),refreshToken:kZ().meta({description:"Refresh token from the provider"}).optional(),expiresAt:lj().meta({description:"Expiry date of the token"}).optional(),user:lw({name:lw({firstName:kZ().optional(),lastName:kZ().optional()}).optional(),email:kZ().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:lu(kZ()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:ln().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:kZ().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalData:lA(kZ(),lp()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),pG=m3("/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 a=>{let b=await a.getSignedCookie(a.context.authCookies.sessionToken.name,a.context.secret);if(b)try{await a.context.internalAdapter.deleteSession(b)}catch(b){a.context.logger.error("Failed to delete session from database",b)}return ml(a),a.json({success:!0})}),pH=lw({name:kZ(),email:kj(k_,void 0),password:kZ().nonempty(),image:kZ().optional(),callbackURL:kZ().optional(),rememberMe:ln().optional()}).and(lA(kZ(),lp())),pI=lA(kZ().meta({description:"Field name must be a string"}),lp()),pJ=lA(kZ().meta({description:"Field name must be a string"}),lp()),pK=m3("/change-password",{method:"POST",operationId:"changePassword",body:lw({newPassword:kZ().meta({description:"The new password to set"}),currentPassword:kZ().meta({description:"The current password is required"}),revokeOtherSessions:ln().meta({description:"Must be a boolean value"}).optional()}),use:[nw],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 a=>{let{newPassword:b,currentPassword:c,revokeOtherSessions:d}=a.body,e=a.context.session,f=a.context.password.config.minPasswordLength;if(b.length<f)throw a.context.logger.warn("Password is too short"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_SHORT);let g=a.context.password.config.maxPasswordLength;if(b.length>g)throw a.context.logger.warn("Password is too long"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_LONG);let h=(await a.context.internalAdapter.findAccounts(e.user.id)).find(a=>"credential"===a.providerId&&a.password);if(!h||!h.password)throw em.LG.from("BAD_REQUEST",hg.CREDENTIAL_ACCOUNT_NOT_FOUND);let i=await a.context.password.hash(b);if(!await a.context.password.verify({hash:h.password,password:c}))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);await a.context.internalAdapter.updateAccount(h.id,{password:i});let j=null;if(d){await a.context.internalAdapter.deleteUserSessions(e.user.id);let b=await a.context.internalAdapter.createSession(e.user.id);if(!b)throw em.LG.from("INTERNAL_SERVER_ERROR",hg.FAILED_TO_GET_SESSION);await mj(a,{session:b,user:e.user}),j=b.token}return a.json({token:j,user:hk(a.context.options,e.user)})}),pL=m3.serverOnly({method:"POST",body:lw({newPassword:kZ().meta({description:"The new password to set is required"})}),use:[nw]},async a=>{let{newPassword:b}=a.body,c=a.context.session,d=a.context.password.config.minPasswordLength;if(b.length<d)throw a.context.logger.warn("Password is too short"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_SHORT);let e=a.context.password.config.maxPasswordLength;if(b.length>e)throw a.context.logger.warn("Password is too long"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_LONG);let f=(await a.context.internalAdapter.findAccounts(c.user.id)).find(a=>"credential"===a.providerId&&a.password),g=await a.context.password.hash(b);if(!f)return await a.context.internalAdapter.linkAccount({userId:c.user.id,providerId:"credential",accountId:c.user.id,password:g}),a.json({status:!0});throw em.LG.from("BAD_REQUEST",hg.PASSWORD_ALREADY_SET)}),pM=m3("/delete-user",{method:"POST",use:[nw],body:lw({callbackURL:kZ().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:kZ().meta({description:"The password of the user is required to delete the user"}).optional(),token:kZ().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 a=>{if(!a.context.options.user?.deleteUser?.enabled)throw a.context.logger.error("Delete user is disabled. Enable it in the options"),em.LG.fromStatus("NOT_FOUND");let b=a.context.session;if(a.body.password){let c=(await a.context.internalAdapter.findAccounts(b.user.id)).find(a=>"credential"===a.providerId&&a.password);if(!c||!c.password)throw em.LG.from("BAD_REQUEST",hg.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await a.context.password.verify({hash:c.password,password:a.body.password}))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD)}if(a.body.token)return await pN({...a,query:{token:a.body.token}}),a.json({success:!0,message:"User deleted"});if(a.context.options.user.deleteUser?.sendDeleteAccountVerification){let c=om(32,"0-9","a-z");await a.context.internalAdapter.createVerificationValue({value:b.user.id,identifier:`delete-account-${c}`,expiresAt:new Date(Date.now()+1e3*(a.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let d=`${a.context.baseURL}/delete-user/callback?token=${c}&callbackURL=${encodeURIComponent(a.body.callbackURL||"/")}`;return await a.context.runInBackgroundOrAwait(a.context.options.user.deleteUser.sendDeleteAccountVerification({user:b.user,url:d,token:c},a.request)),a.json({success:!0,message:"Verification email sent"})}if(!a.body.password&&0!==a.context.sessionConfig.freshAge){let c=new Date(b.session.createdAt).getTime(),d=1e3*a.context.sessionConfig.freshAge;if(Date.now()-c>=d)throw em.LG.from("BAD_REQUEST",hg.SESSION_EXPIRED)}let c=a.context.options.user.deleteUser?.beforeDelete;c&&await c(b.user,a.request),await a.context.internalAdapter.deleteUser(b.user.id),await a.context.internalAdapter.deleteUserSessions(b.user.id),ml(a);let d=a.context.options.user.deleteUser?.afterDelete;return d&&await d(b.user,a.request),a.json({success:!0,message:"User deleted"})}),pN=m3("/delete-user/callback",{method:"GET",query:lw({token:kZ().meta({description:"The token to verify the deletion request"}),callbackURL:kZ().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[m8(a=>a.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 a=>{if(!a.context.options.user?.deleteUser?.enabled)throw a.context.logger.error("Delete user is disabled. Enable it in the options"),em.LG.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let b=await nu(a,{disableCookieCache:eI(a.context.options)});if(!b)throw em.LG.from("NOT_FOUND",hg.FAILED_TO_GET_USER_INFO);let c=await a.context.internalAdapter.consumeVerificationValue(`delete-account-${a.query.token}`);if(!c||c.value!==b.user.id)throw em.LG.from("NOT_FOUND",hg.INVALID_TOKEN);let d=a.context.options.user.deleteUser?.beforeDelete;d&&await d(b.user,a.request),await a.context.internalAdapter.deleteUser(b.user.id),await a.context.internalAdapter.deleteUserSessions(b.user.id),await a.context.internalAdapter.deleteAccounts(b.user.id),ml(a);let e=a.context.options.user.deleteUser?.afterDelete;if(e&&await e(b.user,a.request),a.query.callbackURL)throw a.redirect(a.query.callbackURL||"/");return a.json({success:!0,message:"User deleted"})}),pO=m3("/change-email",{method:"POST",body:lw({newEmail:kj(k_,void 0).meta({description:"The new email address to set must be a valid email address"}),callbackURL:kZ().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[nw],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 a=>{if(!a.context.options.user?.changeEmail?.enabled)throw a.context.logger.error("Change email is disabled."),em.LG.from("BAD_REQUEST",hg.CHANGE_EMAIL_DISABLED);let b=a.body.newEmail.toLowerCase();if(b===a.context.session.user.email)throw a.context.logger.warn("Email is the same"),em.LG.fromStatus("BAD_REQUEST",{message:"Email is the same"});let c=!0!==a.context.session.user.emailVerified&&a.context.options.user.changeEmail.updateEmailWithoutVerification,d=a.context.options.emailVerification?.sendVerificationEmail,e=d&&a.context.session.user.emailVerified&&a.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!c&&!e&&!d)throw a.context.logger.error("Verification email isn't enabled."),em.LG.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await a.context.internalAdapter.findUserByEmail(b))return await of(a.context.secret,a.context.session.user.email,b,a.context.options.emailVerification?.expiresIn),a.context.logger.info("Change email attempt for existing email"),a.json({status:!0});if(c){if(await a.context.internalAdapter.updateUserByEmail(a.context.session.user.email,{email:b}),await mj(a,{session:a.context.session.session,user:{...a.context.session.user,email:b}}),d){let c=await of(a.context.secret,b,void 0,a.context.options.emailVerification?.expiresIn),e=`${a.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(a.body.callbackURL||"/")}`;await a.context.runInBackgroundOrAwait(d({user:{...a.context.session.user,email:b},url:e,token:c},a.request))}return a.json({status:!0})}if(e){let c=await of(a.context.secret,a.context.session.user.email,b,a.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),d=`${a.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(a.body.callbackURL||"/")}`;return await a.context.runInBackgroundOrAwait(e({user:a.context.session.user,newEmail:b,url:d,token:c},a.request)),a.json({status:!0})}if(!d)throw a.context.logger.error("Verification email isn't enabled."),em.LG.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let f=await of(a.context.secret,a.context.session.user.email,b,a.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),g=`${a.context.baseURL}/verify-email?token=${f}&callbackURL=${encodeURIComponent(a.body.callbackURL||"/")}`;return await a.context.runInBackgroundOrAwait(d({user:{...a.context.session.user,email:b},url:g,token:f},a.request)),a.json({status:!0})}),pP=mJ((a,b,c)=>{if(Array.isArray(a[b])&&Array.isArray(c))return a[b]=c,!0}),pQ=new WeakMap;function pR(a,b){let c=a.options;return c?.operationId??c?.metadata?.openapi?.operationId??b??a.path??"/:virtual"}function pS(a,b){b&&b.forEach((b,c)=>{a.responseHeaders?"set-cookie"===c.toLowerCase()?a.responseHeaders.append(c,b):a.responseHeaders.set(c,b):a.responseHeaders=new Headers({[c]:b})})}function pT(a){let b=a[hz.Ri],c=a.headers&&a.headers!==b?new Headers(a.headers):null;if(!b&&!c)return null;let d=new Headers;return b?.forEach((a,b)=>{d.append(b,a)}),c?.forEach((a,b)=>{"set-cookie"===b.toLowerCase()?d.append(b,a):d.set(b,a)}),d}async function pU(a,b,c,d){let e={};for(let f of b){let b=!1;try{b=f.matcher(a)}catch(c){let b=pQ.get(f.handler)??"unknown";throw a.context.logger.error(`An error occurred during ${b} hook matcher execution:`,c),new em.LG("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!b)continue;let g=pQ.get(f.handler)??"unknown",h=c.path??"/:virtual",i=await (0,mA.f)(`hook before ${h} ${g}`,{[mC]:"before",[mE.DR]:h,[mD]:g,[mB]:d},()=>f.handler({...a,returnHeaders:!0})).catch(b=>{throw m$(b)&&(0,ek.p8)(a.context.logger.level,"debug")&&(b.stack=b.errorStack),b});pS(a.context,i?.headers);let j=i?.response;if(j&&"object"==typeof j){if("context"in j&&"object"==typeof j.context){let{headers:a,...b}=j.context;a instanceof Headers&&(e.headers?a.forEach((a,b)=>{e.headers?.set(b,a)}):e.headers=a),e=pP(b,e);continue}return j}}return{context:e}}async function pV(a,b,c,d){for(let e of b){if(!e.matcher(a))continue;let b=pQ.get(e.handler)??"unknown",f=c.path??"/:virtual",g=await (0,mA.f)(`hook after ${f} ${b}`,{[mC]:"after",[mE.DR]:f,[mD]:b,[mB]:d},()=>e.handler(a)).catch(b=>{if(m$(b))return(0,ek.p8)(a.context.logger.level,"debug")&&(b.stack=b.errorStack),{response:b,headers:pT(b)};throw b});pS(a.context,g.headers),void 0!==g.response&&(a.context.returned=g.response)}return{response:a.context.returned,headers:a.context.responseHeaders}}async function pW(a,b){let c=b.operationId??pR(a),d=a.path??"/:virtual",e=a.options?.method,f=Array.isArray(e)?e[0]:e,g=b.method??b.request?.method??f??"?",h=b.asResponse??eF(b.request),i={...b,context:{...b.context,returned:void 0,responseHeaders:void 0,session:b.context.session??null},path:a.path,headers:b.headers?new Headers(b.headers):void 0};return(0,mA.f)(`${g} ${d}`,{[mE.DR]:d,[mB]:c},async()=>my(i,async()=>{var e;let f,g,j,k,l,m,n,{beforeHooks:o,afterHooks:p}=(f=(e=i.context).options.plugins||[],g=[],j=[],(k=e.options.hooks?.before)&&(pQ.set(k,"user"),g.push({matcher:()=>!0,handler:k})),(l=e.options.hooks?.after)&&(pQ.set(l,"user"),j.push({matcher:()=>!0,handler:l})),m=f.flatMap(a=>(a.hooks?.before??[]).map(b=>(pQ.set(b.handler,`plugin:${a.id}`),b))),n=f.flatMap(a=>(a.hooks?.after??[]).map(b=>(pQ.set(b.handler,`plugin:${a.id}`),b))),m.length&&g.push(...m),n.length&&j.push(...n),{beforeHooks:g,afterHooks:j}),q=await pU(i,o,a,c);if("context"in q&&q.context&&"object"==typeof q.context){let{headers:a,...b}=q.context;if(a){i.headers||(i.headers=new Headers);let b=i.headers;a.forEach((a,c)=>{b.set(c,a)})}i=pP(b,i)}else if(q){let a=i.context.responseHeaders;return h?hI(q,{headers:a}):b.returnHeaders?{headers:a,response:q}:q}i.asResponse=!1,i.returnHeaders=!0,i.returnStatus=!0;let r=await my(i,()=>(0,mA.f)(`handler ${d}`,{[mE.DR]:d,[mB]:c},()=>a(i))).catch(a=>{if(m$(a))return{response:a,status:a.statusCode,headers:pT(a)};throw a});if(r instanceof Response)return r;i.context.returned=r.response,i.context.responseHeaders=r.headers??void 0;let s=await pV(i,p,a,c);if(void 0!==s.response&&(r.response=s.response),r.headers=s.headers??r.headers,m$(r.response)&&(0,ek.p8)(i.context.logger.level,"debug")&&(r.response.stack=r.response.errorStack),m$(r.response)&&!h)throw r.headers&&Object.defineProperty(r.response,hz.Ri,{enumerable:!1,configurable:!0,writable:!1,value:r.headers}),r.response;return h?hI(r.response,{headers:r.headers??void 0,status:r.status}):b.returnHeaders?b.returnStatus?{headers:r.headers,response:r.response,status:r.status}:{headers:r.headers,response:r.response}:b.returnStatus?{response:r.response,status:r.status}:r.response}))}async function pX(a,b){if(a.baseURL)return a;let c=function(a){if(eF(a?.request))return a.request;if(!a?.headers)return;let b=a.headers instanceof Headers?a.headers:new Headers(a.headers);if(b.has("host")||b.has("x-forwarded-host"))return b}(b),d=a.options.baseURL,e=eE(d)&&!!d.fallback;if(void 0===c&&!e)throw new em.LG("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 mU(a,c,mT(a.options))}catch(a){if(a instanceof em.$l)throw new em.LG("INTERNAL_SERVER_ERROR",{message:a.message});throw a}}function pY(a,b){let c=b.plugins?.reduce((a,b)=>({...a,...b.endpoints}),{})??{},d=b.plugins?.map(b=>b.middlewares?.map(c=>{let d=async d=>{let e=await a;return(0,mA.f)(`middleware ${c.path} ${b.id}`,{[mC]:"middleware",[mE.DR]:c.path,[mD]:`plugin:${b.id}`},()=>c.middleware({...d,context:{...e,...d.context}}))};return d.options=c.middleware.options,{path:c.path,middleware:d}})).filter(a=>void 0!==a).flat()||[];return{api:function(a,b){let c={};for(let[d,e]of Object.entries(a))c[d]=async a=>{let c=pR(e,d),f=async()=>{let d=await b,f=eE(d.options.baseURL)?await pX(d,a):d;return pW(e,{...a,context:f,operationId:c,asResponse:a?.asResponse??eF(a?.request)})};return await nn()?f():np(new WeakMap,f)},c[d].path=e.path,c[d].options=e.options;return c}({signInSocial:m3("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:pF,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 a=>{let b=await mV(a.context.socialProviders,{value:a.body.provider});if(!b)throw a.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:a.body.provider}),em.LG.from("NOT_FOUND",hg.PROVIDER_NOT_FOUND);if(a.body.idToken){if(!b.verifyIdToken)throw a.context.logger.error("Provider does not support id token verification",{provider:a.body.provider}),em.LG.from("NOT_FOUND",hg.ID_TOKEN_NOT_SUPPORTED);let{token:c,nonce:d}=a.body.idToken;if(!await b.verifyIdToken(c,d))throw a.context.logger.warn("Invalid id token",{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.INVALID_TOKEN);let e=await b.getUserInfo({idToken:c,accessToken:a.body.idToken.accessToken,refreshToken:a.body.idToken.refreshToken,user:a.body.idToken.user});if(!e||!e?.user)throw a.context.logger.error("Failed to get user info",{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.FAILED_TO_GET_USER_INFO);if(!e.user.email)throw a.context.logger.error(nC(a.body.provider,{source:"id_token"}),{provider:a.body.provider}),em.LG.from("UNAUTHORIZED",hg.USER_EMAIL_NOT_FOUND);let f=await oj(a,{userInfo:{...e.user,email:e.user.email,id:String(e.user.id),name:e.user.name||"",image:e.user.image,emailVerified:e.user.emailVerified||!1},account:{providerId:b.id,accountId:String(e.user.id),accessToken:a.body.idToken.accessToken},callbackURL:a.body.callbackURL,disableSignUp:b.disableImplicitSignUp&&!a.body.requestSignUp||b.disableSignUp});if(f.error)throw em.LG.from("UNAUTHORIZED",{message:f.error,code:"OAUTH_LINK_ERROR"});return await mj(a,f.data),a.json({redirect:!1,token:f.data.session.token,url:void 0,user:hk(a.context.options,f.data.user)})}let{codeVerifier:c,state:d}=await ot(a,void 0,a.body.additionalData),e=await b.createAuthorizationURL({state:d,codeVerifier:c,redirectURI:`${a.context.baseURL}/callback/${b.id}`,scopes:a.body.scopes,loginHint:a.body.loginHint});return a.body.disableRedirect||a.setHeader("Location",e.toString()),a.json({url:e.toString(),redirect:!a.body.disableRedirect})}),callbackOAuth:pw,getSession:nt(),signOut:pG,signUpEmail:m3("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[na],body:pH,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 a=>(0,mz.iD)(a.context.adapter,async()=>{let b;if(!a.context.options.emailAndPassword?.enabled||a.context.options.emailAndPassword?.disableSignUp)throw em.LG.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let c=a.body,{name:d,email:e,password:f,image:g,callbackURL:h,rememberMe:i,...j}=c;if(!kj(k_,void 0).safeParse(e).success)throw em.LG.from("BAD_REQUEST",hg.INVALID_EMAIL);if(!f||"string"!=typeof f)throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);let k=a.context.password.config.minPasswordLength;if(f.length<k)throw a.context.logger.warn("Password is too short"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_SHORT);let l=a.context.password.config.maxPasswordLength;if(f.length>l)throw a.context.logger.warn("Password is too long"),em.LG.from("BAD_REQUEST",hg.PASSWORD_TOO_LONG);let m=a.context.options.emailAndPassword.requireEmailVerification||!1===a.context.options.emailAndPassword.autoSignIn,n=!1===a.context.options.emailAndPassword.autoSignIn||m,o=ho(a.context.options,j,"create"),p=e.toLowerCase(),q=await a.context.internalAdapter.findUserByEmail(p);if(q?.user){if(a.context.logger.info(`Sign-up attempt for existing email: ${e}`),m){let b;await a.context.password.hash(f),a.context.options.emailAndPassword?.onExistingUserSignUp&&await a.context.runInBackgroundOrAwait(a.context.options.emailAndPassword.onExistingUserSignUp({user:q.user},a.request?.clone()));let c=new Date,e=a.context.generateId({model:"user"})||(0,mF.$)(),h={name:d,email:p,emailVerified:!1,image:g??null,createdAt:c,updatedAt:c},i=a.context.options.emailAndPassword?.customSyntheticUser;if(i){let c=Object.keys(a.context.options.user?.additionalFields??{}),d={};for(let a of c)a in o&&(d[a]=o[a]);let f=i({coreFields:h,additionalFields:d,id:e});b=hl(a.context.options,f)}else b=hl(a.context.options,{...h,...o,id:e});return a.json({token:null,user:hk(a.context.options,b)})}throw em.LG.from("UNPROCESSABLE_ENTITY",hg.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let r=await a.context.password.hash(f);try{if(!(b=await a.context.internalAdapter.createUser({email:p,name:d,image:g,...o,emailVerified:!1})))throw em.LG.from("BAD_REQUEST",hg.FAILED_TO_CREATE_USER)}catch(b){if((0,ey.yz)()&&a.context.logger.error("Failed to create user",b),m$(b))throw b;throw a.context.logger?.error("Failed to create user",b),em.LG.from("UNPROCESSABLE_ENTITY",hg.FAILED_TO_CREATE_USER)}if(!b)throw em.LG.from("UNPROCESSABLE_ENTITY",hg.FAILED_TO_CREATE_USER);if(await a.context.internalAdapter.linkAccount({userId:b.id,providerId:"credential",accountId:b.id,password:r}),a.context.options.emailVerification?.sendOnSignUp??a.context.options.emailAndPassword.requireEmailVerification){let d=await of(a.context.secret,b.email,void 0,a.context.options.emailVerification?.expiresIn),e=c.callbackURL?encodeURIComponent(c.callbackURL):encodeURIComponent("/"),f=`${a.context.baseURL}/verify-email?token=${d}&callbackURL=${e}`;a.context.options.emailVerification?.sendVerificationEmail&&await a.context.runInBackgroundOrAwait(a.context.options.emailVerification.sendVerificationEmail({user:b,url:f,token:d},a.request?.clone()))}if(n)return a.json({token:null,user:hk(a.context.options,b)});let s=await a.context.internalAdapter.createSession(b.id,!1===i);if(!s)throw em.LG.from("BAD_REQUEST",hg.FAILED_TO_CREATE_SESSION);return await mj(a,{session:s,user:b},!1===i),a.json({token:s.token,user:hk(a.context.options,b)})})),signInEmail:m3("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[na],cloneRequest:!0,body:lw({email:kZ().meta({description:"Email of the user"}),password:kZ().meta({description:"Password of the user"}),callbackURL:kZ().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:ln().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 a=>{if(!a.context.options?.emailAndPassword?.enabled)throw a.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!"),em.LG.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:b,password:c}=a.body;if(!kj(k_,void 0).safeParse(b).success)throw em.LG.from("BAD_REQUEST",hg.INVALID_EMAIL);let d=await a.context.internalAdapter.findUserByEmail(b,{includeAccounts:!0});if(!d)throw await a.context.password.hash(c),a.context.logger.warn("User not found"),em.LG.from("UNAUTHORIZED",hg.INVALID_EMAIL_OR_PASSWORD);let e=d.accounts.find(a=>"credential"===a.providerId);if(!e)throw await a.context.password.hash(c),a.context.logger.warn("Credential account not found"),em.LG.from("UNAUTHORIZED",hg.INVALID_EMAIL_OR_PASSWORD);let f=e?.password;if(!f)throw await a.context.password.hash(c),a.context.logger.warn("Password not found"),em.LG.from("UNAUTHORIZED",hg.INVALID_EMAIL_OR_PASSWORD);if(!await a.context.password.verify({hash:f,password:c}))throw a.context.logger.warn("Invalid password"),em.LG.from("UNAUTHORIZED",hg.INVALID_EMAIL_OR_PASSWORD);if(a.context.options?.emailAndPassword?.requireEmailVerification&&!d.user.emailVerified){if(!a.context.options?.emailVerification?.sendVerificationEmail)throw em.LG.from("FORBIDDEN",hg.EMAIL_NOT_VERIFIED);if(a.context.options?.emailVerification?.sendOnSignIn){let b=await of(a.context.secret,d.user.email,void 0,a.context.options.emailVerification?.expiresIn),c=a.body.callbackURL?encodeURIComponent(a.body.callbackURL):encodeURIComponent("/"),e=`${a.context.baseURL}/verify-email?token=${b}&callbackURL=${c}`;await a.context.runInBackgroundOrAwait(a.context.options.emailVerification.sendVerificationEmail({user:d.user,url:e,token:b},a.request?.clone()))}throw em.LG.from("FORBIDDEN",hg.EMAIL_NOT_VERIFIED)}let g=await a.context.internalAdapter.createSession(d.user.id,!1===a.body.rememberMe);if(!g)throw a.context.logger.error("Failed to create session"),em.LG.from("UNAUTHORIZED",hg.FAILED_TO_CREATE_SESSION);return await mj(a,{session:g,user:d.user},!1===a.body.rememberMe),a.body.callbackURL&&a.setHeader("Location",a.body.callbackURL),a.json({redirect:!!a.body.callbackURL,token:g.token,url:a.body.callbackURL,user:hk(a.context.options,d.user)})}),resetPassword:pD,verifyPassword:pE,verifyEmail:oi,sendVerificationEmail:oh,changeEmail:pO,changePassword:pK,setPassword:pL,updateSession:m3("/update-session",{method:"POST",operationId:"updateSession",body:pI,use:[nv],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 a=>{var b;let c=a.body;if("object"!=typeof c||Array.isArray(c))throw em.LG.from("BAD_REQUEST",hg.BODY_MUST_BE_AN_OBJECT);let d=a.context.session,e=(b=a.context.options,hn(c,{fields:hj(b,"session","input"),action:"update"}));if(0===Object.keys(e).length)throw em.LG.fromStatus("BAD_REQUEST",{message:"No fields to update"});let f=await a.context.internalAdapter.updateSession(d.session.token,{...e,updatedAt:new Date});if(!f&&eI(a.context.options))throw ml(a),em.LG.from("UNAUTHORIZED",hg.FAILED_TO_GET_SESSION);let g=f??{...d.session,...e,updatedAt:new Date};return await mj(a,{session:g,user:d.user}),a.json({session:hm(a.context.options,g)})}),updateUser:m3("/update-user",{method:"POST",operationId:"updateUser",body:pJ,use:[nv],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 a=>{let b=a.body;if("object"!=typeof b||Array.isArray(b))throw em.LG.from("BAD_REQUEST",hg.BODY_MUST_BE_AN_OBJECT);if(b.email)throw em.LG.from("BAD_REQUEST",hg.EMAIL_CAN_NOT_BE_UPDATED);let{name:c,image:d,...e}=b,f=a.context.session,g=ho(a.context.options,e,"update");if(void 0===d&&void 0===c&&0===Object.keys(g).length)throw em.LG.fromStatus("BAD_REQUEST",{message:"No fields to update"});let h=await a.context.internalAdapter.updateUser(f.user.id,{name:c,image:d,...g})??{...f.user,...void 0!==c&&{name:c},...void 0!==d&&{image:d},...g};return await mj(a,{session:f.session,user:h}),a.json({status:!0})}),deleteUser:pM,requestPasswordReset:pB,requestPasswordResetCallback:pC,listSessions:m3("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[nx],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 a=>{try{let b=(await a.context.internalAdapter.listSessions(a.context.session.user.id,{onlyActiveSessions:!0})).filter(a=>a.expiresAt>new Date);return a.json(b.map(b=>hm(a.context.options,b)))}catch(b){throw a.context.logger.error(b),a.error("INTERNAL_SERVER_ERROR")}}),revokeSession:ny,revokeSessions:nz,revokeOtherSessions:nA,linkSocialAccount:pm,listUserAccounts:pl,deleteUserCallback:pN,unlinkAccount:pn,refreshToken:ps,getAccessToken:pr,accountInfo:pt,...c,ok:pz,error:py},a),middlewares:d}}var pZ=c(51455),p$=c(48161),p_=c.n(p$);async function p0(a,b){return{database:b?.database,adapter:b?.adapter,emailVerification:{sendVerificationEmail:!!a.emailVerification?.sendVerificationEmail,sendOnSignUp:!!a.emailVerification?.sendOnSignUp,sendOnSignIn:!!a.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!a.emailVerification?.autoSignInAfterVerification,expiresIn:a.emailVerification?.expiresIn,beforeEmailVerification:!!a.emailVerification?.beforeEmailVerification,afterEmailVerification:!!a.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!a.emailAndPassword?.enabled,disableSignUp:!!a.emailAndPassword?.disableSignUp,requireEmailVerification:!!a.emailAndPassword?.requireEmailVerification,maxPasswordLength:a.emailAndPassword?.maxPasswordLength,minPasswordLength:a.emailAndPassword?.minPasswordLength,sendResetPassword:!!a.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:a.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!a.emailAndPassword?.onPasswordReset,password:{hash:!!a.emailAndPassword?.password?.hash,verify:!!a.emailAndPassword?.password?.verify},autoSignIn:!!a.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!a.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(a.socialProviders||{}).map(async b=>{let c=a.socialProviders?.[b];if(!c)return{};let d="function"==typeof c?await c():c;return{id:b,mapProfileToUser:!!d.mapProfileToUser,disableDefaultScope:!!d.disableDefaultScope,disableIdTokenSignIn:!!d.disableIdTokenSignIn,disableImplicitSignUp:d.disableImplicitSignUp,disableSignUp:d.disableSignUp,getUserInfo:!!d.getUserInfo,overrideUserInfoOnSignIn:!!d.overrideUserInfoOnSignIn,prompt:d.prompt,verifyIdToken:!!d.verifyIdToken,scope:d.scope,refreshAccessToken:!!d.refreshAccessToken}})),plugins:a.plugins?.map(a=>a.id.toString()),user:{modelName:a.user?.modelName,fields:a.user?.fields,additionalFields:a.user?.additionalFields,changeEmail:{enabled:a.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!a.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:a.verification?.modelName,disableCleanup:a.verification?.disableCleanup,fields:a.verification?.fields},session:{modelName:a.session?.modelName,additionalFields:a.session?.additionalFields,cookieCache:{enabled:a.session?.cookieCache?.enabled,maxAge:a.session?.cookieCache?.maxAge,strategy:a.session?.cookieCache?.strategy},disableSessionRefresh:a.session?.disableSessionRefresh,expiresIn:a.session?.expiresIn,fields:a.session?.fields,freshAge:a.session?.freshAge,preserveSessionInDatabase:a.session?.preserveSessionInDatabase,storeSessionInDatabase:a.session?.storeSessionInDatabase,updateAge:a.session?.updateAge},account:{modelName:a.account?.modelName,fields:a.account?.fields,encryptOAuthTokens:a.account?.encryptOAuthTokens,updateAccountOnSignIn:a.account?.updateAccountOnSignIn,accountLinking:{enabled:a.account?.accountLinking?.enabled,trustedProviders:a.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:a.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:a.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!a.hooks?.after,before:!!a.hooks?.before},secondaryStorage:!!a.secondaryStorage,advanced:{cookiePrefix:!!a.advanced?.cookiePrefix,cookies:!!a.advanced?.cookies,crossSubDomainCookies:{domain:!!a.advanced?.crossSubDomainCookies?.domain,enabled:a.advanced?.crossSubDomainCookies?.enabled,additionalCookies:a.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:a.advanced?.database?.generateId,defaultFindManyLimit:a.advanced?.database?.defaultFindManyLimit},useSecureCookies:a.advanced?.useSecureCookies,ipAddress:{disableIpTracking:a.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:a.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:a.advanced?.disableCSRFCheck,cookieAttributes:{expires:a.advanced?.defaultCookieAttributes?.expires,secure:a.advanced?.defaultCookieAttributes?.secure,sameSite:a.advanced?.defaultCookieAttributes?.sameSite,domain:!!a.advanced?.defaultCookieAttributes?.domain,path:a.advanced?.defaultCookieAttributes?.path,httpOnly:a.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:a.trustedOrigins?.length,rateLimit:{storage:a.rateLimit?.storage,modelName:a.rateLimit?.modelName,window:a.rateLimit?.window,customStorage:!!a.rateLimit?.customStorage,enabled:a.rateLimit?.enabled,max:a.rateLimit?.max},onAPIError:{errorURL:a.onAPIError?.errorURL,onError:!!a.onAPIError?.onError,throw:a.onAPIError?.throw},logger:{disabled:a.logger?.disabled,level:a.logger?.level,log:!!a.logger?.log},databaseHooks:{user:{create:{after:!!a.databaseHooks?.user?.create?.after,before:!!a.databaseHooks?.user?.create?.before},update:{after:!!a.databaseHooks?.user?.update?.after,before:!!a.databaseHooks?.user?.update?.before}},session:{create:{after:!!a.databaseHooks?.session?.create?.after,before:!!a.databaseHooks?.session?.create?.before},update:{after:!!a.databaseHooks?.session?.update?.after,before:!!a.databaseHooks?.session?.update?.before}},account:{create:{after:!!a.databaseHooks?.account?.create?.after,before:!!a.databaseHooks?.account?.create?.before},update:{after:!!a.databaseHooks?.account?.update?.after,before:!!a.databaseHooks?.account?.update?.before}},verification:{create:{after:!!a.databaseHooks?.verification?.create?.after,before:!!a.databaseHooks?.verification?.create?.before},update:{after:!!a.databaseHooks?.verification?.update?.after,before:!!a.databaseHooks?.verification?.update?.before}}}}}async function p1(a){let b=await mq("SHA-256").digest(a);return mb.encode(b)}async function p2(){if(h)return h;try{let a=process.cwd();if(!a)return;let b=await pZ.readFile(de.join(a,"package.json"),"utf-8");return h=JSON.parse(b)}catch{}}async function p3(a){if(h)return h.dependencies?.[a]||h.devDependencies?.[a]||h.peerDependencies?.[a];try{let b=process.cwd();if(!b)throw Error("no-cwd");let c=de.join(b,"node_modules",a,"package.json"),d=await pZ.readFile(c,"utf-8");return JSON.parse(d).version||await p4(a)||void 0}catch{}return p4(a)}async function p4(a){let b=await p2();if(b)return({...b.dependencies,...b.devDependencies,...b.peerDependencies})[a]}async function p5(){return(await p2())?.name}async function p6(){try{let a,b,c=p$.cpus();return{deploymentVendor:(a=process.env,(b=(...b)=>b.some(b=>!!a[b]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":b("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":b("NETLIFY","NETLIFY_URL")?"netlify":b("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":b("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":b("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":b("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":b("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":b("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":b("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":b("DYNO","HEROKU_APP_NAME")?"heroku":b("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":b("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:p$.platform(),systemRelease:p$.release(),systemArchitecture:p$.arch(),cpuCount:c.length,cpuModel:c.length?c[0].model:null,cpuSpeed:c.length?c[0].speed:null,memory:p$.totalmem(),isWSL:await qc(),isDocker:await p9(),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 p7(){try{return dd.statSync("/.dockerenv"),!0}catch{return!1}}async function p8(){try{return dd.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function p9(){return void 0===i&&(i=await p7()||await p8()),i}let qa=async()=>{try{return dd.statSync("/run/.containerenv"),!0}catch{return!1}};async function qb(){return void 0===j&&(j=await qa()||await p9()),j}async function qc(){try{if("linux"!==process.platform)return!1;if(p$.release().toLowerCase().includes("microsoft")){if(await qb())return!1;return!0}return!!dd.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!await qb()}catch{return!1}}let qd=null;async function qe(a){if(qd)return qd;let b=await p5();return b?qd=await p1(a?a+b:b):a?qd=await p1(a):qd=(0,ol.q)("a-z","A-Z","0-9")(32)}async function qf(){for(let[a,b]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 c=await p3(a);if(c)return{name:b,version:c}}}async function qg(){for(let[a,b]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 c=await p3(a);if(c)return{name:b,version:c}}}let qh=async function(){};async function qi(a,b){let c,d=a.telemetry?.debug||(0,ey.$F)("BETTER_AUTH_TELEMETRY_DEBUG",!1),e=ey.Km.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!e&&!b?.customTrack)return{publish:qh};let f=async a=>{b?.customTrack?await b.customTrack(a).catch(ek.vF.error):e&&(d?ek.vF.info("telemetry event",JSON.stringify(a,null,2)):await oV(e,{method:"POST",body:a}).catch(ek.vF.error))},g=async()=>{let c=a.telemetry?.enabled!==void 0&&a.telemetry.enabled;return((0,ey.$F)("BETTER_AUTH_TELEMETRY",!1)||c)&&(b?.skipTestCheck||!(0,ey.Nu)())},h=await g();return h&&(c=await qe("string"==typeof a.baseURL?a.baseURL:void 0),f({type:"init",payload:{config:await p0(a,b),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 qf(),framework:await qg(),environment:"production"===(0,ey.lh)("NODE_ENV")?"production":"false"!==ey._K.CI&&("BUILD_ID"in ey._K||"BUILD_NUMBER"in ey._K||"CI"in ey._K||"CI_APP_ID"in ey._K||"CI_BUILD_ID"in ey._K||"CI_BUILD_NUMBER"in ey._K||"CI_NAME"in ey._K||"CONTINUOUS_INTEGRATION"in ey._K||"RUN_ID"in ey._K)?"ci":(0,ey.Nu)()?"test":"development",systemInfo:await p6(),packageManager:function(){let a=ey._K.npm_config_user_agent;if(!a)return;let b=a.split(" ")[0],c=b.lastIndexOf("/"),d=b.substring(0,c);return{name:"npminstall"===d?"cnpm":d,version:b.substring(c+1)}}()},anonymousId:c})),{publish:async b=>{h&&(c||(c=await qe("string"==typeof a.baseURL?a.baseURL:void 0)),await f({type:b.type,payload:b.payload,anonymousId:c}))}}}async function qj(a,b,c){let d,e,f,g,h=eI(b);h||(b=mK(b,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:b.session?.expiresIn||604800}}})),b.database||(b=mK(b,{account:{storeAccountCookie:!0}}));let i=b.plugins||[],j=(p=b,p.advanced?.crossSubDomainCookies?.enabled,[]),k=(0,ek.h)(b.logger),l=eE(b.baseURL);if(eE(b.baseURL)){let{allowedHosts:a}=b.baseURL;if(!a||0===a.length)throw new em.$l('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let m=l?void 0:eC("string"==typeof b.baseURL?b.baseURL:void 0,b.basePath);m||l||k.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"===a.id&&b.advanced?.database?.generateId===!1&&k.error(`[better-auth] Misconfiguration detected.
|
|
448
|
+
You are using the memory DB with generateId: false.
|
|
449
|
+
This will cause no id to be generated for any model.
|
|
450
|
+
Most of the features of Better Auth will not work correctly.`);let n=b.secrets??((q=ey._K.BETTER_AUTH_SECRETS)?q.split(",").map(a=>{let b=(a=a.trim()).indexOf(":");if(-1===b)throw new em.$l(`Invalid BETTER_AUTH_SECRETS entry: "${a}". Expected format: "<version>:<secret>"`);let c=parseInt(a.slice(0,b),10);if(!Number.isInteger(c)||c<0)throw new em.$l(`Invalid version in BETTER_AUTH_SECRETS: "${a.slice(0,b)}". Version must be a non-negative integer.`);let d=a.slice(b+1).trim();if(!d)throw new em.$l(`Empty secret value for version ${c} in BETTER_AUTH_SECRETS.`);return{version:c,value:d}}):null),o=b.secret||ey._K.BETTER_AUTH_SECRET||ey._K.AUTH_SECRET||"";if(n)!function(a,b){var c;let d;if(0===a.length)throw new em.$l("`secrets` array must contain at least one entry.");let e=new Set;for(let b of a){let a=parseInt(String(b.version),10);if(!Number.isInteger(a)||a<0||String(a)!==String(b.version).trim())throw new em.$l(`Invalid version ${b.version} in \`secrets\`. Version must be a non-negative integer.`);if(!b.value)throw new em.$l(`Empty secret value for version ${a} in \`secrets\`.`);if(e.has(a))throw new em.$l(`Duplicate version ${a} in \`secrets\`. Each version must be unique.`);e.add(a)}let f=a[0];f.value.length<32&&b.warn(`[better-auth] Warning: the current secret (version ${f.version}) should be at least 32 characters long for adequate security.`),120>(0===(d=new Set(c=f.value).size)?0:Math.log2(Math.pow(d,c.length)))&&b.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(n,k),d=n[0].value,e=function(a,b){let c=new Map;for(let b of a)c.set(parseInt(String(b.version),10),b.value);return{keys:c,currentVersion:parseInt(String(a[0].version),10),legacySecret:b&&"better-auth-secret-12345678901234567890"!==b?b:void 0}}(n,o);else{var p,q,r=d=o||"better-auth-secret-12345678901234567890";let a="better-auth-secret-12345678901234567890"===r;if(!(0,ey.Nu)()){let b;if(a&&ey.KV)throw new em.$l("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!r)throw new em.$l("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");r.length<32&&k.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===(b=new Set(r).size)?0:Math.log2(Math.pow(b,r.length)))&&k.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}e=d}!function(a,b){let c=new Map;a.plugins?.forEach(a=>{if(a.endpoints){for(let[b,d]of Object.entries(a.endpoints))if(d&&"path"in d&&"string"==typeof d.path){let e=d.path,f=[];d.options&&"method"in d.options&&(Array.isArray(d.options.method)?f=d.options.method:"string"==typeof d.options.method&&(f=[d.options.method])),0===f.length&&(f=["*"]),c.has(e)||c.set(e,[]),c.get(e).push({pluginId:a.id,endpointKey:b,methods:f})}}});let d=[];for(let[a,b]of c.entries())if(b.length>1){let c=new Map,e=!1;for(let a of b)for(let d of a.methods)c.has(d)||c.set(d,[]),c.get(d).push(a.pluginId),c.get(d).length>1&&(e=!0),"*"===d&&b.length>1?e=!0:"*"!==d&&c.has("*")&&(e=!0);if(e){let e=[...new Set(b.map(a=>a.pluginId))],f=[];for(let[a,d]of c.entries())(d.length>1||"*"===a&&b.length>1||"*"!==a&&c.has("*"))&&f.push(a);d.push({path:a,plugins:e,conflictingMethods:f})}}if(d.length>0){let a=d.map(a=>` - "${a.path}" [${a.conflictingMethods.join(", ")}] used by plugins: ${a.plugins.join(", ")}`).join("\n");b.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
451
|
+
${a}
|
|
452
|
+
|
|
453
|
+
To resolve this, you can:
|
|
454
|
+
1. Use only one of the conflicting plugins
|
|
455
|
+
2. Configure the plugins to use different paths (if supported)
|
|
456
|
+
3. Ensure plugins use different HTTP methods for the same path
|
|
457
|
+
`)}}(b={...b,secret:d,baseURL:l?b.baseURL:m?new URL(m).origin:"",basePath:b.basePath||"/api/auth",plugins:i.concat(j)},k);let s=mh(b),t=(0,ej.y)(b),u=(await Promise.all(Object.entries(b.socialProviders||{}).map(async([a,b])=>{let c="function"==typeof b?await b():b;if(null==c||!1===c.enabled)return null;c.clientId||k.warn(`Social provider ${a} is missing clientId or clientSecret`);let d=pj[a](c);return d.disableImplicitSignUp=c.disableImplicitSignUp,d}))).filter(a=>null!==a),v=({model:a,size:c})=>{if("function"==typeof b.advanced?.generateId)return b.advanced.generateId({model:a,size:c});let d=b?.advanced?.database?.generateId;return"function"==typeof d?d({model:a,size:c}):"uuid"===d?crypto.randomUUID():"serial"!==d&&!1!==d&&(0,mF.$)(c)},{publish:w}=await qi(b,{adapter:a.id,database:"function"==typeof b.database?"adapter":c(b.database)}),x=new Set(b.plugins.map(a=>a.id)),y=await mS(b),z=await mW(b),A={appName:b.appName||"Better Auth",baseURL:m||"",version:(0,mu.H)(),socialProviders:u,options:b,oauthConfig:{storeStateStrategy:b.account?.storeStateStrategy||(h?"database":"cookie"),skipStateCookieCheck:!!b.account?.skipStateCookieCheck},tables:t,trustedOrigins:y,trustedProviders:z,isTrustedOrigin(a,b){return this.trustedOrigins.some(c=>eH(a,c,b))},sessionConfig:{updateAge:b.session?.updateAge!==void 0?b.session.updateAge:86400,expiresIn:b.session?.expiresIn||604800,freshAge:b.session?.freshAge===void 0?86400:b.session.freshAge,cookieRefreshCache:(f=b.session?.cookieCache?.refreshCache,g=b.session?.cookieCache?.maxAge||300,h&&f?(k.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!==f&&void 0!==f&&(!0===f?{enabled:!0,updateAge:Math.floor(.2*g)}:{enabled:!0,updateAge:void 0!==f.updateAge?f.updateAge:Math.floor(.2*g)}))},secret:d,secretConfig:e,rateLimit:{...b.rateLimit,enabled:b.rateLimit?.enabled??ey.KV,window:b.rateLimit?.window||10,max:b.rateLimit?.max||100,storage:b.rateLimit?.storage||(b.secondaryStorage?"secondary-storage":"memory")},authCookies:s,logger:k,generateId:v,session:null,secondaryStorage:b.secondaryStorage,password:{hash:b.emailAndPassword?.password?.hash||eN,verify:b.emailAndPassword?.password?.verify||eP,config:{minPasswordLength:b.emailAndPassword?.minPasswordLength||8,maxPasswordLength:b.emailAndPassword?.maxPasswordLength||128},checkPassword:mY},setNewSession(a){this.newSession=a},newSession:null,adapter:a,internalAdapter:mH(a,{options:b,logger:k,hooks:b.databaseHooks?[{source:"user",hooks:b.databaseHooks}]:[],generateId:v}),createAuthCookie:mg(b),async runMigrations(){throw new em.$l("runMigrations will be set by the specific init implementation")},publishTelemetry:w,skipCSRFCheck:!!b.advanced?.disableCSRFCheck,skipOriginCheck:b.advanced?.disableOriginCheck!==void 0?b.advanced.disableOriginCheck:!!(0,ey.Nu)(),runInBackground:b.advanced?.backgroundTasks?.handler??(a=>{a.catch(()=>{})}),async runInBackgroundOrAwait(a){try{b.advanced?.backgroundTasks?.handler?a instanceof Promise&&b.advanced.backgroundTasks.handler(a.catch(a=>{k.error("Failed to run background task:",a)})):await a}catch(a){k.error("Failed to run background task:",a)}},getPlugin:a=>b.plugins.find(b=>b.id===a)??null,hasPlugin:a=>x.has(a)},B=mR(A);return eK(B)&&await B,A}let qk=async a=>{let b=await en(a),c=await qj(b,a,a=>(0,eo.dG)(a)||"unknown");return c.runMigrations=async function(){if(!a.database||"updateMany"in a.database)throw new em.$l("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:b}=await eu(a);await b()},c};var ql=c(37807);function qm(a,b,c){return"pg"===c?be(a,b):aP`LOWER(${a}) LIKE LOWER(${b})`}function qn(a,b){return 0===b.length?aP`false`:aP`LOWER(${a}) IN (${aP.join(b.map(a=>aP`LOWER(${a})`),aP`, `)})`}function qo(a,b){return 0===b.length?aP`true`:aP`LOWER(${a}) NOT IN (${aP.join(b.map(a=>aP`LOWER(${a})`),aP`, `)})`}function qp(a,b){return aP`LOWER(${a}) = LOWER(${b})`}function qq(a,b){return aP`LOWER(${a}) <> LOWER(${b})`}function qr(a,b,c){let d=0;return(a&&"object"==typeof a&&"rowCount"in a?d=a.rowCount:Array.isArray(a)?d=a.length>0&&qs(a[0])?qt(a[0]):a.length:qs(a)&&(d=qt(a)),"number"!=typeof d)?(ek.vF.error(`[Drizzle Adapter] The result of the ${b} operation is not a number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.`,{result:a,...c}),0):d}function qs(a){return!!a&&"object"==typeof a&&("affectedRows"in a||"rowsAffected"in a||"changes"in a)}function qt(a){return a.affectedRows??a.rowsAffected??a.changes}let qu="1.6.19",qv=hf({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"}),qw="two_factor",qx="trust_device";async function qy(a){let b=a=>{throw em.LG.from("UNAUTHORIZED",qv[a])},c=await nu(a);if(!c){let c=a.context.createAuthCookie(qw),d=await a.getSignedCookie(c.name,a.context.secret);if(!d)throw em.LG.from("UNAUTHORIZED",qv.INVALID_TWO_FACTOR_COOKIE);let e=await a.context.internalAdapter.findVerificationValue(d);if(!e)throw em.LG.from("UNAUTHORIZED",qv.INVALID_TWO_FACTOR_COOKIE);let f=await a.context.internalAdapter.findUserById(e.value);if(!f)throw em.LG.from("UNAUTHORIZED",qv.INVALID_TWO_FACTOR_COOKIE);let g=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);return{valid:async a=>{let b=await a.context.internalAdapter.consumeVerificationValue(d);if(!b||b.value!==f.id)throw mk(a,c),em.LG.from("UNAUTHORIZED",qv.INVALID_TWO_FACTOR_COOKIE);let e=await a.context.internalAdapter.createSession(b.value,!!g);if(!e)throw em.LG.from("INTERNAL_SERVER_ERROR",{message:"failed to create session",code:"FAILED_TO_CREATE_SESSION"});if(await mj(a,{session:e,user:f}),mk(a,c),a.body.trustDevice){let b=a.context.getPlugin("two-factor").options?.trustDeviceMaxAge??2592e3,c=a.context.createAuthCookie(qx,{maxAge:b}),d=`trust-device-${om(32)}`,e=await mf("SHA-256","base64urlnopad").sign(a.context.secret,`${f.id}!${d}`);await a.context.internalAdapter.createVerificationValue({value:f.id,identifier:d,expiresAt:new Date(Date.now()+1e3*b)}),await a.setSignedCookie(c.name,`${e}!${d}`,a.context.secret,c.attributes),mk(a,a.context.authCookies.dontRememberToken)}return a.json({token:e.token,user:hk(a.context.options,f)})},invalid:b,session:{session:null,user:f},key:d}}return{valid:async a=>a.json({token:c.session.token,user:hk(a.context.options,c.user)}),invalid:b,session:c,key:`${c.user.id}!${c.session.id}`}}async function qz(a,b,c){let d=JSON.stringify(a);return c?.storeBackupCodes==="encrypted"?ob({data:d,key:b}):"object"==typeof c?.storeBackupCodes&&"encrypt"in c?.storeBackupCodes?c.storeBackupCodes.encrypt(d):d}async function qA(a,b){let c=b?.customBackupCodesGenerate?b.customBackupCodesGenerate():Array.from({length:b?.amount??10}).fill(null).map(()=>om(b?.length??10,"a-z","0-9","A-Z")).map(a=>`${a.slice(0,5)}-${a.slice(5)}`);return{backupCodes:c,encryptedBackupCodes:await qz(c,a,b)}}async function qB(a,b,c){let d=await qC(a.backupCodes,b,c);return d?{status:d.includes(a.code),updated:d.filter(b=>b!==a.code)}:{status:!1,updated:null}}async function qC(a,b,c){return c?.storeBackupCodes==="encrypted"?(0,hy.$)(await oc({key:b,data:a})):"object"==typeof c?.storeBackupCodes&&"decrypt"in c?.storeBackupCodes?(0,hy.$)(await c?.storeBackupCodes.decrypt(a)):(0,hy.$)(a)}let qD=lw({code:kZ().meta({description:'A backup code to verify. Eg: "123456"'}),disableSession:ln().meta({description:"If true, the session cookie will not be set."}).optional(),trustDevice:ln().meta({description:"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true"}).optional()}),qE=lw({userId:l_().meta({description:'The user ID to view all backup codes. Eg: "user-id"'})}),qF=async a=>{let b=await mq("SHA-256").digest(new TextEncoder().encode(a));return mc.encode(new Uint8Array(b),{padding:!1})},qG=lw({code:kZ().meta({description:'The otp code to verify. Eg: "012345"'}),trustDevice:ln().optional().meta({description:"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true"})}),qH=lw({trustDevice:ln().optional().meta({description:"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true"})}).optional();function qI(a){return a?"0123456789ABCDEFGHIJKLMNOPQRSTUV":"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"}let qJ={encode(a,b={}){let c=qI(!1);return function(a,b,c){let d="",e=0,f=0;for(let c of a)for(e=e<<8|c,f+=8;f>=5;)f-=5,d+=b[e>>f&31];if(f>0&&(d+=b[e<<5-f&31]),c){let a=(8-d.length%8)%8;d+="=".repeat(a)}return d}("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){"string"!=typeof a&&(a=new TextDecoder().decode(a));let b=qI(!1);return function(a,b){let c=function(a){let b=new Map;for(let c=0;c<a.length;c++)b.set(a[c],c);return b}(b),d=[],e=0,f=0;for(let b of a){if("="===b)break;let a=c.get(b);if(void 0===a)throw Error(`Invalid Base32 character: ${b}`);for(e=e<<5|a,f+=5;f>=8;)f-=8,d.push(e>>f&255)}return Uint8Array.from(d)}(a,b)}};async function qK(a,{counter:b,digits:c,hash:d="SHA-1"}){let e=c??6;if(e<1||e>8)throw TypeError("Digits must be between 1 and 8");let f=new ArrayBuffer(8);new DataView(f).setBigUint64(0,BigInt(b),!1);let g=new Uint8Array(f),h=new Uint8Array(await mf(d).sign(a,g)),i=15&h[h.length-1];return(((127&h[i])<<24|(255&h[i+1])<<16|(255&h[i+2])<<8|255&h[i+3])%10**e).toString().padStart(e,"0")}async function qL(a,b){let c=b?.digits??6,d=b?.period??30,e=Math.floor(Date.now()/(1e3*d));return await qK(a,{counter:e,digits:c,hash:b?.hash})}async function qM(a,{window:b=1,digits:c=6,secret:d,period:e=30}){let f=Math.floor(Date.now()/(1e3*e)),g=!1;for(let e=-b;e<=b;e++)g=function(a,b){let c=a.length^b.length;for(let d=0;d<b.length;d++)c|=a.charCodeAt(d)^b.charCodeAt(d);return 0===c}(a,await qK(d,{counter:f+e,digits:c}))||g;return g}let qN=(a,b)=>{let c=b?.digits??6,d=b?.period??30;return{hotp:b=>qK(a,{counter:b,digits:c}),totp:()=>qL(a,{digits:c,period:d}),verify:(b,e)=>qM(b,{secret:a,digits:c,period:d,...e}),url:(b,e)=>(function({issuer:a,account:b,secret:c,digits:d=6,period:e=30}){let f=encodeURIComponent(a),g=encodeURIComponent(b),h=`otpauth://totp/${f}:${g}`,i=new URLSearchParams({secret:qJ.encode(c,{padding:!1}),issuer:a});return void 0!==d&&i.set("digits",d.toString()),void 0!==e&&i.set("period",e.toString()),`${h}?${i.toString()}`})({issuer:b,account:e,secret:a,digits:c,period:d})}},qO=lw({secret:kZ().meta({description:"The secret to generate the TOTP code"})}),qP=lw({code:kZ().meta({description:'The otp code to verify. Eg: "012345"'}),trustDevice:ln().meta({description:"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true"}).optional()}),qQ={start:{label:"Start",requiresLogin:!1,note:"Local auto-created account \xb7 always signed in."},auth:{label:"Auth",requiresLogin:!0,note:"Email + password required each session."},vps:{label:"VPS",requiresLogin:!0,note:"Access over your Tailscale tailnet; runs in Docker."},portable:{label:"Portable",requiresLogin:!0,note:"USB drive mounted as root across machines."}};function qR(){let a=process.env.CONSTELLA_RUN_MODE;return a&&a in qQ?a:"start"}let qS=qR(),qT=process.env.BETTER_AUTH_URL??"http://localhost:3000",qU="start"===qS||!!process.env.BETTER_AUTH_SECRET;qU||console.error(`[auth] FATAL: BETTER_AUTH_SECRET is required in '${qS}' mode (sessions would be forgeable). Set it in your environment.`);let qV={};process.env.GITHUB_CLIENT_ID&&process.env.GITHUB_CLIENT_SECRET&&(qV.github={clientId:process.env.GITHUB_CLIENT_ID,clientSecret:process.env.GITHUB_CLIENT_SECRET,scope:["repo","read:user"]}),process.env.GOOGLE_CLIENT_ID&&process.env.GOOGLE_CLIENT_SECRET&&(qV.google={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET}),Object.keys(qV);let qW=((a,b)=>{let c=b(a),{api:d}=pY(c,a);return{handler:async b=>{let d,e=await c,f=e.options.basePath||"/api/auth";if(eE(a.baseURL))d=await mU(e,b,mT(e.options));else{d=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));let a=e.options;if(!e.options.baseURL){let c=eC(void 0,f,b,void 0,e.options.advanced?.trustedProxyHeaders);if(!c)throw new em.$l("Could not get base URL from request. Please provide a valid base URL.");d.baseURL=c,d.options={...e.options,baseURL:eD(c)||void 0},a=d.options}d.trustedOrigins=await mS(a,b),d.trustedProviders=await mW(a,b)}let{handler:g}=((a,b)=>{let{api:c,middlewares:d}=pY(a,b),e=new URL(a.baseURL).pathname;return((a,b)=>{if(!b?.openapi?.disabled){let c={path:"/api/reference",...b?.openapi};a.openapi=hW(c.path,{method:"GET"},async b=>{let d,e;return new Response((d=await lV(a),e=c.scalar,`<!doctype html>
|
|
458
|
+
<html>
|
|
459
|
+
<head>
|
|
460
|
+
<title>Scalar API Reference</title>
|
|
461
|
+
<meta charset="utf-8" />
|
|
462
|
+
<meta
|
|
463
|
+
name="viewport"
|
|
464
|
+
content="width=device-width, initial-scale=1" />
|
|
465
|
+
</head>
|
|
466
|
+
<body>
|
|
467
|
+
<script
|
|
468
|
+
id="api-reference"
|
|
469
|
+
type="application/json">
|
|
470
|
+
${JSON.stringify(d)}
|
|
471
|
+
</script>
|
|
472
|
+
<script>
|
|
473
|
+
var configuration = {
|
|
474
|
+
favicon: ${e?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(e.logo)}`:void 0} ,
|
|
475
|
+
theme: ${e?.theme||"saturn"},
|
|
476
|
+
metaData: {
|
|
477
|
+
title: ${e?.title||"Open API Reference"},
|
|
478
|
+
description: ${e?.description||"Better Call Open API"},
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
document.getElementById('api-reference').dataset.configuration =
|
|
482
|
+
JSON.stringify(configuration)
|
|
483
|
+
</script>
|
|
484
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
485
|
+
</body>
|
|
486
|
+
</html>`),{headers:{"Content-Type":"text/html"}})})}let c=lX(),d=lX();for(let b of Object.values(a))if(!(!b.options||!b.path||b.options?.metadata?.SERVER_ONLY))for(let a of Array.isArray(b.options?.method)?b.options.method:[b.options?.method])l$(c,a,b.path,b);if(b?.routerMiddleware?.length)for(let{path:a,middleware:c}of b.routerMiddleware)l$(d,"*",a,c);let e=async a=>{let e=new URL(a.url),f=e.pathname,g=b?.basePath&&"/"!==b.basePath?f.split(b.basePath).reduce((a,c,d)=>(0!==d&&(d>1?a.push(`${b.basePath}${c}`):a.push(c)),a),[]).join(""):e.pathname;if(!g?.length||/\/{2,}/.test(g))return new Response(null,{status:404,statusText:"Not Found"});let h=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=a.static[c];if(d&&d.methods){let a=d.methods[b]||d.methods[""];if(void 0!==a)return a[0]}let e=lY(c),f=function a(b,c,d,e,f){if(f===e.length){if(c.methods){let a=c.methods[d]||c.methods[""];if(a)return a}if(c.param&&c.param.methods){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}return}let g=e[f];if(c.static){let h=c.static[g];if(h){let c=a(b,h,d,e,f+1);if(c)return c}}if(c.param){let h=a(b,c.param,d,e,f+1);if(h){if(c.param.hasRegexParam){let a=h.find(a=>a.paramsRegexp[f]?.test(g))||h.find(a=>!a.paramsRegexp[f]);return a?[a]:void 0}return h}}if(c.wildcard&&c.wildcard.methods)return c.wildcard.methods[d]||c.wildcard.methods[""]}(a,a.root,b,e,0)?.[0];if(void 0!==f)return{data:f.data,params:f.paramsMap?lZ(e,f.paramsMap):void 0}}(c,a.method,g);if(g.endsWith("/")!==h?.data?.path?.endsWith("/")&&!b?.skipTrailingSlashes||!h?.data)return new Response(null,{status:404,statusText:"Not Found"});let i={};e.searchParams.forEach((a,b)=>{b in i?Array.isArray(i[b])?i[b].push(a):i[b]=[i[b],a]:i[b]=a});let j=h.data;try{let c=j.options.metadata?.allowedMediaTypes||b?.allowedMediaTypes,e={path:g,method:a.method,headers:a.headers,params:h.params?JSON.parse(JSON.stringify(h.params)):{},request:a,body:j.options.disableBody?void 0:await hB(j.options.cloneRequest?a.clone():a,c),query:i,_flag:"router",asResponse:!0,context:b?.routerContext},f=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=lY(c);return(function a(b,c,d,e,f,g=[]){let h=e[f];if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];a&&g.push(...a)}if(c.param&&(a(b,c.param,d,e,f+1,g),f===e.length&&c.param.methods)){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;b?.[b?.length-1]?.[2]&&g.push(...a)}}let i=c.static?.[h];if(i&&a(b,i,d,e,f+1,g),f===e.length&&c.methods){let a=c.methods[d]||c.methods[""];a&&g.push(...a)}return g})(a,a.root,b,d,0).map(a=>({data:a.data,params:a.paramsMap?lZ(d,a.paramsMap):void 0}))}(d,"*",g);if(f?.length)for(let{data:a,params:b}of f){let c=await a({...e,params:b,asResponse:!1});if(c instanceof Response)return c}return await j(e)}catch(c){if(b?.onError)try{let d=await b.onError(c,a);if(d instanceof Response)return hI(d)}catch(a){if(hC(a))return hI(a);throw a}if(b?.throwError)throw c;if(hC(c))return hI(c);return console.error("# SERVER_ERROR: ",c),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async a=>{let c=await b?.onRequest?.(a);if(c instanceof Response)return c;let d=hE(c)?c:a,f=await e(d),g=await b?.onResponse?.(f,d);return g instanceof Response?g:f},endpoints:a}})(c,{routerContext:a,openapi:{disabled:!0},basePath:e,routerMiddleware:[{path:"/**",middleware:m7},...d],allowedMediaTypes:["application/json"],skipTrailingSlashes:b.advanced?.skipTrailingSlashes??!1,async onRequest(b){let c=a.options.disabledPaths||[],d=m_(b.url,e);if(c.includes(d))return new Response("Not Found",{status:404});let f=b;for(let b of a.options.plugins||[])if(b.onRequest){let c=await (0,mA.f)(`onRequest ${b.id}`,{[mC]:"onRequest",[mD]:`plugin:${b.id}`},()=>b.onRequest(f,a));if(c&&"response"in c)return c.response;c&&"request"in c&&(f=c.request)}return await nj(f,a)||f},async onResponse(b,c){for(let c of a.options.plugins||[])if(c.onResponse){let d=await (0,mA.f)(`onResponse ${c.id}`,{[mC]:"onResponse",[mD]:`plugin:${c.id}`,[mE.OR]:b.status},()=>c.onResponse(b,a));if(d)return d.response}return b},onError(c){if(m$(c)&&"FOUND"===c.status)return;if(b.onAPIError?.throw)throw c;if(b.onAPIError?.onError)return void b.onAPIError.onError(c,a);let d=b.logger?.level,e="error"===d||"warn"===d||"debug"===d?ek.vF:void 0;if(b.logger?.disabled!==!0){if(c&&"object"==typeof c&&"message"in c&&"string"==typeof c.message&&(c.message.includes("no column")||c.message.includes("column")||c.message.includes("relation")||c.message.includes("table")||c.message.includes("does not exist")))return void a.logger?.error(c.message);m$(c)?("INTERNAL_SERVER_ERROR"===c.status&&a.logger.error(c.status,c),e?.error(c.message)):a.logger?.error(c&&"object"==typeof c&&"name"in c?c.name:"",c)}}})})(d,a);return(0,mz.vp)(d.adapter,()=>g(b))},api:d,options:a,$context:c,$ERROR_CODES:{...a.plugins?.reduce((a,b)=>b.$ERROR_CODES?{...a,...b.$ERROR_CODES}:a,{}),...hg}}})({baseURL:qT,secret:process.env.BETTER_AUTH_SECRET,database:(Q={provider:"sqlite",schema:{user:dm,session:dn,account:dp,verification:dq,twoFactor:eb}},q=null,r=!1,s=(a,b=!1)=>({getFieldName:c,getDefaultFieldName:d,getDefaultModelName:e,options:f,schema:g})=>{function h(b){let c=Q.schema||a._.fullSchema;if(!c)throw new em.$l("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let d=c[b];if(!d)throw new em.$l(`[# Drizzle Adapter]: The model "${b}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return d}"mysql"!==Q.provider||f.advanced?.database?.generateId!==!1||r||(r=!0,ek.vF.warn('[Drizzle Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth\'s default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.'));let i=async(d,i,k,l)=>{if("mysql"!==Q.provider)return(await i.returning())[0];await i.execute();let m=h(d),n=i.config?.values;if(l?.length){let b=j(l.map(a=>void 0!==k[a.field]?{...a,value:k[a.field]}:a),d);return(await a.select().from(m).where(...b))[0]}let o=async a=>{let b=n?.[0]?.id?.value;if(b)return(await a.select().from(m).where(aX(m.id,b)).limit(1).execute())[0]??null;if(k.id)return(await a.select().from(m).where(aX(m.id,k.id)).limit(1).execute())[0]??null;if(f.advanced?.database?.generateId==="serial"&&m.id){let b=(await a.select({id:aP`LAST_INSERT_ID()`}).from(m).limit(1).execute())[0]?.id;if(b)return(await a.select().from(m).where(aX(m.id,b)).limit(1).execute())[0]??null}let h=g[e(d)]?.fields;if(h)for(let[b,e]of Object.entries(h)){if(!e.unique)continue;let f=c({model:d,field:b}),g=k[f];if(null==g||!m[f])continue;let h=await a.select().from(m).where(aX(m[f],g)).limit(1).execute();if(h[0])return h[0]}let i=[];for(let[a,b]of Object.entries(k))void 0!==b&&m[a]&&i.push(null===b?a6(m[a]):aX(m[a],b));if(i.length>0){let b=aZ(...i);if(b){let c=await a.select().from(m).where(b).limit(2).execute();if(1===c.length)return c[0]}}return ek.vF.warn(`[Drizzle Adapter] Unable to safely identify the inserted "${d}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return b?o(a):a.transaction(o)};function j(a,b){let d=h(b);if(!a)return[];if(1===a.length){let e=a[0];if(!e)return[];let f=c({model:b,field:e.field});if(!d[f])throw new em.$l(`The field "${e.field}" does not exist in the schema for the model "${b}". Please update your schema.`);let g=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(a=>"string"==typeof a));if("in"===e.operator){if(!Array.isArray(e.value))throw new em.$l(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return g?[qn(d[f],e.value)]:[a4(d[f],e.value)]}if("not_in"===e.operator){if(!Array.isArray(e.value))throw new em.$l(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return g?[qo(d[f],e.value)]:[a5(d[f],e.value)]}return"contains"===e.operator?g&&"string"==typeof e.value?[qm(d[f],`%${e.value}%`,Q.provider)]:[bc(d[f],`%${e.value}%`)]:"starts_with"===e.operator?g&&"string"==typeof e.value?[qm(d[f],`${e.value}%`,Q.provider)]:[bc(d[f],`${e.value}%`)]:"ends_with"===e.operator?g&&"string"==typeof e.value?[qm(d[f],`%${e.value}`,Q.provider)]:[bc(d[f],`%${e.value}`)]:"lt"===e.operator?[a2(d[f],e.value)]:"lte"===e.operator?[a3(d[f],e.value)]:"ne"===e.operator?null===e.value?[a7(d[f])]:g&&"string"==typeof e.value?[qq(d[f],e.value)]:[aY(d[f],e.value)]:"gt"===e.operator?[a0(d[f],e.value)]:"gte"===e.operator?[a1(d[f],e.value)]:null===e.value?[a6(d[f])]:g&&"string"==typeof e.value?[qp(d[f],e.value)]:[aX(d[f],e.value)]}let e=a.filter(a=>"AND"===a.connector||!a.connector),f=a.filter(a=>"OR"===a.connector),g=aZ(...e.map(a=>{let e=c({model:b,field:a.field}),f=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new em.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return f?qn(d[e],a.value):a4(d[e],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new em.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return f?qo(d[e],a.value):a5(d[e],a.value)}return"contains"===a.operator?f&&"string"==typeof a.value?qm(d[e],`%${a.value}%`,Q.provider):bc(d[e],`%${a.value}%`):"starts_with"===a.operator?f&&"string"==typeof a.value?qm(d[e],`${a.value}%`,Q.provider):bc(d[e],`${a.value}%`):"ends_with"===a.operator?f&&"string"==typeof a.value?qm(d[e],`%${a.value}`,Q.provider):bc(d[e],`%${a.value}`):"lt"===a.operator?a2(d[e],a.value):"lte"===a.operator?a3(d[e],a.value):"gt"===a.operator?a0(d[e],a.value):"gte"===a.operator?a1(d[e],a.value):"ne"===a.operator?null===a.value?a7(d[e]):f&&"string"==typeof a.value?qq(d[e],a.value):aY(d[e],a.value):null===a.value?a6(d[e]):f&&"string"==typeof a.value?qp(d[e],a.value):aX(d[e],a.value)})),i=a$(...f.map(a=>{let e=c({model:b,field:a.field});if(!d[e])throw new em.$l(`The field "${a.field}" does not exist in the schema for the model "${b}". Please update your schema.`);let f=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new em.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return f?qn(d[e],a.value):a4(d[e],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new em.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return f?qo(d[e],a.value):a5(d[e],a.value)}return"contains"===a.operator?f&&"string"==typeof a.value?qm(d[e],`%${a.value}%`,Q.provider):bc(d[e],`%${a.value}%`):"starts_with"===a.operator?f&&"string"==typeof a.value?qm(d[e],`${a.value}%`,Q.provider):bc(d[e],`${a.value}%`):"ends_with"===a.operator?f&&"string"==typeof a.value?qm(d[e],`%${a.value}`,Q.provider):bc(d[e],`%${a.value}`):"lt"===a.operator?a2(d[e],a.value):"lte"===a.operator?a3(d[e],a.value):"gt"===a.operator?a0(d[e],a.value):"gte"===a.operator?a1(d[e],a.value):"ne"===a.operator?null===a.value?a7(d[e]):f&&"string"==typeof a.value?qq(d[e],a.value):aY(d[e],a.value):null===a.value?a6(d[e]):f&&"string"==typeof a.value?qp(d[e],a.value):aX(d[e],a.value)}));return e.length&&f.length?[aZ(g,i)]:e.length?[g]:f.length?[i]:[]}function k(b){if(a.query[b])return b;if(Q.usePlural){let c=`${b}s`;if(a.query[c])return c}if(Q.schema){let c=Q.schema[b];if(c){let b=a._.fullSchema;if(b){for(let d of Object.keys(a.query))if(b[d]===c)return d}}}return null}return{async create({model:b,data:d}){let e=h(b);if(!e)throw new em.$l("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");for(let a in d){let d;try{d=c({model:b,field:a})}catch{d=a}if(!e[d])throw new em.$l(`The field "${a}" does not exist in the "${b}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}return await i(b,a.insert(e).values(d),d)},async findOne({model:b,where:d,select:e,join:g}){let i=h(b),l=j(d,b);if(f.experimental?.joins){let d=k(b);if(a.query&&d){let h,i=[];if(g)for(let[a,b]of(h={},Object.entries(g))){let c=b.limit??f.advanced?.database?.defaultFindManyLimit??100,d="one-to-one"===b.relation,e=d||Q.usePlural?"":"s";h[`${a}${e}`]=!!d||{limit:c},d||i.push(`${a}${e}`)}let j=await a.query[d].findFirst({where:l[0],columns:e?.length&&e.length>0?e.reduce((a,d)=>(a[c({model:b,field:d})]=!0,a),{}):void 0,with:h});if(j)for(let a of i){let b=Q.usePlural?a:a.slice(0,-1);j[b]=j[a],a!==b&&delete j[a]}return j}ek.vF.error(`[# Drizzle Adapter]: The model "${b}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),ek.vF.info("Falling back to regular query")}let m=await a.select(e?.length&&e.length>0?e.reduce((a,d)=>{let e=c({model:b,field:d});return{...a,[e]:i[e]}},{}):void 0).from(i).where(...l);return m.length?m[0]:null},async findMany({model:b,where:d,sortBy:e,limit:g,select:i,offset:l,join:m}){let n=h(b),o=d?j(d,b):[],p=e?.direction==="desc"?br:bq;if(f.experimental?.joins){let d=k(b);if(d){let h,j,k=[];if(m)for(let[a,b]of(h={},Object.entries(m))){let c="one-to-one"===b.relation,d=b.limit??f.advanced?.database?.defaultFindManyLimit??100,e=c||Q.usePlural?"":"s";h[`${a}${e}`]=!!c||{limit:d},c||k.push(`${a}${e}`)}e?.field&&(j=[p(n[c({model:b,field:e?.field})])]);let q=await a.query[d].findMany({where:o[0],with:h,columns:i?.length&&i.length>0?i.reduce((a,d)=>(a[c({model:b,field:d})]=!0,a),{}):void 0,limit:g??100,offset:l??0,orderBy:j});if(q)for(let a of q)for(let b of k){let c=Q.usePlural?b:b.slice(0,-1);c!==b&&(a[c]=a[b],delete a[b])}return q}ek.vF.error(`[# Drizzle Adapter]: The model "${b}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),ek.vF.info("Falling back to regular query")}let q=a.select(i?.length&&i.length>0?i.reduce((a,d)=>{let e=c({model:b,field:d});return{...a,[e]:n[e]}},{}):void 0).from(n);return void 0!==g&&(q=q.limit(g)),void 0!==l&&(q=q.offset(l)),e?.field&&(q=q.orderBy(p(n[c({model:b,field:e?.field})]))),await q.where(...o)},async count({model:b,where:c}){let d=h(b),e=c?j(c,b):[];return(await a.select({count:aP`count(${aP.raw("*")})`.mapWith(Number)}).from(d).where(...e))[0].count},async update({model:b,where:c,update:d}){let e=h(b),f=j(c,b);return await i(b,a.update(e).set(d).where(...f),d,c)},async updateMany({model:b,where:c,update:d}){let e=h(b),f=j(c,b);return qr(await a.update(e).set(d).where(...f),"updateMany",{model:b,where:c})},async delete({model:b,where:c}){let d=h(b),e=j(c,b);return await a.delete(d).where(...e)},async deleteMany({model:b,where:c}){let d=h(b),e=j(c,b);return qr(await a.delete(d).where(...e),"deleteMany",{model:b,where:c})},async consumeOne({model:d,where:e}){let f=h(d),g=j(e,d),i=c({model:d,field:"id"}),k=f[i];if("mysql"===Q.provider){let c=async a=>{let b=(await a.select().from(f).where(...g).for("update").limit(1))[0];if(!b)return null;let c=b[i]??b.id;return null!=c&&k&&qr(await a.delete(f).where(aX(k,c)).execute(),"consumeOne",{model:d,where:e})>0?b:null};return b?c(a):a.transaction(c)}if(!k)return null;let l=a.select({id:k}).from(f).where(...g).limit(1);return(await a.delete(f).where(a4(k,l)).returning())[0]??null},async incrementOne({model:d,where:e,increment:f,set:g}){let i=h(d),k=j(e,d),l=c({model:d,field:"id"}),m=i[l],n={};for(let[a,b]of Object.entries(f)){let e=c({model:d,field:a}),f=i[e];if(!f)throw new em.$l(`The field "${a}" does not exist in the schema for the model "${d}". Please update your schema.`);n[e]=aP`${f} + ${b}`}if(g)for(let[a,b]of Object.entries(g)){let e=c({model:d,field:a});if(!i[e])throw new em.$l(`The field "${a}" does not exist in the schema for the model "${d}". Please update your schema.`);n[e]=b}if("mysql"===Q.provider){let c=async a=>{let b=(await a.select().from(i).where(...k).for("update").limit(1))[0];if(!b)return null;let c=b[l]??b.id;return null!=c&&m?(await a.update(i).set(n).where(aX(m,c)).execute(),(await a.select().from(i).where(aX(m,c)).limit(1).execute())[0]??null):null};return b?c(a):a.transaction(c)}if(!m)return null;let o=a.select({id:m}).from(i).where(...k).limit(1);return(await a.update(i).set(n).where(a4(m,o)).returning())[0]??null},options:Q}},t=null,t={config:{adapterId:"drizzle",adapterName:"Drizzle Adapter",usePlural:Q.usePlural??!1,debugLogs:Q.debugLogs??!1,supportsUUIDs:"pg"===Q.provider,supportsJSON:"pg"===Q.provider,supportsArrays:"pg"===Q.provider,customTransformOutput:({data:a,fieldAttributes:b})=>"date"===b.type?null==a?a:new Date(a):a,transaction:!!Q.transaction&&(a=>ei.transaction(b=>a((0,ql.I)({config:{...t.config,transaction:!1},adapter:s(b,!0)})(q))))},adapter:s(ei)},u=(0,ql.I)(t),a=>(q=a,u(a))),emailAndPassword:{enabled:!0,autoSignIn:!0,requireEmailVerification:!1},socialProviders:qV,account:{accountLinking:{enabled:!0,trustedProviders:["github","google"]}},session:{expiresIn:2592e3,additionalFields:{activeOrgId:{type:"string",required:!1}}},plugins:[(v="twoFactor",w=R?.trustDeviceMaxAge??2592e3,x=R?.allowPasswordless,y={storeBackupCodes:"encrypted",...R?.backupCodeOptions},z={...S={...R?.totpOptions,allowPasswordless:R?.totpOptions?.allowPasswordless??x},digits:S?.digits||6,period:S?.period||30},A=kZ().meta({description:"User password"}),B=S?.allowPasswordless?lw({password:A.optional()}):lw({password:A}),C="twoFactor",D={id:"totp",version:qu,endpoints:{generateTOTP:m3.serverOnly({method:"POST",body:qO,metadata:{openapi:{summary:"Generate TOTP code",description:"Use this endpoint to generate a TOTP code",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{code:{type:"string"}}}}}}}}}},async a=>{if(S?.disable)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),em.LG.from("BAD_REQUEST",{message:"totp isn't configured",code:"TOTP_NOT_CONFIGURED"});return{code:await qN(a.body.secret,{period:z.period,digits:z.digits}).totp()}}),getTOTPURI:m3("/two-factor/get-totp-uri",{method:"POST",use:[nv],body:B,metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string"}}}}}}}}}},async a=>{if(S?.disable)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),em.LG.from("BAD_REQUEST",{message:"totp isn't configured",code:"TOTP_NOT_CONFIGURED"});let b=a.context.session.user,c=await a.context.adapter.findOne({model:C,where:[{field:"userId",value:b.id}]});if(!c)throw em.LG.from("BAD_REQUEST",qv.TOTP_NOT_ENABLED);let d=await oc({key:a.context.secretConfig,data:c.secret});if(await mZ(a,b.id,S?.allowPasswordless)){if(!a.body.password)throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);await a.context.password.checkPassword(b.id,a)}return{totpURI:qN(d,{digits:z.digits,period:z.period}).url(S?.issuer||a.context.appName,b.email)}}),verifyTOTP:m3("/two-factor/verify-totp",{method:"POST",body:qP,metadata:{openapi:{summary:"Verify two factor TOTP",description:"Verify two factor TOTP",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{if(S?.disable)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),em.LG.from("BAD_REQUEST",{message:"totp isn't configured",code:"TOTP_NOT_CONFIGURED"});let{session:b,valid:c,invalid:d}=await qy(a),e=b.user,f=!b.session,g=await a.context.adapter.findOne({model:C,where:[{field:"userId",value:e.id}]});if(!g||f&&!1===g.verified)throw em.LG.from("BAD_REQUEST",qv.TOTP_NOT_ENABLED);if(!await qN(await oc({key:a.context.secretConfig,data:g.secret}),{period:z.period,digits:z.digits}).verify(a.body.code))return d("INVALID_CODE");if(!0!==g.verified){if(!e.twoFactorEnabled){let c=b.session,d=await a.context.internalAdapter.updateUser(e.id,{twoFactorEnabled:!0});await mj(a,{session:await a.context.internalAdapter.createSession(e.id,!1,c),user:d}),await a.context.internalAdapter.deleteSession(c.token)}await a.context.adapter.update({model:C,update:{verified:!0},where:[{field:"id",value:g.id}]})}return c(a)})}},T={...y,allowPasswordless:R?.backupCodeOptions?.allowPasswordless??x},E="twoFactor",F=kZ().meta({description:"The users password."}),G=T.allowPasswordless?lw({password:F.optional()}):lw({password:F}),H={id:"backup_code",version:qu,endpoints:{verifyBackupCode:m3("/two-factor/verify-backup-code",{method:"POST",body:qD,metadata:{openapi:{description:"Verify a backup code for two-factor authentication",responses:{200:{description:"Backup code verified successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the user"},email:{type:"string",format:"email",nullable:!0,description:"User's email address"},emailVerified:{type:"boolean",nullable:!0,description:"Whether the email is verified"},name:{type:"string",nullable:!0,description:"User's name"},image:{type:"string",format:"uri",nullable:!0,description:"User's profile image URL"},twoFactorEnabled:{type:"boolean",description:"Whether two-factor authentication is enabled for the user"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the user was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the user was last updated"}},required:["id","twoFactorEnabled","createdAt","updatedAt"],description:"The authenticated user object with two-factor details"},session:{type:"object",properties:{token:{type:"string",description:"Session token"},userId:{type:"string",description:"ID of the user associated with the session"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the session was created"},expiresAt:{type:"string",format:"date-time",description:"Timestamp when the session expires"}},required:["token","userId","createdAt","expiresAt"],description:"The current session object, included unless disableSession is true"}},required:["user","session"]}}}}}}}},async a=>{let{session:b,valid:c}=await qy(a),d=b.user,e=await a.context.adapter.findOne({model:E,where:[{field:"userId",value:d.id}]});if(!e)throw em.LG.from("BAD_REQUEST",qv.BACKUP_CODES_NOT_ENABLED);let f=await qB({backupCodes:e.backupCodes,code:a.body.code},a.context.secretConfig,T);if(!f.status||!f.updated)throw em.LG.from("UNAUTHORIZED",qv.INVALID_BACKUP_CODE);let g=await qz(f.updated,a.context.secretConfig,T);if(!await a.context.adapter.incrementOne({model:E,where:[{field:"id",value:e.id},{field:"backupCodes",value:e.backupCodes}],increment:{},set:{backupCodes:g}}))throw em.LG.fromStatus("CONFLICT",{message:"Failed to verify backup code. Please try again."});return a.body.disableSession?a.json({token:b.session?.token,user:hk(a.context.options,b.user)}):c(a)}),generateBackupCodes:m3("/two-factor/generate-backup-codes",{method:"POST",body:G,use:[nv],metadata:{openapi:{description:"Generate new backup codes for two-factor authentication",responses:{200:{description:"Backup codes generated successfully",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the backup codes were generated successfully",enum:[!0]},backupCodes:{type:"array",items:{type:"string"},description:"Array of generated backup codes in plain text"}},required:["status","backupCodes"]}}}}}}}},async a=>{let b=a.context.session.user;if(!b.twoFactorEnabled)throw em.LG.from("BAD_REQUEST",qv.TWO_FACTOR_NOT_ENABLED);if(await mZ(a,b.id,T.allowPasswordless)){if(!a.body.password)throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);await a.context.password.checkPassword(b.id,a)}let c=await a.context.adapter.findOne({model:E,where:[{field:"userId",value:b.id}]});if(!c)throw em.LG.from("BAD_REQUEST",qv.TWO_FACTOR_NOT_ENABLED);let d=await qA(a.context.secretConfig,T);return await a.context.adapter.update({model:E,update:{backupCodes:d.encryptedBackupCodes},where:[{field:"id",value:c.id}]}),a.json({status:!0,backupCodes:d.backupCodes})}),viewBackupCodes:m3.serverOnly({method:"POST",body:qE},async a=>{let b=await a.context.adapter.findOne({model:E,where:[{field:"userId",value:a.body.userId}]});if(!b)throw em.LG.from("BAD_REQUEST",qv.BACKUP_CODES_NOT_ENABLED);let c=await qC(b.backupCodes,a.context.secretConfig,T);if(!c)throw em.LG.from("BAD_REQUEST",qv.INVALID_BACKUP_CODE);return a.json({status:!0,backupCodes:c})})}},I=(a=>{let b={storeOTP:"plain",digits:6,...a,period:60*(a?.period||3)*1e3};async function c(a,c){return"hashed"===b.storeOTP?await qF(c):"object"==typeof b.storeOTP&&"hash"in b.storeOTP?await b.storeOTP.hash(c):"object"==typeof b.storeOTP&&"encrypt"in b.storeOTP?await b.storeOTP.encrypt(c):"encrypted"===b.storeOTP?await ob({key:a.context.secretConfig,data:c}):c}async function d(a,c,d){return"hashed"===b.storeOTP?[c,await qF(d)]:"encrypted"===b.storeOTP?[await oc({key:a.context.secretConfig,data:c}),d]:"object"==typeof b.storeOTP&&"encrypt"in b.storeOTP?[await b.storeOTP.decrypt(c),d]:"object"==typeof b.storeOTP&&"hash"in b.storeOTP?[c,await b.storeOTP.hash(d)]:[c,d]}return{id:"otp",version:qu,endpoints:{sendTwoFactorOTP:m3("/two-factor/send-otp",{method:"POST",body:qH,metadata:{openapi:{summary:"Send two factor OTP",description:"Send two factor OTP to the user",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async d=>{if(!a||!a.sendOTP)throw d.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),em.LG.from("BAD_REQUEST",{message:"otp isn't configured",code:"OTP_NOT_CONFIGURED"});let{session:e,key:f}=await qy(d),g=om(b.digits,"0-9"),h=await c(d,g);await d.context.internalAdapter.createVerificationValue({value:`${h}:0`,identifier:`2fa-otp-${f}`,expiresAt:new Date(Date.now()+b.period)});let i=a.sendOTP({user:e.user,otp:g},d);return i instanceof Promise&&await d.context.runInBackgroundOrAwait(i.catch(a=>{d.context.logger.error("Failed to send two-factor OTP",a)})),d.json({status:!0})}),verifyTwoFactorOTP:m3("/two-factor/verify-otp",{method:"POST",body:qG,metadata:{openapi:{summary:"Verify two factor OTP",description:"Verify two factor OTP",responses:{200:{description:"Two-factor OTP verified successfully",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"Session token for the authenticated session"},user:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the user"},email:{type:"string",format:"email",nullable:!0,description:"User's email address"},emailVerified:{type:"boolean",nullable:!0,description:"Whether the email is verified"},name:{type:"string",nullable:!0,description:"User's name"},image:{type:"string",format:"uri",nullable:!0,description:"User's profile image URL"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the user was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the user was last updated"}},required:["id","createdAt","updatedAt"],description:"The authenticated user object"}},required:["token","user"]}}}}}}}},async b=>{let{session:c,key:e,valid:f,invalid:g}=await qy(b),h=await b.context.internalAdapter.consumeVerificationValue(`2fa-otp-${e}`);if(!h)throw em.LG.from("BAD_REQUEST",qv.OTP_HAS_EXPIRED);let[i,j]=h.value?.split(":")??[],k=a?.allowedAttempts||5,l=parseInt(j,10)||0;if(l>=k)throw em.LG.from("BAD_REQUEST",qv.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);let[m,n]=await d(b,i,b.body.code);if(function(a,b){"string"==typeof a&&(a=new TextEncoder().encode(a)),"string"==typeof b&&(b=new TextEncoder().encode(b));let c=new Uint8Array(a),d=new Uint8Array(b),e=c.length^d.length,f=Math.max(c.length,d.length);for(let a=0;a<f;a++)e|=(a<c.length?c[a]:0)^(a<d.length?d[a]:0);return 0===e}(new TextEncoder().encode(m),new TextEncoder().encode(n))){if(!c.user.twoFactorEnabled){if(!c.session)throw em.LG.from("BAD_REQUEST",hg.FAILED_TO_CREATE_SESSION);let a=await b.context.internalAdapter.updateUser(c.user.id,{twoFactorEnabled:!0}),d=await b.context.internalAdapter.createSession(c.user.id,!1,c.session);return await mj(b,{session:d,user:a}),await b.context.internalAdapter.deleteSession(c.session.token),b.json({token:d.token,user:hk(b.context.options,a)})}return f(b)}return await b.context.internalAdapter.createVerificationValue({value:`${i}:${l+1}`,identifier:`2fa-otp-${e}`,expiresAt:h.expiresAt}),g("INVALID_CODE")})}}})(R?.otpOptions),J=kZ().meta({description:"User password"}),K=x?lw({password:J.optional(),issuer:kZ().meta({description:"Custom issuer for the TOTP URI"}).optional()}):lw({password:J,issuer:kZ().meta({description:"Custom issuer for the TOTP URI"}).optional()}),L=x?lw({password:J.optional()}):lw({password:J}),{id:"two-factor",version:qu,endpoints:{...D.endpoints,...I.endpoints,...H.endpoints,enableTwoFactor:m3("/two-factor/enable",{method:"POST",body:K,use:[nv],metadata:{openapi:{summary:"Enable two factor authentication",description:"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string",description:"TOTP URI"},backupCodes:{type:"array",items:{type:"string"},description:"Backup codes"}}}}}}}}}},async a=>{let b=a.context.session.user,{password:c,issuer:d}=a.body;if(await mZ(a,b.id,x)&&(!c||!await mX(a,{password:c,userId:b.id})))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);let e=om(32),f=await ob({key:a.context.secretConfig,data:e}),g=await qA(a.context.secretConfig,y);if(R?.skipVerificationOnEnable){let c=await a.context.internalAdapter.updateUser(b.id,{twoFactorEnabled:!0});await mj(a,{session:await a.context.internalAdapter.createSession(c.id,!1,a.context.session.session),user:c}),await a.context.internalAdapter.deleteSession(a.context.session.session.token)}let h=await a.context.adapter.findOne({model:v,where:[{field:"userId",value:b.id}]});await a.context.adapter.deleteMany({model:v,where:[{field:"userId",value:b.id}]}),await a.context.adapter.create({model:v,data:{secret:f,backupCodes:g.encryptedBackupCodes,userId:b.id,verified:null!=h&&!1!==h.verified||!!R?.skipVerificationOnEnable}});let i=qN(e,{digits:R?.totpOptions?.digits||6,period:R?.totpOptions?.period}).url(d||R?.issuer||a.context.appName,b.email);return a.json({totpURI:i,backupCodes:g.backupCodes})}),disableTwoFactor:m3("/two-factor/disable",{method:"POST",body:L,use:[nw],metadata:{openapi:{summary:"Disable two factor authentication",description:"Use this endpoint to disable two factor authentication.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{let b=a.context.session.user,{password:c}=a.body;if(await mZ(a,b.id,x)&&(!c||!await mX(a,{password:c,userId:b.id})))throw em.LG.from("BAD_REQUEST",hg.INVALID_PASSWORD);let d=await a.context.internalAdapter.updateUser(b.id,{twoFactorEnabled:!1});await a.context.adapter.delete({model:v,where:[{field:"userId",value:d.id}]}),await mj(a,{session:await a.context.internalAdapter.createSession(d.id,!1,a.context.session.session),user:d}),await a.context.internalAdapter.deleteSession(a.context.session.session.token);let e=a.context.createAuthCookie(qx,{maxAge:w}),f=await a.getSignedCookie(e.name,a.context.secret);if(f){let[,b]=f.split("!");b&&await a.context.internalAdapter.deleteVerificationByIdentifier(b),mk(a,e)}return a.json({status:!0})})},options:R,hooks:{after:[{matcher:a=>"/sign-in/email"===a.path||"/sign-in/username"===a.path||"/sign-in/phone-number"===a.path,handler:m1(async a=>{let b=a.context.newSession;if(!b||!b?.user.twoFactorEnabled)return;let c=a.context.createAuthCookie(qx,{maxAge:w}),d=await a.getSignedCookie(c.name,a.context.secret);if(d){let[e,f]=d.split("!");if(e&&f&&e===await mf("SHA-256","base64urlnopad").sign(a.context.secret,`${b.user.id}!${f}`)){let d=await a.context.internalAdapter.findVerificationValue(f);if(d&&d.value===b.user.id&&d.expiresAt>new Date){await a.context.internalAdapter.deleteVerificationByIdentifier(f);let d=`trust-device-${om(32)}`,e=await mf("SHA-256","base64urlnopad").sign(a.context.secret,`${b.user.id}!${d}`);await a.context.internalAdapter.createVerificationValue({value:b.user.id,identifier:d,expiresAt:new Date(Date.now()+1e3*w)});let g=a.context.createAuthCookie(qx,{maxAge:w});await a.setSignedCookie(g.name,`${e}!${d}`,a.context.secret,c.attributes);return}}mk(a,c)}ml(a,!0),await a.context.internalAdapter.deleteSession(b.session.token),a.context.setNewSession(null);let e=R?.twoFactorCookieMaxAge??600,f=a.context.createAuthCookie(qw,{maxAge:e}),g=`2fa-${om(20)}`;await a.context.internalAdapter.createVerificationValue({value:b.user.id,identifier:g,expiresAt:new Date(Date.now()+1e3*e)}),await a.setSignedCookie(f.name,g,a.context.secret,f.attributes);let h=[];if(!R?.totpOptions?.disable){let c=await a.context.adapter.findOne({model:v,where:[{field:"userId",value:b.user.id}]});c&&!1!==c.verified&&h.push("totp")}return R?.otpOptions?.sendOTP&&h.push("otp"),a.json({twoFactorRedirect:!0,twoFactorMethods:h})})}]},schema:function(a,b){if(!b)return a;for(let c in b){let d=b[c]?.modelName;for(let e in d&&(a[c].modelName=d),a[c].fields){let d=b[c]?.fields?.[e];d&&(a[c].fields[e].fieldName=d)}}return a}({user:{fields:{twoFactorEnabled:{type:"boolean",required:!1,defaultValue:!1,input:!1}}},twoFactor:{fields:{secret:{type:"string",required:!0,returned:!1,index:!0},backupCodes:{type:"string",required:!0,returned:!1},userId:{type:"string",required:!0,returned:!1,references:{model:"user",field:"id"},index:!0},verified:{type:"boolean",required:!1,defaultValue:!0,input:!1}}}},{...R?.schema,twoFactor:{...R?.schema?.twoFactor,...R?.twoFactorTable?{modelName:R.twoFactorTable}:{}}}),rateLimit:[{pathMatcher:a=>a.startsWith("/two-factor/"),window:10,max:3}],$ERROR_CODES:qv}),(M=!1,{id:"next-cookies",version:qu,hooks:{before:[{matcher:a=>"/get-session"===a.path,handler:m1(async a=>{let b;if(M||(!function(a,b){let c=a.options.plugins||[];if(0===c.length)return;let d=c.findIndex(a=>a.id===b);-1===d||c.slice(d+1).some(a=>a.hooks&&Array.isArray(a.hooks.after)&&a.hooks.after.length>0)&&a.logger.warn(`[better-auth] Cookie integration plugin "${b}" 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.`)}(a.context,"next-cookies"),M=!0),"_flag"in a&&"router"===a._flag)return;try{let{headers:a}=await Promise.resolve().then(c.bind(c,82650));b=await a()}catch{return}let d="1"===b.get("RSC"),e=!!b.get("next-action");d&&!e&&await ns(!0)})}],after:[{matcher:a=>!0,handler:m1(async a=>{let b=a.context.responseHeaders;if((!("_flag"in a)||"router"!==a._flag)&&b instanceof Headers){let a,d,e=b?.get("set-cookie");if(!e)return;let f=(d=new Map,hs(e).forEach(a=>{let[b,...c]=a.split(";").map(a=>a.trim()),[e,...f]=(b||"").split("="),g=hv(f.join("="));if(!e)return;let h={value:hr(g)};c.forEach(a=>{let[b,...c]=a.split("="),d=c.join("="),e=b.trim().toLowerCase();switch(e){case"max-age":h["max-age"]=d?parseInt(d.trim(),10):void 0;break;case"expires":h.expires=d?new Date(d.trim()):void 0;break;case"domain":h.domain=d?d.trim():void 0;break;case"path":h.path=d?d.trim():void 0;break;case"secure":h.secure=!0;break;case"httponly":h.httponly=!0;break;case"samesite":h.samesite=d?d.trim().toLowerCase():void 0;break;case"partitioned":h.partitioned=!0;break;default:h[e]=!d||d.trim()}}),d.set(e,h)}),d);try{let{cookies:b}=await Promise.resolve().then(c.bind(c,82650));a=await b()}catch(a){if(a instanceof Error&&(a.message.startsWith("`cookies` was called outside a request scope.")||a.message.includes("Cannot find module")))return;throw a}f.forEach((b,c)=>{if(c)try{a.set(c,b.value,{maxAge:b["max-age"],expires:b.expires,domain:b.domain,path:b.path,secure:b.secure,httpOnly:b.httponly,sameSite:b.samesite,partitioned:b.partitioned})}catch{}});return}})}]}})],advanced:{useSecureCookies:qT.startsWith("https://")}},qk);var qX=c(31421);function qY(){return process.env.CONSTELLA_HOME?ef(process.env.CONSTELLA_HOME):(0,de.join)((0,p$.homedir)(),".constella")}c(77030);let qZ=new Set;function q$(a){if(!/^[A-Za-z0-9_-]{6,64}$/.test(a))throw Error("Invalid orgId");let b=(0,de.join)(qY(),"organizations",a,"workspace");if(!qZ.has(a)){qZ.add(a);try{let c=(0,de.join)(qY(),"organizations",a,"constella"),d=!(0,dd.existsSync)(b)||0===(0,dd.readdirSync)(b).length;if((0,dd.existsSync)(c)&&d)try{(0,dd.renameSync)(c,b)}catch{(0,dd.mkdirSync)(b,{recursive:!0}),0===(0,dd.readdirSync)(b).length&&(0,dd.cpSync)(c,b,{recursive:!0})}}catch{}}return b}function q_(a,b){let c=(0,de.normalize)((0,de.join)(a,b));if(c!==a&&!c.startsWith(a+de.sep))throw Error("Path escapes workspace: "+b);if((0,dd.existsSync)(a)){let d;try{d=dd.realpathSync.native(a)}catch{d=a}let e=function(a){let b=a;for(;;){if((0,dd.existsSync)(b))try{return dd.realpathSync.native(b)}catch{return b}let a=(0,de.dirname)(b);if(a===b)return b;b=a}}(c);if(e!==d&&!e.startsWith(d+de.sep))throw Error("Path escapes workspace (symlink): "+b)}return c}function q0(a,b=""){let c=q_(q$(a),b);return(0,dd.existsSync)(c)?(0,dd.readdirSync)(c).map(a=>{let d=(0,de.join)(c,a),e=(b?b+"/":"")+a;return{name:a,path:e,isDir:(0,dd.statSync)(d).isDirectory()}}).sort((a,b)=>a.isDir===b.isDir?a.name.localeCompare(b.name):a.isDir?-1:1):[]}let q1=new Set(["node_modules",".git",".next",".turbo","dist","build","out","coverage",".cache","archives",".testdev",".pnpm-store",".vercel","vendor"]);function q2(a,b){let c=q_(q$(a),b);return(0,dd.existsSync)(c)?(0,dd.readFileSync)(c,"utf8"):null}function q3(a,b,c){let d=q_(q$(a),b);(0,dd.mkdirSync)((0,de.dirname)(d),{recursive:!0}),(0,dd.writeFileSync)(d,c,"utf8")}let q4="win32"===process.platform,q5=new Map;async function q6(a){var b;let c=q5.get(a);if(!c)return{running:!1,status:"stopped",logs:[]};c.status="stopped";try{c.proc?.pid&&(q4?(0,qX.spawn)("taskkill",["/PID",String(c.proc.pid),"/T","/F"],{windowsHide:!0}):process.kill(-c.proc.pid,"SIGKILL"))}catch{try{c.proc?.kill("SIGKILL")}catch{}}for(let a of"server stopped".split(/\r?\n/)){let b=a.trimEnd();b&&(c.logs.push({c:"info",t:b}),"starting"===c.status&&/(ready|listening|localhost:|started server|compiled)/i.test(b)&&(c.status="running"))}return c.logs.length>400&&c.logs.splice(0,c.logs.length-400),{running:"running"===(b=c).status||"starting"===b.status,status:b.status,port:b.port,url:b.url,project:b.label,logs:b.logs.slice(-120)}}async function q7(a,b=3e5){try{let c=Date.now()-b,d=await ei.select().from(dQ).where(aX(dQ.workspaceId,a));if(!d.length)return 0;let e=new Map;for(let a of d){let b=e.get(a.runId)??[];b.push(a),e.set(a.runId,b)}let f=new Set((await ei.select({id:dO.id}).from(dO).where(aX(dO.workspaceId,a))).map(a=>a.id)),g=0;for(let[b,d]of e){let e=d.reduce((a,b)=>Math.max(a,b.seq),0);f.has(b)||d.some(a=>"done"===a.kind)||e>c||(await ei.delete(dQ).where(aZ(aX(dQ.workspaceId,a),aX(dQ.runId,b))),g+=d.length)}return g}catch(a){return console.error("[events-prune] pruneOrphanRuns failed:",a),0}}let q8={TypeScript:"typescript",JavaScript:"javascript",Python:"python",Go:"go",Rust:"rust",Java:"java",Kotlin:"kotlin","C#":"csharp",Ruby:"ruby",PHP:"php",Elixir:"elixir",Swift:"swift","C++":"cpp",Scala:"scala",Dart:"dart",C:"c",Clojure:"clojure",Haskell:"haskell",Lua:"lua","Objective-C":"objectivec",Erlang:"erlang","Node.js":"node",Bun:"bun",Deno:"deno","Python 3":"python3",PyPy:"pypy",JVM:"jvm",".NET":"dotnet","BEAM (Erlang VM)":"beam",React:"react",Vue:"vue",Svelte:"svelte",Angular:"angular",SolidJS:"solidjs",Preact:"preact",Qwik:"qwik",Lit:"lit","Alpine.js":"alpine","Next.js":"nextjs",Nuxt:"nuxt",Remix:"remix",SvelteKit:"sveltekit",Astro:"astro",Gatsby:"gatsby","Vite (SPA)":"vite",NestJS:"nestjs",Fastify:"fastify",Express:"express",Hono:"hono",Koa:"koa",Django:"django",Flask:"flask",FastAPI:"fastapi","Spring Boot":"spring-boot",Spring:"spring",Laravel:"laravel",Symfony:"symfony","Ruby on Rails":"rails",Gin:"gin",Fiber:"fiber",Actix:"actix",Phoenix:"phoenix","ASP.NET Core":"aspnet-core",AdonisJS:"adonisjs","React Native":"react-native",Flutter:"flutter",PostgreSQL:"postgresql",MySQL:"mysql",MariaDB:"mariadb",SQLite:"sqlite",MongoDB:"mongodb",Redis:"redis",Supabase:"supabase",Prisma:"prisma",Drizzle:"drizzle",TypeORM:"typeorm",Sequelize:"sequelize",SQLAlchemy:"sqlalchemy","Django ORM":"django-orm",Mongoose:"mongoose",GORM:"gorm","Tailwind CSS":"tailwind","CSS Modules":"css-modules","styled-components":"styled-components",Sass:"sass",Jest:"jest",Vitest:"vitest",Cypress:"cypress",Playwright:"playwright",Docker:"docker",Podman:"podman",BullMQ:"bullmq",RabbitMQ:"rabbitmq",Kafka:"kafka",Celery:"celery","Auth.js":"authjs",Keycloak:"keycloak",R:"r",Ember:"ember",Backbone:"backbone",Hugo:"hugo",Jekyll:"jekyll",Eleventy:"eleventy",Docusaurus:"docusaurus",CodeIgniter:"codeigniter",GraphQL:"graphql",Nginx:"nginx",Android:"android",Ionic:"ionic",Xamarin:"xamarin",NativeScript:"nativescript",Bootstrap:"bootstrap",Bulma:"bulma",Vuetify:"vuetify",Selenium:"selenium",Mocha:"mocha",Jasmine:"jasmine",Puppeteer:"puppeteer",TensorFlow:"tensorflow",PyTorch:"pytorch","scikit-learn":"scikit-learn",Keras:"keras",Pandas:"pandas",NumPy:"numpy",Jupyter:"jupyter",D3:"d3","Chart.js":"chart-js",Grafana:"grafana",Plotly:"plotly",Azure:"azure",Jenkins:"jenkins",CircleCI:"circleci",Terraform:"terraform",Ansible:"ansible",Vagrant:"vagrant",Firebase:"firebase",Appwrite:"appwrite",Amplify:"amplify",Heroku:"heroku"},q9=[{match:/\bceo\b|chief exec/i,profile:{stackPrefixes:[],allPrefixes:["process/","design/","engineering/architecture/"],core:["app-planning","requirements-to-specs","specs-to-issues","architecture-before-code"]}},{match:/product owner|\bpo\b|product manager/i,profile:{stackPrefixes:[],allPrefixes:["process/"],core:["product-discovery","requirements-to-specs","specs-to-issues","prioritization-moscow-rice"]}},{match:/\bcto\b|chief tech|tech lead|architect/i,profile:{stackPrefixes:["stacks/"],allPrefixes:["engineering/architecture/","engineering/security/","engineering/performance/","process/architecture-before-code","process/adr-technical-decisions"],core:["system-design-fundamentals","software-architecture-patterns","architecture-before-code","api-design-rest-graphql"]}},{match:/front\s?end|\bui\b|\bux\b|web designer/i,profile:{stackPrefixes:["stacks/frontend/","stacks/styling/","stacks/meta/","stacks/mobile/","stacks/testing/"],allPrefixes:["design/","engineering/frontend/","engineering/performance/web-performance-core-vitals"],core:["design-systems","ui-ux-principles","responsive-layout","color-and-typography","accessibility-wcag"]}},{match:/back\s?end|server|\bapi\b/i,profile:{stackPrefixes:["stacks/backend/","stacks/database/","stacks/orm/","stacks/queue/","stacks/runtime/","stacks/baas/","stacks/auth/"],allPrefixes:["engineering/backend/","engineering/architecture/","engineering/performance/"],core:["backend-fundamentals","api-design-rest-graphql","data-modeling","auth-and-authorization"]}},{match:/cyber\s?sec|security|appsec|\bsec\b/i,profile:{stackPrefixes:["stacks/auth/"],allPrefixes:["engineering/security/","process/security-by-design","process/review-code-perf-security"],core:["owasp-top-10","owasp-asvs","secrets-management","secure-auth-sessions"]}},{match:/\bqa\b|quality|test/i,profile:{stackPrefixes:["stacks/testing/"],allPrefixes:["engineering/testing/","process/testing-before-done"],core:["testing-strategy-pyramid","tdd-and-coverage","unit-integration-e2e"]}},{match:/devops|\bops\b|infra|platform|sre|deploy/i,profile:{stackPrefixes:["stacks/infra/","stacks/container/","stacks/runtime/"],allPrefixes:["engineering/architecture/scalability-reliability","engineering/security/secrets-management"],core:["scalability-reliability","secrets-management"]}},{match:/\bdocs?\b|documentation|technical writer/i,profile:{stackPrefixes:["stacks/"],allPrefixes:["process/readme-generation"],core:["readme-generation"]}}],ra={stackPrefixes:["stacks/"],allPrefixes:["process/","engineering/practices/"],core:[]};function rb(){let a=[process.env.CONSTELLA_PKG_ROOT,ee(),process.cwd()].filter(Boolean).map(a=>(0,de.join)(a,"skills"));for(let b of a)try{if((0,dd.statSync)(b).isDirectory())return b}catch{}return a[0]??(0,de.join)(ee(),"skills")}function rc(a,b){let c=a.match(RegExp(`^${b}:\\s*(.+)$`,"m"));return c?c[1].trim().replace(/^["']|["']$/g,"").trim():""}let rd=null;function re(){if(rd)return rd;let a=rb(),b=new Map;try{(0,dd.statSync)(a).isDirectory()&&function c(d,e){let f;if(!(e>8)){try{f=(0,dd.readdirSync)(d,{withFileTypes:!0})}catch{return}for(let g of f){let f=(0,de.join)(d,g.name);if(g.isDirectory()){c(f,e+1);continue}if("SKILL.md"!==g.name)continue;let h="";try{h=(0,dd.readFileSync)(f,"utf8")}catch{continue}let i=h.match(/^---\n([\s\S]*?)\n---/),j=i?.[1]??"",k=f.split(/[\\/]/).slice(-2,-1)[0]||rc(j,"name");if(!k||b.has(k))continue;let l=f.slice(a.length).replace(/^[\\/]+/,"").replace(/\\/g,"/");b.set(k,{name:k,relPath:l,description:rc(j,"description")||`${k} skill.`,domain:rc(j,"domain")||l.split("/")[0]||"",category:rc(j,"category")||"",sources:function(a,b){let c=a.match(RegExp(`(?:^|\\n)${b}:\\s*\\n([\\s\\S]*?)(?=\\n\\S|$)`));return c?c[1].split("\n").map(a=>a.match(/^\s*-\s+(.+?)\s*$/)?.[1]?.replace(/^["']|["']$/g,"").trim()).filter(a=>!!a):[]}(j,"official_sources")})}}}(a,0)}catch{}return rd=b,b}function rf(a){return re().get(a)??null}let rg=["clean-code","git-workflow","code-review-practices","refactoring","code-optimization","owasp-top-10","secrets-management","appsec-fundamentals","testing-strategy-pyramid","tdd-and-coverage","unit-integration-e2e","ui-ux-principles","responsive-layout","accessibility-wcag","architecture-before-code","requirements-to-specs","specs-to-issues","testing-before-done","security-by-design","review-code-perf-security","research-official-docs","authoring-agent-skills","readme-generation"];Object.fromEntries([{key:"language",label:"Language",opts:["TypeScript","JavaScript","Python","Go","Rust","Java","Kotlin","C#","Ruby","PHP","Elixir","Swift","C++","C","Scala","Dart","Clojure","Haskell","Lua","R","Objective-C","Erlang","None"]},{key:"runtime",label:"Runtime",opts:["Node.js","Bun","Deno","Python 3","PyPy","JVM",".NET","BEAM (Erlang VM)","None"]},{key:"frontend",label:"Frontend",opts:["React","Vue","Svelte","Angular","SolidJS","Preact","Qwik","Lit","HTMX","Alpine.js","Ember","Backbone","HTML/CSS","Vanilla JS","None"]},{key:"meta",label:"Meta-framework / SSG",opts:["Next.js","Nuxt","Remix","SvelteKit","Astro","Gatsby","Vite (SPA)","Hugo","Jekyll","Eleventy","Docusaurus","Static (no framework)","None"]},{key:"backend",label:"Backend framework",opts:["NestJS","Fastify","Express","Hono","Koa","Django","Flask","FastAPI","Spring Boot","Spring","Laravel","Symfony","CodeIgniter","Ruby on Rails","Gin","Fiber","Actix","Phoenix","ASP.NET Core","AdonisJS","GraphQL","Nginx","None"]},{key:"mobile",label:"Mobile",opts:["React Native","Flutter","Android","Ionic","Xamarin","NativeScript","None"]},{key:"database",label:"Database",opts:["PostgreSQL","MySQL","MariaDB","SQLite","MongoDB","Redis","CockroachDB","Cassandra","DynamoDB","Supabase","PlanetScale","Neon","None"]},{key:"orm",label:"ORM / Data layer",opts:["Prisma","Drizzle","TypeORM","Sequelize","SQLAlchemy","Django ORM","Mongoose","Knex","Diesel","GORM","None"]},{key:"styling",label:"Styling / UI",opts:["Tailwind CSS","Plain CSS","CSS Modules","styled-components","Sass","Vanilla Extract","UnoCSS","shadcn/ui","MUI","Bootstrap","Bulma","Vuetify","Chakra UI","None"]},{key:"testing",label:"Testing",opts:["Jest","Vitest","Cypress","Playwright","Selenium","Mocha","Jasmine","Puppeteer","None"]},{key:"aiml",label:"AI / ML",opts:["TensorFlow","PyTorch","scikit-learn","Keras","Pandas","NumPy","Jupyter","None"]},{key:"dataviz",label:"Data viz",opts:["D3","Chart.js","Grafana","Plotly","None"]},{key:"container",label:"Container",opts:["Docker","Podman","containerd","None"]},{key:"infra",label:"Infra / DevOps",opts:["Tailscale","Cloudflare","Vercel","Netlify","Fly.io","Railway","AWS","GCP","Azure","Kubernetes","Jenkins","CircleCI","Terraform","Ansible","Vagrant","None"]},{key:"baas",label:"Backend-as-a-service",opts:["Firebase","Appwrite","Amplify","Heroku","Supabase","None"]},{key:"queue",label:"Queue / Cache",opts:["Redis","BullMQ","RabbitMQ","Kafka","NATS","Celery","None"]},{key:"auth",label:"Auth",opts:["Auth.js","Clerk","Lucia","Supabase Auth","Keycloak","Auth0","Passport","None"]}].map(a=>[a.key,a.label]));let rh=[{handle:"ada",name:"Ada",role:"CEO",color:"#e0a44e",reportsTo:null,model:"sonnet",provider:"cli_claude_code",temperature:.4,dailyCapUsd:15,tier:"critical",identity:"Decisive, outcome-driven leader. Speaks in goals, not tasks. Protects scope and budget.",ritual:"Read the company goals, decompose into epics, delegate to leads, review what shipped."},{handle:"linus",name:"Linus",role:"CTO",color:"#9a5cff",reportsTo:"ada",model:"sonnet",provider:"cli_claude_code",temperature:.3,dailyCapUsd:40,tier:"critical",identity:"Systems thinker. Balances delivery speed against technical debt.",ritual:"Turn epics into tickets, route work to specialists, clear blockers, review PRs."},{handle:"donald",name:"Donald",role:"Product Owner",color:"#4fc9b0",reportsTo:"ada",model:"haiku",provider:"cli_claude_code",temperature:.4,dailyCapUsd:20,tier:"heavy",identity:"Customer voice. Ruthless about priority and clarity.",ritual:"Groom the backlog with MoSCoW, plan the sprint, track delivery, close with a retro."},{handle:"margaret",name:"Margaret",role:"Backend",color:"#3fb98f",reportsTo:"linus",model:"sonnet",provider:"cli_claude_code",temperature:.3,dailyCapUsd:50,tier:"heavy",identity:"Pragmatic server engineer. Values correctness, small diffs and green tests.",ritual:"Pull one ticket, read context, implement on a branch, never push without a passing suite."},{handle:"grace",name:"Grace",role:"Frontend",color:"#5b8def",reportsTo:"linus",model:"sonnet",provider:"cli_claude_code",temperature:.5,dailyCapUsd:45,tier:"heavy",identity:"Craft-focused UI engineer. Cares about accessibility and clean component APIs.",ritual:"Read the design tokens, build the smallest component that works, typecheck before PR."},{handle:"edsger",name:"Edsger",role:"QA",color:"#e8688f",reportsTo:"linus",model:"haiku",provider:"cli_claude_code",temperature:.2,dailyCapUsd:25,tier:"heavy",identity:"Skeptical quality gate. Assumes nothing works until proven by a test.",ritual:"Reproduce, cover with a test, run the suite, then gate the sign-off."},{handle:"werner",name:"Werner",role:"DevOps",color:"#f0a35e",reportsTo:"linus",model:"haiku",provider:"cli_claude_code",temperature:.3,dailyCapUsd:20,tier:"heavy",identity:"Reliability-minded operator. Automates the boring, guards the leases.",ritual:"Build, deploy a preview, report the URL, never leave an env leased too long."},{handle:"barbara",name:"Barbara",role:"Docs",color:"#b3d97a",reportsTo:"ada",model:"haiku",provider:"cli_claude_code",temperature:.4,dailyCapUsd:15,tier:"light",identity:"Patient explainer. Turns changes into understandable docs.",ritual:"Watch merges, draft docs while context is fresh, verify every link."},{handle:"whitfield",name:"Whitfield",role:"CyberSec",color:"#c4a0ff",reportsTo:"linus",model:"opus",provider:"cli_claude_code",temperature:.2,dailyCapUsd:30,tier:"critical",identity:"Adversarial reviewer. Thinks like an attacker, writes like an auditor.",ritual:"Audit every change for secret handling and injection, file findings with a concrete fix."},{handle:"vannevar",name:"Vannevar",role:"Knowledge",color:"#7ac5e0",reportsTo:"ada",model:"haiku",provider:"cli_claude_code",temperature:.2,dailyCapUsd:10,tier:"light",identity:"Keeper of the company's semantic memory. Indexes every document AND conversation into embeddings so any agent can recall anything instantly.",ritual:"Keep the embedding server healthy; re-index the workspace docs and the chat (team room, DMs, Telegram) into the RAG index so retrieval stays current."}],ri=[{name:"open-pr",summary:"Branch, commit, open a PR with a test plan and request CTO review.",trigger:"When a work product is ready to merge",steps:["Create a branch from main","Commit the change set","Open a PR with summary + test plan","Request review from the CTO"]},{name:"run-suite",summary:"Detect the package manager, run the test task and gate sign-off on red.",trigger:"Before any sign-off",steps:["Detect package manager","Run the workspace test task","Parse results","Block sign-off if red"]},{name:"secret-scan",summary:"Scan for plaintext keys, verify vault references and flag log leaks.",trigger:"On every adapter change",steps:["Grep for plaintext keys","Check vault references","Flag any echo to logs"]},{name:"telegram-notify",summary:"Format a digest and POST it to the Telegram Bot API.",trigger:"When a routine completes",steps:["Format the digest","Resolve the chat id from secrets","POST to Telegram Bot API"]},{name:"moscow-prioritise",summary:"Score backlog items and re-order them with the MoSCoW method.",trigger:"During backlog grooming",steps:["Score each item","Assign Must/Should/Could/Won't","Re-order the backlog"]},{name:"gguf-validate",summary:"Pull a GGUF, verify SHA-256 and bind to loopback.",trigger:"When installing a local model",steps:["Download the GGUF","Verify SHA-256","Bind to 127.0.0.1 only"]}],rj=ri.filter(a=>"telegram-notify"!==a.name&&"gguf-validate"!==a.name).map(a=>a.name);var rk=c(80733),rl=c(90977),rm=c.n(rl),rn=c(57075),ro=c(46466),rp=c(54410),rq=c(82650),rr=c(26675);async function rs(){return qW.api.getSession({headers:await (0,rq.headers)()})}async function rt(a,b){if(b){let[c]=await ei.select({org:dr}).from(ds).innerJoin(dr,aX(ds.orgId,dr.id)).where(aZ(aX(ds.userId,a),aX(dr.id,b)));if(c)return c.org}let c=await ei.select({org:dr}).from(ds).innerJoin(dr,aX(ds.orgId,dr.id)).where(aX(ds.userId,a));return c[0]?.org??null}async function ru(a){let[b]=await ei.select().from(dt).where(aX(dt.orgId,a));return b??null}async function rv(){let a=await rs();a||(0,rr.redirect)("start"===qR()?"/api/dev-login":"/login"),"1"===process.env.CONSTELLA_FORCE_ONBOARDING&&(0,rr.redirect)("/onboarding");let b=await rt(a.user.id,a.session.activeOrgId);b||(0,rr.redirect)("/onboarding");let c=await ru(b.id);return c||(0,rr.redirect)("/onboarding"),{session:a,org:b,workspace:c}}let rw=process.env.OLLAMA_URL??"http://127.0.0.1:11434",rx=process.env.CONSTELLA_EMBED_MODEL??"nomic-embed-text",ry=/nomic/i.test(rx),rz=(a,b)=>`search_${b}: ${a}`,rA=process.env.CONSTELLA_EMBED_URL??"http://127.0.0.1:8083",rB=[".claude","DOCS","PO","Reports","specs","issues"];function rC(a){let b=a.replace(/\\/g,"/");return!(b.startsWith(".claude/kb/")||b.startsWith(".claude/skills/"))&&(b.startsWith("mock/")?/\.(md|html?|css|jsx?|tsx?|txt|json)$/i.test(b):b.endsWith(".md")&&rB.some(a=>b===`${a}.md`||b.startsWith(`${a}/`)))}async function rD(a,b="document"){try{let c=await fetch(`${rw}/api/embeddings`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:rx,prompt:ry?rz(a,b):a}),signal:AbortSignal.timeout(8e3)});if(c.ok){let a=await c.json();if(Array.isArray(a.embedding)&&a.embedding.length)return a.embedding}}catch{}try{let c=await fetch(`${rA}/v1/embeddings`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({input:rz(a,b),model:"nomic-embed"}),signal:AbortSignal.timeout(8e3)});if(c.ok){let a=await c.json(),b=a?.data?.[0]?.embedding;if(Array.isArray(b)&&b.length)return b}}catch{}return null}function rE(a){let b=a.split(/\n(?=#{1,3}\s)/).map(a=>a.trim()).filter(Boolean),c=[];for(let d of b.length?b:[a])if(d)if(d.length<=1200)c.push(d);else for(let a=0;a<d.length;a+=1200)c.push(d.slice(a,a+1200));return c.slice(0,40)}async function rF(a){let[b]=await ei.select().from(dt).where(aX(dt.orgId,a));if(!b)return{ok:!1,chunks:0,embedded:!1};let c=(function a(b,c=""){let d=[];for(let e of q0(b,c))if(e.isDir){if(q1.has(e.name))continue;d.push(...a(b,e.path))}else d.push(e.path);return d})(a).filter(rC);await ei.delete(d2).where(aX(d2.workspaceId,b.id));let d=0,e=!1;for(let f of c)for(let c of rE(q2(a,f)??"")){let a=await rD(c);a&&(e=!0),await ei.insert(d2).values({id:(0,eL.randomUUID)(),workspaceId:b.id,path:f,chunk:c,vector:a?JSON.stringify(a):null}),d++}return{ok:!0,chunks:d+=await rG(a),embedded:e}}async function rG(a){let[b]=await ei.select().from(dt).where(aX(dt.orgId,a));if(!b)return 0;await ei.delete(d2).where(aZ(aX(d2.workspaceId,b.id),bc(d2.path,"chat/%")));let c=await ei.select().from(dO).where(aX(dO.workspaceId,b.id)).orderBy(bq(dO.createdAt)),d=new Map;for(let a of c){let b=(a.text??"").replace(/\s+/g," ").trim();if(!b)continue;let c="operator"===a.fromKind?"Operator":"@"+(a.fromHandle??"agent"),e=d.get(a.channel);e||(e=[],d.set(a.channel,e)),e.push(`${c}: ${b}`)}let e=0;for(let[a,c]of d)for(let d of rE(c.slice(-400).join("\n"))){let c=await rD(d);await ei.insert(d2).values({id:(0,eL.randomUUID)(),workspaceId:b.id,path:`chat/${a}`,chunk:d,vector:c?JSON.stringify(c):null}),e++}return e}async function rH(a,b){if(!rC(b))return;let[c]=await ei.select().from(dt).where(aX(dt.orgId,a));if(c)for(let d of(await ei.delete(d2).where(aZ(aX(d2.workspaceId,c.id),aX(d2.path,b))),rE(q2(a,b)??""))){let a=await rD(d);await ei.insert(d2).values({id:(0,eL.randomUUID)(),workspaceId:c.id,path:b,chunk:d,vector:a?JSON.stringify(a):null})}}async function rI(a,b){if(!rC(b))return;let[c]=await ei.select().from(dt).where(aX(dt.orgId,a));c&&await ei.delete(d2).where(aZ(aX(d2.workspaceId,c.id),aX(d2.path,b)))}let rJ=new Map;function rK(a,b,c=.02){let d=0;try{d=(0,dd.statSync)(a).size}catch{return{ok:!1,actual:0,expected:b,message:"file missing after download"}}if(!b||b<=0)return{ok:!0,actual:d,expected:b,message:"size ok (no expected size)"};let e=d/b,f=e>=1-c&&e<=1+c;return{ok:f,actual:d,expected:b,message:f?"size verified":`size mismatch — got ${d} bytes, expected ~${b} (truncated/corrupt)`}}let rL=new Map,rM=[{repo:"Qwen2.5-0.5B-Instruct",paramsB:.5,kind:"chat"},{repo:"Qwen2.5-1.5B-Instruct",paramsB:1.5,kind:"chat"},{repo:"Qwen2.5-3B-Instruct",paramsB:3,kind:"chat"},{repo:"Qwen2.5-7B-Instruct",paramsB:7,kind:"chat"},{repo:"Qwen2.5-14B-Instruct",paramsB:14,kind:"chat"},{repo:"Qwen2.5-32B-Instruct",paramsB:32,kind:"chat"},{repo:"Qwen2.5-72B-Instruct",paramsB:72,kind:"chat"},{repo:"Qwen2.5-Coder-1.5B-Instruct",paramsB:1.5,kind:"code"},{repo:"Qwen2.5-Coder-3B-Instruct",paramsB:3,kind:"code"},{repo:"Qwen2.5-Coder-7B-Instruct",paramsB:7,kind:"code"},{repo:"Qwen2.5-Coder-14B-Instruct",paramsB:14,kind:"code"},{repo:"Qwen2.5-Coder-32B-Instruct",paramsB:32,kind:"code"},{repo:"Qwen3-0.6B",paramsB:.6,kind:"chat"},{repo:"Qwen3-1.7B",paramsB:1.7,kind:"chat"},{repo:"Qwen3-4B",paramsB:4,kind:"chat"},{repo:"Qwen3-8B",paramsB:8,kind:"chat"},{repo:"Qwen3-14B",paramsB:14,kind:"chat"},{repo:"Qwen3-32B",paramsB:32,kind:"chat"},{repo:"Llama-3.2-1B-Instruct",paramsB:1,kind:"chat"},{repo:"Llama-3.2-3B-Instruct",paramsB:3,kind:"chat"},{repo:"Meta-Llama-3.1-8B-Instruct",paramsB:8,kind:"chat"},{repo:"Meta-Llama-3.1-70B-Instruct",paramsB:70,kind:"chat"},{repo:"Llama-3.3-70B-Instruct",paramsB:70,kind:"chat"},{repo:"gemma-2-2b-it",paramsB:2,kind:"chat"},{repo:"gemma-2-9b-it",paramsB:9,kind:"chat"},{repo:"gemma-2-27b-it",paramsB:27,kind:"chat"},{repo:"gemma-3-1b-it",paramsB:1,kind:"chat"},{repo:"gemma-3-4b-it",paramsB:4,kind:"chat"},{repo:"gemma-3-12b-it",paramsB:12,kind:"chat"},{repo:"gemma-3-27b-it",paramsB:27,kind:"chat"},{repo:"Mistral-7B-Instruct-v0.3",paramsB:7,kind:"chat"},{repo:"Mistral-Nemo-Instruct-2407",paramsB:12,kind:"chat"},{repo:"Mistral-Small-Instruct-2409",paramsB:22,kind:"chat"},{repo:"Mistral-Small-24B-Instruct-2501",paramsB:24,kind:"chat"},{repo:"Codestral-22B-v0.1",paramsB:22,kind:"code"},{repo:"Phi-3.1-mini-4k-instruct",paramsB:3.8,kind:"chat"},{repo:"DeepSeek-R1-Distill-Qwen-1.5B",paramsB:1.5,kind:"reasoning"},{repo:"DeepSeek-R1-Distill-Qwen-7B",paramsB:7,kind:"reasoning"},{repo:"DeepSeek-R1-Distill-Qwen-14B",paramsB:14,kind:"reasoning"},{repo:"DeepSeek-R1-Distill-Qwen-32B",paramsB:32,kind:"reasoning"},{repo:"DeepSeek-R1-Distill-Llama-8B",paramsB:8,kind:"reasoning"},{repo:"DeepSeek-Coder-V2-Lite-Instruct",paramsB:16,kind:"code"},{repo:"Yi-1.5-9B-Chat",paramsB:9,kind:"chat"},{repo:"Yi-1.5-34B-Chat",paramsB:34,kind:"chat"},{repo:"granite-3.0-8b-instruct",paramsB:8,kind:"chat"},{repo:"granite-3.1-8b-instruct",paramsB:8,kind:"chat"},{repo:"SmolLM2-360M-Instruct",paramsB:.36,kind:"chat"},{repo:"SmolLM2-1.7B-Instruct",paramsB:1.7,kind:"chat"},{repo:"aya-expanse-8b",paramsB:8,kind:"chat"},{repo:"aya-expanse-32b",paramsB:32,kind:"chat"},{repo:"Falcon3-7B-Instruct",paramsB:7,kind:"chat"},{repo:"Falcon3-10B-Instruct",paramsB:10,kind:"chat"},{repo:"EXAONE-3.5-2.4B-Instruct",paramsB:2.4,kind:"chat"},{repo:"EXAONE-3.5-7.8B-Instruct",paramsB:7.8,kind:"chat"},{repo:"Qwen3.5-0.8B",paramsB:.8,kind:"chat"},{repo:"Qwen3.5-2B",paramsB:2,kind:"chat"},{repo:"Qwen3.5-9B",paramsB:9,kind:"chat"},{repo:"Qwen3.5-27B",paramsB:27,kind:"chat"},{repo:"Qwen3.5-35B-A3B",paramsB:35,kind:"chat"},{repo:"Qwen3.6-27B",paramsB:27,kind:"chat"},{repo:"Qwen3.6-35B-A3B",paramsB:35,kind:"chat"},{repo:"Qwen3-30B-A3B",paramsB:30,kind:"chat"},{repo:"Qwen3-30B-A3B-Instruct-2507",paramsB:30,kind:"chat"},{repo:"Qwen3-Next-80B-A3B-Instruct",paramsB:80,kind:"chat"},{repo:"Qwen3-4B-Thinking-2507",paramsB:4,kind:"reasoning"},{repo:"QwQ-32B",paramsB:32,kind:"reasoning"},{repo:"Qwen2.5-7B-Instruct-1M",paramsB:7,kind:"chat"},{repo:"Qwen2.5-Coder-0.5B-Instruct",paramsB:.5,kind:"code"},{repo:"Qwen2.5-Coder-3B",paramsB:3,kind:"code"},{repo:"Qwen2.5-Coder-32B",paramsB:32,kind:"code"},{repo:"Qwen2.5-Math-7B-Instruct",paramsB:7,kind:"chat"},{repo:"Qwen2-500M-Instruct",paramsB:.5,kind:"chat"},{repo:"Qwen1.5-32B-Chat",paramsB:32,kind:"chat"},{repo:"gemma-4-E2B-it",paramsB:2,kind:"chat"},{repo:"gemma-4-E4B-it",paramsB:4,kind:"chat"},{repo:"gemma-4-12B-it",paramsB:12,kind:"chat"},{repo:"gemma-4-26B-A4B-it",paramsB:26,kind:"chat"},{repo:"gemma-4-31B-it",paramsB:31,kind:"chat"},{repo:"gemma-3-270m-it",paramsB:.27,kind:"chat"},{repo:"gemma-1.1-2b-it",paramsB:2,kind:"chat"},{repo:"codegemma-2b",paramsB:2,kind:"code"},{repo:"codegemma-7b",paramsB:7,kind:"code"},{repo:"codegemma-7b-it",paramsB:7,kind:"code"},{repo:"codegemma-1.1-7b-it",paramsB:7,kind:"code"},{repo:"Ministral-3-3B-Instruct-2512",paramsB:3,kind:"chat"},{repo:"Ministral-3-8B-Instruct-2512",paramsB:8,kind:"chat"},{repo:"Ministral-3-14B-Instruct-2512",paramsB:14,kind:"chat"},{repo:"Ministral-3-3B-Reasoning-2512",paramsB:3,kind:"reasoning"},{repo:"Ministral-3-8B-Reasoning-2512",paramsB:8,kind:"reasoning"},{repo:"Ministral-3-14B-Reasoning-2512",paramsB:14,kind:"reasoning"},{repo:"Mistral-Small-3.1-24B-Instruct-2503",paramsB:24,kind:"chat"},{repo:"Mistral-Small-3.2-24B-Instruct-2506",paramsB:24,kind:"chat"},{repo:"Devstral-Small-2-24B-Instruct-2512",paramsB:24,kind:"code"},{repo:"mathstral-7B-v0.1",paramsB:7,kind:"chat"},{repo:"dolphin-2.8-mistral-7b-v02",paramsB:7,kind:"chat"},{repo:"WizardLM-2-7B",paramsB:7,kind:"chat"},{repo:"DeepSeek-R1-0528-Qwen3-8B",paramsB:8,kind:"reasoning"},{repo:"DeepSeek-R1-Distill-Llama-70B",paramsB:70,kind:"reasoning"},{repo:"deepseek-coder-1.3B-kexer",paramsB:1.3,kind:"code"},{repo:"deepseek-coder-6.7B-kexer",paramsB:6.7,kind:"code"},{repo:"granite-3.2-8b-instruct",paramsB:8,kind:"chat"},{repo:"granite-4.1-3b",paramsB:3,kind:"chat"},{repo:"granite-4.1-8b",paramsB:8,kind:"chat"},{repo:"granite-4.1-30b",paramsB:30,kind:"chat"},{repo:"Olmo-3-32B-Think",paramsB:32,kind:"reasoning"},{repo:"Seed-OSS-36B-Instruct",paramsB:36,kind:"chat"},{repo:"ERNIE-4.5-21B-A3B-PT",paramsB:21,kind:"chat"},{repo:"LFM2-24B-A2B",paramsB:24,kind:"chat"},{repo:"LFM2.5-1.2B-Instruct",paramsB:1.2,kind:"chat"},{repo:"LFM2.5-1.2B-Thinking",paramsB:1.2,kind:"reasoning"},{repo:"NVIDIA-Nemotron-3-Nano-4B",paramsB:4,kind:"chat"},{repo:"Hermes-4-70B",paramsB:70,kind:"chat"},{repo:"Llama-3.1-Tulu-3-8B",paramsB:8,kind:"chat"},{repo:"Meta-Llama-3-70B-Instruct",paramsB:70,kind:"chat"},{repo:"Llama3-ChatQA-1.5-70B",paramsB:70,kind:"chat"},{repo:"Llama-3-Groq-8B-Tool-Use",paramsB:8,kind:"chat"},{repo:"aya-23-8B",paramsB:8,kind:"chat"},{repo:"aya-23-35B",paramsB:35,kind:"chat"},{repo:"SmolLM2-135M-Instruct",paramsB:.135,kind:"chat"},{repo:"Yi-Coder-1.5B",paramsB:1.5,kind:"code"},{repo:"Yi-Coder-9B-Chat",paramsB:9,kind:"code"},{repo:"OpenCoder-1.5B-Instruct",paramsB:1.5,kind:"code"},{repo:"stable-code-instruct-3b",paramsB:3,kind:"code"},{repo:"internlm2-math-plus-7b",paramsB:7,kind:"chat"},{repo:"internlm2-math-plus-20b",paramsB:20,kind:"chat"}],rN={Q3_K_L:.55,Q4_K_M:.67,Q6_K:.9,Q8_0:1.13},rO=[{id:"nomic-embed-q8",name:"nomic-embed-text-v1.5 (Q8_0)",url:"https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/resolve/main/nomic-embed-text-v1.5.Q8_0.gguf",params:"137M",quant:"Q8_0",sizeBytes:146e6,kind:"embed",paramsB:.137},...function(){let a=[];for(let d of rM){var b,c;let e=d.vendor??"lmstudio-community";for(let f of(b=d.paramsB)<=9?["Q3_K_L","Q4_K_M","Q6_K","Q8_0"]:b<=34?["Q3_K_L","Q4_K_M","Q6_K"]:["Q3_K_L","Q4_K_M"]){let b=`${d.repo}-${f}.gguf`;a.push({id:`${d.repo}-${f}`.toLowerCase().replace(/[^a-z0-9]+/g,"-"),name:`${d.repo} (${f})`,url:`https://huggingface.co/${e}/${d.repo}-GGUF/resolve/main/${b}`,params:(c=d.paramsB)<1?`${Math.round(1e3*c)}M`:`${c}B`,quant:f,sizeBytes:Math.round(1e9*d.paramsB*rN[f]),kind:d.kind,paramsB:d.paramsB})}}return a}()];var rP=c(20177);let rQ=process.env.OLLAMA_URL??"http://127.0.0.1:11434",rR=process.env.LLAMACPP_URL??"http://127.0.0.1:8082",rS=process.env.CONSTELLA_EMBED_URL??"http://127.0.0.1:8083",rT=null;async function rU(){if(rT){let a=p_().totalmem()/0x40000000,b=p_().freemem()/0x40000000;return{...rT,ram:`${a.toFixed(0)} GB \xb7 ${b.toFixed(1)} free`}}let a=p_().cpus(),b=(a[0]?.model??"Unknown CPU").replace(/\s+/g," ").trim(),c=a.length,d=p_().totalmem()/0x40000000,e=p_().freemem()/0x40000000,f=`${d.toFixed(0)} GB \xb7 ${e.toFixed(1)} free`,g=p_().platform(),h="—",i="—",j="CPU",k=[];try{let a=(0,qX.execSync)("nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits",{timeout:4e3,stdio:["ignore","pipe","ignore"]}).toString().trim();if(a){let[b,c]=a.split("\n")[0].split(",");h=b.trim(),i=`${Math.round(Number(c)/1024)} GB`,j="CUDA",k.push("CUDA")}}catch{}if("CPU"===j&&"darwin"===g){j="Metal",k.push("Metal");let a="Apple Silicon";try{let b=(0,qX.execFileSync)("sysctl",["-n","machdep.cpu.brand_string"],{timeout:3e3,stdio:["ignore","pipe","ignore"]}).toString().trim();b&&(a=b)}catch{/apple/i.test(b)&&(a=b)}h=/apple/i.test(a)?`${a} GPU`:"Apple GPU","arm64"===p_().arch()&&(i=`${Math.max(1,Math.round(.7*d))} GB unified`)}k.push("arm64"===p_().arch()?"NEON":"AVX2");let l="—";try{if("win32"===g){let a=(qY()[0]||"C").toUpperCase(),b=/^[A-Z]$/.test(a)?a:"C",c=(0,qX.execFileSync)("powershell",["-NoProfile","-Command",`(Get-PSDrive ${b}).Free`],{timeout:5e3,stdio:["ignore","pipe","ignore"]}).toString().trim(),d=Number(c.replace(/[^\d]/g,""));d>0&&(l=`${(d/0x40000000).toFixed(0)} GB`)}else{let a=(0,qX.execFileSync)("df",["-h",qY()],{timeout:4e3,stdio:["ignore","pipe","ignore"]}).toString().trim().split("\n"),b=(a[a.length-1]??"").split(/\s+/);b[3]&&(l=b[3])}}catch{}return rT={cpu:b,cores:c,ram:f,gpu:h,vram:i,diskFree:l,backend:j,accel:k,recommendedQuant:d>=32?"Q5_K_M":d>=16?"Q4_K_M":"Q4_0",maxParams:d>=64?"70B":d>=32?"34B":d>=16?"13B":"7B"}}async function rV(){try{return(0,qX.execSync)("ollama --version",{timeout:3e3,stdio:"ignore"}),!0}catch{return!1}}async function rW(a){let b=await rV(),c=[];if("start"===a){if(!b)return{up:!1,installed:!1,log:["Ollama is not installed — get it at https://ollama.com, then retry."]};if((await rZ()).up)return{up:!0,installed:b,log:[`server already running on ${rQ}`]};try{let a=(0,qX.spawn)("ollama",["serve"],{detached:!0,stdio:"ignore"}),d="";a.on("error",a=>{d=String(a instanceof Error?a.message:a)}),a.unref(),c.push("$ ollama serve"),await new Promise(a=>setTimeout(a,2e3));let e=(await rZ()).up;return d&&c.push("spawn failed: "+d),c.push(e?`✓ ready \xb7 ${rQ}`:"still stopped — the port may be busy; run `ollama serve` in a terminal to see the error."),(0,rp.revalidatePath)("/models"),{up:e,installed:b,log:c}}catch(a){return{up:!1,installed:b,log:["failed to start: "+String(a instanceof Error?a.message:a)]}}}try{"win32"===p_().platform()?(0,qX.execSync)("taskkill /IM ollama.exe /F",{stdio:"ignore",timeout:4e3}):(0,qX.execSync)("pkill -f 'ollama serve'",{stdio:"ignore",timeout:4e3}),c.push("server stopped")}catch{c.push("no running ollama process found")}return(0,rp.revalidatePath)("/models"),{up:!1,installed:b,log:c}}async function rX(){try{let a=await fetch(`${rQ}/api/ps`,{signal:AbortSignal.timeout(3e3)});if(!a.ok)return{running:[]};return{running:((await a.json()).models??[]).map(a=>({name:a.name,vram:a.size_vram??0}))}}catch{return{running:[]}}}async function rY(a){try{let b=await fetch(`${rQ}/api/generate`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:a,prompt:"",keep_alive:"30m"}),signal:AbortSignal.timeout(12e4)});if(!b.ok)return{ok:!1,error:`Ollama ${b.status}`};return await b.json().catch(()=>({})),(0,rp.revalidatePath)("/models"),{ok:!0}}catch(b){let a=String(b instanceof Error?b.message:b);return{ok:!1,error:/abort|fetch failed|ECONN/i.test(a)?"Ollama not running":a}}}async function rZ(){try{let a=await fetch(`${rQ}/api/tags`,{signal:AbortSignal.timeout(3e3)});if(!a.ok)return{up:!1,models:[]};let b=await a.json();return{up:!0,models:(b.models??[]).map(a=>({name:a.name,size:a.size??0}))}}catch{return{up:!1,models:[]}}}async function r$(a){let b=await rZ(),[c]=await ei.select().from(dy).where(aZ(aX(dy.workspaceId,a),aX(dy.catalogId,"ollama"))),d={status:b.up?"connected":"needs_sync",modelCount:b.models.length,lastSync:b.up?new Date:null};c?await ei.update(dy).set(d).where(aX(dy.id,c.id)):await ei.insert(dy).values({id:(0,eL.randomUUID)(),workspaceId:a,catalogId:"ollama",adapter:"local_ollama",kind:"local",auth:"local",syncStatus:"implemented",...d})}async function r_(a){let{workspace:b}=await rv();if(!a.trim())return{ok:!1,error:"no model name"};try{let c=await fetch(`${rQ}/api/pull`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:a.trim(),stream:!1}),signal:AbortSignal.timeout(18e5)});if(!c.ok){let a=await c.text().catch(()=>"");return{ok:!1,error:`Ollama ${c.status}${a?": "+a.slice(0,120):""}`}}let d=await c.json().catch(()=>({}));return await r$(b.id),(0,rp.revalidatePath)("/models"),{ok:"success"===d.status||null==d.error,error:d.error}}catch(b){let a=String(b instanceof Error?b.message:b);return{ok:!1,error:/abort|fetch failed|ECONN/i.test(a)?"Ollama not running — start it, then retry.":a}}}async function r0(a){let{workspace:b}=await rv();try{await fetch(`${rQ}/api/delete`,{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({name:a})})}catch{}return await r$(b.id),(0,rp.revalidatePath)("/models"),{ok:!0}}async function r1(a){let{workspace:b}=await rv(),c=rO.find(b=>b.id===a);if(!c)return{ok:!1,error:"unknown model"};let d=(0,de.join)(qY(),"models");(0,dd.mkdirSync)(d,{recursive:!0});let e=function(a){try{if("win32"===p_().platform()){let b=(a[0]||"C").toUpperCase(),c=/^[A-Z]$/.test(b)?b:"C",d=(0,qX.execFileSync)("powershell",["-NoProfile","-Command",`(Get-PSDrive ${c}).Free`],{timeout:6e3,stdio:["ignore","pipe","ignore"]}).toString().trim();return Number(d.replace(/[^\d]/g,""))||0}let b=(0,qX.execFileSync)("df",["-k",a],{timeout:5e3,stdio:["ignore","pipe","ignore"]}).toString().trim().split("\n"),c=(b[b.length-1]??"").split(/\s+/),d=Number(c[3]);return d?1024*d:0}catch{return 0}}(d);if(e&&c.sizeBytes&&e<1.1*c.sizeBytes)return{ok:!1,error:`not enough free space — need ~${(c.sizeBytes/1e9).toFixed(1)} GB, ${(e/1e9).toFixed(1)} GB free`};let f=c.url.split("/").pop()??`${c.id}.gguf`,g=(0,de.join)(d,f);rL.set(a,{received:0,total:0,done:!1});try{if(!(0,dd.existsSync)(g)){let b=await fetch(c.url,{signal:AbortSignal.timeout(36e5)});if(!b.ok||!b.body)return rL.set(a,{received:0,total:0,done:!0,error:`download failed (${b.status})`}),{ok:!1,error:`download failed (${b.status})`};let d=Number(b.headers.get("content-length"))||c.sizeBytes||0,e=0;rL.set(a,{received:0,total:d,done:!1});let f=new rn.PassThrough;f.on("data",b=>{e+=b.length;let c=rL.get(a);c&&(c.received=e)}),await (0,ro.pipeline)(rn.Readable.fromWeb(b.body),f,(0,dd.createWriteStream)(g));let h=rK(g,d);if(!h.ok){try{(0,dd.rmSync)(g)}catch{}return rL.set(a,{received:e,total:d,done:!0,error:h.message}),{ok:!1,error:h.message}}}if((rL.set(a,{received:1,total:1,done:!0}),c.sha256)&&await new Promise((a,b)=>{let c=(0,eL.createHash)("sha256");(0,dd.createReadStream)(g).on("data",a=>c.update(a)).on("end",()=>a(c.digest("hex"))).on("error",b)})!==c.sha256)return{ok:!1,error:"SHA-256 mismatch — file corrupt"};let d=(0,dd.statSync)(g).size,[e]=await ei.select().from(dB).where(aX(dB.file,g));return e||await ei.insert(dB).values({id:(0,eL.randomUUID)(),workspaceId:b.id,name:c.name,file:g,quant:c.quant,params:c.params,sizeBytes:d,sha256:c.sha256??"",bind:"127.0.0.1:8082"}),/embed|nomic|bge|mxbai|gte/i.test(c.name)&&sh().catch(()=>{}),(0,rp.revalidatePath)("/models"),{ok:!0,path:g}}catch(d){let b=String(d instanceof Error?d.message:d),c=rL.get(a);return rL.set(a,{received:c?.received??0,total:c?.total??0,done:!0,error:b}),{ok:!1,error:b}}}async function r2(a){return rL.get(a)??null}async function r3(a){await rv();let[b]=await ei.select().from(dB).where(aX(dB.id,a));if(!b)return{ok:!1,error:"model not found"};try{b.file&&(0,dd.existsSync)(b.file)&&(0,dd.rmSync)(b.file,{force:!0})}catch{}return await ei.delete(dB).where(aX(dB.file,b.file)),(0,rp.revalidatePath)("/models"),{ok:!0}}function r4(){return(0,de.join)(qY(),"bin","llama")}function r5(){try{let a=(0,de.join)(r4(),"INSTALLED");if(!(0,dd.existsSync)(a))return null;let b=(0,dd.readFileSync)(a,"utf8").trim();return b&&(0,dd.existsSync)(b)?b:null}catch{return null}}async function r6(a,b,c,d){let e=/\.(tar\.gz|tgz)$/i.test(b),f=(0,de.join)(c,b.replace(/[^\w.\-]+/g,"_"));(0,dd.mkdirSync)(c,{recursive:!0});let g=await fetch(a,{signal:AbortSignal.timeout(18e5)});if(!g.ok||!g.body)return d&&rL.set(d,{received:0,total:0,done:!0,error:`download failed (${g.status})`}),`download failed (${g.status})`;let h=Number(g.headers.get("content-length"))||0,i=rn.Readable.fromWeb(g.body);if(d){let a=0;rL.set(d,{received:0,total:h,done:!1});let b=new rn.PassThrough;b.on("data",b=>{a+=b.length;let c=rL.get(d);c&&(c.received=a)}),await (0,ro.pipeline)(i,b,(0,dd.createWriteStream)(f))}else await (0,ro.pipeline)(i,(0,dd.createWriteStream)(f));let j=rK(f,h);if(!j.ok){try{(0,dd.rmSync)(f)}catch{}return j.message}e?(0,qX.execFileSync)("tar",["-xzf",f,"-C",c],{stdio:"ignore",timeout:12e4}):new(rm())(f).extractAllTo(c,!0);try{(0,dd.rmSync)(f)}catch{}return null}async function r7(){try{let a=await fetch("https://api.github.com/repos/ggml-org/llama.cpp/releases/latest",{headers:{"User-Agent":"constella",Accept:"application/vnd.github+json"},signal:AbortSignal.timeout(15e3)});if(!a.ok)return null;return(await a.json()).assets??[]}catch{return null}}let r8=!1;async function r9(a=!1){let b;if("win32"!==p_().platform())return{ok:!0,fetched:!1};let c=r4();try{b=(0,dd.readdirSync)(c)}catch{return{ok:!1,fetched:!1,reason:"no llama dir"}}let d=b.some(a=>/^ggml-cuda\.dll$/i.test(a)),e=b.some(a=>/^cudart64_\d+\.dll$/i.test(a));if(!d||e)return{ok:e||!d,fetched:!1};if(r8&&!a)return{ok:!1,fetched:!1,reason:"already attempted this run"};r8=!0;let f="12";try{let a=(0,dd.readFileSync)((0,de.join)(c,"ggml-cuda.dll")).toString("latin1").match(/cudart64_(\d+)\.dll/i);a&&(f=a[1])}catch{}let g=await r7();if(!g)return{ok:!1,fetched:!1,reason:"GitHub unreachable"};let h=g.filter(a=>/cudart/i.test(a.name)&&/x64|amd64/i.test(a.name)),i=h.find(a=>RegExp(`cuda-${f}\\.`,"i").test(a.name))??h[0];if(!i)return{ok:!1,fetched:!1,reason:"no cudart asset in the latest release"};let j=await r6(i.browser_download_url,i.name,c).catch(a=>String(a instanceof Error?a.message:a));if(j)return{ok:!1,fetched:!1,reason:j};let k=!1;try{k=(0,dd.readdirSync)(c).some(a=>/^cudart64_\d+\.dll$/i.test(a))}catch{}return{ok:k,fetched:k}}async function sa(){let a;await rv();let b=[];if(r5()||await sb()){let a=await r9(!0).catch(()=>null);return{ok:!0,installed:!0,log:["llama-server already installed.",...a?.fetched?["✓ fetched the CUDA runtime DLLs — GPU enabled."]:a&&!a.ok?[`⚠ CUDA runtime still missing (${a.reason??"unknown"}).`]:[]]}}let c=await rU(),d=/cuda|nvidia/i.test(c.backend)||(c.accel??[]).some(a=>/cuda|nvidia/i.test(a));b.push(`platform ${p_().platform()}/${p_().arch()} \xb7 backend ${c.backend} → ${d?"CUDA":"CPU"} build`);try{let c=await fetch("https://api.github.com/repos/ggml-org/llama.cpp/releases/latest",{headers:{"User-Agent":"constella",Accept:"application/vnd.github+json"},signal:AbortSignal.timeout(15e3)});if(!c.ok)return{ok:!1,installed:!1,log:b,error:403===c.status?"GitHub API rate-limited — try again later or install manually from the releases page.":`GitHub releases API ${c.status}`};a=(await c.json()).assets??[]}catch(a){return{ok:!1,installed:!1,log:b,error:"couldn't reach GitHub: "+String(a instanceof Error?a.message:a)}}let e=function(a,b){let c=p_().platform(),d="win32"===c?/win/i:"darwin"===c?/macos/i:/(ubuntu|linux)/i,e="arm64"===p_().arch(),f=a.filter(a=>/\.(zip|tar\.gz|tgz)$/i.test(a.name)&&d.test(a.name));e||(f=f.filter(a=>!/arm64|aarch64/i.test(a.name)));let g=/cuda|hip|vulkan|sycl|kompute|musa|cann|adreno/i,h=a=>{if(!a.length)return null;let b=e?a.filter(a=>/arm64|aarch64/i.test(a.name)):a.filter(a=>/x64|amd64/i.test(a.name)),c=(b.length?b:a).sort((a,b)=>a.name.length-b.name.length)[0];return c?{name:c.name,url:c.browser_download_url}:null};if(b){let a=f.filter(a=>/cuda/i.test(a.name));if(a.length)return h(a)}let i=f.filter(a=>!g.test(a.name));return h(i.length?i:f)}(a,!!d);if(!e)return{ok:!1,installed:!1,log:b,error:"no matching prebuilt for this platform — install manually from the releases page."};b.push(`downloading ${e.name}…`);let f=r4();(0,dd.mkdirSync)(f,{recursive:!0}),rL.set("llama-server",{received:0,total:0,done:!1});try{let a=await r6(e.url,e.name,f,"llama-server");if(a)return rL.set("llama-server",{received:0,total:0,done:!0,error:a}),{ok:!1,installed:!1,log:b,error:a};if(d){let a=await r9(!0);b.push(a.ok?a.fetched?"✓ CUDA runtime DLLs installed — GPU enabled.":"CUDA runtime already present.":`⚠ CUDA runtime not installed (${a.reason??"unknown"}) — runs on CPU; retries on next Start/Install.`)}}catch(a){return{ok:!1,installed:!1,log:b,error:"download/extract failed: "+String(a instanceof Error?a.message:a)}}let g=function a(b,c,d){let e;if(d<0)return null;try{e=(0,dd.readdirSync)(b,{withFileTypes:!0})}catch{return null}for(let a of e)if(a.isFile()&&a.name===c)return(0,de.join)(b,a.name);for(let f of e)if(f.isDirectory()){let e=a((0,de.join)(b,f.name),c,d-1);if(e)return e}return null}(f,"win32"===p_().platform()?"llama-server.exe":"llama-server",5);if(!g)return{ok:!1,installed:!1,log:b,error:"downloaded, but llama-server wasn't found in the archive."};if("win32"!==p_().platform())try{(0,dd.chmodSync)(g,493)}catch{}return(0,dd.writeFileSync)((0,de.join)(f,"INSTALLED"),g,"utf8"),rL.set("llama-server",{received:1,total:1,done:!0}),b.push(`✓ installed → ${g}`),await sm().catch(()=>{}),(0,rp.revalidatePath)("/models"),{ok:!0,installed:!0,path:g,log:b}}async function sb(){if(r5())return!0;try{return(0,qX.execSync)("llama-server --version",{timeout:3e3,stdio:"ignore"}),!0}catch{return!1}}async function sc(){try{let a=await fetch(`${rR}/v1/models`,{signal:AbortSignal.timeout(2500)});if(!a.ok)return{up:!1,model:null};let b=await a.json(),c=b.data?.[0]?.id;return{up:!0,model:c?c.split(/[\\/]/).pop()??c:null}}catch{return{up:!1,model:null}}}async function sd(a){try{var b;let c,d=await rU();if(!/cuda|metal/i.test(d.backend))return[];let e=(b=d.vram,(c=/([\d.]+)\s*GB/i.exec(b||""))?1e9*parseFloat(c[1]):0);if(a&&e&&1.15*a>e)return[];return["-ngl","99"]}catch{return[]}}function se(){try{let a=ei.select({file:dB.file,name:dB.name}).from(dB).all().find(a=>/embed|nomic|bge|mxbai|gte/i.test(a.name)&&a.file&&(0,dd.existsSync)(a.file));return a?{file:a.file,name:a.name}:null}catch{return null}}function sf(){try{let a=ei.select({file:dB.file,name:dB.name,sizeBytes:dB.sizeBytes}).from(dB).all().find(a=>!/embed|nomic|bge|mxbai|gte/i.test(a.name)&&a.file&&(0,dd.existsSync)(a.file));return a?{file:a.file,name:a.name,sizeBytes:a.sizeBytes}:null}catch{return null}}async function sg(){try{return(await fetch(`${rS}/health`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function sh(){if(await sg())return{up:!0};let a=r5();if(!a)return{up:!1,reason:"llama-server not installed"};let b=se();if(!b)return{up:!1,reason:"no embedding model installed (download nomic-embed-text)"};try{await r9().catch(()=>{});let c=await sd(),d=(0,qX.spawn)(a,["-m",b.file,"--embeddings","--host","127.0.0.1","--port","8083","-c","2048","--pooling","mean",...c],{detached:!0,stdio:"ignore"});d.on("error",()=>{}),d.unref()}catch(a){return{up:!1,reason:"spawn failed: "+String(a instanceof Error?a.message:a)}}for(let a=0;a<24;a++)if(await new Promise(a=>setTimeout(a,500)),await sg())return{up:!0,model:b.name};return{up:!1,reason:"embedding server didn't come up in time"}}async function si(){if((await sc()).up)return{up:!0};let a=r5();if(!a)return{up:!1,reason:"llama-server not installed"};let b=sf();if(!b)return{up:!1,reason:"no chat GGUF installed"};try{await r9().catch(()=>{});let c=await sd(b.sizeBytes),d=(0,qX.spawn)(a,["-m",b.file,"--host","127.0.0.1","--port","8082","-c","4096",...c],{detached:!0,stdio:"ignore"});d.on("error",()=>{}),d.unref()}catch(a){return{up:!1,reason:"spawn failed: "+String(a instanceof Error?a.message:a)}}for(let a=0;a<24;a++)if(await new Promise(a=>setTimeout(a,500)),(await sc()).up)return{up:!0,model:b.name};return{up:!1,reason:"llama server didn't come up in time"}}async function sj(){let a=se();return{up:await sg(),model:a?.name??null,installed:!!a}}async function sk(){let a=await sh();return(0,rp.revalidatePath)("/models"),a}async function sl(){let{org:a}=await rv();await sh().catch(()=>{});let b=await rF(a.id);return(0,rp.revalidatePath)("/models"),b}async function sm(){let{workspace:a}=await rv(),b=await sc(),c=new Set((await ei.select({file:dB.file}).from(dB)).map(a=>a.file)).size,d={status:b.up?"connected":"needs_sync",modelCount:c,lastSync:b.up?new Date:null},[e]=await ei.select().from(dy).where(aZ(aX(dy.workspaceId,a.id),aX(dy.catalogId,"llamacpp")));return e?await ei.update(dy).set(d).where(aX(dy.id,e.id)):await ei.insert(dy).values({id:(0,eL.randomUUID)(),workspaceId:a.id,catalogId:"llamacpp",adapter:"local_llamacpp",kind:"local",auth:"local",syncStatus:"implemented",...d}),(0,rp.revalidatePath)("/models"),{ok:!0}}async function sn(a){let b;await rv();let c=await sb(),d=[];if(!c)return{up:!1,installed:!1,log:["llama-server not found — install llama.cpp from https://github.com/ggml-org/llama.cpp/releases (or `brew install llama.cpp`), then retry."]};if((await sc()).up)return{up:!0,installed:c,log:[`server already running on ${rR}`]};let e=0;if(a){let d,[f]=await ei.select().from(dB).where(aX(dB.id,a));if(f&&(d=f.name,/embed|nomic|bge|mxbai|gte/i.test(d))){let a=await sh();return{up:a.up,installed:c,log:[`${f.name} is an EMBEDDING model — started the RAG embedding server on :8083 (it can't power chat on :8082).`,a.up?`✓ embeddings ready \xb7 ${rS}`:`embeddings: ${a.reason??"failed to start"}`]}}b=f?.file,e=f?.sizeBytes??0}if(!b){let a=sf();b=a?.file,e=a?.sizeBytes??0}if(!b||!(0,dd.existsSync)(b)){let a=se();if(a){let b=await sh();return{up:!1,installed:c,log:[`Your only local model (${a.name}) is an EMBEDDING model — it powers RAG on the embeddings server (${rS}), not the chat server.`,b.up?"✓ embeddings server is running.":`embeddings: ${b.reason??"not started"}`,"Download a chat/instruct GGUF (e.g. Qwen, Llama) below to run the chat server on :8082."]}}return{up:!1,installed:c,log:["no GGUF model on disk — download one below first."]}}try{let a=r5()??"llama-server";await r9().catch(()=>{});let f=await sd(e),g=(0,qX.spawn)(a,["-m",b,"--host","127.0.0.1","--port","8082","-c","4096",...f],{detached:!0,stdio:"ignore"}),h="";g.on("error",a=>{h=String(a instanceof Error?a.message:a)}),g.unref(),d.push(`$ llama-server -m ${b.split(/[\\/]/).pop()} --port 8082${f.length?" -ngl 99 (GPU)":" (CPU)"}`);let i=!1;for(let a=0;a<12&&!i;a++)await new Promise(a=>setTimeout(a,1e3)),i=(await sc()).up;return h&&d.push("spawn failed: "+h),d.push(i?`✓ ready \xb7 ${rR}`:"still starting — large models take longer; run llama-server in a terminal to see progress."),await sm(),(0,rp.revalidatePath)("/models"),{up:i,installed:c,log:d}}catch(a){return{up:!1,installed:c,log:["failed to start: "+String(a instanceof Error?a.message:a)]}}}async function so(){let a=await sb(),b=[];try{"win32"===p_().platform()?(0,qX.execSync)("taskkill /IM llama-server.exe /F",{stdio:"ignore",timeout:4e3}):(0,qX.execSync)("pkill -f llama-server",{stdio:"ignore",timeout:4e3}),b.push("server stopped")}catch{b.push("no running llama-server process found")}return await sm(),(0,rp.revalidatePath)("/models"),{up:!1,installed:a,log:b}}(0,rP.D)([rU,rV,rW,rX,rY,rZ,r_,r0,r1,r2,r3,sa,sb,sc,sg,sh,si,sj,sk,sl,sm,sn,so]),(0,rk.A)(rU,"000911a332ed4e8c11185b59a924359e4a0f6c390d",null),(0,rk.A)(rV,"00bae47d888f4b3bf4c9a20f29c31510a0cbc92fad",null),(0,rk.A)(rW,"409ceb256bb4d7cdf0bdc9bf3eb07ed3e593b50ee7",null),(0,rk.A)(rX,"005af7b0b6152b36052f976ee5872cabdcb0601110",null),(0,rk.A)(rY,"40759d10169a9e1ce2ce147d6e907961a78c56c919",null),(0,rk.A)(rZ,"0089ffbe108a72b6a822fca7c02bf50eeb3e707d16",null),(0,rk.A)(r_,"40eda67e3953ca06a8de7e1e89ce192f8f3f845c2c",null),(0,rk.A)(r0,"40396805f615607165c344c07c5a16fc0b680f8f5e",null),(0,rk.A)(r1,"409c7634f3d98b4f9b9b11d9f1b06f129f8ee477da",null),(0,rk.A)(r2,"40124108057342c612c2f357a7e8190a76aeca2758",null),(0,rk.A)(r3,"40542ac1b1eca7bab158a31b48910ebdfae0c41136",null),(0,rk.A)(sa,"00d4d2587dceadf689c62e230f0fade2ff16d91a98",null),(0,rk.A)(sb,"00e318bbd05ffdc87e3b0e7289a07686109da77f01",null),(0,rk.A)(sc,"00952f0a7cb615f33b4b79eb7a467467281a5af3fe",null),(0,rk.A)(sg,"00f24a176e753da0c54b460d5733d3d22e2eda478a",null),(0,rk.A)(sh,"00510f5a6050a4b0ade51541d5d9e16ec0f020a374",null),(0,rk.A)(si,"008f263120259e54c66f16a365a0252bf2fc3c4a90",null),(0,rk.A)(sj,"00246beed3841520b6281529abd4b518e33fe5e86f",null),(0,rk.A)(sk,"0012006a55cfe2592f83591f9000342265af6934bc",null),(0,rk.A)(sl,"00533b64ea6f4a2acbd0745ed94cae49abc4cad513",null),(0,rk.A)(sm,"00d8163946f7329359c5b20bbbf7009692d192bcf0",null),(0,rk.A)(sn,"4087db27a0971eec3d866e787e2fdc1e5469606ebc",null),(0,rk.A)(so,"0017cc8a4ad40128920f52b25416e9396cee2630a7",null);let sp="win32"===process.platform;process.env.CONSTELLA_RUN_MODE,null!=process.env.CONSTELLA_AGENT_FULL_ACCESS&&process.env.CONSTELLA_AGENT_FULL_ACCESS;let sq=new Map,sr=new Set;function ss(a,b,c,d,e,f,g,h=sp){return new Promise(i=>{let j=Date.now(),k=(0,qX.spawn)(a,b,{cwd:d,shell:h,windowsHide:!0,env:f??process.env});!function(a,b){if(a){if(sr.has(a)){sr.delete(a);try{b.kill("SIGKILL")}catch{}return}sq.set(a,b)}}(g,k);let l="",m="",n=!1,o=()=>{g&&(sq.delete(g),sr.delete(g))},p=setTimeout(()=>{n=!0;try{k.kill("SIGKILL")}catch{}},e);k.stdout.on("data",a=>l+=a.toString()),k.stderr.on("data",a=>m+=a.toString()),k.on("error",a=>{clearTimeout(p),o(),i({code:-1,stdout:l,stderr:m+String(a),durationMs:Date.now()-j,timedOut:n})}),k.on("close",a=>{clearTimeout(p),o(),i({code:a,stdout:l,stderr:m,durationMs:Date.now()-j,timedOut:n})}),c&&k.stdin.write(c),k.stdin.end()})}async function st(a){try{if("opencode"===a){let a=await ss("opencode",["models"],"",process.cwd(),2e4);if(0!==a.code)return[];return a.stdout.split("\n").map(a=>a.trim()).filter(a=>/^[\w.-]+\/[\w./:-]+$/.test(a)).slice(0,200)}if("aider"===a){let a=await ss("aider",["--list-models","/"],"",process.cwd(),25e3);if(0!==a.code)return[];return a.stdout.split("\n").map(a=>a.replace(/^[-*\s]+/,"").trim()).filter(a=>/^[\w.-]+\/[\w./:-]+$/.test(a)).slice(0,200)}}catch{}return[]}async function su(a){let b=await ss(a,["--version"],"",process.cwd(),15e3);return 0!==b.code?null:(b.stdout||b.stderr).trim().split("\n")[0]||"ok"}async function sv(a){let b=(0,p$.homedir)(),c=(...a)=>a.some(a=>(0,dd.existsSync)((0,de.join)(b,a)));try{switch(a){case"claude":return c(".claude/.credentials.json",".claude.json",".config/claude")?"ready":"needs_login";case"codex":return c(".codex/auth.json",".codex")?"ready":"needs_login";case"aider":return process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.DEEPSEEK_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY||process.env.GROQ_API_KEY?"ready":"needs_login";case"opencode":{let a=await ss("opencode",["auth","list"],"",process.cwd(),8e3);if(0===a.code&&/\w/.test(a.stdout)&&!/\b(no|none|not)\b.*(auth|provider|credential|logged)/i.test(a.stdout))return"ready";return c(".local/share/opencode/auth.json",".config/opencode")?"ready":"needs_login"}case"copilot":return c(".config/github-copilot/apps.json",".config/github-copilot",".copilot")?"ready":"needs_login";case"cursor-agent":return c(".config/cursor-agent",".cursor-agent",".cursor")?"ready":"needs_login";case"openclaw":return c(".openclaw",".config/openclaw")?"ready":"unknown";case"hermes":return c(".hermes",".config/hermes")?"ready":"unknown";case"cline":return c(".cline",".config/cline")?"ready":"unknown";case"kilocode":return c(".kilocode",".config/kilocode")?"ready":"unknown"}}catch{}return"unknown"}let sw={cli_claude_code:["opus","sonnet","haiku"],cli_codex:["gpt-5-codex","o4-mini"],cli_openclaw:["(default)","openai/gpt-5.4","anthropic/claude-sonnet-4"],cli_hermes:["(default)","anthropic/claude-sonnet-4.6","openai/gpt-5.5"],cli_aider:["(default)","anthropic/claude-sonnet-4-6","openai/gpt-5.2","deepseek/deepseek-chat"],cli_opencode:["(default)","anthropic/claude-sonnet-4-6","openai/gpt-5.2"],cli_copilot:["(default)","claude-sonnet-4.5","gpt-5"],cli_cursor:["(default)","claude-4.5-sonnet","gpt-5"],cli_cline:["(default)"],cli_kilo:["(default)"]};function sx(a,b){if("cli_codex"===a||"cli_codex_cli"===a)return"codex";if("cli_openclaw"===a)return"openclaw";if("cli_hermes"===a)return"hermes";if("cli_aider"===a)return"aider";if("cli_opencode"===a)return"opencode";if("cli_copilot"===a||"cli_copilot_cli"===a)return"copilot";if("cli_cursor"===a||"cli_cursor_cli"===a)return"cursor-agent";if("cli_cline"===a||"cli_cline_cli"===a)return"cline";if("cli_kilo"===a||"cli_kilo_code"===a)return"kilocode";if("cli_claude_code"===a)return"claude";let c=(b??"").toLowerCase();return c.startsWith("codex")||c.startsWith("gpt")||c.startsWith("o1")||c.startsWith("o3")||c.startsWith("o4")?"codex":"claude"}let sy={anthropic:"anthropic",openai:"openai",google_gemini:"google",xai_grok:"xai",deepseek:"deepseek",cohere:"cohere",groq:"groq",nvidia_nim:"nvidia",together:"togetherai",fireworks:"fireworks-ai",cerebras:"cerebras",perplexity:"perplexity",openrouter:"openrouter",mistral:"mistral",moonshot:"moonshotai",dashscope:"alibaba",zhipu:"zhipuai",azure_openai:"azure",aws_bedrock:"amazon-bedrock",vertex_ai:"google-vertex",claude_code:"anthropic",gemini_cli:"google"};function sz(a){return sy[a]?sy[a]:a.replace(/_(grok|gemini|nim|cli|openai|api|server|rt)$/g,"").replace(/_/g,"-")}let sA={anthropic:["sonnet-4","sonnet","opus-4","opus"],openai:["gpt-5.2","gpt-5.1","gpt-5","gpt-4.1","o4"],google:["gemini-3-pro","gemini-3","gemini-2.5-pro","pro"],xai:["grok-4","grok-3","grok"],groq:["llama-4","llama-3.3","llama-3.1"],deepseek:["deepseek-chat","deepseek-v3","deepseek-reasoner"],mistral:["mistral-large","mistral-medium"],openrouter:["claude-sonnet","gpt-5","gemini"]},sB=(a,b,c,d,e,f,g,h)=>({id:a,name:b,context:c,outputLimit:d,inputCost:e,outputCost:f,caps:{reasoning:!!g.reasoning,tools:!!g.tools,vision:!!g.vision},released:h}),sC={anthropic:[sB("claude-opus-4-8","Claude Opus 4.8",1e6,64e3,5,25,{reasoning:!0,tools:!0,vision:!0},"2026-02-01"),sB("claude-opus-4-7","Claude Opus 4.7",1e6,64e3,5,25,{reasoning:!0,tools:!0,vision:!0},"2025-12-01"),sB("claude-sonnet-4-6","Claude Sonnet 4.6",1e6,64e3,3,15,{reasoning:!0,tools:!0,vision:!0},"2026-01-15"),sB("claude-haiku-4-5","Claude Haiku 4.5",2e5,32e3,1,5,{tools:!0,vision:!0},"2025-10-01")],openai:[sB("gpt-5.2","GPT-5.2",4e5,128e3,1.25,10,{reasoning:!0,tools:!0,vision:!0},"2026-03-01"),sB("gpt-5.1","GPT-5.1",4e5,128e3,1.25,10,{reasoning:!0,tools:!0,vision:!0},"2025-12-01"),sB("gpt-5","GPT-5",4e5,128e3,1.25,10,{reasoning:!0,tools:!0,vision:!0},"2025-08-01"),sB("o4-mini","o4-mini",2e5,1e5,1.1,4.4,{reasoning:!0,tools:!0},"2025-04-01")],google:[sB("gemini-3-pro","Gemini 3 Pro",2e6,64e3,2,12,{reasoning:!0,tools:!0,vision:!0},"2026-02-01"),sB("gemini-3-flash","Gemini 3 Flash",1e6,64e3,.3,2.5,{tools:!0,vision:!0},"2026-02-01"),sB("gemini-2.5-pro","Gemini 2.5 Pro",2e6,64e3,1.25,10,{reasoning:!0,tools:!0,vision:!0},"2025-06-01")],xai:[sB("grok-4.3","Grok 4.3",256e3,64e3,3,15,{reasoning:!0,tools:!0,vision:!0},"2026-02-01"),sB("grok-4","Grok 4",256e3,64e3,3,15,{reasoning:!0,tools:!0,vision:!0},"2025-09-01"),sB("grok-3","Grok 3",131072,32e3,3,15,{tools:!0,vision:!0},"2025-02-01")],deepseek:[sB("deepseek-chat","DeepSeek Chat",128e3,8e3,.27,1.1,{tools:!0},"2025-12-01"),sB("deepseek-reasoner","DeepSeek Reasoner",128e3,64e3,.55,2.19,{reasoning:!0,tools:!0},"2025-12-01")],groq:[sB("llama-4-scout","Llama 4 Scout",131072,8e3,.11,.34,{tools:!0,vision:!0},"2025-04-01"),sB("llama-3.3-70b","Llama 3.3 70B",131072,32e3,.59,.79,{tools:!0},"2024-12-01")]},sD=null;function sE(){return(0,de.join)(qY(),"cache","models-dev.json")}async function sF(){try{let a=await fetch("https://models.dev/api.json",{signal:AbortSignal.timeout(1e4),headers:{accept:"application/json"}});if(!a.ok)return null;let b=await a.json();if(!b||"object"!=typeof b)return null;let c={};for(let[a,d]of Object.entries(b)){let b=d?.models,e=function(a){if(!a||"object"!=typeof a)return[];let b=[];for(let[c,d]of Object.entries(a)){let a=d??{},e=String(a.id??c),f=e.includes("/")?e.split("/").pop():e;if(!f)continue;let g=a.modalities??{},h=Array.isArray(g.input)?g.input:[],i=a.limit??{},j=a.cost??{},k={reasoning:!0===a.reasoning,tools:!0===a.tool_call,vision:!0===a.attachment||h.includes("image")};b.push({id:f,name:String(a.name??f),context:Number(i.context??0)||0,outputLimit:Number(i.output??0)||0,inputCost:Number(j.input??0)||0,outputCost:Number(j.output??0)||0,caps:k,released:"string"==typeof a.release_date?a.release_date:""})}return b}(b);e.length&&(c[a]=e)}return Object.keys(c).length?c:null}catch{return null}}async function sG(){if(sD&&Date.now()-sD.at<864e5)return sD.data;let a=function(){try{let a=sE();if(!(0,dd.existsSync)(a))return null;let b=JSON.parse((0,dd.readFileSync)(a,"utf8"));if(!b?.data||"object"!=typeof b.data)return null;return{at:Number(b.at??(0,dd.statSync)(a).mtimeMs),data:b.data}}catch{return null}}();if(a&&Date.now()-a.at<864e5)return sD=a,a.data;let b=await sF();if(b){sD={at:Date.now(),data:b};try{(0,dd.mkdirSync)((0,de.join)(qY(),"cache"),{recursive:!0}),(0,dd.writeFileSync)(sE(),JSON.stringify({at:Date.now(),data:b}),"utf8")}catch{}return b}return a?(sD=a,a.data):{}}async function sH(){return Object.keys(await sG()).length}async function sI(a){let b=sz(a),c=await sG();return c[b]?.length?c[b]:sC[b]??[]}async function sJ(a,b,c=9e3){try{let d=await fetch(a,{headers:b,signal:AbortSignal.timeout(c)});if(!d.ok)return null;return await d.json()}catch{return null}}async function sK(a){let{catalogId:b,adapter:c,baseUrl:d,apiKey:e}=a;if(c.startsWith("cli_"))return"cli_opencode"===c?(await st("opencode")).map(a=>({id:a})):"cli_aider"===c?(await st("aider")).map(a=>({id:a})):null;if(/ollama/i.test(b)||c.includes("ollama")){let a=(d||"http://127.0.0.1:11434").replace(/\/$/,"").replace(/\/v1$/,""),b=await sJ(`${a}/api/tags`,{});return b?(b.models??[]).map(a=>({id:String(a.name??"")})).filter(a=>a.id):[]}if(!d)return null;let f=d.replace(/\/$/,""),g="http_anthropic"===c||"anthropic"===b,h=g?"https://api.anthropic.com/v1/models":f.endsWith("/models")?f:f+(f.includes("/v1")?"/models":"/v1/models"),i=g?e?{"x-api-key":e,"anthropic-version":"2023-06-01"}:{}:e?{authorization:`Bearer ${e}`}:{},j=await sJ(h,i);return j?(Array.isArray(j.data)?j.data:Array.isArray(j.models)?j.models:[]).map(a=>{let b=String(a.id??a.name??"");if(!b)return null;let c={id:b};"string"==typeof a.display_name?c.name=a.display_name:"string"==typeof a.name&&(c.name=a.name),"number"==typeof a.context_length&&(c.context=a.context_length);let d=a.pricing;if(d){let a=Number(d.prompt),b=Number(d.completion);Number.isFinite(a)&&a>0&&(c.inputCost=1e6*a),Number.isFinite(b)&&b>0&&(c.outputCost=1e6*b)}return c}).filter(a=>!!a).slice(0,200):[]}async function sL(){let a=await sG(),b=new Map;for(let c of Object.values(a))for(let a of c){let c=a.id.toLowerCase();b.has(c)||b.set(c,a)}return b}async function sM(a,b){let c=await sI(a);if(!b||0===b.length)return c;let d=new Map;for(let a of c)d.set(a.id.toLowerCase(),a);let e=await sL(),f=a=>{let b=a.toLowerCase(),c=a.includes("/")?a.split("/").pop().toLowerCase():b;return d.get(b)??d.get(c)??e.get(b)??e.get(c)},g=[];for(let a of b){let b=f(a.id);g.push({id:a.id,name:a.name||b?.name||a.id,context:a.context??b?.context??0,outputLimit:b?.outputLimit??0,inputCost:a.inputCost??b?.inputCost??0,outputCost:a.outputCost??b?.outputCost??0,caps:b?.caps??{reasoning:!1,tools:!1,vision:!1},released:b?.released??""})}return g}function sN(){let a=process.env.CONSTELLA_VAULT_KEY;if(!a)throw Error("CONSTELLA_VAULT_KEY is not set");let b=Buffer.from(a,"base64");if(32!==b.length)throw Error("CONSTELLA_VAULT_KEY must decode to 32 bytes");return b}async function sO(a,b,c,d){let e=(0,eL.randomBytes)(12),f=(0,eL.createCipheriv)("aes-256-gcm",sN(),e),g=Buffer.concat([f.update(c,"utf8"),f.final()]),h=f.getAuthTag(),i=Buffer.concat([g,h]).toString("base64");await ei.delete(dz).where(aZ(aX(dz.workspaceId,a),aX(dz.ref,b))),await ei.insert(dz).values({id:(0,eL.randomUUID)(),workspaceId:a,providerId:d,ref:b,ciphertext:i,iv:e.toString("base64")})}async function sP(a,b){let[c]=await ei.select().from(dz).where(aZ(aX(dz.workspaceId,a),aX(dz.ref,b)));if(!c)return null;let d=Buffer.from(c.ciphertext,"base64"),e=d.subarray(d.length-16),f=d.subarray(0,d.length-16),g=(0,eL.createDecipheriv)("aes-256-gcm",sN(),Buffer.from(c.iv,"base64"));return g.setAuthTag(e),Buffer.concat([g.update(f),g.final()]).toString("utf8")}async function sQ(a,b){await ei.delete(dz).where(aZ(aX(dz.workspaceId,a),aX(dz.ref,b)))}let sR=Object.fromEntries([{id:"anthropic",displayName:"Anthropic",category:"cloud_api",connectionTypes:["api_key","oauth"],defaultAdapter:"http_anthropic",baseUrl:"https://api.anthropic.com",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"available",notes:"Claude family. Model list mapped from provider capabilities."},{id:"openai",displayName:"OpenAI",category:"cloud_api",connectionTypes:["api_key","oauth"],defaultAdapter:"http_openai",baseUrl:"https://api.openai.com/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"available",notes:"GPT-4o/o-series + DALL\xb7E + Whisper."},{id:"google_gemini",displayName:"Google AI / Gemini",category:"cloud_api",connectionTypes:["api_key","oauth"],defaultAdapter:"http_google",baseUrl:"https://generativelanguage.googleapis.com",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"available",notes:"Gemini 1.5/2.x via AI Studio API key."},{id:"xai_grok",displayName:"xAI / Grok",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_xai",baseUrl:"https://api.x.ai/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"available",notes:"OpenAI-compatible REST. Grok-2/3."},{id:"deepseek",displayName:"DeepSeek",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_deepseek",baseUrl:"https://api.deepseek.com",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"deepseek-chat / deepseek-reasoner."},{id:"cohere",displayName:"Cohere",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_cohere",baseUrl:"https://api.cohere.com/v2",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"Command R/R+ and strong rerank/embeddings."},{id:"ai21",displayName:"AI21",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_ai21",baseUrl:"https://api.ai21.com/studio/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"perplexity",displayName:"Perplexity",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_perplexity",baseUrl:"https://api.perplexity.ai",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"available"},{id:"groq",displayName:"Groq",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_groq",baseUrl:"https://api.groq.com/openai/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"Ultra-low-latency LPU inference, OpenAI-compatible."},{id:"nvidia_nim",displayName:"NVIDIA / NIM",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_nvidia",baseUrl:"https://integrate.api.nvidia.com/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"available",notes:"NIM microservices, OpenAI-compatible."},{id:"together",displayName:"Together AI",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_together",baseUrl:"https://api.together.xyz/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available"},{id:"fireworks",displayName:"Fireworks AI",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_fireworks",baseUrl:"https://api.fireworks.ai/inference/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available"},{id:"cerebras",displayName:"Cerebras",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_cerebras",baseUrl:"https://api.cerebras.ai/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,status:"available",notes:"Wafer-scale fast inference."},{id:"huggingface",displayName:"Hugging Face",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_hf",baseUrl:"https://api-inference.huggingface.co",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"replicate",displayName:"Replicate",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_replicate",baseUrl:"https://api.replicate.com/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"anyscale",displayName:"Anyscale",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_anyscale",baseUrl:"https://api.endpoints.anyscale.com/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"Endpoints product changing — adapter pending."},{id:"databricks",displayName:"Databricks",category:"cloud_api",connectionTypes:["api_key","oauth"],defaultAdapter:"http_databricks",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!0,status:"requires_setup"},{id:"stability",displayName:"Stability AI",category:"image",connectionTypes:["api_key"],defaultAdapter:"http_stability",baseUrl:"https://api.stability.ai",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"elevenlabs",displayName:"ElevenLabs",category:"audio",connectionTypes:["api_key"],defaultAdapter:"http_elevenlabs",baseUrl:"https://api.elevenlabs.io/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,status:"available",notes:"TTS / voice."},{id:"voyage",displayName:"Voyage AI",category:"embedding",connectionTypes:["api_key"],defaultAdapter:"http_voyage",baseUrl:"https://api.voyageai.com/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"available"},{id:"jina",displayName:"Jina AI",category:"embedding",connectionTypes:["api_key"],defaultAdapter:"http_jina",baseUrl:"https://api.jina.ai/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"available"},{id:"runpod",displayName:"RunPod",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_runpod",baseUrl:"https://api.runpod.ai/v2",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"requires_setup"},{id:"lambda",displayName:"Lambda Labs",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_lambda",baseUrl:"https://api.lambdalabs.com/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"modal",displayName:"Modal",category:"cloud_api",connectionTypes:["api_key","custom_endpoint"],defaultAdapter:"http_modal",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"requires_setup"},{id:"baseten",displayName:"Baseten",category:"cloud_api",connectionTypes:["api_key"],defaultAdapter:"http_baseten",baseUrl:"https://inference.baseten.co/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"requires_setup"},{id:"openrouter",displayName:"OpenRouter",category:"router",connectionTypes:["api_key","oauth"],defaultAdapter:"http_openrouter",baseUrl:"https://openrouter.ai/api/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"available",notes:"Aggregates 300+ models across providers — full live list."},{id:"omnirouter",displayName:"OmniRouter",category:"router",connectionTypes:["api_key"],defaultAdapter:"http_omnirouter",baseUrl:"https://api.omnirouter.ai/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,status:"experimental",notes:"OpenAI-compatible multi-provider router."},{id:"litellm",displayName:"LiteLLM",category:"openai_compatible",connectionTypes:["api_key","openai_compatible","custom_endpoint"],defaultAdapter:"http_litellm",baseUrl:"http://localhost:4000",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"Self-hosted proxy; unifies 100+ providers."},{id:"portkey",displayName:"Portkey",category:"router",connectionTypes:["api_key"],defaultAdapter:"http_portkey",baseUrl:"https://api.portkey.ai/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Gateway with virtual keys."},{id:"helicone",displayName:"Helicone",category:"router",connectionTypes:["api_key"],defaultAdapter:"http_helicone",baseUrl:"https://oai.helicone.ai/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"experimental",notes:"Observability proxy in front of OpenAI-compatible providers."},{id:"openai_compatible",displayName:"OpenAI-compatible endpoint",category:"openai_compatible",connectionTypes:["openai_compatible","api_key","custom_endpoint"],defaultAdapter:"http_openai_compat",baseUrl:"https://",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"Any server exposing /v1/chat/completions + /v1/models."},{id:"lmstudio_server",displayName:"LM Studio (OpenAI server)",category:"openai_compatible",connectionTypes:["openai_compatible","local"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:1234/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"available",notes:"Local OpenAI-compatible server from LM Studio."},{id:"ollama_openai",displayName:"Ollama (OpenAI endpoint)",category:"openai_compatible",connectionTypes:["openai_compatible","local"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:11434/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"Ollama's OpenAI-compatible surface."},{id:"vllm_server",displayName:"vLLM (OpenAI server)",category:"openai_compatible",connectionTypes:["openai_compatible","local"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:8000/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"High-throughput self-hosted serving."},{id:"tgi",displayName:"Text Generation Inference",category:"openai_compatible",connectionTypes:["openai_compatible","local","custom_endpoint"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:8080/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"experimental",notes:"HF TGI with OpenAI route."},{id:"localai",displayName:"LocalAI",category:"openai_compatible",connectionTypes:["openai_compatible","local"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:8080/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"available",notes:"Drop-in OpenAI replacement, fully local."},{id:"azure_openai",displayName:"Azure OpenAI",category:"cloud_platform",connectionTypes:["api_key","oauth"],defaultAdapter:"http_azure_openai",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"requires_setup"},{id:"aws_bedrock",displayName:"AWS Bedrock",category:"cloud_platform",connectionTypes:["api_key","custom_endpoint"],defaultAdapter:"sdk_bedrock",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"requires_setup",notes:"SigV4 auth; multi-vendor models."},{id:"vertex_ai",displayName:"Google Vertex AI",category:"cloud_platform",connectionTypes:["oauth","api_key"],defaultAdapter:"sdk_vertex",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!0,supportsVision:!0,supportsTools:!0,status:"requires_setup",notes:"GCP service-account / ADC."},{id:"cloudflare",displayName:"Cloudflare Workers AI",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_cloudflare",baseUrl:"https://api.cloudflare.com/client/v4",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,status:"experimental"},{id:"oci_genai",displayName:"Oracle OCI Generative AI",category:"cloud_platform",connectionTypes:["api_key","custom_endpoint"],defaultAdapter:"sdk_oci",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"OCI SDK signing — adapter pending."},{id:"watsonx",displayName:"IBM watsonx",category:"cloud_platform",connectionTypes:["api_key","oauth"],defaultAdapter:"http_watsonx",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!0,status:"requires_setup"},{id:"dashscope",displayName:"Alibaba DashScope / Qwen",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_dashscope",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"experimental",notes:"Qwen models, OpenAI-compatible mode."},{id:"qianfan",displayName:"Baidu Qianfan",category:"cloud_platform",connectionTypes:["api_key","oauth"],defaultAdapter:"http_qianfan",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!0,status:"planned",notes:"ERNIE; access-token auth — adapter pending."},{id:"hunyuan",displayName:"Tencent Hunyuan",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_hunyuan",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"TC3-HMAC signing — adapter pending."},{id:"zhipu",displayName:"Zhipu AI (GLM)",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_zhipu",baseUrl:"https://open.bigmodel.cn/api/paas/v4",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"experimental"},{id:"moonshot",displayName:"Moonshot AI / Kimi",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_moonshot",baseUrl:"https://api.moonshot.cn/v1",supportsModelSync:!0,supportsApiKey:!0,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"OpenAI-compatible; long context."},{id:"minimax",displayName:"MiniMax",category:"cloud_platform",connectionTypes:["api_key"],defaultAdapter:"http_minimax",baseUrl:"https://api.minimax.chat/v1",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"Group-id + key auth — adapter pending."},{id:"ollama",displayName:"Ollama",category:"local_runtime",connectionTypes:["local","cli"],defaultAdapter:"local_ollama",baseUrl:"http://localhost:11434",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsVision:!0,supportsTools:!0,status:"available",notes:"Pulls + serves local models; live /api/tags list."},{id:"llamacpp",displayName:"llama.cpp",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_llamacpp",baseUrl:"http://127.0.0.1:8082",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"available",notes:"GGUF models, SHA-256 verified, bound to 127.0.0.1."},{id:"lmstudio",displayName:"LM Studio",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_lmstudio",baseUrl:"http://localhost:1234",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsVision:!0,status:"available",notes:"Desktop runtime + local server."},{id:"vllm",displayName:"vLLM",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_vllm",baseUrl:"http://localhost:8000",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"available",notes:"GPU serving engine."},{id:"localai_rt",displayName:"LocalAI",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_localai",baseUrl:"http://localhost:8080",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"available"},{id:"gpt4all",displayName:"GPT4All",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_gpt4all",baseUrl:"http://localhost:4891/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"experimental"},{id:"koboldcpp",displayName:"KoboldCpp",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_kobold",baseUrl:"http://localhost:5001",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,status:"experimental"},{id:"jan",displayName:"Jan",category:"local_runtime",connectionTypes:["local"],defaultAdapter:"local_jan",baseUrl:"http://localhost:1337/v1",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"experimental"},{id:"anythingllm",displayName:"AnythingLLM (local)",category:"local_runtime",connectionTypes:["local","api_key"],defaultAdapter:"local_anythingllm",baseUrl:"http://localhost:3001/api",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"Workspace API — adapter pending."},{id:"openwebui",displayName:"Open WebUI (backend)",category:"local_runtime",connectionTypes:["local","openai_compatible"],defaultAdapter:"http_openai_compat",baseUrl:"http://localhost:3000/api",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"experimental"},{id:"claude_code",displayName:"Claude Code",category:"cli",connectionTypes:["cli","oauth"],defaultAdapter:"cli_claude_code",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!0,supportsTools:!0,status:"available",notes:"Drives the local Claude Code CLI / agent."},{id:"codex_cli",displayName:"Codex CLI",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_codex",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"OpenAI Codex CLI agent."},{id:"openclaw",displayName:"OpenClaw",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_openclaw",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"OpenClaw CLI — headless `openclaw infer model run --json` (provider-routed). No token/cost reported."},{id:"hermes_cli",displayName:"Hermes (Nous Research)",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_hermes",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Hermes agent CLI — headless `hermes -z`. Configure providers via `hermes model`."},{id:"gemini_cli",displayName:"Gemini CLI",category:"cli",connectionTypes:["cli","oauth"],defaultAdapter:"cli_gemini",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!0,supportsTools:!0,status:"experimental"},{id:"aider",displayName:"Aider",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_aider",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Headless `aider --message --yes-always`; provider-routed via its own env keys. Model list from `aider --list-models`. No token/cost reported."},{id:"opencode",displayName:"OpenCode",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_opencode",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Headless `opencode run`; providers via `opencode auth login`. Model list from `opencode models`. No token/cost reported."},{id:"copilot_cli",displayName:"GitHub Copilot CLI",category:"cli",connectionTypes:["cli","oauth"],defaultAdapter:"cli_copilot",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!0,supportsTools:!0,status:"experimental",notes:"Headless `copilot -p --allow-all-tools`; sign in with the Copilot CLI. No token/cost reported."},{id:"cursor_cli",displayName:"Cursor CLI",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_cursor",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Headless `cursor-agent -p --output-format json`; sign in via `cursor-agent login`. `-p` can hang → bounded timeout. No token/cost reported."},{id:"cline_cli",displayName:"Cline CLI",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_cline",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Headless `cline --json -y`; provider-routed via its own config. No token/cost reported."},{id:"kilo_code",displayName:"Kilo Code CLI",category:"cli",connectionTypes:["cli"],defaultAdapter:"cli_kilo",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,supportsTools:!0,status:"experimental",notes:"Headless `kilocode --yes`; provider-routed via its own config. No token/cost reported."},{id:"openai_cli",displayName:"OpenAI CLI",category:"cli",connectionTypes:["cli","api_key"],defaultAdapter:"cli_openai",supportsModelSync:!1,supportsApiKey:!0,supportsOAuth:!1,status:"planned",notes:"Thin CLI over the API — adapter pending."},{id:"ollama_cli",displayName:"Ollama CLI",category:"cli",connectionTypes:["cli","local"],defaultAdapter:"cli_ollama",supportsModelSync:!0,supportsApiKey:!1,supportsOAuth:!1,status:"available",notes:"`ollama run/list` driven."},{id:"custom_cli",displayName:"Custom CLI provider",category:"cli",connectionTypes:["cli","custom_endpoint"],defaultAdapter:"cli_custom",supportsModelSync:!1,supportsApiKey:!1,supportsOAuth:!1,status:"requires_setup",notes:"Define your own command + arg template."}].map(a=>[a.id,a])),sS=a=>sR[a];async function sT(a,b,c=12e3){let d=new AbortController,e=setTimeout(()=>d.abort(),c);try{let c,e=await fetch(a,{headers:b,signal:d.signal}),f=await e.text();try{c=JSON.parse(f)}catch{c=void 0}return{ok:e.ok,status:e.status,json:c,error:e.ok?void 0:f.slice(0,200)||e.statusText}}catch(a){return{ok:!1,status:0,error:a instanceof Error?a.message:String(a)}}finally{clearTimeout(e)}}function sU(a){return a&&"object"==typeof a?Array.isArray(a.data)?a.data.length:Array.isArray(a.models)?a.models.length:0:0}async function sV(a,b){let c=a.defaultAdapter;if(c.startsWith("cli_")){let a=sx(c);return await su(a)?{ok:!0,count:(sw[c]??sw.cli_claude_code).length}:{ok:!1,count:0,error:`${a} CLI not found on PATH`}}if("local_ollama"===c||"ollama"===a.id||"ollama_openai"===a.id){let b=a.baseUrl||"http://127.0.0.1:11434",c=await sT(b.replace(/\/$/,"")+"/api/tags",{});return c.ok?{ok:!0,count:sU(c.json)}:{ok:!1,count:0,error:c.error||"Ollama not reachable at "+b}}if("local_runtime"===a.category){let c=a.baseUrl||"http://127.0.0.1:8080",d=await sT(c.replace(/\/$/,"")+"/v1/models",b?{Authorization:"Bearer "+b}:{});return d.ok?{ok:!0,count:sU(d.json)}:{ok:!1,count:0,error:d.error||"local runtime not reachable"}}if(!b)return{ok:!1,count:0,error:"no API key in vault — connect with a key first"};if("http_anthropic"===c||"anthropic"===a.id){let a=await sT("https://api.anthropic.com/v1/models",{"x-api-key":b,"anthropic-version":"2023-06-01"});return a.ok?{ok:!0,count:sU(a.json)}:{ok:!1,count:0,error:a.error||"auth failed ("+a.status+")"}}let d=(a.baseUrl||"https://api.openai.com/v1").replace(/\/$/,""),e=d.endsWith("/models")?d:d+(d.includes("/v1")?"/models":"/v1/models"),f=await sT(e,{Authorization:"Bearer "+b});return f.ok?{ok:!0,count:sU(f.json)}:{ok:!1,count:0,error:f.error||"auth failed ("+f.status+")"}}async function sW(a,b){let{workspace:c}=await rv(),d=sS(a);if(!d)return;let e=(0,eL.randomUUID)();await ei.insert(dy).values({id:e,workspaceId:c.id,catalogId:a,adapter:d.defaultAdapter,kind:"cli"===d.category?"cli":"local_runtime"===d.category?"local":"cloud",auth:d.connectionTypes.includes("api_key")?"api_key":d.connectionTypes[0],status:"needs_sync",syncStatus:d.supportsModelSync?"implemented":"manual"}),b&&await sO(c.id,`${a}_api_key`,b,e),(0,rp.revalidatePath)("/models"),await sX(e)}async function sX(a){let b,{workspace:c}=await rv(),[d]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,c.id)));if(!d)return{ok:!1,error:"not found"};let e=sS(d.catalogId);if(!e)return{ok:!1,error:"unknown provider"};let f=await sP(c.id,`${d.catalogId}_api_key`),g=await sV(e,f),h=null;if("cli"===e.category){let a=sx(e.defaultAdapter);b=(h=await su(a).catch(()=>null))?await sv(a).catch(()=>"unknown"):"needs_login"}else b="local_runtime"===e.category?g.ok?"ready":"unknown":f&&g.ok?"ready":"needs_key";return await ei.update(dy).set({status:g.ok?"connected":"error",modelCount:g.count,lastSync:new Date,cliVersion:h,authState:b}).where(aX(dy.id,a)),g.ok&&await sY(a).catch(()=>{}),(0,rp.revalidatePath)("/models"),g}async function sY(a){let{workspace:b}=await rv(),[c]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id)));if(!c)return{ok:!1,count:0,error:"not found"};let d=await sZ(c);return(0,rp.revalidatePath)("/models"),d}async function sZ(a){let b,c,d,e=sS(a.catalogId);if(!e)return{ok:!1,count:0,error:"unknown provider"};let f=await sP(a.workspaceId,`${a.catalogId}_api_key`),g="cli"===e.category;try{b=await sK({catalogId:a.catalogId,adapter:a.adapter,baseUrl:e.baseUrl,apiKey:f})}catch{b=null}if(g){let e=sx(a.adapter);d=(c=await su(e).catch(()=>null))?await sv(e).catch(()=>"unknown"):"needs_login",null===b&&(b=(sw[a.adapter]??[]).filter(a=>"(default)"!==a).map(a=>({id:a})))}if(null===b)return{ok:!0,count:0};let h=await sM(a.catalogId,b),i=new Date,j=h.length?function(a,b){if(!b.length)return"";let c=sA[sz(a)];if(c)for(let a of c){let c=b.filter(b=>b.id.toLowerCase().includes(a));if(c.length)return c.sort((a,b)=>(b.released||"").localeCompare(a.released||"")),c[0].id}let d=b.filter(a=>a.released);return d.length?(d.sort((a,b)=>b.released.localeCompare(a.released)),d[0].id):b[0].id}(a.catalogId,h):null;if(h.length)await ei.delete(dA).where(aX(dA.providerId,a.id)),await ei.insert(dA).values(h.map(b=>({id:(0,eL.randomUUID)(),workspaceId:a.workspaceId,providerId:a.id,catalogId:a.catalogId,modelId:b.id,name:b.name,context:b.context,outputLimit:b.outputLimit,inputCost:b.inputCost,outputCost:b.outputCost,caps:b.caps,released:b.released,isDefault:b.id===j,lastSeen:i})));else if(!g)return{ok:!1,count:0,error:"no models returned"};let k=g&&!c?"needs_sync":"connected";return await ei.update(dy).set({status:k,modelCount:h.length||(g?a.modelCount:0),lastSync:i,defaultModel:j||a.defaultModel,...g?{cliVersion:c??null,authState:d??null}:{}}).where(aX(dy.id,a.id)),{ok:!0,count:h.length}}async function s$(a=12){let b,c=new Date(Date.now()-60*a*6e4);try{b=await ei.select().from(dy).where(aZ(aX(dy.status,"connected"),a$(a6(dy.lastSync),a2(dy.lastSync,c))))}catch{return{refreshed:0}}let d=0;for(let a of b.slice(0,50))try{let b=await sZ(a);b.ok&&b.count>0&&d++}catch{}return{refreshed:d}}async function s_(a){let{workspace:b}=await rv(),c=(await ei.select().from(dA).where(aZ(aX(dA.providerId,a),aX(dA.workspaceId,b.id)))).map(a=>({id:a.modelId,name:a.name,context:a.context,outputLimit:a.outputLimit,inputCost:a.inputCost,outputCost:a.outputCost,caps:a.caps??{reasoning:!1,tools:!1,vision:!1},released:a.released,isDefault:a.isDefault}));return c.sort((a,b)=>Number(b.isDefault)-Number(a.isDefault)||(b.released||"").localeCompare(a.released||"")||a.name.localeCompare(b.name)),{models:c}}async function s0(a){let{workspace:b}=await rv(),[c]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id)));if(!c)return{ok:!1,error:"not found"};let d=sS(c.catalogId);if(!d)return{ok:!1,error:"unknown provider"};let e=await sP(b.id,`${c.catalogId}_api_key`),f=await sV(d,e);return await ei.update(dy).set({status:f.ok?"connected":"error"}).where(aX(dy.id,a)),(0,rp.revalidatePath)("/models"),{ok:f.ok,error:f.error}}async function s1(a){let{workspace:b}=await rv(),[c]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id)));if(!c)return{models:[],error:"not found"};let d=sS(c.catalogId);if(!d?.baseUrl)return{models:[],error:"no public endpoint for this provider"};let e=await sP(b.id,`${c.catalogId}_api_key`),f=d.baseUrl.replace(/\/$/,"");try{let a=/ollama/i.test(c.catalogId)||c.adapter.includes("ollama")?`${f.replace(/\/v1$/,"")}/api/tags`:`${f}/models`,b=await fetch(a,{headers:e?{authorization:`Bearer ${e}`}:{},signal:AbortSignal.timeout(8e3)});if(!b.ok)return{models:[],error:`endpoint ${b.status}`};let d=await b.json();return{models:(d.data??d.models??[]).map(a=>a.id??a.name??"").filter(Boolean).slice(0,80)}}catch(b){let a=String(b instanceof Error?b.message:b);return{models:[],error:/abort|fetch failed|ECONN/i.test(a)?"endpoint unreachable":a}}}async function s2(a){let{workspace:b}=await rv(),[c]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id)));c&&await sQ(b.id,`${c.catalogId}_api_key`),await ei.delete(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id))),(0,rp.revalidatePath)("/models")}async function s3(a){let{workspace:b}=await rv(),[c]=await ei.select().from(dy).where(aZ(aX(dy.id,a),aX(dy.workspaceId,b.id)));c&&(await sQ(b.id,`${c.catalogId}_api_key`),await ei.update(dy).set({auth:"none",status:"needs_sync",modelCount:0}).where(aX(dy.id,a)),(0,rp.revalidatePath)("/models"))}function s4(a,b){let c=RegExp(`##\\s+${b}\\s*\\n([\\s\\S]*?)(?:\\n##\\s|$)`,"i");return a.match(c)?.[1].trim()??""}function s5(a){return a.split("\n").find(a=>a.trim()&&!a.startsWith("#")&&!a.startsWith("**")&&!a.startsWith("---")&&!a.startsWith("|"))?.trim()??""}function s6(a,b){let c=a.split("\n").find(a=>a.startsWith("# "));return c?c.slice(2).trim():b}async function s7(a){let[b]=await ei.select().from(dt).where(aX(dt.orgId,a));return b??null}async function s8(a,b,c){let d=q2(b,`.claude/skills/${c}.md`)??"",e=s5(d),f=(d.match(/\*\*Trigger:\*\*\s*(.+)/)?.[1]??"").trim(),g=s4(d,"Procedure")||"",[h]=await ei.select().from(dw).where(aZ(aX(dw.workspaceId,a),aX(dw.name,c)));h?await ei.update(dw).set({summary:e,trigger:f,...g?{instructions:g}:{},indexed:"indexed"}).where(aX(dw.id,h.id)):await ei.insert(dw).values({id:(0,eL.randomUUID)(),workspaceId:a,name:c,summary:e,trigger:f,instructions:g,native:!0,provisional:!1,indexed:"indexed"})}async function s9(a,b,c){let d=q2(b,`.claude/agents/${c}/Agent.md`)??"";if(!d)return;let[e]=await ei.select().from(du).where(aZ(aX(du.workspaceId,a),aX(du.handle,c)));if(!e)return;let f=function(a){let b=a.match(/^---\n([\s\S]*?)\n---/);if(!b)return{};let c={};for(let a of b[1].split("\n")){let b=a.indexOf(":");b>0&&(c[a.slice(0,b).trim()]=a.slice(b+1).trim())}return c}(d),g={identity:(d.match(/\*\*Identity:\*\*\s*(.+)/)?.[1]??"").trim(),ritual:(d.match(/\*\*Ritual:\*\*\s*(.+)/)?.[1]??"").trim(),tone:(d.match(/\*\*Tone:\*\*\s*(.+)/)?.[1]??"").trim()||(e.persona?.tone??""),systemPrompt:s4(d,"System prompt")},h={...f.provider?{adapter:f.provider}:{},...f.model?{model:f.model}:{},...f.temperature?{temperature:parseFloat(f.temperature)}:{},...f.dailyCapUsd?{dailyCapUsd:parseFloat(f.dailyCapUsd)}:{},...f.tierFloor?{tierFloor:f.tierFloor}:{},...f.reportsTo&&"null"!==f.reportsTo?{reportsTo:f.reportsTo}:{},persona:g};for(let d of(await ei.update(du).set(h).where(aX(du.id,e.id)),[...(q2(b,`.claude/agents/${c}/skills.md`)??"").matchAll(/`([a-z0-9-]+)`/g)].map(a=>a[1]))){let[b]=await ei.select().from(dw).where(aZ(aX(dw.workspaceId,a),aX(dw.name,d)));b&&await ei.insert(dx).values({agentId:e.id,skillId:b.id}).onConflictDoNothing()}}async function ta(a,b,c){let d=c.split("/").pop()??c;if("README.md"===d)return;let e=q2(b,c)??"",f=s6(e,d),[g]=await ei.select().from(dJ).where(aZ(aX(dJ.workspaceId,a),aX(dJ.title,f)));g?await ei.update(dJ).set({body:e}).where(aX(dJ.id,g.id)):await ei.insert(dJ).values({id:(0,eL.randomUUID)(),workspaceId:a,title:f,type:"Report",body:e})}async function tb(a,b,c,d){let e=q2(b,c)??"",f=s6(e,c.split("/").pop()??c),g=s5(e),[h]=await ei.select().from(d3).where(aZ(aX(d3.workspaceId,a),aX(d3.path,c)));h?await ei.update(d3).set({title:f,summary:g,updatedAt:new Date}).where(aX(d3.id,h.id)):await ei.insert(d3).values({id:(0,eL.randomUUID)(),workspaceId:a,kind:d,path:c,title:f,summary:g})}function tc(a){(a.startsWith(".claude/skills")||a.endsWith("/skills.md"))&&(0,rp.revalidatePath)("/skills"),a.startsWith(".claude/agents")&&(0,rp.revalidatePath)("/agents/[handle]","page"),a.startsWith("DOCS")&&(0,rp.revalidatePath)("/docs"),a.startsWith("PO")&&(0,rp.revalidatePath)("/pm"),a.startsWith("Reports")&&(0,rp.revalidatePath)("/reports"),(0,rp.revalidatePath)("/code")}async function td(a,b,c=!0){let d,e=await s7(a);if(!e)return{ok:!1};let f=e.id;if(!function(a,b){if(!rC(b))return;let c=a+"::"+b,d=rJ.get(c);d&&clearTimeout(d),rJ.set(c,setTimeout(()=>{rJ.delete(c),rH(a,b).catch(()=>{})},2500))}(a,b),d=b.match(/^\.claude\/skills\/(.+)\.md$/))await s8(f,a,d[1]);else if(d=b.match(/^\.claude\/agents\/([^/]+)\/(?:Agent|skills)\.md$/))await s9(f,a,d[1]);else if(/^Reports\/.+\.md$/.test(b))await ta(f,a,b);else if(/^DOCS\/.+\.md$/.test(b))await tb(f,a,b,"docs");else{if(!/^PO\/.+\.md$/.test(b))return{ok:!0};await tb(f,a,b,"po")}return c&&tc(b),{ok:!0}}async function te(a,b){let c,d=await s7(a);if(!d)return{ok:!1};let e=d.id;return rI(a,b).catch(()=>{}),(c=b.match(/^\.claude\/skills\/(.+)\.md$/))?await ei.delete(dw).where(aZ(aX(dw.workspaceId,e),aX(dw.name,c[1]))):/^(?:DOCS|PO)\/.+\.md$/.test(b)&&await ei.delete(d3).where(aZ(aX(d3.workspaceId,e),aX(d3.path,b))),tc(b),{ok:!0}}async function tf(a=!0){let{org:b}=await rv(),c=b.id;for(let a of q0(c,".claude/skills"))!a.isDir&&a.name.endsWith(".md")&&await td(c,a.path,!1);for(let a of q0(c,".claude/agents"))a.isDir&&await td(c,`${a.path}/Agent.md`,!1);for(let a of["DOCS","PO","Reports"])for(let b of q0(c,a))!b.isDir&&b.name.endsWith(".md")&&await td(c,b.path,!1);return a&&(0,rp.revalidatePath)("/","layout"),{ok:!0}}(0,rP.D)([sW,sX,sY,s$,s_,s0,s1,s2,s3]),(0,rk.A)(sW,"60f2d99bd9913d5d38a04def28f7e3fcb2a6d6ea8d",null),(0,rk.A)(sX,"40285308ac1222140508a12c926b094a13a3fe4023",null),(0,rk.A)(sY,"4054ef53cfe8c42d237d6c4072286918b65ab3e258",null),(0,rk.A)(s$,"40adb9c8c106cd10e05e3e78b577df1ee50362fe34",null),(0,rk.A)(s_,"40c857bef8925fda0db0221187e910447a78f6a41b",null),(0,rk.A)(s0,"4039a15603d07697017218712584fc555a221e81e0",null),(0,rk.A)(s1,"40ee21fca8f6bf3d5064941aecdadd7a30a1b5e2ff",null),(0,rk.A)(s2,"4038cc68b3a0991c0653c28a722bbd191c10103e5f",null),(0,rk.A)(s3,"404fc69338d752357a7ecd696abe48f74584fbfa1e",null),(0,rP.D)([td,te,tf]),(0,rk.A)(td,"70a46437d24a869b795096850f1c425b6a005ed18d",null),(0,rk.A)(te,"6093a9352b08d51ca6703d0f62ffba3775e442c3d4",null),(0,rk.A)(tf,"401995b3fc3b6a1a216db6da852e8c4f490c594646",null),c(27912);let tg=`You are Vannevar, the Knowledge agent — Constella's CENTRAL SOURCE OF TRUTH. You own the Knowledge Base (KB): a curated, classified, state-aware layer over the semantic RAG index.
|
|
487
|
+
|
|
488
|
+
## What the KB is for
|
|
489
|
+
Agents must not leave reusable knowledge scattered in chat. When anything important is created, changed, discovered, reviewed or completed, it is captured into a typed kb_entry, deduped, lifecycle-tracked (active → superseded → obsolete → archived), embedded, and made retrievable. You keep it organised, current and trustworthy.
|
|
490
|
+
|
|
491
|
+
## Where each kind of knowledge lives (taxonomy → kb_entry.type)
|
|
492
|
+
- decision — technical/architectural decisions and their rationale.
|
|
493
|
+
- spec / issue / goal / plan — the work artifacts and their intent.
|
|
494
|
+
- architecture — system structure, boundaries, data flow.
|
|
495
|
+
- business-rule — product/domain rules that constrain implementation.
|
|
496
|
+
- code-change — what a task produced (files touched + summary).
|
|
497
|
+
- dependency / integration — libraries, services, external systems and how they connect.
|
|
498
|
+
- bug / fix — defects found and the corrections applied.
|
|
499
|
+
- test — test runs and their verdicts.
|
|
500
|
+
- review — code-review outcomes; vuln — security findings and risks.
|
|
501
|
+
- doc — documentation written or updated.
|
|
502
|
+
- user-context — what the operator/user wants, their constraints and preferences.
|
|
503
|
+
- history — milestones and important project history (deliveries, pivots).
|
|
504
|
+
- command — useful executed commands / runbook steps.
|
|
505
|
+
- file-structure — where things live in the workspace.
|
|
506
|
+
- ui-pattern — UI/UX conventions to keep consistent.
|
|
507
|
+
- stack — the official technology stack.
|
|
508
|
+
- env-config — environment and configuration facts.
|
|
509
|
+
Classify every entry by organisation, workspace, goal, spec, issue, task, agent, module and file where known.
|
|
510
|
+
|
|
511
|
+
## Ingestion (when knowledge comes in)
|
|
512
|
+
1. Receive the new information. 2. Identify its type. 3. Classify it by goal/spec/issue/module/file/agent. 4. Check for duplicates (same content or same source). 5. Decide: new, an update, a replacement, or obsolete. 6. Write a tight technical summary. 7. Keep a reference to the original source. 8. Generate/refresh embeddings. 9. Update the RAG index. 10. Make it available to every agent.
|
|
513
|
+
|
|
514
|
+
## Curation (keep it true)
|
|
515
|
+
- Merge near-duplicates into one canonical entry; mark the rest superseded.
|
|
516
|
+
- When new knowledge contradicts old, the newest active truth wins; mark the old obsolete.
|
|
517
|
+
- Never present knowledge from a cancelled/archived/done goal as current without saying so.
|
|
518
|
+
- Surface coverage GAPS: modules with code but no knowledge, claims with no source.
|
|
519
|
+
|
|
520
|
+
## Answering a query (when an agent or the operator asks)
|
|
521
|
+
1. Understand the intent. 2. Search the KB/RAG and the structured sources. 3. Filter out obsolete, cancelled and archived knowledge. 4. Prefer the most recent, active, confident facts. 5. Answer objectively and briefly. 6. ALWAYS include internal references (goal, spec, issue, file, decision, plan). 7. If there isn't enough to answer, say so plainly — do not guess.
|
|
522
|
+
|
|
523
|
+
You are authoritative but honest: cite where each fact comes from, and flag when knowledge is missing rather than inventing it.`,th=`# Knowledge Base — taxonomy & flows
|
|
524
|
+
|
|
525
|
+
> Owned by the Knowledge agent (@vannevar). The KB is Constella's single source of truth: a curated,
|
|
526
|
+
> classified, state-aware layer over the semantic RAG index. See docs/KB_RAG.md and docs/KB_AGENT.md.
|
|
527
|
+
|
|
528
|
+
${tg}
|
|
529
|
+
`,ti=!1;function tj(){if(ti)return;ti=!0,eh.exec(`
|
|
530
|
+
CREATE TABLE IF NOT EXISTS kb_entry (
|
|
531
|
+
id TEXT PRIMARY KEY,
|
|
532
|
+
workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
|
|
533
|
+
type TEXT NOT NULL DEFAULT 'note',
|
|
534
|
+
title TEXT NOT NULL,
|
|
535
|
+
summary TEXT NOT NULL DEFAULT '',
|
|
536
|
+
body TEXT NOT NULL DEFAULT '',
|
|
537
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
538
|
+
goal_id TEXT,
|
|
539
|
+
spec_id TEXT,
|
|
540
|
+
issue_id TEXT,
|
|
541
|
+
task_id TEXT,
|
|
542
|
+
module TEXT NOT NULL DEFAULT '',
|
|
543
|
+
paths TEXT,
|
|
544
|
+
agent_handle TEXT NOT NULL DEFAULT '',
|
|
545
|
+
source_kind TEXT NOT NULL DEFAULT '',
|
|
546
|
+
source_ref TEXT NOT NULL DEFAULT '',
|
|
547
|
+
supersedes_id TEXT,
|
|
548
|
+
hash TEXT NOT NULL DEFAULT '',
|
|
549
|
+
confidence INTEGER NOT NULL DEFAULT 70,
|
|
550
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
551
|
+
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
552
|
+
);
|
|
553
|
+
CREATE INDEX IF NOT EXISTS kb_ws_type_idx ON kb_entry (workspace_id, type);
|
|
554
|
+
CREATE INDEX IF NOT EXISTS kb_ws_goal_idx ON kb_entry (workspace_id, goal_id);
|
|
555
|
+
CREATE TABLE IF NOT EXISTS kb_query_log (
|
|
556
|
+
id TEXT PRIMARY KEY,
|
|
557
|
+
workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
|
|
558
|
+
agent_handle TEXT NOT NULL DEFAULT '',
|
|
559
|
+
query TEXT NOT NULL DEFAULT '',
|
|
560
|
+
hits INTEGER NOT NULL DEFAULT 0,
|
|
561
|
+
mode TEXT NOT NULL DEFAULT '',
|
|
562
|
+
refs TEXT,
|
|
563
|
+
answered_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
564
|
+
);
|
|
565
|
+
CREATE INDEX IF NOT EXISTS kb_query_ws_idx ON kb_query_log (workspace_id, answered_at);
|
|
566
|
+
`);let a=new Set(eh.prepare("PRAGMA table_info(rag_chunk)").all().map(a=>a.name));a.has("kb_entry_id")||eh.exec("ALTER TABLE rag_chunk ADD COLUMN kb_entry_id TEXT"),a.has("obsolete")||eh.exec("ALTER TABLE rag_chunk ADD COLUMN obsolete INTEGER NOT NULL DEFAULT 0");let b=new Set(eh.prepare("PRAGMA table_info(message)").all().map(a=>a.name));b.has("task_id")||eh.exec("ALTER TABLE message ADD COLUMN task_id TEXT"),b.has("kind")||eh.exec("ALTER TABLE message ADD COLUMN kind TEXT"),b.has("blocks")||eh.exec("ALTER TABLE message ADD COLUMN blocks TEXT"),new Set(eh.prepare("PRAGMA table_info(agent_skill)").all().map(a=>a.name)).has("auto")||eh.exec("ALTER TABLE agent_skill ADD COLUMN auto INTEGER NOT NULL DEFAULT 1"),new Set(eh.prepare("PRAGMA table_info(skill)").all().map(a=>a.name)).has("proposed_role")||eh.exec("ALTER TABLE skill ADD COLUMN proposed_role TEXT"),new Set(eh.prepare("PRAGMA table_info(notification_pref)").all().map(a=>a.name)).has("reduced_motion")||eh.exec("ALTER TABLE notification_pref ADD COLUMN reduced_motion INTEGER NOT NULL DEFAULT 0"),eh.exec(`
|
|
567
|
+
CREATE TABLE IF NOT EXISTS file_lock (
|
|
568
|
+
workspace_id TEXT NOT NULL,
|
|
569
|
+
path TEXT NOT NULL,
|
|
570
|
+
task_id TEXT NOT NULL DEFAULT '',
|
|
571
|
+
agent_id TEXT NOT NULL DEFAULT '',
|
|
572
|
+
agent_handle TEXT NOT NULL DEFAULT '',
|
|
573
|
+
acquired_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
574
|
+
heartbeat_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
575
|
+
PRIMARY KEY (workspace_id, path)
|
|
576
|
+
);
|
|
577
|
+
`),eh.exec(`
|
|
578
|
+
CREATE TABLE IF NOT EXISTS synced_block (
|
|
579
|
+
workspace_id TEXT NOT NULL,
|
|
580
|
+
slug TEXT NOT NULL,
|
|
581
|
+
kind TEXT NOT NULL DEFAULT 'note',
|
|
582
|
+
title TEXT NOT NULL DEFAULT '',
|
|
583
|
+
body TEXT NOT NULL DEFAULT '',
|
|
584
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
585
|
+
updated_by TEXT NOT NULL DEFAULT '',
|
|
586
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
587
|
+
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
588
|
+
PRIMARY KEY (workspace_id, slug)
|
|
589
|
+
);
|
|
590
|
+
CREATE TABLE IF NOT EXISTS block_proposal (
|
|
591
|
+
id TEXT PRIMARY KEY,
|
|
592
|
+
workspace_id TEXT NOT NULL,
|
|
593
|
+
slug TEXT NOT NULL,
|
|
594
|
+
kind TEXT NOT NULL DEFAULT 'note',
|
|
595
|
+
title TEXT NOT NULL DEFAULT '',
|
|
596
|
+
body TEXT NOT NULL DEFAULT '',
|
|
597
|
+
by_agent_handle TEXT NOT NULL DEFAULT '',
|
|
598
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
599
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
600
|
+
decided_at INTEGER,
|
|
601
|
+
decided_by TEXT NOT NULL DEFAULT ''
|
|
602
|
+
);
|
|
603
|
+
CREATE INDEX IF NOT EXISTS block_prop_ws_idx ON block_proposal (workspace_id, status);
|
|
604
|
+
`)}let tk=(a,b)=>`kb/${a}/${b}`;async function tl(a,b){try{tj();let c=await ei.select({id:d4.id,type:d4.type}).from(d4).where(aZ(aX(d4.workspaceId,a),aX(d4.goalId,b),a4(d4.status,["active","superseded"])));if(!c.length)return 0;for(let d of(await ei.update(d4).set({status:"obsolete",updatedAt:new Date}).where(aZ(aX(d4.workspaceId,a),aX(d4.goalId,b),a4(d4.status,["active","superseded"]))),c))await ei.update(d2).set({obsolete:!0}).where(aZ(aX(d2.workspaceId,a),aX(d2.path,tk(d.type,d.id))));return c.length}catch{return 0}}async function tm(){let a=0;try{for(let b of(await ei.select().from(dt))){let[c]=await ei.select().from(du).where(aZ(aX(du.workspaceId,b.id),aX(du.handle,"vannevar")));if(!c)continue;let d=c.persona??{};if(d.systemPrompt!==tg){await ei.update(du).set({persona:{...d,identity:"Keeper of the company's single source of truth. Every reusable thing the team learns flows through me: I classify it, dedupe it, keep it current, and serve it back with references.",ritual:"Ingest new knowledge, retire what's superseded or obsolete, keep summaries tight, surface gaps, and answer any teammate's question with the most recent, active, referenced truth — or say plainly when we don't know yet.",tone:d.tone??"precise",systemPrompt:tg}}).where(aX(du.id,c.id));try{q3(b.orgId,".claude/kb/TAXONOMY.md",th)}catch{}a++}}}catch{}return{updated:a}}process.env.LLAMACPP_URL;let tn=!1;function to(){tn||(tn=!0,eh.exec(`
|
|
605
|
+
CREATE TABLE IF NOT EXISTS deploy_run (
|
|
606
|
+
id TEXT PRIMARY KEY,
|
|
607
|
+
workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
|
|
608
|
+
status TEXT NOT NULL DEFAULT 'idle',
|
|
609
|
+
run_id TEXT NOT NULL DEFAULT '',
|
|
610
|
+
steps TEXT NOT NULL DEFAULT '[]',
|
|
611
|
+
summary TEXT NOT NULL DEFAULT '',
|
|
612
|
+
build_log TEXT NOT NULL DEFAULT '',
|
|
613
|
+
checklist TEXT NOT NULL DEFAULT '[]',
|
|
614
|
+
last_export TEXT,
|
|
615
|
+
started_at INTEGER,
|
|
616
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
617
|
+
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
618
|
+
);
|
|
619
|
+
CREATE UNIQUE INDEX IF NOT EXISTS deploy_run_ws_uq ON deploy_run (workspace_id);
|
|
620
|
+
`))}let tp=/^[a-z0-9][a-z0-9-]{0,60}$/;async function tq(a,b,c,d){let e=`block/${b}`;for(let f of(await ei.delete(d2).where(aZ(aX(d2.workspaceId,a),aX(d2.path,e))),rE(`# ${c||b}
|
|
621
|
+
${(d||"").trim()}`.slice(0,6e3)))){let b=await rD(f);await ei.insert(d2).values({id:(0,eL.randomUUID)(),workspaceId:a,path:e,chunk:f,vector:b?JSON.stringify(b):null,obsolete:!1})}}async function tr(a,b){try{tj();let c=(b.slug||"").toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60);if(!c||!tp.test(c))return{ok:!1,slug:""};let d=(b.title??"").slice(0,200),e=(b.body??"").slice(0,2e4),f=(b.kind??"note").slice(0,40),g=(b.updatedBy??"operator").slice(0,60),[h]=await ei.select().from(d7).where(aZ(aX(d7.workspaceId,a),aX(d7.slug,c)));return h?await ei.update(d7).set({kind:f,title:d||h.title,body:e,version:h.version+1,updatedBy:g,updatedAt:new Date}).where(aZ(aX(d7.workspaceId,a),aX(d7.slug,c))):await ei.insert(d7).values({workspaceId:a,slug:c,kind:f,title:d||c,body:e,version:1,updatedBy:g}),await tq(a,c,d||h?.title||c,e),{ok:!0,slug:c}}catch{return{ok:!1,slug:""}}}async function ts(a){let b=0;try{tj();let[c]=await ei.select().from(dt).where(aX(dt.orgId,a));if(!c)return{seeded:b};let d=new Set((await ei.select({slug:d7.slug}).from(d7).where(aX(d7.workspaceId,c.id))).map(a=>a.slug)),e=Object.entries(c.stack??{}).filter(([,a])=>a&&"None"!==a).map(([a,b])=>`- **${a}:** ${b}`).join("\n");for(let a of[{slug:"mission",kind:"mission",title:"Mission",body:c.mission||""},{slug:"objective",kind:"objective",title:"Objective",body:c.objective||""},{slug:"official-stack",kind:"stack",title:"Official stack",body:e}])!d.has(a.slug)&&a.body.trim()&&(await tr(c.id,{...a,updatedBy:"system"}),b++)}catch{}return{seeded:b}}async function tt(){let a=0;try{for(let b of(await ei.select({orgId:dt.orgId}).from(dt)))a+=(await ts(b.orgId)).seeded}catch{}return{seeded:a}}let tu=!1;async function tv(){if(!tu){tu=!0;try{if(!qU)throw Error(`BETTER_AUTH_SECRET is required in '${qS}' run mode (sessions would be forgeable).`)}catch(a){console.error("[boot] FATAL:",a.message),process.exit(1)}try{tj()}catch(a){console.error("[boot] ensureKbTables failed:",a)}try{for(let a of(to(),to(),eh.prepare("SELECT workspace_id, steps FROM deploy_run WHERE status = 'running'").all())){let b=(function(a,b){if(!a)return b;try{return JSON.parse(a)}catch{return b}})(a.steps,[]).map(a=>"running"===a.status?{...a,status:"error",detail:a.detail||"interrupted by restart"}:a);eh.prepare("UPDATE deploy_run SET status = 'failed', steps = ?, updated_at = unixepoch() WHERE workspace_id = ?").run(JSON.stringify(b),a.workspace_id)}}catch(a){console.error("[boot] ensureDeployTables failed:",a)}try{for(let a of q5.keys())q6(a);q5.clear();let a=await ei.update(du).set({status:"idle"}).where(a4(du.status,["working","review"])).returning({id:du.id}),b=await ei.select().from(dE).where(aX(dE.col,"doing")),c=0;for(let a of b){if(a.goalId){let b=await ei.query.goal.findFirst({where:aX(dC.id,a.goalId)});if(b&&"active"!==b.status)continue}await ei.update(dE).set({col:"todo"}).where(aX(dE.id,a.id)),c++}let d=0,e=0;for(let a of(await ei.select().from(dC).where(a4(dC.status,["cancelled","archived"])))){let b=a.status,c=await ei.update(dG).set({status:b}).where(aZ(aX(dG.goalId,a.id),aY(dG.status,b))).returning({id:dG.id}),f=await ei.update(dH).set({status:b}).where(aZ(aX(dH.goalId,a.id),aY(dH.status,b))).returning({id:dH.id});d+=c.length+f.length,e+=await tl(a.workspaceId,a.id)}e&&console.log(`[boot] retired ${e} KB entr(y/ies) from cancelled/archived goals`);let f=0;for(let a of(await ei.select({id:dt.id}).from(dt)))f+=await q7(a.id);console.log(`[boot] reconciled: ${a.length} agent(s) → idle, ${c} orphan task(s) → todo, ${d} spec/issue status synced, ${f} orphan event(s) pruned`)}catch(a){console.error("[boot] reconcile failed:",a)}try{let a=function(){let a=ei.select({id:dt.id,orgId:dt.orgId,stack:dt.stack}).from(dt).all(),b=[...re().keys()],c=0;for(let d of a){let a=ei.select({id:du.id,handle:du.handle}).from(du).where(aX(du.workspaceId,d.id)).all();if(!a.length)continue;let e=Object.fromEntries(a.map(a=>[a.handle,a.id]));try{c+=function(a){let{orgId:b,wsId:c,names:d,agentIds:e}=a,f=a.linkNames?new Set(a.linkNames):null,g=0;for(let a of d){let d=rf(a);if(!d||ei.select({id:dw.id}).from(dw).where(aZ(aX(dw.workspaceId,c),aX(dw.name,a))).get())continue;let h=function(a){let b=rf(a);if(!b)return null;try{return(0,dd.readFileSync)((0,de.join)(rb(),b.relPath),"utf8")}catch{return null}}(a);if(!h)continue;let i=h.replace(/^---\n[\s\S]*?\n---\n?/,"").trim(),j=`When working with ${a} in this project.`,k=`# Skill — ${a}
|
|
622
|
+
|
|
623
|
+
**Trigger:** ${j}
|
|
624
|
+
|
|
625
|
+
${d.description}
|
|
626
|
+
|
|
627
|
+
## Procedure
|
|
628
|
+
${i}
|
|
629
|
+
`;q3(b,`.claude/skills/${a}.md`,k);let l=(0,eL.randomUUID)();if(ei.insert(dw).values({id:l,workspaceId:c,name:a,summary:d.description,trigger:j,instructions:i,native:!0,provisional:!1,indexed:"indexed"}).run(),!f||f.has(a))for(let a of Object.keys(e))ei.insert(dx).values({agentId:e[a],skillId:l}).run();g++}return{seeded:g}}({orgId:d.orgId,wsId:d.id,names:b,agentIds:e,linkNames:[]}).seeded,function(a){let b=ei.select({stack:dt.stack}).from(dt).where(aX(dt.id,a)).get();if(!b)return;let c=b.stack??{},d=new Set(re().keys()),e=ei.select({id:dw.id,name:dw.name}).from(dw).where(aX(dw.workspaceId,a)).all(),f=new Map(e.map(a=>[a.name,a.id])),g=new Map(e.map(a=>[a.id,a.name])),h=ei.select({id:du.id,role:du.role}).from(du).where(aX(du.workspaceId,a)).all();for(let a of h){let b=new Set((function(a,b){let c=re(),d=function(a){let b=(a??"").trim();for(let a of q9)if(a.match.test(b))return a.profile;return ra}(b),e=new Set(function(a){let b=re(),c=[...rg];for(let b of Object.values(a??{})){let a=q8[b];a&&c.push(a)}return[...new Set(c)].filter(a=>b.has(a))}(a)),f=new Set(rg.filter(a=>c.has(a)));for(let[a,b]of c)d.allPrefixes.some(a=>b.relPath.startsWith(a))?f.add(a):d.stackPrefixes.some(a=>b.relPath.startsWith(a))&&e.has(a)&&f.add(a);return[...f]})(c,a.role).filter(a=>f.has(a))),e=ei.select({skillId:dx.skillId,auto:dx.auto}).from(dx).where(aX(dx.agentId,a.id)).all(),h=new Set(e.map(a=>a.skillId));for(let c of e){let e=g.get(c.skillId);c.auto&&e&&d.has(e)&&!b.has(e)&&ei.delete(dx).where(aZ(aX(dx.agentId,a.id),aX(dx.skillId,c.skillId))).run()}for(let c of b){let b=f.get(c);b&&!h.has(b)&&ei.insert(dx).values({agentId:a.id,skillId:b,auto:!0}).onConflictDoNothing().run()}}h.length}(d.id)}catch(a){console.error("[skill-backfill] workspace",d.id,"failed:",a)}}return{workspaces:a.length,seeded:c}}();a.seeded&&console.log(`[boot] backfilled ${a.seeded} library skill(s) across ${a.workspaces} workspace(s)`)}catch(a){console.error("[boot] skill backfill failed:",a)}try{let a=function(){let a=ei.select().from(dt).all(),b=0;for(let c of a){let a=new Set(ei.select({handle:du.handle}).from(du).where(aX(du.workspaceId,c.id)).all().map(a=>a.handle)),d=ei.select({id:dw.id,provisional:dw.provisional}).from(dw).where(aX(dw.workspaceId,c.id)).all().filter(a=>!a.provisional).map(a=>a.id),e={orgId:c.orgId,slug:c.slug,company:c.name,mission:c.mission,objective:c.objective,stack:c.stack??{}};for(let f of rh){if(a.has(f.handle))continue;let g=(0,eL.randomUUID)();try{for(let[a,b]of(ei.insert(du).values({id:g,workspaceId:c.id,handle:f.handle,name:f.name,role:f.role,color:f.color,reportsTo:f.reportsTo,dailyCapUsd:f.dailyCapUsd,tierFloor:f.tier,status:"idle",lastPulse:new Date,health:"alive"}).run(),function(a,b){var c,d;let e,f,g=`.claude/agents/${a.handle}`;return[[`${g}/Agent.md`,`---
|
|
630
|
+
handle: ${a.handle}
|
|
631
|
+
name: ${a.name}
|
|
632
|
+
role: ${a.role}
|
|
633
|
+
reportsTo: ${a.reportsTo??"null"}
|
|
634
|
+
provider: ${a.provider}
|
|
635
|
+
model: ${a.model}
|
|
636
|
+
temperature: ${a.temperature}
|
|
637
|
+
dailyCapUsd: ${a.dailyCapUsd}
|
|
638
|
+
tierFloor: ${a.tier}
|
|
639
|
+
---
|
|
640
|
+
# ${a.name} — ${a.role}
|
|
641
|
+
|
|
642
|
+
**Identity:** ${a.identity}
|
|
643
|
+
|
|
644
|
+
**Ritual:** ${a.ritual}
|
|
645
|
+
|
|
646
|
+
## Responsibilities
|
|
647
|
+
- Own the ${a.role} function for ${b.company}; deliver outcomes, not busywork.
|
|
648
|
+
- Follow the rituals above every working cycle.
|
|
649
|
+
|
|
650
|
+
## Communication style
|
|
651
|
+
- Concise and direct. Lead with the decision or result, then the reasoning.
|
|
652
|
+
|
|
653
|
+
## Behavior
|
|
654
|
+
${(c=a.temperature)<=.3?"Behavior (temperature low): be precise and deterministic. Give the single most correct, conventional answer; minimize speculation and creative variation; keep output tight and repeatable. Best for code, reviews and tools.":c<=.6?"Behavior (temperature balanced): be accurate and direct, but use reasonable judgment and allow a little exploration where the task clearly benefits.":c<=.85?"Behavior (temperature high): be creative and exploratory. Offer alternatives and non-obvious approaches and elaborate where it adds value — while staying correct and on-spec.":"Behavior (temperature max): be highly exploratory and generative. Brainstorm broadly, propose multiple distinct options and novel angles; favor breadth — still grounded in the requirements."}
|
|
655
|
+
|
|
656
|
+
## Decision-making rules
|
|
657
|
+
- Optimise for the company objective: "${b.objective||"ship value"}".
|
|
658
|
+
- Prefer the smallest change that works; escalate when blocked${a.reportsTo?` to @${a.reportsTo}`:""}.
|
|
659
|
+
|
|
660
|
+
## Execution rules
|
|
661
|
+
- Work one item at a time to completion. Stop at the daily budget cap ($${a.dailyCapUsd}).
|
|
662
|
+
- Use the skills listed in \`skills.md\`; use only the tools listed in \`tools.md\`.
|
|
663
|
+
|
|
664
|
+
## Workspace boundaries
|
|
665
|
+
- All file operations are restricted to this organization's workspace directory.
|
|
666
|
+
- Never read, write or delete anything outside it.
|
|
667
|
+
|
|
668
|
+
## Working with the Code module
|
|
669
|
+
- Read context from the workspace before editing; make small, reviewable diffs.
|
|
670
|
+
- Edit and create files directly on disk (the directory is the source of truth).
|
|
671
|
+
|
|
672
|
+
## Collaboration
|
|
673
|
+
- Coordinate via the team room / DMs; hand off across roles per \`.claude/routing.md\`.
|
|
674
|
+
|
|
675
|
+
## Allowed
|
|
676
|
+
- Read, create, edit, delete and search files **inside this workspace**.
|
|
677
|
+
|
|
678
|
+
## Not allowed
|
|
679
|
+
- Touch any path outside the workspace; inline secrets; exceed the budget cap.
|
|
680
|
+
|
|
681
|
+
## System prompt
|
|
682
|
+
You are ${a.name}, the ${a.role} of ${b.company}. ${a.identity} Ritual: ${a.ritual} Always
|
|
683
|
+
follow the skill procedures, stay within this workspace directory, and stop at your budget ceiling.
|
|
684
|
+
`],[`${g}/pulse.md`,`# Pulse — ${a.name}
|
|
685
|
+
|
|
686
|
+
intervalSec: 30
|
|
687
|
+
maxMissed: 2
|
|
688
|
+
wakeOn:
|
|
689
|
+
- queued_task
|
|
690
|
+
- mention
|
|
691
|
+
healthCheck: 1-token ping to ${a.provider} (${a.model})
|
|
692
|
+
|
|
693
|
+
## Liveness checks
|
|
694
|
+
- **Alive:** a pulse was recorded within \`intervalSec * maxMissed\`.
|
|
695
|
+
- **Functional:** the agent's executor (CLI/provider) responds to the health ping.
|
|
696
|
+
- **Blocked:** the agent has work but cannot proceed (budget, dependency, error).
|
|
697
|
+
|
|
698
|
+
## Wake / recover
|
|
699
|
+
- The sweep wakes a stale agent when it has a \`queued_task\` or is \`@mentioned\`.
|
|
700
|
+
- On repeated failure, mark **down**, log to \`Reports/error-report.md\`, and recover on the next healthy ping.
|
|
701
|
+
|
|
702
|
+
## Status values
|
|
703
|
+
\`idle\` \xb7 \`working\` \xb7 \`review\` \xb7 \`blocked\` (status) — \`alive\` \xb7 \`stale\` \xb7 \`down\` (health).
|
|
704
|
+
|
|
705
|
+
## Reporting
|
|
706
|
+
- Each sweep writes \`Reports/agent-status.md\` and \`Reports/system-health.md\`.
|
|
707
|
+
- Errors are appended to \`Reports/error-report.md\`.
|
|
708
|
+
`],[`${g}/tools.md`,(e="CyberSec"===a.role?["secret-scan","review.signoff","fs.read"]:"DevOps"===a.role?["run-suite","deploy.preview","telegram-notify"]:"Backend"===a.role||"Frontend"===a.role?["fs.read","fs.write","run-suite","open-pr"]:"QA"===a.role?["run-suite","review.gate"]:"Docs"===a.role?["fs.read","fs.write"]:"Knowledge"===a.role?["fs.read","rag.reindex","rag.index-chat","embed.health"]:["core.delegate","core.approve"],`# Tools — ${a.name}
|
|
709
|
+
|
|
710
|
+
Provider: ${a.provider} \xb7 Model: ${a.model}
|
|
711
|
+
|
|
712
|
+
| Tool | Purpose | Allowed | Forbidden |
|
|
713
|
+
|---|---|---|---|
|
|
714
|
+
${e.map(a=>`| \`${a}\` | ${a.includes("fs")?"Workspace file access":a.includes("run")?"Run the test suite":a.includes("deploy")?"Preview deploy":a.includes("review")?"Review / sign-off":"Core action"} | inside this workspace | any path outside the workspace |`).join("\n")}
|
|
715
|
+
|
|
716
|
+
## File access rules
|
|
717
|
+
- All file operations are restricted to this organization's workspace (cwd-jailed).
|
|
718
|
+
- Reads/edits/writes auto-accept **inside** the workspace; nothing outside is reachable.
|
|
719
|
+
|
|
720
|
+
## Execution limits & safety
|
|
721
|
+
- Stop at the daily budget cap ($${a.dailyCapUsd}). Never inline or echo secrets.
|
|
722
|
+
- Use a tool only when its purpose matches the task; otherwise skip it.
|
|
723
|
+
`)],[`${g}/skills.md`,(f=[...new Set([...rj,..."DevOps"===(d=a.role)?["telegram-notify"]:"Backend"===d||"DevOps"===d?["gguf-validate"]:[]])],`# Skills — ${a.name}
|
|
724
|
+
|
|
725
|
+
Assigned procedures. Each links to a real file in \`../../skills/\`.
|
|
726
|
+
|
|
727
|
+
${f.map(a=>{let b=ri.find(b=>b.name===a);return`## \`${a}\`
|
|
728
|
+
- **File:** \`.claude/skills/${a}.md\`
|
|
729
|
+
- **Use when:** ${b?.trigger??"as appropriate"}
|
|
730
|
+
- **Summary:** ${b?.summary??""}`}).join("\n\n")}
|
|
731
|
+
|
|
732
|
+
## Rituals
|
|
733
|
+
${a.ritual}
|
|
734
|
+
`)]]}(f,e)))q3(c.orgId,a,b);for(let a of d)ei.insert(dx).values({agentId:g,skillId:a}).run();b++}catch(a){console.error("[roster-backfill]",c.id,f.handle,"failed:",a)}}}return{added:b}}();a.added&&console.log(`[boot] backfilled ${a.added} roster agent(s) into existing workspace(s)`)}catch(a){console.error("[boot] roster backfill failed:",a)}try{let a=await tm();a.updated&&console.log(`[boot] seeded the KB-Agent prompt for ${a.updated} workspace(s)`)}catch(a){console.error("[boot] KB-Agent seed failed:",a)}try{let a=await tt();a.seeded&&console.log(`[boot] seeded ${a.seeded} default knowledge block(s)`)}catch(a){console.error("[boot] block seed failed:",a)}sh().then(a=>{a.up&&console.log(`[boot] embedding server up (${a.model??"model"}) — RAG is semantic`)}).catch(()=>{}),si().then(a=>{a.up&&console.log(`[boot] llama.cpp serving ${a.model??"a model"} on 127.0.0.1:8082`)}).catch(()=>{}),sH().then(a=>{a&&console.log(`[boot] model catalog warmed (${a} providers from models.dev)`)}).then(()=>s$()).then(a=>{a.refreshed&&console.log(`[boot] refreshed model list for ${a.refreshed} provider(s)`)}).catch(()=>{})}}},67449:(a,b,c)=>{"use strict";c.d(b,{K:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"OrNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"OrNode",left:a,right:b})})},68454:a=>{"use strict";var b=Object.defineProperty,c=Object.getOwnPropertyDescriptor,d=Object.getOwnPropertyNames,e=Object.prototype.hasOwnProperty,f={},g={RequestCookies:()=>n,ResponseCookies:()=>o,parseCookie:()=>j,parseSetCookie:()=>k,stringifyCookie:()=>i};for(var h in g)b(f,h,{get:g[h],enumerable:!0});function i(a){var b;let c=["path"in a&&a.path&&`Path=${a.path}`,"expires"in a&&(a.expires||0===a.expires)&&`Expires=${("number"==typeof a.expires?new Date(a.expires):a.expires).toUTCString()}`,"maxAge"in a&&"number"==typeof a.maxAge&&`Max-Age=${a.maxAge}`,"domain"in a&&a.domain&&`Domain=${a.domain}`,"secure"in a&&a.secure&&"Secure","httpOnly"in a&&a.httpOnly&&"HttpOnly","sameSite"in a&&a.sameSite&&`SameSite=${a.sameSite}`,"partitioned"in a&&a.partitioned&&"Partitioned","priority"in a&&a.priority&&`Priority=${a.priority}`].filter(Boolean),d=`${a.name}=${encodeURIComponent(null!=(b=a.value)?b:"")}`;return 0===c.length?d:`${d}; ${c.join("; ")}`}function j(a){let b=new Map;for(let c of a.split(/; */)){if(!c)continue;let a=c.indexOf("=");if(-1===a){b.set(c,"true");continue}let[d,e]=[c.slice(0,a),c.slice(a+1)];try{b.set(d,decodeURIComponent(null!=e?e:"true"))}catch{}}return b}function k(a){if(!a)return;let[[b,c],...d]=j(a),{domain:e,expires:f,httponly:g,maxage:h,path:i,samesite:k,secure:n,partitioned:o,priority:p}=Object.fromEntries(d.map(([a,b])=>[a.toLowerCase().replace(/-/g,""),b]));{var q,r,s={name:b,value:decodeURIComponent(c),domain:e,...f&&{expires:new Date(f)},...g&&{httpOnly:!0},..."string"==typeof h&&{maxAge:Number(h)},path:i,...k&&{sameSite:l.includes(q=(q=k).toLowerCase())?q:void 0},...n&&{secure:!0},...p&&{priority:m.includes(r=(r=p).toLowerCase())?r:void 0},...o&&{partitioned:!0}};let a={};for(let b in s)s[b]&&(a[b]=s[b]);return a}}a.exports=((a,f,g,h)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let i of d(f))e.call(a,i)||i===g||b(a,i,{get:()=>f[i],enumerable:!(h=c(f,i))||h.enumerable});return a})(b({},"__esModule",{value:!0}),f);var l=["strict","lax","none"],m=["low","medium","high"],n=class{constructor(a){this._parsed=new Map,this._headers=a;const b=a.get("cookie");if(b)for(const[a,c]of j(b))this._parsed.set(a,{name:a,value:c})}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...a){let b="string"==typeof a[0]?a[0]:a[0].name;return this._parsed.get(b)}getAll(...a){var b;let c=Array.from(this._parsed);if(!a.length)return c.map(([a,b])=>b);let d="string"==typeof a[0]?a[0]:null==(b=a[0])?void 0:b.name;return c.filter(([a])=>a===d).map(([a,b])=>b)}has(a){return this._parsed.has(a)}set(...a){let[b,c]=1===a.length?[a[0].name,a[0].value]:a,d=this._parsed;return d.set(b,{name:b,value:c}),this._headers.set("cookie",Array.from(d).map(([a,b])=>i(b)).join("; ")),this}delete(a){let b=this._parsed,c=Array.isArray(a)?a.map(a=>b.delete(a)):b.delete(a);return this._headers.set("cookie",Array.from(b).map(([a,b])=>i(b)).join("; ")),c}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(a=>`${a.name}=${encodeURIComponent(a.value)}`).join("; ")}},o=class{constructor(a){var b,c,d;this._parsed=new Map,this._headers=a;const e=null!=(d=null!=(c=null==(b=a.getSetCookie)?void 0:b.call(a))?c:a.get("set-cookie"))?d:[];for(const a of Array.isArray(e)?e:function(a){if(!a)return[];var b,c,d,e,f,g=[],h=0;function i(){for(;h<a.length&&/\s/.test(a.charAt(h));)h+=1;return h<a.length}for(;h<a.length;){for(b=h,f=!1;i();)if(","===(c=a.charAt(h))){for(d=h,h+=1,i(),e=h;h<a.length&&"="!==(c=a.charAt(h))&&";"!==c&&","!==c;)h+=1;h<a.length&&"="===a.charAt(h)?(f=!0,h=e,g.push(a.substring(b,d)),b=h):h=d+1}else h+=1;(!f||h>=a.length)&&g.push(a.substring(b,a.length))}return g}(e)){const b=k(a);b&&this._parsed.set(b.name,b)}}get(...a){let b="string"==typeof a[0]?a[0]:a[0].name;return this._parsed.get(b)}getAll(...a){var b;let c=Array.from(this._parsed.values());if(!a.length)return c;let d="string"==typeof a[0]?a[0]:null==(b=a[0])?void 0:b.name;return c.filter(a=>a.name===d)}has(a){return this._parsed.has(a)}set(...a){let[b,c,d]=1===a.length?[a[0].name,a[0].value,a[0]]:a,e=this._parsed;return e.set(b,function(a={name:"",value:""}){return"number"==typeof a.expires&&(a.expires=new Date(a.expires)),a.maxAge&&(a.expires=new Date(Date.now()+1e3*a.maxAge)),(null===a.path||void 0===a.path)&&(a.path="/"),a}({name:b,value:c,...d})),function(a,b){for(let[,c]of(b.delete("set-cookie"),a)){let a=i(c);b.append("set-cookie",a)}}(e,this._headers),this}delete(...a){let[b,c]="string"==typeof a[0]?[a[0]]:[a[0].name,a[0]];return this.set({...c,name:b,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(i).join("; ")}}},68877:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"LRUCache",{enumerable:!0,get:function(){return e}});class c{constructor(a,b,c){this.prev=null,this.next=null,this.key=a,this.data=b,this.size=c}}class d{constructor(){this.prev=null,this.next=null}}class e{constructor(a,b,c){this.cache=new Map,this.totalSize=0,this.maxSize=a,this.calculateSize=b,this.onEvict=c,this.head=new d,this.tail=new d,this.head.next=this.tail,this.tail.prev=this.head}addToHead(a){a.prev=this.head,a.next=this.head.next,this.head.next.prev=a,this.head.next=a}removeNode(a){a.prev.next=a.next,a.next.prev=a.prev}moveToHead(a){this.removeNode(a),this.addToHead(a)}removeTail(){let a=this.tail.prev;return this.removeNode(a),a}set(a,b){let d=(null==this.calculateSize?void 0:this.calculateSize.call(this,b))??1;if(d<=0)throw Object.defineProperty(Error(`LRUCache: calculateSize returned ${d}, but size must be > 0. Items with size 0 would never be evicted, causing unbounded cache growth.`),"__NEXT_ERROR_CODE",{value:"E1045",enumerable:!1,configurable:!0});if(d>this.maxSize)return console.warn("Single item size exceeds maxSize"),!1;let e=this.cache.get(a);if(e)e.data=b,this.totalSize=this.totalSize-e.size+d,e.size=d,this.moveToHead(e);else{let e=new c(a,b,d);this.cache.set(a,e),this.addToHead(e),this.totalSize+=d}for(;this.totalSize>this.maxSize&&this.cache.size>0;){let a=this.removeTail();this.cache.delete(a.key),this.totalSize-=a.size,null==this.onEvict||this.onEvict.call(this,a.key,a.data)}return!0}has(a){return this.cache.has(a)}get(a){let b=this.cache.get(a);if(b)return this.moveToHead(b),b.data}*[Symbol.iterator](){let a=this.head.next;for(;a&&a!==this.tail;){let b=a;yield[b.key,b.data],a=a.next}}remove(a){let b=this.cache.get(a);b&&(this.removeNode(b),this.cache.delete(a),this.totalSize-=b.size)}get size(){return this.cache.size}get currentSize(){return this.totalSize}}},69832:(a,b,c)=>{"use strict";c.d(b,{U:()=>g});var d=c(18110),e=c(60812),f=c(4224);let g=(0,d.CN)({is:a=>"UpdateQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"UpdateQueryNode",table:1===a.length?a[0]:f.v.create(a),...b&&{with:b}}),createWithoutTable:()=>(0,d.CN)({kind:"UpdateQueryNode"}),cloneWithFromItems:(a,b)=>(0,d.CN)({...a,from:a.from?e.N.cloneWithFroms(a.from,b):e.N.create(b)}),cloneWithUpdates:(a,b)=>(0,d.CN)({...a,updates:a.updates?(0,d.CN)([...a.updates,...b]):b}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b})})},71056:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"removePathPrefix",{enumerable:!0,get:function(){return e}});let d=c(42960);function e(a,b){if(!(0,d.pathHasPrefix)(a,b))return a;let c=a.slice(b.length);return c.startsWith("/")?c:`/${c}`}},72188:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={ACTION_HEADER:function(){return f},FLIGHT_HEADERS:function(){return p},NEXT_ACTION_NOT_FOUND_HEADER:function(){return w},NEXT_ACTION_REVALIDATED_HEADER:function(){return z},NEXT_DID_POSTPONE_HEADER:function(){return s},NEXT_HMR_REFRESH_HASH_COOKIE:function(){return k},NEXT_HMR_REFRESH_HEADER:function(){return j},NEXT_HTML_REQUEST_ID_HEADER:function(){return y},NEXT_INSTANT_PREFETCH_HEADER:function(){return n},NEXT_INSTANT_TEST_COOKIE:function(){return o},NEXT_IS_PRERENDER_HEADER:function(){return v},NEXT_REQUEST_ID_HEADER:function(){return x},NEXT_REWRITTEN_PATH_HEADER:function(){return t},NEXT_REWRITTEN_QUERY_HEADER:function(){return u},NEXT_ROUTER_PREFETCH_HEADER:function(){return h},NEXT_ROUTER_SEGMENT_PREFETCH_HEADER:function(){return i},NEXT_ROUTER_STALE_TIME_HEADER:function(){return r},NEXT_ROUTER_STATE_TREE_HEADER:function(){return g},NEXT_RSC_UNION_QUERY:function(){return q},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return m},RSC_HEADER:function(){return e}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="rsc",f="next-action",g="next-router-state-tree",h="next-router-prefetch",i="next-router-segment-prefetch",j="next-hmr-refresh",k="__next_hmr_refresh_hash__",l="next-url",m="text/x-component",n="next-instant-navigation-testing-prefetch",o="next-instant-navigation-testing",p=[e,g,h,j,i],q="_rsc",r="x-nextjs-stale-time",s="x-nextjs-postponed",t="x-nextjs-rewritten-path",u="x-nextjs-rewritten-query",v="x-nextjs-prerender",w="x-nextjs-action-not-found",x="x-nextjs-request-id",y="x-nextjs-html-request-id",z="x-action-revalidated";("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},73560:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={INTERCEPTION_ROUTE_MARKERS:function(){return g},extractInterceptionRouteInformation:function(){return i},isInterceptionRouteAppPath:function(){return h}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(10045),g=["(..)(..)","(.)","(..)","(...)"];function h(a){return void 0!==a.split("/").find(a=>g.find(b=>a.startsWith(b)))}function i(a){let b,c,d;for(let e of a.split("/"))if(c=g.find(a=>e.startsWith(a))){[b,d]=a.split(c,2);break}if(!b||!c||!d)throw Object.defineProperty(Error(`Invalid interception route: ${a}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`),"__NEXT_ERROR_CODE",{value:"E269",enumerable:!1,configurable:!0});switch(b=(0,f.normalizeAppPath)(b),c){case"(.)":d="/"===b?`/${d}`:b+"/"+d;break;case"(..)":if("/"===b)throw Object.defineProperty(Error(`Invalid interception route: ${a}. Cannot use (..) marker at the root level, use (.) instead.`),"__NEXT_ERROR_CODE",{value:"E207",enumerable:!1,configurable:!0});d=b.split("/").slice(0,-1).concat(d).join("/");break;case"(...)":d="/"+d;break;case"(..)(..)":let e=b.split("/");if(e.length<=2)throw Object.defineProperty(Error(`Invalid interception route: ${a}. Cannot use (..)(..) marker at the root level or one level up.`),"__NEXT_ERROR_CODE",{value:"E486",enumerable:!1,configurable:!0});d=e.slice(0,-2).concat(d).join("/");break;default:throw Object.defineProperty(Error("Invariant: unexpected marker"),"__NEXT_ERROR_CODE",{value:"E112",enumerable:!1,configurable:!0})}return{interceptingRoute:b,interceptedRoute:d}}},73769:(a,b,c)=>{a.exports=function(a){var b=c(74075),d={chunkSize:(parseInt(a.length/1024)+1)*1024};return{deflate:function(){return b.deflateRawSync(a,d)},deflateAsync:function(c){var e=b.createDeflateRaw(d),f=[],g=0;e.on("data",function(a){f.push(a),g+=a.length}),e.on("end",function(){var a=Buffer.alloc(g),b=0;a.fill(0);for(var d=0;d<f.length;d++){var e=f[d];e.copy(a,b),b+=e.length}c&&c(a)}),e.end(a)}}}},75525:(a,b,c)=>{"use strict";c.d(b,{V:()=>e});var d=c(18110);class e{nodeStack=[];#aV=(0,d.CN)({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(a,b){if(!a)return a;this.nodeStack.push(a);let c=this.transformNodeImpl(a,b);return this.nodeStack.pop(),(0,d.CN)(c)}transformNodeImpl(a,b){return this.#aV[a.kind](a,b)}transformNodeList(a,b){return a?(0,d.CN)(a.map(a=>this.transformNode(a,b))):a}transformSelectQuery(a,b){return{kind:"SelectQueryNode",from:this.transformNode(a.from,b),selections:this.transformNodeList(a.selections,b),distinctOn:this.transformNodeList(a.distinctOn,b),joins:this.transformNodeList(a.joins,b),groupBy:this.transformNode(a.groupBy,b),orderBy:this.transformNode(a.orderBy,b),where:this.transformNode(a.where,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),limit:this.transformNode(a.limit,b),offset:this.transformNode(a.offset,b),with:this.transformNode(a.with,b),having:this.transformNode(a.having,b),explain:this.transformNode(a.explain,b),setOperations:this.transformNodeList(a.setOperations,b),fetch:this.transformNode(a.fetch,b),top:this.transformNode(a.top,b)}}transformSelection(a,b){return{kind:"SelectionNode",selection:this.transformNode(a.selection,b)}}transformColumn(a,b){return{kind:"ColumnNode",column:this.transformNode(a.column,b)}}transformAlias(a,b){return{kind:"AliasNode",node:this.transformNode(a.node,b),alias:this.transformNode(a.alias,b)}}transformTable(a,b){return{kind:"TableNode",table:this.transformNode(a.table,b)}}transformFrom(a,b){return{kind:"FromNode",froms:this.transformNodeList(a.froms,b)}}transformReference(a,b){return{kind:"ReferenceNode",column:this.transformNode(a.column,b),table:this.transformNode(a.table,b)}}transformAnd(a,b){return{kind:"AndNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformOr(a,b){return{kind:"OrNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformValueList(a,b){return{kind:"ValueListNode",values:this.transformNodeList(a.values,b)}}transformParens(a,b){return{kind:"ParensNode",node:this.transformNode(a.node,b)}}transformJoin(a,b){return{kind:"JoinNode",joinType:a.joinType,table:this.transformNode(a.table,b),on:this.transformNode(a.on,b)}}transformRaw(a,b){return{kind:"RawNode",sqlFragments:(0,d.CN)([...a.sqlFragments]),parameters:this.transformNodeList(a.parameters,b)}}transformWhere(a,b){return{kind:"WhereNode",where:this.transformNode(a.where,b)}}transformInsertQuery(a,b){return{kind:"InsertQueryNode",into:this.transformNode(a.into,b),columns:this.transformNodeList(a.columns,b),values:this.transformNode(a.values,b),returning:this.transformNode(a.returning,b),onConflict:this.transformNode(a.onConflict,b),onDuplicateKey:this.transformNode(a.onDuplicateKey,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),orAction:this.transformNode(a.orAction,b),replace:a.replace,explain:this.transformNode(a.explain,b),defaultValues:a.defaultValues,top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformValues(a,b){return{kind:"ValuesNode",values:this.transformNodeList(a.values,b)}}transformDeleteQuery(a,b){return{kind:"DeleteQueryNode",from:this.transformNode(a.from,b),using:this.transformNode(a.using,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),orderBy:this.transformNode(a.orderBy,b),limit:this.transformNode(a.limit,b),explain:this.transformNode(a.explain,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformReturning(a,b){return{kind:"ReturningNode",selections:this.transformNodeList(a.selections,b)}}transformCreateTable(a,b){return{kind:"CreateTableNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),constraints:this.transformNodeList(a.constraints,b),indexes:this.transformNodeList(a.indexes,b),temporary:a.temporary,ifNotExists:a.ifNotExists,onCommit:a.onCommit,frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),selectQuery:this.transformNode(a.selectQuery,b)}}transformColumnDefinition(a,b){return{kind:"ColumnDefinitionNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),references:this.transformNode(a.references,b),primaryKey:a.primaryKey,autoIncrement:a.autoIncrement,unique:a.unique,notNull:a.notNull,unsigned:a.unsigned,defaultTo:this.transformNode(a.defaultTo,b),check:this.transformNode(a.check,b),generated:this.transformNode(a.generated,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),nullsNotDistinct:a.nullsNotDistinct,identity:a.identity,ifNotExists:a.ifNotExists}}transformAddColumn(a,b){return{kind:"AddColumnNode",column:this.transformNode(a.column,b)}}transformDropTable(a,b){return{kind:"DropTableNode",table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade,temporary:a.temporary}}transformOrderBy(a,b){return{kind:"OrderByNode",items:this.transformNodeList(a.items,b)}}transformOrderByItem(a,b){return{kind:"OrderByItemNode",orderBy:this.transformNode(a.orderBy,b),direction:this.transformNode(a.direction,b),collation:this.transformNode(a.collation,b),nulls:a.nulls}}transformGroupBy(a,b){return{kind:"GroupByNode",items:this.transformNodeList(a.items,b)}}transformGroupByItem(a,b){return{kind:"GroupByItemNode",groupBy:this.transformNode(a.groupBy,b)}}transformUpdateQuery(a,b){return{kind:"UpdateQueryNode",table:this.transformNode(a.table,b),from:this.transformNode(a.from,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),updates:this.transformNodeList(a.updates,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),explain:this.transformNode(a.explain,b),limit:this.transformNode(a.limit,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b),orderBy:this.transformNode(a.orderBy,b)}}transformColumnUpdate(a,b){return{kind:"ColumnUpdateNode",column:this.transformNode(a.column,b),value:this.transformNode(a.value,b)}}transformLimit(a,b){return{kind:"LimitNode",limit:this.transformNode(a.limit,b)}}transformOffset(a,b){return{kind:"OffsetNode",offset:this.transformNode(a.offset,b)}}transformOnConflict(a,b){return{kind:"OnConflictNode",columns:this.transformNodeList(a.columns,b),constraint:this.transformNode(a.constraint,b),indexExpression:this.transformNode(a.indexExpression,b),indexWhere:this.transformNode(a.indexWhere,b),updates:this.transformNodeList(a.updates,b),updateWhere:this.transformNode(a.updateWhere,b),doNothing:a.doNothing}}transformOnDuplicateKey(a,b){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(a.updates,b)}}transformCreateIndex(a,b){return{kind:"CreateIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists,where:this.transformNode(a.where,b),nullsNotDistinct:a.nullsNotDistinct}}transformList(a,b){return{kind:"ListNode",items:this.transformNodeList(a.items,b)}}transformDropIndex(a,b){return{kind:"DropIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade}}transformPrimaryKeyConstraint(a,b){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformUniqueConstraint(a,b){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),nullsNotDistinct:a.nullsNotDistinct,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformForeignKeyConstraint(a,b){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(a.columns,b),references:this.transformNode(a.references,b),name:this.transformNode(a.name,b),onDelete:a.onDelete,onUpdate:a.onUpdate,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformSetOperation(a,b){return{kind:"SetOperationNode",operator:a.operator,expression:this.transformNode(a.expression,b),all:a.all}}transformReferences(a,b){return{kind:"ReferencesNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),onDelete:a.onDelete,onUpdate:a.onUpdate}}transformCheckConstraint(a,b){return{kind:"CheckConstraintNode",expression:this.transformNode(a.expression,b),name:this.transformNode(a.name,b)}}transformWith(a,b){return{kind:"WithNode",expressions:this.transformNodeList(a.expressions,b),recursive:a.recursive}}transformCommonTableExpression(a,b){return{kind:"CommonTableExpressionNode",name:this.transformNode(a.name,b),materialized:a.materialized,expression:this.transformNode(a.expression,b)}}transformCommonTableExpressionName(a,b){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b)}}transformHaving(a,b){return{kind:"HavingNode",having:this.transformNode(a.having,b)}}transformCreateSchema(a,b){return{kind:"CreateSchemaNode",schema:this.transformNode(a.schema,b),ifNotExists:a.ifNotExists}}transformDropSchema(a,b){return{kind:"DropSchemaNode",schema:this.transformNode(a.schema,b),ifExists:a.ifExists,cascade:a.cascade}}transformAlterTable(a,b){return{kind:"AlterTableNode",table:this.transformNode(a.table,b),renameTo:this.transformNode(a.renameTo,b),setSchema:this.transformNode(a.setSchema,b),columnAlterations:this.transformNodeList(a.columnAlterations,b),addConstraint:this.transformNode(a.addConstraint,b),dropConstraint:this.transformNode(a.dropConstraint,b),renameConstraint:this.transformNode(a.renameConstraint,b),addIndex:this.transformNode(a.addIndex,b),dropIndex:this.transformNode(a.dropIndex,b)}}transformDropColumn(a,b){return{kind:"DropColumnNode",column:this.transformNode(a.column,b),ifExists:a.ifExists}}transformRenameColumn(a,b){return{kind:"RenameColumnNode",column:this.transformNode(a.column,b),renameTo:this.transformNode(a.renameTo,b)}}transformAlterColumn(a,b){return{kind:"AlterColumnNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),dataTypeExpression:this.transformNode(a.dataTypeExpression,b),setDefault:this.transformNode(a.setDefault,b),dropDefault:a.dropDefault,setNotNull:a.setNotNull,dropNotNull:a.dropNotNull}}transformModifyColumn(a,b){return{kind:"ModifyColumnNode",column:this.transformNode(a.column,b)}}transformAddConstraint(a,b){return{kind:"AddConstraintNode",constraint:this.transformNode(a.constraint,b)}}transformDropConstraint(a,b){return{kind:"DropConstraintNode",constraintName:this.transformNode(a.constraintName,b),ifExists:a.ifExists,modifier:a.modifier}}transformRenameConstraint(a,b){return{kind:"RenameConstraintNode",oldName:this.transformNode(a.oldName,b),newName:this.transformNode(a.newName,b)}}transformCreateView(a,b){return{kind:"CreateViewNode",name:this.transformNode(a.name,b),temporary:a.temporary,orReplace:a.orReplace,ifNotExists:a.ifNotExists,materialized:a.materialized,columns:this.transformNodeList(a.columns,b),as:this.transformNode(a.as,b)}}transformRefreshMaterializedView(a,b){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(a.name,b),concurrently:a.concurrently,withNoData:a.withNoData}}transformDropView(a,b){return{kind:"DropViewNode",name:this.transformNode(a.name,b),ifExists:a.ifExists,materialized:a.materialized,cascade:a.cascade}}transformGenerated(a,b){return{kind:"GeneratedNode",byDefault:a.byDefault,always:a.always,identity:a.identity,stored:a.stored,expression:this.transformNode(a.expression,b)}}transformDefaultValue(a,b){return{kind:"DefaultValueNode",defaultValue:this.transformNode(a.defaultValue,b)}}transformOn(a,b){return{kind:"OnNode",on:this.transformNode(a.on,b)}}transformSelectModifier(a,b){return{kind:"SelectModifierNode",modifier:a.modifier,rawModifier:this.transformNode(a.rawModifier,b),of:this.transformNodeList(a.of,b)}}transformCreateType(a,b){return{kind:"CreateTypeNode",name:this.transformNode(a.name,b),enum:this.transformNode(a.enum,b)}}transformDropType(a,b){return{kind:"DropTypeNode",name:this.transformNode(a.name,b),additionalNames:this.transformNodeList(a.additionalNames,b),cascade:a.cascade,ifExists:a.ifExists}}transformExplain(a,b){return{kind:"ExplainNode",format:a.format,options:this.transformNode(a.options,b)}}transformSchemableIdentifier(a,b){return{kind:"SchemableIdentifierNode",schema:this.transformNode(a.schema,b),identifier:this.transformNode(a.identifier,b)}}transformAggregateFunction(a,b){return{kind:"AggregateFunctionNode",func:a.func,aggregated:this.transformNodeList(a.aggregated,b),distinct:a.distinct,orderBy:this.transformNode(a.orderBy,b),withinGroup:this.transformNode(a.withinGroup,b),filter:this.transformNode(a.filter,b),over:this.transformNode(a.over,b)}}transformOver(a,b){return{kind:"OverNode",orderBy:this.transformNode(a.orderBy,b),partitionBy:this.transformNode(a.partitionBy,b)}}transformPartitionBy(a,b){return{kind:"PartitionByNode",items:this.transformNodeList(a.items,b)}}transformPartitionByItem(a,b){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(a.partitionBy,b)}}transformBinaryOperation(a,b){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(a.leftOperand,b),operator:this.transformNode(a.operator,b),rightOperand:this.transformNode(a.rightOperand,b)}}transformUnaryOperation(a,b){return{kind:"UnaryOperationNode",operator:this.transformNode(a.operator,b),operand:this.transformNode(a.operand,b)}}transformUsing(a,b){return{kind:"UsingNode",tables:this.transformNodeList(a.tables,b)}}transformFunction(a,b){return{kind:"FunctionNode",func:a.func,arguments:this.transformNodeList(a.arguments,b)}}transformCase(a,b){return{kind:"CaseNode",value:this.transformNode(a.value,b),when:this.transformNodeList(a.when,b),else:this.transformNode(a.else,b),isStatement:a.isStatement}}transformWhen(a,b){return{kind:"WhenNode",condition:this.transformNode(a.condition,b),result:this.transformNode(a.result,b)}}transformJSONReference(a,b){return{kind:"JSONReferenceNode",reference:this.transformNode(a.reference,b),traversal:this.transformNode(a.traversal,b)}}transformJSONPath(a,b){return{kind:"JSONPathNode",inOperator:this.transformNode(a.inOperator,b),pathLegs:this.transformNodeList(a.pathLegs,b)}}transformJSONPathLeg(a,b){return{kind:"JSONPathLegNode",type:a.type,value:a.value}}transformJSONOperatorChain(a,b){return{kind:"JSONOperatorChainNode",operator:this.transformNode(a.operator,b),values:this.transformNodeList(a.values,b)}}transformTuple(a,b){return{kind:"TupleNode",values:this.transformNodeList(a.values,b)}}transformMergeQuery(a,b){return{kind:"MergeQueryNode",into:this.transformNode(a.into,b),using:this.transformNode(a.using,b),whens:this.transformNodeList(a.whens,b),with:this.transformNode(a.with,b),top:this.transformNode(a.top,b),endModifiers:this.transformNodeList(a.endModifiers,b),output:this.transformNode(a.output,b),returning:this.transformNode(a.returning,b)}}transformMatched(a,b){return{kind:"MatchedNode",not:a.not,bySource:a.bySource}}transformAddIndex(a,b){return{kind:"AddIndexNode",name:this.transformNode(a.name,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists}}transformCast(a,b){return{kind:"CastNode",expression:this.transformNode(a.expression,b),dataType:this.transformNode(a.dataType,b)}}transformFetch(a,b){return{kind:"FetchNode",rowCount:this.transformNode(a.rowCount,b),modifier:a.modifier}}transformTop(a,b){return{kind:"TopNode",expression:a.expression,modifiers:a.modifiers}}transformOutput(a,b){return{kind:"OutputNode",selections:this.transformNodeList(a.selections,b)}}transformAlterType(a,b){return{kind:"AlterTypeNode",name:this.transformNode(a.name,b),addValue:this.transformNode(a.addValue,b),renameTo:this.transformNode(a.renameTo,b),renameValue:this.transformNode(a.renameValue,b),setSchema:this.transformNode(a.setSchema,b)}}transformAddValue(a,b){return{kind:"AddValueNode",value:this.transformNode(a.value,b),ifNotExists:a.ifNotExists,isBefore:a.isBefore,neighborValue:this.transformNode(a.neighborValue,b)}}transformRenameValue(a,b){return{kind:"RenameValueNode",oldValue:this.transformNode(a.oldValue,b),newValue:this.transformNode(a.newValue,b)}}transformDataType(a,b){return a}transformSelectAll(a,b){return a}transformIdentifier(a,b){return a}transformValue(a,b){return a}transformPrimitiveValueList(a,b){return a}transformOperator(a,b){return a}transformDefaultInsertValue(a,b){return a}transformOrAction(a,b){return a}transformCollate(a,b){return a}}},76051:(a,b,c)=>{"use strict";c.d(b,{q:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"ValueNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueNode",value:a}),createImmediate:a=>(0,d.CN)({kind:"ValueNode",value:a,immediate:!0})})},76609:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"isDynamicRoute",{enumerable:!0,get:function(){return g}});let d=c(73560),e=/\/[^/]*\[[^/]+\][^/]*(?=\/|$)/,f=/\/\[[^/]+\](?=\/|$)/;function g(a,b=!0){return((0,d.isInterceptionRouteAppPath)(a)&&(a=(0,d.extractInterceptionRouteInformation)(a).interceptedRoute),b)?f.test(a):e.test(a)}},77509:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={isNodeNextRequest:function(){return g},isNodeNextResponse:function(){return h},isWebNextRequest:function(){return e},isWebNextResponse:function(){return f}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e=a=>!1,f=a=>!1,g=a=>!0,h=a=>!0},79308:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"Batcher",{enumerable:!0,get:function(){return e}});let d=c(67017);class e{constructor(a,b=a=>a()){this.cacheKeyFn=a,this.schedulerFn=b,this.pending=new Map}static create(a){return new e(null==a?void 0:a.cacheKeyFn,null==a?void 0:a.schedulerFn)}async batch(a,b){let c=this.cacheKeyFn?await this.cacheKeyFn(a):a;if(null===c)return b({resolve:a=>Promise.resolve(a),key:a});let e=this.pending.get(c);if(e)return e;let{promise:f,resolve:g,reject:h}=new d.DetachedPromise;return this.pending.set(c,f),this.schedulerFn(async()=>{try{let c=await b({resolve:g,key:a});g(c)}catch(a){h(a)}finally{this.pending.delete(c)}}),f}}},79362:(a,b,c)=>{"use strict";c.d(b,{c:()=>d});class d{#$;#_;#aW;constructor(){this.#$=new Promise((a,b)=>{this.#aW=b,this.#_=a})}get promise(){return this.#$}resolve=a=>{this.#_?.(a),this.#_=this.#aW=void 0};reject=a=>{this.#aW?.(a),this.#aW=this.#_=void 0}}},79458:(a,b,c)=>{"use strict";c.d(b,{U:()=>e});var d=c(88743);class e extends d.l{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(a,b){}async releaseMigrationLock(a,b){}}},79953:(a,b,c)=>{"use strict";c.d(b,{H:()=>i,Q:()=>h});let d=Symbol.for("better-auth:global"),e=null,f={},g="1.6.19";function h(){return globalThis[d]||(globalThis[d]={version:g,epoch:1,context:f},e=globalThis[d]),(e=globalThis[d]).version!==g&&(e.version=g,e.epoch++),globalThis[d]}function i(){return h().version}},79957:(a,b)=>{"use strict";function c(a){return null!==a&&"object"==typeof a&&"then"in a&&"function"==typeof a.then}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"isThenable",{enumerable:!0,get:function(){return c}})},80178:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={isAbortError:function(){return k},pipeToNodeResponse:function(){return l}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(5568),g=c(67017),h=c(4028),i=c(11010),j=c(24191);function k(a){return(null==a?void 0:a.name)==="AbortError"||(null==a?void 0:a.name)===f.ResponseAbortedName}async function l(a,b,c){try{let{errored:d,destroyed:e}=b;if(d||e)return;let k=(0,f.createAbortController)(b),l=function(a,b){let c=!1,d=new g.DetachedPromise;function e(){d.resolve()}a.on("drain",e),a.once("close",()=>{a.off("drain",e),d.resolve()});let f=new g.DetachedPromise;return a.once("finish",()=>{f.resolve()}),new WritableStream({write:async b=>{if(!c){if(c=!0,"performance"in globalThis&&process.env.NEXT_OTEL_PERFORMANCE_PREFIX){let a=(0,j.getClientComponentLoaderMetrics)();a&&performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,{start:a.clientComponentLoadStart,end:a.clientComponentLoadStart+a.clientComponentLoadTimes})}a.flushHeaders(),(0,h.getTracer)().trace(i.NextNodeServerSpan.startResponse,{spanName:"start response"},()=>void 0)}try{let c=a.write(b);"flush"in a&&"function"==typeof a.flush&&a.flush(),c||(await d.promise,d=new g.DetachedPromise)}catch(b){throw a.end(),Object.defineProperty(Error("failed to write chunk to response",{cause:b}),"__NEXT_ERROR_CODE",{value:"E321",enumerable:!1,configurable:!0})}},abort:b=>{a.writableFinished||a.destroy(b)},close:async()=>{if(b&&await b,!a.writableFinished)return a.end(),f.promise}})}(b,c);await a.pipeTo(l,{signal:k.signal})}catch(a){if(k(a))return;throw Object.defineProperty(Error("failed to pipe response",{cause:a}),"__NEXT_ERROR_CODE",{value:"E180",enumerable:!1,configurable:!0})}}},80184:(a,b,c)=>{"use strict";c.d(b,{z:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"RawNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"RawNode",sqlFragments:(0,d.CN)(a),parameters:(0,d.CN)(b)}),createWithSql:a=>e.create([a],[]),createWithChild:a=>e.create(["",""],[a]),createWithChildren:a=>e.create(Array(a.length+1).fill(""),a)})},80185:(a,b,c)=>{"use strict";c.d(b,{l:()=>r});var d=c(98051),e=c(60351),f=c(80184),g=c(76051),h=c(45541),i=c(27800),j=c(2929),k=c(19105),l=c(50182),m=c(18110),n=c(24492);class o{#a;constructor(a){this.#a=(0,m.CN)(a)}get expressionType(){}get isRawBuilder(){return!0}as(a){return new q(this,a)}$castTo(){return new o({...this.#a})}$notNull(){return new o(this.#a)}withPlugin(a){return new o({...this.#a,plugins:void 0!==this.#a.plugins?(0,m.CN)([...this.#a.plugins,a]):(0,m.CN)([a])})}toOperationNode(){return this.#aX(this.#aY())}compile(a){return this.#aZ(this.#aY(a))}async execute(a,b){let c=this.#aY(a);return c.executeQuery(this.#aZ(c),b)}#aY(a){let b=void 0!==a?a.getExecutor():n.W;return void 0!==this.#a.plugins?b.withPlugins(this.#a.plugins):b}#aX(a){return a.transformQuery(this.#a.rawNode,this.#a.queryId)}#aZ(a){return a.compileQuery(this.#aX(a),this.#a.queryId)}}function p(a){return new o(a)}class q{#a$;#f;constructor(a,b){this.#a$=a,this.#f=b}get expression(){return this.#a$}get alias(){return this.#f}get rawBuilder(){return this.#a$}toOperationNode(){return l.N.create(this.#a$.toOperationNode(),(0,e.N)(this.#f)?this.#f.toOperationNode():d.O.create(this.#f))}}let r=Object.assign((a,...b)=>p({queryId:(0,k.a)(),rawNode:f.z.create(a,b?.map(s)??[])}),{ref:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,h.q5)(a))}),val:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,j.$s)(a))}),table:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,i.M$)(a))}),id(...a){let b=Array(a.length+1).fill(".");return b[0]="",b[b.length-1]="",p({queryId:(0,k.a)(),rawNode:f.z.create(b,a.map(d.O.create))})},lit:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild(g.q.createImmediate(a))}),raw:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithSql(a)}),join(a,b=r`, `){let c=Array(Math.max(2*a.length-1,0)),d=b.toOperationNode();for(let b=0;b<a.length;++b)c[2*b]=s(a[b]),b!==a.length-1&&(c[2*b+1]=d);return p({queryId:(0,k.a)(),rawNode:f.z.createWithChildren(c)})}});function s(a){return(0,e.N)(a)?a.toOperationNode():(0,j.$s)(a)}},80627:(a,b,c)=>{"use strict";c.d(b,{O:()=>K,A:()=>L});var d=c(60266),e=c(37694),f=c(27800),g=c(19105),h=c(10469),i=c(45541),j=c(31341),k=c(38441),l=c(14877),m=c(5496),n=c(18110);let o=(0,n.CN)({is:a=>"UnaryOperationNode"===a.kind,create:(a,b)=>(0,n.CN)({kind:"UnaryOperationNode",operator:a,operand:b})});var p=c(2929),q=c(24492),r=c(22943),s=c(17532),t=c(50182),u=c(98051),v=c(16891);let w=(0,n.CN)({is:a=>"JSONPathLegNode"===a.kind,create:(a,b)=>(0,n.CN)({kind:"JSONPathLegNode",type:a,value:b})});var x=c(47536),y=c(33866),z=c(60351),A=c(76051);let B=/^#-\d+$/;class C{#g;constructor(a){this.#g=a}at(a){if("number"!=typeof a&&"string"!=typeof a||"number"==typeof a&&!Number.isInteger(a)||"string"==typeof a&&"last"!==a&&!B.test(a))throw Error(`Unexpected index value in .at(...): ${a}`);return this.#a_("ArrayLocation",a)}key(a){return this.#a_("Member",a)}#a_(a,b){return new D(y.Q.is(this.#g)?y.Q.cloneWithTraversal(this.#g,x.c.is(this.#g.traversal)?x.c.cloneWithLeg(this.#g.traversal,w.create(a,b)):v.k.cloneWithValue(this.#g.traversal,A.q.createImmediate(b))):x.c.cloneWithLeg(this.#g,w.create(a,b)))}}class D extends C{#g;constructor(a){super(a),this.#g=a}get expressionType(){}as(a){return new E(this,a)}$castTo(){return new D(this.#g)}$notNull(){return new D(this.#g)}toOperationNode(){return this.#g}}class E{#a0;#f;constructor(a,b){this.#a0=a,this.#f=b}get expression(){return this.#a0}get alias(){return this.#f}toOperationNode(){return t.N.create(this.#a0.toOperationNode(),(0,z.N)(this.#f)?this.#f.toOperationNode():u.O.create(this.#f))}}var F=c(2529),G=c(59255);let H=(0,n.CN)({is:a=>"TupleNode"===a.kind,create:a=>(0,n.CN)({kind:"TupleNode",values:(0,n.CN)(a)})});var I=c(44901);let J=(0,n.CN)({is:a=>"CastNode"===a.kind,create:(a,b)=>(0,n.CN)({kind:"CastNode",expression:a,dataType:b})});function K(a=q.W){function b(a,b){return new l.Is(function(a,b){if((0,m.Gq)(a))return o.create(m.zX.create(a),(0,i.$O)(b));throw Error(`invalid unary operator ${JSON.stringify(a)}`)}(a,b))}let c=Object.assign(function(a,b,c){return new l.Is((0,j.ds)(a,b,c))},{fn:void 0,eb:void 0,selectFrom:b=>(0,d.c)({queryId:(0,g.a)(),executor:a,queryNode:e.L.createFrom((0,f.JB)(b))}),case:a=>new r.OU({node:s.P.create((0,n.b0)(a)?void 0:(0,i.$O)(a))}),ref:(a,b)=>(0,n.b0)(b)?new l.Is((0,i.q5)(a)):new C((0,i.NF)(a,b)),jsonPath:()=>new C(x.c.create()),table:a=>new l.Is((0,f.M$)(a)),val:a=>new l.Is((0,p.$s)(a)),refTuple:(...a)=>new l.Is(H.create(a.map(i.$O))),tuple:(...a)=>new l.Is(H.create(a.map(p.$s))),lit:a=>new l.Is((0,p.dJ)(a)),unary:b,not:a=>b("not",a),exists:a=>b("exists",a),neg:a=>b("-",a),between:(a,b,c)=>new l.Is(F.l.create((0,i.$O)(a),m.zX.create("between"),G.s.create((0,p.$s)(b),(0,p.$s)(c)))),betweenSymmetric:(a,b,c)=>new l.Is(F.l.create((0,i.$O)(a),m.zX.create("between symmetric"),G.s.create((0,p.$s)(b),(0,p.$s)(c)))),and:a=>new l.Is((0,n.MH)(a)?(0,j.KN)(a,"and"):(0,j.Ve)(a,"and")),or:a=>new l.Is((0,n.MH)(a)?(0,j.KN)(a,"or"):(0,j.Ve)(a,"or")),parens(...a){let b=(0,j.GB)(a);return new l.Is(k.k.is(b)?b:k.k.create(b))},cast:(a,b)=>new l.Is(J.create((0,i.$O)(a),(0,I.Q)(b)))});return c.fn=(0,h.t)(),c.eb=c,c}function L(a){return K()}},80733:(a,b,c)=>{"use strict";Object.defineProperty(b,"A",{enumerable:!0,get:function(){return d.registerServerReference}});let d=c(46076)},80848:(a,b,c)=>{"use strict";c.d(b,{f:()=>f});var d=c(18110);let e=(0,d.CN)({is:a=>"TopNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"TopNode",expression:a,modifiers:b})});function f(a,b){var c;if(!(0,d.Et)(a)&&!(0,d.sI)(a))throw Error(`Invalid top expression: ${a}`);if(!(0,d.b0)(b)&&"percent"!==(c=b)&&"with ties"!==c&&"percent with ties"!==c)throw Error(`Invalid top modifiers: ${b}`);return e.create(a,b)}},81222:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"unstable_rethrow",{enumerable:!0,get:function(){return d}});let d=c(2565).unstable_rethrow;("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},81605:(a,b,c)=>{"use strict";function d(a){switch(a){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${a}`)}}function e(...a){let b=a.map(d).join("");if(0===b.length)throw Error("No valid characters provided for random string generation.");let c=b.length;return(a,...e)=>{let f;if(a<=0)throw Error("Length must be a positive integer.");let g=b,h=c;e.length>0&&(h=(g=e.map(d).join("")).length);let i=Math.floor(256/h)*h,j=new Uint8Array(2*a),k=j.length,l="",m=k;for(;l.length<a;)m>=k&&(crypto.getRandomValues(j),m=0),(f=j[m++])<i&&(l+=g[f%h]);return l}}c.d(b,{q:()=>e})},81769:(a,b)=>{let c={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};for(let a of Object.keys(c))b[a]=function(a){return function(...b){return b.length&&(a=a.replace(/\{(\d)\}/g,(a,c)=>b[c]||"")),Error("ADM-ZIP: "+a)}}(c[a])},82069:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"getNextPathnameInfo",{enumerable:!0,get:function(){return g}});let d=c(61634),e=c(71056),f=c(42960);function g(a,b){let{basePath:c,i18n:g,trailingSlash:h}=b.nextConfig??{},i={pathname:a,trailingSlash:"/"!==a?a.endsWith("/"):h};c&&(0,f.pathHasPrefix)(i.pathname,c)&&(i.pathname=(0,e.removePathPrefix)(i.pathname,c),i.basePath=c);let j=i.pathname;if(i.pathname.startsWith("/_next/data/")&&i.pathname.endsWith(".json")){let a=i.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/");i.buildId=a[0],j="index"!==a[1]?`/${a.slice(1).join("/")}`:"/",!0===b.parseData&&(i.pathname=j)}if(g){let a=b.i18nProvider?b.i18nProvider.analyze(i.pathname):(0,d.normalizeLocalePath)(i.pathname,g.locales);i.locale=a.detectedLocale,i.pathname=a.pathname??i.pathname,!a.detectedLocale&&i.buildId&&(a=b.i18nProvider?b.i18nProvider.analyze(j):(0,d.normalizeLocalePath)(j,g.locales)).detectedLocale&&(i.locale=a.detectedLocale)}return i}},82650:(a,b,c)=>{"use strict";c.d(b,{cookies:()=>d.U,headers:()=>e.b});var d=c(4592),e=c(65211);c(5020)},83403:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={getSortedRouteObjects:function(){return f.getSortedRouteObjects},getSortedRoutes:function(){return f.getSortedRoutes},isDynamicRoute:function(){return g.isDynamicRoute}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(60525),g=c(76609)},83707:(a,b,c)=>{let d=c(29021),e=c(33873),f=c(1887),g=c(81769),h="object"==typeof process&&"win32"===process.platform,i=a=>"object"==typeof a&&null!==a,j=new Uint32Array(256).map((a,b)=>{for(let a=0;a<8;a++)(1&b)!=0?b=0xedb88320^b>>>1:b>>>=1;return b>>>0});function k(a){this.sep=e.sep,this.fs=d,i(a)&&i(a.fs)&&"function"==typeof a.fs.statSync&&(this.fs=a.fs)}a.exports=k,k.prototype.makeDir=function(a){let b,c=this;b=a.split(c.sep)[0],a.split(c.sep).forEach(function(a){var d;if(a&&":"!==a.substr(-1,1)){b+=c.sep+a;try{d=c.fs.statSync(b)}catch(a){if(a.message&&a.message.startsWith("ENOENT"))c.fs.mkdirSync(b);else throw a}if(d&&d.isFile())throw g.FILE_IN_THE_WAY(`"${b}"`)}})},k.prototype.writeFileTo=function(a,b,c,d){if(this.fs.existsSync(a)){var f;if(!c||this.fs.statSync(a).isDirectory())return!1}var g=e.dirname(a);this.fs.existsSync(g)||this.makeDir(g);try{f=this.fs.openSync(a,"w",438)}catch(b){this.fs.chmodSync(a,438),f=this.fs.openSync(a,"w",438)}if(f)try{this.fs.writeSync(f,b,0,b.length,0)}finally{this.fs.closeSync(f)}return this.fs.chmodSync(a,d||438),!0},k.prototype.writeFileToAsync=function(a,b,c,d,f){"function"==typeof d&&(f=d,d=void 0);let g=this;g.fs.exists(a,function(h){if(h&&!c)return f(!1);g.fs.stat(a,function(c,i){if(h&&i.isDirectory())return f(!1);var j=e.dirname(a);g.fs.exists(j,function(c){c||g.makeDir(j),g.fs.open(a,"w",438,function(c,e){c?g.fs.chmod(a,438,function(){g.fs.open(a,"w",438,function(c,e){g.fs.write(e,b,0,b.length,0,function(){g.fs.close(e,function(){g.fs.chmod(a,d||438,function(){f(!0)})})})})}):e?g.fs.write(e,b,0,b.length,0,function(){g.fs.close(e,function(){g.fs.chmod(a,d||438,function(){f(!0)})})}):g.fs.chmod(a,d||438,function(){f(!0)})})})})})},k.prototype.findFiles=function(a){let b=this;return function a(c,d,f){"boolean"==typeof d&&(f=d,d=void 0);let g=[];return b.fs.readdirSync(c).forEach(function(h){let i=e.join(c,h),j=b.fs.statSync(i);(!d||d.test(i))&&g.push(e.normalize(i)+(j.isDirectory()?b.sep:"")),j.isDirectory()&&f&&(g=g.concat(a(i,d,f)))}),g}(a,void 0,!0)},k.prototype.findFilesAsync=function(a,b){let c=this,d=[];c.fs.readdir(a,function(f,g){if(f)return b(f);let h=g.length;if(!h)return b(null,d);g.forEach(function(f){f=e.join(a,f),c.fs.stat(f,function(a,g){if(a)return b(a);g&&(d.push(e.normalize(f)+(g.isDirectory()?c.sep:"")),g.isDirectory()?c.findFilesAsync(f,function(a,c){if(a)return b(a);d=d.concat(c),--h||b(null,d)}):--h||b(null,d))})})})},k.prototype.getAttributes=function(){},k.prototype.setAttributes=function(){},k.crc32update=function(a,b){return j[(a^b)&255]^a>>>8},k.crc32=function(a){"string"==typeof a&&(a=Buffer.from(a,"utf8"));let b=a.length,c=-1;for(let d=0;d<b;)c=k.crc32update(c,a[d++]);return~c>>>0},k.methodToString=function(a){switch(a){case f.STORED:return"STORED ("+a+")";case f.DEFLATED:return"DEFLATED ("+a+")";default:return"UNSUPPORTED ("+a+")"}},k.canonical=function(a){if(!a)return"";let b=e.posix.normalize("/"+a.split("\\").join("/"));return e.join(".",b)},k.zipnamefix=function(a){if(!a)return"";let b=e.posix.normalize("/"+a.split("\\").join("/"));return e.posix.join(".",b)},k.findLast=function(a,b){if(!Array.isArray(a))throw TypeError("arr is not array");let c=a.length>>>0;for(let d=c-1;d>=0;d--)if(b(a[d],d,a))return a[d]},k.sanitize=function(a,b){a=e.resolve(e.normalize(a));for(var c=b.split("/"),d=0,f=c.length;d<f;d++){var g=e.normalize(e.join(a,c.slice(d,f).join(e.sep)));if(0===g.indexOf(a))return g}return e.normalize(e.join(a,e.basename(b)))},k.toBuffer=function(a,b){return Buffer.isBuffer(a)?a:a instanceof Uint8Array?Buffer.from(a):"string"==typeof a?b(a):Buffer.alloc(0)},k.readBigUInt64LE=function(a,b){let c=a.readUInt32LE(b);return 0x100000000*a.readUInt32LE(b+4)+c},k.fromDOS2Date=function(a){return new Date((a>>25&127)+1980,Math.max((a>>21&15)-1,0),Math.max(a>>16&31,1),a>>11&31,a>>5&63,(31&a)<<1)},k.fromDate2DOS=function(a){let b=0,c=0;return a.getFullYear()>1979&&(b=(a.getFullYear()-1980&127)<<9|a.getMonth()+1<<5|a.getDate(),c=a.getHours()<<11|a.getMinutes()<<5|a.getSeconds()>>1),b<<16|c},k.isWin=h,k.crcTable=j},84643:(a,b,c)=>{"use strict";function d(){throw Object.defineProperty(Error("`forbidden()` is experimental and only allowed to be enabled when `experimental.authInterrupts` is enabled."),"__NEXT_ERROR_CODE",{value:"E488",enumerable:!1,configurable:!0})}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"forbidden",{enumerable:!0,get:function(){return d}}),c(15707).HTTP_ERROR_FALLBACK_ERROR_CODE,("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},84698:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={NEXT_PATCH_SYMBOL:function(){return p},createPatchedFetcher:function(){return v},patchFetch:function(){return w},validateRevalidate:function(){return q},validateTags:function(){return r}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(11010),g=c(4028),h=c(52730),i=c(4190),j=c(87143),k=c(1159),l=c(63033),m=c(46752),n=c(15092);c(94931);let o=c(21689),p=Symbol.for("next-patch");function q(a,b){try{let c;if(!1===a)c=h.INFINITE_CACHE;else if("number"==typeof a&&!isNaN(a)&&a>-1)c=a;else if(void 0!==a)throw Object.defineProperty(Error(`Invalid revalidate value "${a}" on "${b}", must be a non-negative number or false`),"__NEXT_ERROR_CODE",{value:"E179",enumerable:!1,configurable:!0});return c}catch(a){if(a instanceof Error&&a.message.includes("Invalid revalidate"))throw a;return}}function r(a,b){let c=[],d=[];for(let e=0;e<a.length;e++){let f=a[e];if("string"!=typeof f?d.push({tag:f,reason:"invalid type, must be a string"}):f.length>h.NEXT_CACHE_TAG_MAX_LENGTH?d.push({tag:f,reason:`exceeded max length of ${h.NEXT_CACHE_TAG_MAX_LENGTH}`}):c.push((0,o.encodeCacheTag)(f)),c.length>h.NEXT_CACHE_TAG_MAX_ITEMS){console.warn(`Warning: exceeded max tag count for ${b}, dropped tags:`,a.slice(e).join(", "));break}}if(d.length>0)for(let{tag:a,reason:c}of(console.warn(`Warning: invalid tags passed to ${b}: `),d))console.log(`tag: "${a}" ${c}`);return c}function s(a,b){a.shouldTrackFetchMetrics&&(a.fetchMetrics??=[],a.fetchMetrics.push({...b,end:performance.timeOrigin+performance.now(),idx:a.nextFetchId||0}))}async function t(a,b,c,d,e,f){let g=await a.arrayBuffer(),h={headers:Object.fromEntries(a.headers.entries()),body:Buffer.from(g).toString("base64"),status:a.status,url:a.url};return c&&await d.set(b,{kind:m.CachedRouteKind.FETCH,data:h,revalidate:e},c),await f(),new Response(g,{headers:a.headers,status:a.status,statusText:a.statusText})}async function u(a,b,c,d,e,f,g,h,i,j){let[k,l]=(0,n.cloneResponse)(b),o=k.arrayBuffer().then(async a=>{let b=Buffer.from(a),h={headers:Object.fromEntries(k.headers.entries()),body:b.toString("base64"),status:k.status,url:k.url};null==f||f.set(c,h),d&&await e.set(c,{kind:m.CachedRouteKind.FETCH,data:h,revalidate:g},d)}).catch(a=>{(null==j?void 0:j.aborted)||console.warn("Failed to set fetch cache",h,a)}).finally(i),p=`cache-set-${c}`,q=a.pendingRevalidates??={},r=Promise.resolve();return p in q&&(r=q[p]),q[p]=r.then(()=>o).finally(()=>{(null==q?void 0:q[p])&&delete q[p]}),l}function v(a,{workAsyncStorage:b,workUnitAsyncStorage:c}){let d=async function(d,e){var k,o;let p;try{(p=new URL(d instanceof Request?d.url:d)).username="",p.password=""}catch{p=void 0}let v=(null==p?void 0:p.href)??"",w=(null==e||null==(k=e.method)?void 0:k.toUpperCase())||"GET",y=(null==e||null==(o=e.next)?void 0:o.internal)===!0,z="1"===process.env.NEXT_OTEL_FETCH_DISABLED,A=y?void 0:performance.timeOrigin+performance.now(),B=b.getStore(),C=c.getStore(),D=C?(0,l.getCacheSignal)(C):null;D&&D.beginRead();let E=(0,g.getTracer)().trace(y?f.NextNodeServerSpan.internalFetch:f.AppRenderSpan.fetch,{hideSpan:z,kind:g.SpanKind.CLIENT,spanName:["fetch",w,v].filter(Boolean).join(" "),attributes:{"http.url":v,"http.method":w,"net.peer.name":null==p?void 0:p.hostname,"net.peer.port":(null==p?void 0:p.port)||void 0}},async()=>{var b;let c,f,g,k,l,o;if(y||!B||B.isDraftMode)return a(d,e);let p=d&&"object"==typeof d&&"string"==typeof d.method,w=a=>(null==e?void 0:e[a])||(p?d[a]:null),z=a=>{var b,c,f;return void 0!==(null==e||null==(b=e.next)?void 0:b[a])?null==e||null==(c=e.next)?void 0:c[a]:p?null==(f=d.next)?void 0:f[a]:void 0},E=z("revalidate"),F=E,G=r(z("tags")||[],`fetch ${d.toString()}`);if(C)switch(C.type){case"prerender":case"prerender-runtime":case"prerender-client":case"validation-client":case"prerender-ppr":case"prerender-legacy":case"cache":case"private-cache":c=C}if(c&&Array.isArray(G)){let a=c.tags??(c.tags=[]);for(let b of G)a.includes(b)||a.push(b)}let H=null==C?void 0:C.implicitTags,I=B.fetchCache;C&&"unstable-cache"===C.type&&(I="force-no-store");let J=!!B.isUnstableNoStore,K=w("cache"),L="";"string"==typeof K&&void 0!==F&&("force-cache"===K&&0===F||"no-store"===K&&(F>0||!1===F))&&(f=`Specified "cache: ${K}" and "revalidate: ${F}", only one should be specified.`,K=void 0,F=void 0);let M="no-cache"===K||"no-store"===K||"force-no-store"===I||"only-no-store"===I,N=!I&&!K&&!F&&B.forceDynamic;"force-cache"===K&&void 0===F?F=!1:(M||N)&&(F=0),("no-cache"===K||"no-store"===K)&&(L=`cache: ${K}`),o=q(F,B.route);let O=w("headers"),P="function"==typeof(null==O?void 0:O.get)?O:new Headers(O||{}),Q=P.get("authorization")||P.get("cookie"),R=!["get","head"].includes((null==(b=w("method"))?void 0:b.toLowerCase())||"get"),S=void 0==I&&(void 0==K||"default"===K)&&void 0==F,T=!!((Q||R)&&(null==c?void 0:c.revalidate)===0),U=!1;if(!T&&S&&(B.isBuildTimePrerendering?U=!0:T=!0),S&&void 0!==C)switch(C.type){case"prerender":case"prerender-runtime":case"prerender-client":return D&&(D.endRead(),D=null),(0,j.makeHangingPromise)(C.renderSignal,B.route,"fetch()")}switch(I){case"force-no-store":L="fetchCache = force-no-store";break;case"only-no-store":if("force-cache"===K||void 0!==o&&o>0)throw Object.defineProperty(Error(`cache: 'force-cache' used on fetch for ${v} with 'export const fetchCache = 'only-no-store'`),"__NEXT_ERROR_CODE",{value:"E448",enumerable:!1,configurable:!0});L="fetchCache = only-no-store";break;case"only-cache":if("no-store"===K)throw Object.defineProperty(Error(`cache: 'no-store' used on fetch for ${v} with 'export const fetchCache = 'only-cache'`),"__NEXT_ERROR_CODE",{value:"E521",enumerable:!1,configurable:!0});break;case"force-cache":(void 0===F||0===F)&&(L="fetchCache = force-cache",o=h.INFINITE_CACHE)}if(void 0===o?"default-cache"!==I||J?"default-no-store"===I?(o=0,L="fetchCache = default-no-store"):J?(o=0,L="noStore call"):T?(o=0,L="auto no cache"):(L="auto cache",o=c?c.revalidate:h.INFINITE_CACHE):(o=h.INFINITE_CACHE,L="fetchCache = default-cache"):L||(L=`revalidate: ${o}`),!(B.forceStatic&&0===o)&&!T&&c&&o<c.revalidate){if(0===o){if(C)switch(C.type){case"prerender":case"prerender-client":case"prerender-runtime":case"validation-client":return D&&(D.endRead(),D=null),(0,j.makeHangingPromise)(C.renderSignal,B.route,"fetch()")}(0,i.markCurrentScopeAsDynamic)(B,C,`revalidate: 0 fetch ${d} ${B.route}`)}c&&E===o&&(c.revalidate=o)}let V="number"==typeof o&&o>0,{incrementalCache:W}=B,X=!1;if(C)switch(C.type){case"request":case"cache":case"private-cache":X=C.isHmrRefresh??!1,k=C.serverComponentsHmrCache}if(W&&(V||k))try{g=await W.generateCacheKey(v,p?d:e)}catch(a){console.error("Failed to generate cache key for",d)}let Y=B.nextFetchId??1;B.nextFetchId=Y+1;let Z=()=>{},$=async(b,c)=>{let i=["cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","window","duplex",...b?[]:["signal"]];if(p){let a=d,b={body:a._ogBody||a.body};for(let c of i)b[c]=a[c];d=new Request(a.url,b)}else if(e){let{_ogBody:a,body:c,signal:d,...f}=e;e={...f,body:a||c,signal:b?void 0:d}}let j={...e,next:{...null==e?void 0:e.next,fetchType:"origin",fetchIdx:Y}};return a(d,j).then(async a=>{if(!b&&A&&s(B,{start:A,url:v,cacheReason:c||L,cacheStatus:0===o||c?"skip":"miss",cacheWarning:f,status:a.status,method:j.method||"GET"}),200===a.status&&W&&g&&(V||k)){let b=o>=h.INFINITE_CACHE?h.CACHE_ONE_YEAR_SECONDS:o,c=V?{fetchCache:!0,fetchUrl:v,fetchIdx:Y,tags:G,isImplicitBuildTimeCache:U}:void 0;switch(null==C?void 0:C.type){case"prerender":case"prerender-client":case"validation-client":case"prerender-runtime":return t(a,g,c,W,b,Z);case"request":case"prerender-ppr":case"prerender-legacy":case"cache":case"private-cache":case"unstable-cache":case"generate-static-params":case void 0:return u(B,a,g,c,W,k,b,d,Z,w("signal"))}}return await Z(),a}).catch(a=>{throw Z(),a})},_=!1,aa=!1;if(g&&W){let a;if(X&&k&&(a=k.get(g),aa=!0),V&&!a){Z=await W.lock(g);let b=B.isOnDemandRevalidate?null:await W.get(g,{kind:m.IncrementalCacheKind.FETCH,revalidate:o,fetchUrl:v,fetchIdx:Y,tags:G,softTags:null==H?void 0:H.tags});if(S&&C)switch(C.type){case"prerender":case"prerender-client":case"validation-client":case"prerender-runtime":await (x||(x=new Promise(a=>{setTimeout(()=>{x=null,a()},0)})),x)}if(b?await Z():l="cache-control: no-cache (hard refresh)",(null==b?void 0:b.value)&&b.value.kind===m.CachedRouteKind.FETCH)if(B.isStaticGeneration&&b.isStale)_=!0;else{if(b.isStale&&(B.pendingRevalidates??={},!B.pendingRevalidates[g])){let a=$(!0).then(async a=>({body:await a.arrayBuffer(),headers:a.headers,status:a.status,statusText:a.statusText})).finally(()=>{B.pendingRevalidates??={},delete B.pendingRevalidates[g||""]});a.catch(console.error),B.pendingRevalidates[g]=a}a=b.value.data}}if(a){A&&s(B,{start:A,url:v,cacheReason:L,cacheStatus:aa?"hmr":"hit",cacheWarning:f,status:a.status||200,method:(null==e?void 0:e.method)||"GET"});let b=new Response(Buffer.from(a.body,"base64"),{headers:a.headers,status:a.status});return Object.defineProperty(b,"url",{value:a.url}),b}}if(B.isStaticGeneration&&e&&"object"==typeof e){let{cache:a}=e;if("no-store"===a){if(C)switch(C.type){case"prerender":case"prerender-client":case"prerender-runtime":case"validation-client":return D&&(D.endRead(),D=null),(0,j.makeHangingPromise)(C.renderSignal,B.route,"fetch()")}(0,i.markCurrentScopeAsDynamic)(B,C,`no-store fetch ${d} ${B.route}`)}let b="next"in e,{next:f={}}=e;if("number"==typeof f.revalidate&&c&&f.revalidate<c.revalidate){if(0===f.revalidate){if(C)switch(C.type){case"prerender":case"prerender-client":case"prerender-runtime":case"validation-client":return(0,j.makeHangingPromise)(C.renderSignal,B.route,"fetch()")}(0,i.markCurrentScopeAsDynamic)(B,C,`revalidate: 0 fetch ${d} ${B.route}`)}B.forceStatic&&0===f.revalidate||(c.revalidate=f.revalidate)}b&&delete e.next}if(!g||!_)return $(!1,l);{let a=g;B.pendingRevalidates??={};let b=B.pendingRevalidates[a];if(b){let a=await b;return new Response(a.body,{headers:a.headers,status:a.status,statusText:a.statusText})}let c=$(!0,l).then(n.cloneResponse);return(b=c.then(async a=>{let b=a[0];return{body:await b.arrayBuffer(),headers:b.headers,status:b.status,statusText:b.statusText}}).finally(()=>{var b;(null==(b=B.pendingRevalidates)?void 0:b[a])&&delete B.pendingRevalidates[a]})).catch(()=>{}),B.pendingRevalidates[a]=b,c.then(a=>a[1])}});if(D)try{return await E}finally{D&&D.endRead()}return E};return d.__nextPatched=!0,d.__nextGetStaticStore=()=>b,d._nextOriginalFetch=a,globalThis[p]=!0,Object.defineProperty(d,"name",{value:"fetch",writable:!1}),d}function w(a){if(!0===globalThis[p])return;let b=(0,k.createDedupeFetch)(globalThis.fetch);globalThis.fetch=v(b,a)}let x=null},84750:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={PageSignatureError:function(){return e},RemovedPageError:function(){return f},RemovedUAError:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});class e extends Error{constructor({page:a}){super(`The middleware "${a}" accepts an async API directly with the form:
|
|
735
|
+
|
|
736
|
+
export function middleware(request, event) {
|
|
737
|
+
return NextResponse.redirect('/new-location')
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
Read more: https://nextjs.org/docs/messages/middleware-new-signature
|
|
741
|
+
`)}}class f extends Error{constructor(){super("The request.page has been deprecated in favour of `URLPattern`.\n Read more: https://nextjs.org/docs/messages/middleware-request-page\n ")}}class g extends Error{constructor(){super("The request.ua has been removed in favour of `userAgent` function.\n Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n ")}}},85239:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"addPathPrefix",{enumerable:!0,get:function(){return e}});let d=c(39098);function e(a,b){if(!a.startsWith("/")||!b)return a;let{pathname:c,query:e,hash:f}=(0,d.parsePath)(a);return`${b}${c}${e}${f}`}},85556:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"InvariantError",{enumerable:!0,get:function(){return c}});class c extends Error{constructor(a,b){super(`Invariant: ${a.endsWith(".")?a:a+"."} This is a bug in Next.js.`,b),this.name="InvariantError"}}},85680:(a,b,c)=>{"use strict";c.d(b,{z:()=>f});var d=c(9853),e=c(62547);let f=({schema:a,usePlural:b})=>{let c=(0,e.G)({schema:a,usePlural:b});return({field:b,model:e})=>{if("id"===b||"_id"===b)return"id";let f=c(e),g=a[f]?.fields[b];if(!g){let c=Object.entries(a[f].fields).find(([a,c])=>c.fieldName===b);c&&(g=c[1],b=c[0])}if(!g)throw new d.$l(`Field ${b} not found in model ${f}`);return b}}},86965:(a,b,c)=>{"use strict";Object.defineProperty(b,"e",{enumerable:!0,get:function(){return k}});let d=c(52730),e=c(84698),f=c(29294),g=c(63033),h=c(46752),i=0;async function j(a,b,c,e,f,g,i){await b.set(c,{kind:h.CachedRouteKind.FETCH,data:{headers:{},body:JSON.stringify(a),status:200,url:""},revalidate:"number"!=typeof f?d.CACHE_ONE_YEAR_SECONDS:f},{fetchCache:!0,tags:e,fetchIdx:g,fetchUrl:i})}function k(a,b,c={}){if(0===c.revalidate)throw Object.defineProperty(Error(`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${a.toString()}`),"__NEXT_ERROR_CODE",{value:"E57",enumerable:!1,configurable:!0});let d=c.tags?(0,e.validateTags)(c.tags,`unstable_cache ${a.toString()}`):[];(0,e.validateRevalidate)(c.revalidate,`unstable_cache ${a.name||a.toString()}`);let l=`${a.toString()}-${Array.isArray(b)&&b.join(",")}`;return async(...b)=>{let e=f.workAsyncStorage.getStore(),k=g.workUnitAsyncStorage.getStore(),m=(null==e?void 0:e.incrementalCache)||globalThis.__incrementalCache;if(!m)throw Object.defineProperty(Error(`Invariant: incrementalCache missing in unstable_cache ${a.toString()}`),"__NEXT_ERROR_CODE",{value:"E469",enumerable:!1,configurable:!0});let n=k?(0,g.getCacheSignal)(k):null;n&&n.beginRead();try{let f=e&&k?function(a,b){switch(b.type){case"request":let c=b.url.pathname,d=new URLSearchParams(b.url.search),e=[...d.keys()].sort((a,b)=>a.localeCompare(b)).map(a=>`${a}=${d.get(a)}`).join("&");return`${c}${e.length?"?":""}${e}`;case"prerender":case"prerender-client":case"validation-client":case"prerender-runtime":case"prerender-ppr":case"prerender-legacy":case"cache":case"private-cache":case"unstable-cache":case"generate-static-params":return a.route;default:return b}}(e,k):"",n=`${l}-${JSON.stringify(b)}`,o=await m.generateCacheKey(n),p=`unstable_cache ${f} ${a.name?` ${a.name}`:o}`,q=(e?e.nextFetchId:i)??1,r=null==k?void 0:k.implicitTags,s={type:"unstable-cache",phase:"render",implicitTags:r,draftMode:k&&e&&(0,g.getDraftModeProviderForCacheScope)(e,k),rootParams:void 0};if(e){e.nextFetchId=q+1;let f=!1;if(k)switch(k.type){case"cache":case"private-cache":case"prerender":case"prerender-runtime":case"prerender-ppr":case"prerender-legacy":"number"==typeof c.revalidate&&(k.revalidate<c.revalidate||(k.revalidate=c.revalidate));let i=k.tags;if(null===i)k.tags=d.slice();else for(let a of d)i.includes(a)||i.push(a);break;case"unstable-cache":f=!0}if(!f&&"force-no-store"!==e.fetchCache&&!e.isOnDemandRevalidate&&!m.isOnDemandRevalidate&&!e.isDraftMode){let f=await m.get(o,{kind:h.IncrementalCacheKind.FETCH,revalidate:c.revalidate,tags:d,softTags:null==r?void 0:r.tags,fetchIdx:q,fetchUrl:p});if(f&&f.value)if(f.value.kind!==h.CachedRouteKind.FETCH)console.error(`Invariant invalid cacheEntry returned for ${n}`);else{let h=void 0!==f.value.data.body?JSON.parse(f.value.data.body):void 0;if(f.isStale){if(e.pendingRevalidates||(e.pendingRevalidates={}),!e.pendingRevalidates[n]){let f=g.workUnitAsyncStorage.run(s,a,...b).then(async a=>(await j(a,m,o,d,c.revalidate,q,p),a)).catch(a=>(console.error(`revalidating cache with key: ${n}`,a),h));e.isStaticGeneration&&f.catch(()=>{}),e.pendingRevalidates[n]=f}if(e.isStaticGeneration)return await e.pendingRevalidates[n]}return h}}let l=await g.workUnitAsyncStorage.run(s,a,...b);return e.isDraftMode||(e.pendingRevalidates||(e.pendingRevalidates={}),e.pendingRevalidates[n]=j(l,m,o,d,c.revalidate,q,p)),l}{if(i+=1,!m.isOnDemandRevalidate){let a=await m.get(o,{kind:h.IncrementalCacheKind.FETCH,revalidate:c.revalidate,tags:d,fetchIdx:q,fetchUrl:p,softTags:null==r?void 0:r.tags});if(a&&a.value){if(a.value.kind!==h.CachedRouteKind.FETCH)console.error(`Invariant invalid cacheEntry returned for ${n}`);else if(!a.isStale)return void 0!==a.value.data.body?JSON.parse(a.value.data.body):void 0}}let e=await g.workUnitAsyncStorage.run(s,a,...b);return await j(e,m,o,d,c.revalidate,q,p),e}}finally{n&&n.endRead()}}}},87143:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={delayUntilRuntimeStage:function(){return o},getRuntimeStage:function(){return n},isHangingPromiseRejectionError:function(){return g},makeDevtoolsIOAwarePromise:function(){return m},makeHangingPromise:function(){return k}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(94931);function g(a){return"object"==typeof a&&null!==a&&"digest"in a&&a.digest===h}let h="HANGING_PROMISE_REJECTION";class i extends Error{constructor(a,b){super(`During prerendering, ${b} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${b} to a different context by using \`setTimeout\`, \`after\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "${a}".`),this.route=a,this.expression=b,this.digest=h}}let j=new WeakMap;function k(a,b,c){if(a.aborted)return Promise.reject(new i(b,c));{let d=new Promise((d,e)=>{let f=e.bind(null,new i(b,c)),g=j.get(a);if(g)g.push(f);else{let b=[f];j.set(a,b),a.addEventListener("abort",()=>{for(let a=0;a<b.length;a++)b[a]()},{once:!0})}});return d.catch(l),d}}function l(){}function m(a,b,c){return b.stagedRendering?b.stagedRendering.delayUntilStage(c,void 0,a):new Promise(b=>{setTimeout(()=>{b(a)},0)})}function n(a){return a.currentStage===f.RenderStage.EarlyStatic||a.currentStage===f.RenderStage.EarlyRuntime?f.RenderStage.EarlyRuntime:f.RenderStage.Runtime}function o(a,b){let{stagedRendering:c}=a;return c?c.waitForStage(n(c)).then(()=>b):b}},87301:(a,b,c)=>{"use strict";c.d(b,{L:()=>o});var d=c(91408),e=c(37694),f=c(69832),g=c(22046),h=c(21513),i=c(18110);let j=(0,i.CN)({is:a=>"ReturningNode"===a.kind,create:a=>(0,i.CN)({kind:"ReturningNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})}),k=(0,i.CN)({is:a=>"ExplainNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ExplainNode",format:a,options:b})});var l=c(107);let m=(0,i.CN)({is:a=>"OutputNode"===a.kind,create:a=>(0,i.CN)({kind:"OutputNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})});var n=c(54254);let o=(0,i.CN)({is:a=>e.L.is(a)||d.o.is(a)||f.U.is(a)||g.e.is(a)||l.r.is(a),cloneWithEndModifier:(a,b)=>(0,i.CN)({...a,endModifiers:a.endModifiers?(0,i.CN)([...a.endModifiers,b]):(0,i.CN)([b])}),cloneWithWhere:(a,b)=>(0,i.CN)({...a,where:a.where?h.o.cloneWithOperation(a.where,"And",b):h.o.create(b)}),cloneWithJoin:(a,b)=>(0,i.CN)({...a,joins:a.joins?(0,i.CN)([...a.joins,b]):(0,i.CN)([b])}),cloneWithReturning:(a,b)=>(0,i.CN)({...a,returning:a.returning?j.cloneWithSelections(a.returning,b):j.create(b)}),cloneWithoutReturning:a=>(0,i.CN)({...a,returning:void 0}),cloneWithoutWhere:a=>(0,i.CN)({...a,where:void 0}),cloneWithExplain:(a,b,c)=>(0,i.CN)({...a,explain:k.create(b,c?.toOperationNode())}),cloneWithTop:(a,b)=>(0,i.CN)({...a,top:b}),cloneWithOutput:(a,b)=>(0,i.CN)({...a,output:a.output?m.cloneWithSelections(a.output,b):m.create(b)}),cloneWithOrderByItems:(a,b)=>(0,i.CN)({...a,orderBy:a.orderBy?n.O.cloneWithItems(a.orderBy,b):n.O.create(b)}),cloneWithoutOrderBy:a=>(0,i.CN)({...a,orderBy:void 0})})},88035:(a,b,c)=>{"use strict";c.d(b,{C:()=>h,g:()=>g});var d=c(60351),e=c(45541),f=c(18110);class g{#a1;get dynamicReference(){return this.#a1}get refType(){}constructor(a){this.#a1=a}toOperationNode(){return(0,e.vd)(this.#a1)}}function h(a){return(0,f.Gv)(a)&&(0,d.N)(a)&&(0,f.Kg)(a.dynamicReference)}},88743:(a,b,c)=>{"use strict";c.d(b,{l:()=>d});class d{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}},88825:(a,b,c)=>{let d=+(process.versions?process.versions.node:"").split(".")[0]||0;a.exports=function(a,b){var e=c(74075);let f=d>=15&&b>0?{maxOutputLength:b}:{};return{inflate:function(){return e.inflateRawSync(a,f)},inflateAsync:function(b){var c=e.createInflateRaw(f),d=[],g=0;c.on("data",function(a){d.push(a),g+=a.length}),c.on("end",function(){var a=Buffer.alloc(g),c=0;a.fill(0);for(var e=0;e<d.length;e++){var f=d[e];f.copy(a,c),c+=f.length}b&&b(a)}),c.end(a)}}}},88891:(a,b,c)=>{"use strict";c.d(b,{s:()=>g});var d=c(24607);let e=/"/g,f=/[\\'"]/g;class g extends d.n{visitOrAction(a){this.append("or "),this.append(a.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(a){return a.replace(e,'""')}sanitizeJSONPathMemberValue(a){return a.replace(f,a=>"\\"===a?"\\\\":"'"===a?"''":'\\"')}visitDefaultInsertValue(a){this.append("null")}}},89192:(a,b,c)=>{"use strict";c.d(b,{B:()=>p});var d=c(50182),e=c(98051),f=c(48145),g=c(4224),h=c(75525),i=c(18110);let j={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};var k=c(4432),l=c(3694),m=c(62030);let n=(0,i.CN)({json_agg:!0,to_json:!0});class o extends h.V{#a2;#a3=new Set;#a4=new Set;constructor(a){super(),this.#a2=a}transformNodeImpl(a,b){if(!((0,i.Gv)(a)&&(0,i.Kg)(a.kind))||!0!==j[a.kind])return super.transformNodeImpl(a,b);let c=this.#a5(a);for(let a of c)this.#a4.add(a);let d=this.#a6(a);for(let a of d)this.#a3.add(a);let e=super.transformNodeImpl(a,b);for(let a of d)this.#a3.delete(a);for(let a of c)this.#a4.delete(a);return e}transformSchemableIdentifier(a,b){let c=super.transformSchemableIdentifier(a,b);return c.schema||!this.#a3.has(a.identifier.name)?c:{...c,schema:e.O.create(this.#a2)}}transformReferences(a,b){let c=super.transformReferences(a,b);return c.table.table.schema?c:{...c,table:l.H.createWithSchema(this.#a2,c.table.table.identifier.name)}}transformAggregateFunction(a,b){return{...super.transformAggregateFunction({...a,aggregated:[]},b),aggregated:this.#a7(a,b,"aggregated")}}transformFunction(a,b){return{...super.transformFunction({...a,arguments:[]},b),arguments:this.#a7(a,b,"arguments")}}transformSelectModifier(a,b){return{...super.transformSelectModifier({...a,of:void 0},b),of:a.of?.map(a=>l.H.is(a)&&!a.table.schema?{...a,table:this.transformIdentifier(a.table.identifier,b)}:this.transformNode(a,b))}}#a7(a,b,c){return n[a.func]?a[c].map(a=>!l.H.is(a)||a.table.schema?this.transformNode(a,b):{...a,table:this.transformIdentifier(a.table.identifier,b)}):this.transformNodeList(a[c],b)}#a6(a){let b=new Set;if("name"in a&&a.name&&k.y.is(a.name)&&this.#a8(a.name,b),"from"in a&&a.from)for(let c of a.from.froms)this.#a9(c,b);if("into"in a&&a.into&&this.#a9(a.into,b),"table"in a&&a.table&&this.#a9(a.table,b),"joins"in a&&a.joins)for(let c of a.joins)this.#a9(c.table,b);return"using"in a&&a.using&&(f.b.is(a.using)?this.#a9(a.using.table,b):this.#a9(a.using,b)),b}#a5(a){let b=new Set;return"with"in a&&a.with&&this.#ba(a.with,b),b}#a9(a,b){if(l.H.is(a))return this.#a8(a.table,b);if(d.N.is(a)&&l.H.is(a.node))return this.#a8(a.node.table,b);if(g.v.is(a)){for(let c of a.items)this.#a9(c,b);return}if(m.f.is(a)){for(let c of a.tables)this.#a9(c,b);return}}#a8(a,b){let c=a.identifier.name;this.#a3.has(c)||this.#a4.has(c)||b.add(c)}#ba(a,b){for(let c of a.expressions){let a=c.name.table.table.identifier.name;this.#a4.has(a)||b.add(a)}}}class p{#T;constructor(a){this.#T=new o(a)}transformQuery(a){return this.#T.transformNode(a.node,a.queryId)}async transformResult(a){return a.result}}},90386:(a,b,c)=>{"use strict";c.d(b,{U:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"SelectAllNode"===a.kind,create:()=>(0,d.CN)({kind:"SelectAllNode"})})},90588:(a,b,c)=>{"use strict";c.d(b,{s:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"ValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueListNode",values:(0,d.CN)(a)})})},90977:(a,b,c)=>{let d=c(25296),e=c(33873),f=c(9738),g=c(9460),h=(...a)=>d.findLast(a,a=>"boolean"==typeof a),i=(...a)=>d.findLast(a,a=>"string"==typeof a),j={noSort:!1,readEntries:!1,method:d.Constants.NONE,fs:null};a.exports=function(a,b){let c=null,k=Object.assign(Object.create(null),j);a&&"object"==typeof a&&(a instanceof Uint8Array||(Object.assign(k,a),a=k.input?k.input:void 0,k.input&&delete k.input),Buffer.isBuffer(a)&&(c=a,k.method=d.Constants.BUFFER,a=void 0)),Object.assign(k,b);let l=new d(k);if(("object"!=typeof k.decoder||"function"!=typeof k.decoder.encode||"function"!=typeof k.decoder.decode)&&(k.decoder=d.decoder),a&&"string"==typeof a)if(l.fs.existsSync(a))k.method=d.Constants.FILE,k.filename=a,c=l.fs.readFileSync(a);else throw d.Errors.INVALID_FILENAME();let m=new g(c,k),{canonical:n,sanitize:o,zipnamefix:p}=d;function q(a){if(a&&m){var b;if("string"==typeof a&&(b=m.getEntry(e.posix.normalize(a))),"object"==typeof a&&void 0!==a.entryName&&void 0!==a.header&&(b=m.getEntry(a.entryName)),b)return b}return null}function r(a){let{join:b,normalize:c,sep:d}=e.posix;return b(e.isAbsolute(a)?"/":".",c(d+a.split("\\").join(d)+d))}function s(a){if(a instanceof RegExp)return function(b){return a.test(b)};return"function"!=typeof a?()=>!0:a}let t=(a,b)=>{let c=b.slice(-1);return c=c===l.sep?l.sep:"",e.relative(a,b)+c};return{readFile:function(a,b){var c=q(a);return c&&c.getData(b)||null},childCount:function(a){let b=q(a);if(b)return m.getChildCount(b)},readFileAsync:function(a,b){var c=q(a);c?c.getDataAsync(b):b(null,"getEntry failed for:"+a)},readAsText:function(a,b){var c=q(a);if(c){var d=c.getData();if(d&&d.length)return d.toString(b||"utf8")}return""},readAsTextAsync:function(a,b,c){var d=q(a);d?d.getDataAsync(function(a,d){d?b(a,d):a&&a.length?b(a.toString(c||"utf8")):b("")}):b("")},deleteFile:function(a,b=!0){var c=q(a);c&&m.deleteFile(c.entryName,b)},deleteEntry:function(a){var b=q(a);b&&m.deleteEntry(b.entryName)},addZipComment:function(a){m.comment=a},getZipComment:function(){return m.comment||""},addZipEntryComment:function(a,b){var c=q(a);c&&(c.comment=b)},getZipEntryComment:function(a){var b=q(a);return b&&b.comment||""},updateFile:function(a,b){var c=q(a);c&&c.setData(b)},addLocalFile:function(a,b,c,f){if(l.fs.existsSync(a)){b=b?r(b):"";let d=e.win32.basename(e.win32.normalize(a));b+=c||d;let g=l.fs.statSync(a),h=g.isFile()?l.fs.readFileSync(a):Buffer.alloc(0);g.isDirectory()&&(b+=l.sep),this.addFile(b,h,f,g)}else throw d.Errors.FILE_NOT_FOUND(a)},addLocalFileAsync:function(a,b){a="object"==typeof a?a:{localPath:a};let c=e.resolve(a.localPath),{comment:d}=a,{zipPath:f,zipName:g}=a,h=this;l.fs.stat(c,function(a,i){if(a)return b(a,!1);f=f?r(f):"";let j=e.win32.basename(e.win32.normalize(c));if(f+=g||j,i.isFile())l.fs.readFile(c,function(a,c){return a?b(a,!1):(h.addFile(f,c,d,i),setImmediate(b,void 0,!0))});else if(i.isDirectory())return f+=l.sep,h.addFile(f,Buffer.alloc(0),d,i),setImmediate(b,void 0,!0)})},addLocalFolder:function(a,b,c){if(c=s(c),b=b?r(b):"",a=e.normalize(a),l.fs.existsSync(a)){let d=l.findFiles(a);if(d.length)for(let f of d){let d=e.join(b,t(a,f));c(d)&&this.addLocalFile(f,e.dirname(d))}}else throw d.Errors.FILE_NOT_FOUND(a)},addLocalFolderAsync:function(a,b,c,f){f=s(f),c=c?r(c):"",a=e.normalize(a);var g=this;l.fs.open(a,"r",function(e){if(e&&"ENOENT"===e.code)b(void 0,d.Errors.FILE_NOT_FOUND(a));else if(e)b(void 0,e);else{var h=l.findFiles(a),i=-1,j=function(){if((i+=1)<h.length){var d=h[i],e=t(a,d).split("\\").join("/");e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(e)?l.fs.stat(d,function(a,f){a&&b(void 0,a),f.isFile()?l.fs.readFile(d,function(a,d){a?b(void 0,a):(g.addFile(c+e,d,"",f),j())}):(g.addFile(c+e+"/",Buffer.alloc(0),"",f),j())}):process.nextTick(()=>{j()})}else b(!0,void 0)};j()}})},addLocalFolderAsync2:function(a,b){let c=this;a="object"==typeof a?a:{localPath:a},localPath=e.resolve(r(a.localPath));let{zipPath:f,filter:g,namefix:h}=a;if(g instanceof RegExp){var i;i=g,g=function(a){return i.test(a)}}else"function"!=typeof g&&(g=function(){return!0});f=f?r(f):"","latin1"==h&&(h=a=>a.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),"function"!=typeof h&&(h=a=>a);let j=a=>e.join(f,h(t(localPath,a)));l.fs.open(localPath,"r",function(a){a&&"ENOENT"===a.code?b(void 0,d.Errors.FILE_NOT_FOUND(localPath)):a?b(void 0,a):l.findFilesAsync(localPath,function(a,d){if(a)return b(a);(d=d.filter(a=>g(j(a)))).length||b(void 0,!1),setImmediate(d.reverse().reduce(function(a,b){return function(d,f){if(d||!1===f)return setImmediate(a,d,!1);c.addLocalFileAsync({localPath:b,zipPath:e.dirname(j(b)),zipName:e.win32.basename(e.win32.normalize(h(b)))},a)}},b))})})},addLocalFolderPromise:function(a,b){return new Promise((c,d)=>{this.addLocalFolderAsync2(Object.assign({localPath:a},b),(a,b)=>{a&&d(a),b&&c(this)})})},addFile:function(a,b,c,d){let e=q(a=p(a)),g=null!=e;g||((e=new f(k)).entryName=a),e.comment=c||"";let h="object"==typeof d&&d instanceof l.fs.Stats;h&&(e.header.time=d.mtime);var i=16*!!e.isDirectory;let j=e.isDirectory?16384:32768;return h?j|=4095&d.mode:"number"==typeof d?j|=4095&d:j|=e.isDirectory?493:420,i=(i|j<<16)>>>0,e.attr=i,e.setData(b),g||m.setEntry(e),e},getEntries:function(a){return m.password=a,m?m.entries:[]},getEntry:function(a){return q(a)},getEntryCount:function(){return m.getEntryCount()},forEach:function(a){return m.forEach(a)},extractEntryTo:function(a,b,c,f,g,j){f=h(!1,f),g=h(!1,g),c=h(!0,c),j=i(g,j);var k=q(a);if(!k)throw d.Errors.NO_ENTRY();var p=n(k.entryName),r=o(b,j&&!k.isDirectory?j:c?p:e.basename(p));if(k.isDirectory)return m.getEntryChildren(k).forEach(function(a){if(a.isDirectory)return;var h=a.getData();if(!h)throw d.Errors.CANT_EXTRACT_FILE();var i=n(a.entryName),j=o(b,c?i:e.basename(i));let k=g?a.header.fileAttr:void 0;l.writeFileTo(j,h,f,k)}),!0;var s=k.getData(m.password);if(!s)throw d.Errors.CANT_EXTRACT_FILE();if(l.fs.existsSync(r)&&!f)throw d.Errors.CANT_OVERRIDE();let t=g?a.header.fileAttr:void 0;return l.writeFileTo(r,s,f,t),!0},test:function(a){if(!m)return!1;for(var b in m.entries)try{if(b.isDirectory)continue;if(!m.entries[b].getData(a))return!1}catch(a){return!1}return!0},extractAllTo:function(a,b,c,e){if(e=i(c=h(!1,c),e),b=h(!1,b),!m)throw d.Errors.NO_ZIP();m.entries.forEach(function(f){var g=o(a,n(f.entryName));if(f.isDirectory)return void l.makeDir(g);var h=f.getData(e);if(!h)throw d.Errors.CANT_EXTRACT_FILE();let i=c?f.header.fileAttr:void 0;l.writeFileTo(g,h,b,i);try{l.fs.utimesSync(g,f.header.time,f.header.time)}catch(a){throw d.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(a,b,c,f){if(f=((...a)=>d.findLast(a,a=>"function"==typeof a))(b,c,f),c=h(!1,c),b=h(!1,b),!f)return new Promise((d,e)=>{this.extractAllToAsync(a,b,c,function(a){a?e(a):d(this)})});if(!m)return void f(d.Errors.NO_ZIP());a=e.resolve(a);let g=b=>o(a,e.normalize(n(b.entryName))),i=(a,b)=>Error(a+': "'+b+'"'),j=[],k=[];for(let a of(m.entries.forEach(a=>{a.isDirectory?j.push(a):k.push(a)}),j)){let b=g(a),d=c?a.header.fileAttr:void 0;try{l.makeDir(b),d&&l.fs.chmodSync(b,d),l.fs.utimesSync(b,a.header.time,a.header.time)}catch(a){f(i("Unable to create folder",b))}}k.reverse().reduce(function(f,g){return function(h){if(h)f(h);else{let h=e.normalize(n(g.entryName)),j=o(a,h);g.getDataAsync(function(a,e){if(e)f(e);else if(a){let d=c?g.header.fileAttr:void 0;l.writeFileToAsync(j,a,b,d,function(a){a||f(i("Unable to write file",j)),l.fs.utimes(j,g.header.time,g.header.time,function(a){a?f(i("Unable to set times",j)):f()})})}else f(d.Errors.CANT_EXTRACT_FILE())})}}},f)()},writeZip:function(a,b){if(1==arguments.length&&"function"==typeof a&&(b=a,a=""),!a&&k.filename&&(a=k.filename),a){var c=m.compressToBuffer();if(c){var d=l.writeFileTo(a,c,!0);"function"==typeof b&&b(d?null:Error("failed"),"")}}},writeZipPromise:function(a,b){let{overwrite:c,perm:d}=Object.assign({overwrite:!0},b);return new Promise((b,e)=>{!a&&k.filename&&(a=k.filename),a||e("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(f=>{l.writeFileToAsync(a,f,c,d,a=>a?b(a):e("ADM-ZIP: Wasn't able to write zip file"))},e)})},toBufferPromise:function(){return new Promise((a,b)=>{m.toAsyncBuffer(a,b)})},toBuffer:function(a,b,c,d){return"function"==typeof a?(m.toAsyncBuffer(a,b,c,d),null):m.compressToBuffer()}}}},90983:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={djb2Hash:function(){return e},hexHash:function(){return f}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});function e(a){let b=5381;for(let c=0;c<a.length;c++)b=(b<<5)+b+a.charCodeAt(c)|0;return b>>>0}function f(a){return e(a).toString(36).slice(0,5)}},91408:(a,b,c)=>{"use strict";c.d(b,{o:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"InsertQueryNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"InsertQueryNode",into:a,...b&&{with:b},replace:c}),createWithoutInto:()=>(0,d.CN)({kind:"InsertQueryNode"}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},94931:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d,e={RenderStage:function(){return i},StagedRenderingController:function(){return j}};for(var f in e)Object.defineProperty(b,f,{enumerable:!0,get:e[f]});let g=c(85556),h=c(38697);var i=((d={})[d.Before=1]="Before",d[d.EarlyStatic=2]="EarlyStatic",d[d.Static=3]="Static",d[d.EarlyRuntime=4]="EarlyRuntime",d[d.Runtime=5]="Runtime",d[d.Dynamic=6]="Dynamic",d[d.Abandoned=7]="Abandoned",d);class j{constructor(a,b,c){this.abortSignal=a,this.abandonController=b,this.shouldTrackSyncIO=c,this.currentStage=1,this.syncInterruptReason=null,this.staticStageEndTime=1/0,this.runtimeStageEndTime=1/0,this.staticStageListeners=[],this.earlyRuntimeStageListeners=[],this.runtimeStageListeners=[],this.dynamicStageListeners=[],this.staticStagePromise=(0,h.createPromiseWithResolvers)(),this.earlyRuntimeStagePromise=(0,h.createPromiseWithResolvers)(),this.runtimeStagePromise=(0,h.createPromiseWithResolvers)(),this.dynamicStagePromise=(0,h.createPromiseWithResolvers)(),a&&a.addEventListener("abort",()=>{let{reason:b}=a;this.staticStagePromise.promise.catch(k),this.staticStagePromise.reject(b),this.earlyRuntimeStagePromise.promise.catch(k),this.earlyRuntimeStagePromise.reject(b),this.runtimeStagePromise.promise.catch(k),this.runtimeStagePromise.reject(b),this.dynamicStagePromise.promise.catch(k),this.dynamicStagePromise.reject(b)},{once:!0}),b&&b.signal.addEventListener("abort",()=>{this.abandonRender()},{once:!0})}onStage(a,b){if(this.currentStage>=a)b();else if(3===a)this.staticStageListeners.push(b);else if(4===a)this.earlyRuntimeStageListeners.push(b);else if(5===a)this.runtimeStageListeners.push(b);else if(6===a)this.dynamicStageListeners.push(b);else throw Object.defineProperty(new g.InvariantError(`Invalid render stage: ${a}`),"__NEXT_ERROR_CODE",{value:"E881",enumerable:!1,configurable:!0})}shouldTrackSyncInterrupt(){if(!this.shouldTrackSyncIO)return!1;switch(this.currentStage){case 1:case 5:case 6:case 7:default:return!1;case 2:case 3:case 4:return!0}}syncInterruptCurrentStageWithReason(a){if(1!==this.currentStage&&7!==this.currentStage){if(this.abandonController)return void this.abandonController.abort();if(this.abortSignal){this.syncInterruptReason=a,this.currentStage=7;return}switch(this.currentStage){case 2:case 3:case 4:this.syncInterruptReason=a,this.advanceStage(6);return;case 5:return}}}getSyncInterruptReason(){return this.syncInterruptReason}getStaticStageEndTime(){return this.staticStageEndTime}getRuntimeStageEndTime(){return this.runtimeStageEndTime}abandonRender(){let{currentStage:a}=this;switch(a){case 2:this.resolveStaticStage();case 3:this.resolveEarlyRuntimeStage();case 4:this.resolveRuntimeStage();case 5:this.currentStage=7;return}}advanceStage(a){if(a<=this.currentStage)return;let b=this.currentStage;if(this.currentStage=a,b<3&&a>=3&&this.resolveStaticStage(),b<4&&a>=4&&this.resolveEarlyRuntimeStage(),b<5&&a>=5&&(this.staticStageEndTime=performance.now()+performance.timeOrigin,this.resolveRuntimeStage()),b<6&&a>=6){this.runtimeStageEndTime=performance.now()+performance.timeOrigin,this.resolveDynamicStage();return}}resolveStaticStage(){let a=this.staticStageListeners;for(let b=0;b<a.length;b++)a[b]();a.length=0,this.staticStagePromise.resolve()}resolveEarlyRuntimeStage(){let a=this.earlyRuntimeStageListeners;for(let b=0;b<a.length;b++)a[b]();a.length=0,this.earlyRuntimeStagePromise.resolve()}resolveRuntimeStage(){let a=this.runtimeStageListeners;for(let b=0;b<a.length;b++)a[b]();a.length=0,this.runtimeStagePromise.resolve()}resolveDynamicStage(){let a=this.dynamicStageListeners;for(let b=0;b<a.length;b++)a[b]();a.length=0,this.dynamicStagePromise.resolve()}getStagePromise(a){switch(a){case 3:return this.staticStagePromise.promise;case 4:return this.earlyRuntimeStagePromise.promise;case 5:return this.runtimeStagePromise.promise;case 6:return this.dynamicStagePromise.promise;default:throw Object.defineProperty(new g.InvariantError(`Invalid render stage: ${a}`),"__NEXT_ERROR_CODE",{value:"E881",enumerable:!1,configurable:!0})}}waitForStage(a){return this.getStagePromise(a)}delayUntilStage(a,b,c){var d,e,f;let g,h=(d=this.getStagePromise(a),e=b,f=c,g=new Promise((a,b)=>{d.then(a.bind(null,f),b)}),void 0!==e&&(g.displayName=e),g);return this.abortSignal&&h.catch(k),h}}function k(){}},95260:(a,b,c)=>{"use strict";c.d(b,{D:()=>e});let d=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function e(a){let b="";for(let c=0;c<a;++c)b+=d[~~(Math.random()*d.length)];return b}},95962:(a,b,c)=>{"use strict";c.d(b,{G:()=>f});var d=c(79362),e=c(18110);async function f(a,b){let c=new d.c,f=new d.c;return a.provideConnection(async a=>(c.resolve(a),await f.promise),b).catch(a=>c.reject(a)),(0,e.CN)({connection:await c.promise,release:f.resolve})}},96690:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={DynamicServerError:function(){return f},isDynamicServerError:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e="DYNAMIC_SERVER_USAGE";class f extends Error{constructor(a){super(`Dynamic server usage: ${a}`),this.description=a,this.digest=e}}function g(a){return"object"==typeof a&&null!==a&&"digest"in a&&"string"==typeof a.digest&&a.digest===e}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},97551:(a,b,c)=>{"use strict";c.d(b,{u:()=>e});let d=new Set;function e(a){d.has(a)||(d.add(a),console.log(a))}},97762:(a,b)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var c={NEXT_REQUEST_META:function(){return e},addRequestMeta:function(){return h},getRequestMeta:function(){return f},removeRequestMeta:function(){return i},setRequestMeta:function(){return g}};for(var d in c)Object.defineProperty(b,d,{enumerable:!0,get:c[d]});let e=Symbol.for("NextInternalRequestMeta");function f(a,b){let c=a[e]||{};return"string"==typeof b?c[b]:c}function g(a,b){return a[e]=b,b}function h(a,b,c){let d=f(a);return d[b]=c,g(a,d)}function i(a,b){let c=f(a);return delete c[b],g(a,c)}},98051:(a,b,c)=>{"use strict";c.d(b,{O:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"IdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"IdentifierNode",name:a})})},98444:(a,b,c)=>{"use strict";c.d(b,{t:()=>e});var d=c(18110);let e=(0,d.CN)({is:a=>"WhenNode"===a.kind,create:a=>(0,d.CN)({kind:"WhenNode",condition:a}),cloneWithResult:(a,b)=>(0,d.CN)({...a,result:b})})},98789:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});var d={computeCacheBustingSearchParam:function(){return k},computeLegacyCacheBustingSearchParam:function(){return l}};for(var e in d)Object.defineProperty(b,e,{enumerable:!0,get:d[e]});let f=c(90983),g=new TextEncoder;function h(a){return void 0===a?"0":Array.isArray(a)?a.join(","):a}function i(a,b,c,d){return(void 0===a||"0"===a)&&void 0===b&&void 0===c&&void 0===d?null:[a??"0",h(b),h(c),h(d)].join(",")}async function j(a){var b=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",g.encode(a))).subarray(0,12);let c="";for(let a=0;a<b.length;a++)c+=String.fromCharCode(b[a]);return btoa(c).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function k(a,b,c,d){let e=i(a,b,c,d);return null===e?"":j(e)}function l(a,b,c,d){let e=i(a,b,c,d);return null===e?"":(0,f.hexHash)(e)}}};
|