wiki-viewer 2.6.2 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-path-routes-manifest.json +1 -0
- package/.next/standalone/.next/build-manifest.json +3 -3
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/routes-manifest.json +8 -0
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/agent/activity/route.js +7 -7
- package/.next/standalone/.next/server/app/api/agent/activity/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/admin/agents/[agentId]/revoke/route.js +5 -5
- package/.next/standalone/.next/server/app/api/agent/admin/agents/[agentId]/revoke/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/admin/agents/route.js +5 -5
- package/.next/standalone/.next/server/app/api/agent/admin/agents/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/approve/route.js +3 -3
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/approve/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/deny/route.js +5 -5
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/deny/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/route.js +5 -5
- package/.next/standalone/.next/server/app/api/agent/admin/registrations/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/events/[...path]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/agent/events/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/files/[...path]/route.js +8 -8
- package/.next/standalone/.next/server/app/api/agent/files/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/fs/file/[...path]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/agent/fs/file/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/fs/ls/[[...path]]/route.js +7 -7
- package/.next/standalone/.next/server/app/api/agent/fs/ls/[[...path]]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/fs/move/route.js +7 -7
- package/.next/standalone/.next/server/app/api/agent/fs/move/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/fs/search/route.js +7 -7
- package/.next/standalone/.next/server/app/api/agent/fs/search/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/internal/span/route.js +5 -5
- package/.next/standalone/.next/server/app/api/agent/internal/span/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/settings/route.js +8 -8
- package/.next/standalone/.next/server/app/api/agent/settings/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/agent/sidecar/[...path]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/agent/sidecar/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/app-proxy/[...path]/route.js +1 -1
- package/.next/standalone/.next/server/app/api/app-proxy/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/assets/[...path]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/assets/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/[...all]/route.js +3 -3
- package/.next/standalone/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/pdf/save/route.js +5 -5
- package/.next/standalone/.next/server/app/api/pdf/save/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route/app-paths-manifest.json +3 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route/build-manifest.json +9 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route/server-reference-manifest.json +4 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js +9 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js.map +5 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js.nft.json +1 -0
- package/.next/standalone/.next/server/app/api/share/[token]/asset/route_client-reference-manifest.js +3 -0
- package/.next/standalone/.next/server/app/api/share/[token]/route.js +5 -5
- package/.next/standalone/.next/server/app/api/share/[token]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/share/route.js +5 -5
- package/.next/standalone/.next/server/app/api/share/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/admins/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/admins/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/auth-config/route.js +6 -6
- package/.next/standalone/.next/server/app/api/system/auth-config/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/auth-settings/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/auth-settings/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/browse/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/browse/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/clear-root/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/clear-root/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/config/route.js +6 -6
- package/.next/standalone/.next/server/app/api/system/config/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/pins/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/pins/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/reveal/route.js +5 -5
- package/.next/standalone/.next/server/app/api/system/reveal/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/root-status/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/root-status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/set-root/route.js +6 -6
- package/.next/standalone/.next/server/app/api/system/set-root/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/users/route.js +5 -5
- package/.next/standalone/.next/server/app/api/system/users/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/branch/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/branch/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/open/route.js +6 -6
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/open/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/refresh/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/refresh/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/system/workspaces/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/system/workspaces/route.js +4 -4
- package/.next/standalone/.next/server/app/api/system/workspaces/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/upload/[...path]/route.js +6 -6
- package/.next/standalone/.next/server/app/api/upload/[...path]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/app/route.js +8 -8
- package/.next/standalone/.next/server/app/api/wiki/app/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/backlinks/route.js +8 -8
- package/.next/standalone/.next/server/app/api/wiki/backlinks/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/content/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/content/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/download/route.js +8 -8
- package/.next/standalone/.next/server/app/api/wiki/download/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/file/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/file/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/folder/route.js +7 -7
- package/.next/standalone/.next/server/app/api/wiki/folder/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-branches/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/git-branches/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-checkout/route.js +4 -4
- package/.next/standalone/.next/server/app/api/wiki/git-checkout/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-diff/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/git-diff/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-file-info/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/git-file-info/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-history/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/git-history/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/git-pull/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/git-pull/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/move/route.js +5 -5
- package/.next/standalone/.next/server/app/api/wiki/move/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/new-file/route.js +5 -5
- package/.next/standalone/.next/server/app/api/wiki/new-file/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/outlinks/route.js +8 -8
- package/.next/standalone/.next/server/app/api/wiki/outlinks/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/page/route.js +5 -5
- package/.next/standalone/.next/server/app/api/wiki/page/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/presence/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/presence/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/search/route.js +8 -8
- package/.next/standalone/.next/server/app/api/wiki/search/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/slugs/route.js +6 -6
- package/.next/standalone/.next/server/app/api/wiki/slugs/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/upload/route.js +5 -5
- package/.next/standalone/.next/server/app/api/wiki/upload/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/wiki/watch/route.js +5 -5
- package/.next/standalone/.next/server/app/api/wiki/watch/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/index.html +1 -1
- package/.next/standalone/.next/server/app/index.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page/react-loadable-manifest.json +1 -1
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/s/[token]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/signin/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +1 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0zv_j05._.js → [root-of-the-server]__0-mos44._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0nmx3k2._.js → [root-of-the-server]__00xq4wx._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0ovhccp._.js → [root-of-the-server]__038~~rd._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0~rntxj._.js → [root-of-the-server]__04jklyx._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0nzlmkb._.js → [root-of-the-server]__04z5.s-._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0a6j6r4._.js → [root-of-the-server]__04~bqmd._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__05jd.5~._.js +3 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0ajw6de._.js → [root-of-the-server]__05~-fkm._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0esmskc._.js → [root-of-the-server]__06s802c._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0na11h0._.js → [root-of-the-server]__08-0m4o._.js} +4 -4
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0s_8poz._.js → [root-of-the-server]__08mb7mf._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__000spch._.js → [root-of-the-server]__096dpr1._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__09i-r6q._.js +12 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0n9zdf0._.js → [root-of-the-server]__0a_c5s5._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0as-u6z._.js → [root-of-the-server]__0asy5fk._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0l-wu5u._.js → [root-of-the-server]__0bikav1._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0fshk._._.js → [root-of-the-server]__0cynf.m._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0yat~ul._.js → [root-of-the-server]__0dyghs~._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0w~__xz._.js → [root-of-the-server]__0ej__9l._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wfv_by._.js → [root-of-the-server]__0f-y9ak._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0oruwos._.js → [root-of-the-server]__0j456kt._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0zbkgnr._.js → [root-of-the-server]__0kgev~0._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0km~c.f._.js +3 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0.-oq-7._.js → [root-of-the-server]__0le9en3._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0lvz22t._.js +1 -1
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0uibxf_._.js → [root-of-the-server]__0lwoa8u._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0-jzw2_._.js → [root-of-the-server]__0ocu5kq._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0fu72o7._.js → [root-of-the-server]__0omu2ls._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__09t4v4r._.js → [root-of-the-server]__0ou1yo3._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0u81k~2._.js → [root-of-the-server]__0qe_pj_._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wlj-yw._.js → [root-of-the-server]__0snmvie._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__06booxp._.js → [root-of-the-server]__0sqf51n._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0vxex1w._.js → [root-of-the-server]__0syhzuy._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__024967n._.js → [root-of-the-server]__0xblgqt._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0s38pid._.js → [root-of-the-server]__0xzvkcg._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0z3wg9x._.js → [root-of-the-server]__0y6a-84._.js} +4 -4
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ywviax._.js +20 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__071_pmz._.js → [root-of-the-server]__0~1k.~a._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0bvtbax._.js → [root-of-the-server]__0~dajlm._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0sggstu._.js → [root-of-the-server]__0~oj7j3._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0e_9pc5._.js → [root-of-the-server]__0~yn~7e._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0c-ee48._.js → [root-of-the-server]__10l3owp._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0o0v6hf._.js → [root-of-the-server]__10ljgl.._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_1f2cw._.js → [root-of-the-server]__10~3r6l._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__01qcera._.js → [root-of-the-server]__11akjkm._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0aoqat-._.js → [root-of-the-server]__11fcf05._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__02.uul~._.js → [root-of-the-server]__13f0ukk._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_0bqpg._.js → [root-of-the-server]__13hpe9q._.js} +2 -2
- package/.next/standalone/.next/server/chunks/_next-internal_server_app_api_share_[token]_asset_route_actions_0mxwvof.js +3 -0
- package/.next/standalone/.next/server/chunks/src_lib_auth_server_ts_00f4e0h._.js +452 -0
- package/.next/standalone/.next/server/chunks/ssr/{0~w0_katex_dist_katex_mjs_0awdhzw._.js → 0~w0_katex_dist_katex_mjs_1115d6v._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0.j71x7._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/{_0sxeqi8._.js → _03xt0rl._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{_0kcfv3r._.js → _0i3r51-._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_0v4uz-4._.js +3 -3
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0_zq~v6._.js → node_modules__pnpm_0-gfnl9._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0cy5ftq._.js → node_modules__pnpm_0.41jpn._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~5s0h-._.js → node_modules__pnpm_00mt6nh._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_01uc1hl._.js → node_modules__pnpm_06za8g0._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0t16czj._.js → node_modules__pnpm_0752tb8._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0jywdw0._.js → node_modules__pnpm_08.egvu._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0w~3li6._.js → node_modules__pnpm_0a5jwqo._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~xns8v._.js → node_modules__pnpm_0c-_96g._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0w3.bto._.js → node_modules__pnpm_0cxeac7._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_11-1cme._.js → node_modules__pnpm_0do9l33._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0h8t6~c._.js → node_modules__pnpm_0go8~j7._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_02vvjkq._.js → node_modules__pnpm_0h~ckqb._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~l___j._.js → node_modules__pnpm_0knclqg._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_04hymjt._.js → node_modules__pnpm_0lne~4i._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0c5xt34._.js → node_modules__pnpm_0mrjai_._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0abi.df._.js → node_modules__pnpm_0mx7wsr._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0u3p3__._.js → node_modules__pnpm_0oi2w2s._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_131u09o._.js → node_modules__pnpm_0qiaujf._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_10y-1uw._.js → node_modules__pnpm_0r529m.._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0zt6ord._.js → node_modules__pnpm_0s8-kbr._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0j2ck16._.js → node_modules__pnpm_0uvds62._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0bwtedy._.js → node_modules__pnpm_0w7.zt6._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_13kfm1k._.js → node_modules__pnpm_0z5ch94._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0of-lo7._.js → node_modules__pnpm_0zya776._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_05py9u6._.js → node_modules__pnpm_10qgn1p._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0ve~5~d._.js → node_modules__pnpm_113-u.n._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0g7aqxf._.js → node_modules__pnpm_12v.ysz._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_app_s_[token]_page_tsx_0_fzrmd._.js +3 -0
- package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/.next/standalone/.next/server/middleware-manifest.json +5 -5
- package/.next/standalone/.next/server/pages/404.html +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/static/chunks/{0on-0-cxvzy-7.js → 0-.cn_ir_n9jf.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0alhqgtsl8w~~.js → 0jgcnboih8.w8.js} +1 -1
- package/.next/standalone/.next/static/chunks/0pd5k_eu2n6lx.js +17 -0
- package/.next/standalone/.next/static/chunks/{10~nefki4aqgv.js → 0pfnisq~g.lxv.js} +1 -1
- package/.next/standalone/.next/static/chunks/0pw6gfeuvlhiu.css +5 -0
- package/.next/standalone/.next/static/chunks/{0~m~l6t.25dxo.js → 10n.a147w._5n.js} +1 -1
- package/.next/standalone/.next/static/chunks/11_s27j_.g~44.js +1 -0
- package/.next/standalone/package.json +1 -1
- package/package.json +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08n~vj1._.js +0 -12
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0m6r9ip._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0sfrx~.._.js +0 -3
- package/.next/standalone/.next/server/chunks/_0dr1r1g._.js +0 -452
- package/.next/standalone/.next/server/chunks/_101exke._.js +0 -452
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0w2ebbx._.js +0 -3
- package/.next/standalone/.next/static/chunks/0.g_p6_b0v2sp.js +0 -1
- package/.next/standalone/.next/static/chunks/0ncw5hhg~98~p.css +0 -5
- package/.next/standalone/.next/static/chunks/11c7-ic7.2nku.js +0 -17
- /package/.next/standalone/.next/static/{67H1xYhtLYoTKKFA6Djps → JXxkzDy909cpBo90OOfiL}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{67H1xYhtLYoTKKFA6Djps → JXxkzDy909cpBo90OOfiL}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{67H1xYhtLYoTKKFA6Djps → JXxkzDy909cpBo90OOfiL}/_ssgManifest.js +0 -0
|
@@ -1,452 +0,0 @@
|
|
|
1
|
-
module.exports=[223741,473845,e=>{"use strict";let t,r,n,i,a,o,s,c,l,d,u;var p,f,h,m,y=e.i(563811),g=e.i(560912);async function w(t,r){let n;if(t.database)n="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,y.getAuthTables)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await e.A(168315);n=i(r)(t)}return n.transaction||(g.logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),n.transaction=async e=>e(n)),n}var b=e.i(451894);async function A(t){return w(t,async t=>{let{createKyselyAdapter:r}=await e.A(317691),{kysely:n,databaseType:i,transaction:a}=await r(t);if(!n)throw new b.BetterAuthError("Failed to initialize database adapter");let{kyselyAdapter:o}=await e.A(317691);return o(n,{type:i||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:a})(t)})}var E=e.i(177730);function v(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function k(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function _(e,t){if("string"!=typeof e&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(("string"==typeof t||"boolean"==typeof t)&&(t={separator:t}),2==arguments.length&&!(void 0===t||"object"==typeof t&&null!==t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if("\\"===(t=t||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=function e(t,r=!0){if(Array.isArray(t))return`(?:${t.map(t=>`^${e(t,r)}$`).join("|")})`;let n="",i="",a=".";!0===r?(n="/",i="[/\\\\]",a="[^/\\\\]"):r&&((i=function(e){let t="";for(let r=0;r<e.length;r++)t+=v(e[r]);return t}(n=r)).length>1?(i=`(?:${i})`,a=`((?!${i}).)`):a=`[^${i}]`);let o=r?`${i}+?`:"",s=r?`${i}*?`:"",c=r?t.split(n):[t],l="";for(let e=0;e<c.length;e++){let t=c[e],n=c[e+1],i="";if(t||!(e>0)){if(r&&(i=e===c.length-1?s:"**"!==n?o:""),r&&"**"===t){i&&(l+=0===e?"":i,l+=`(?:${a}*?${i})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(l+=v(t[e+1]),e++):"?"===r?l+=a:"*"===r?l+=`${a}*?`:l+=v(r)}l+=i}}return l}(e,t.separator),n=RegExp(`^${r}$`,t.flags),i=k.bind(null,n);return i.options=t,i.pattern=e,i.regexp=n,i}var S=e.i(426232);function x(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)}function T(e,t="/api/auth"){try{let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new b.BetterAuthError(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof b.BetterAuthError)throw t;throw new b.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}if(function(e){try{return"/"!==(x(new URL(e).pathname)||"/")}catch{throw new b.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e))return e;let r=x(e);return t&&"/"!==t?(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`):r}function R(e,t){return!!e&&""!==e.trim()&&("proto"===t?"http"===e||"https"===e:"host"===t&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))&&(/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e)))}function I(e,t,r,n,i){if(e)return T(e,t);if(!1!==n){let e=S.env.BETTER_AUTH_URL||S.env.NEXT_PUBLIC_BETTER_AUTH_URL||S.env.PUBLIC_BETTER_AUTH_URL||S.env.NUXT_PUBLIC_BETTER_AUTH_URL||S.env.NUXT_PUBLIC_AUTH_URL||("/"!==S.env.BASE_URL?S.env.BASE_URL:void 0);if(e)return T(e,t)}let a=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(a&&o&&i&&R(o,"proto")&&R(a,"host"))try{return T(`${o}://${a}`,t)}catch(e){}if(r){let e=U(r.url);if(!e)throw new b.BetterAuthError("Could not get origin from request. Please provide a valid base URL.");return T(e,t)}}function U(e){try{let t=new URL(e);return"null"===t.origin?null:t.origin}catch{return null}}function O(e){return"object"==typeof e&&null!==e&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function P(e){return e instanceof Request||"object"==typeof e&&null!==e&&"[object Request]"===Object.prototype.toString.call(e)&&"string"==typeof e.url&&"object"==typeof e.headers&&null!==e.headers&&"function"==typeof e.headers.get}function C(e,t){let r=P(e)?e.headers:e;if(t){let e=r.get("x-forwarded-host");if(e&&R(e,"host"))return e}let n=r.get("host");if(n&&R(n,"host"))return n;if(P(e))try{return new URL(e.url).host}catch{}return null}let D=(e,t,r)=>{if(e.startsWith("/"))return!!r?.allowRelativePaths&&e.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e);if(t.includes("*")||t.includes("?")){if(t.includes("://"))return _(t)(U(e)||e);let r=function(e){try{return new URL(e).host}catch{return null}}(e);return!!r&&_(t)(r)}let n=function(e){try{return new URL(e).protocol}catch{return null}}(e);return"http:"!==n&&"https:"!==n&&n?e.startsWith(t):t===U(e)};function L(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}var z=e.i(666680);function $(e,t){return new Promise((r,n)=>{(0,z.scrypt)(e.normalize("NFKC"),t,64,{N:16384,r:16,p:1,maxmem:0x4000000},(e,t)=>{e?n(e):r(t)})})}async function N(e){let t=(0,z.randomBytes)(16).toString("hex"),r=await $(e,t);return`${t}:${r.toString("hex")}`}async function j(e,t){let[r,n]=e.split(":");if(!r||!n)throw Error("Invalid password hash");return(await $(t,r)).toString("hex")===n}let H=async({hash:e,password:t})=>j(e,t);function B(e,t=""){if("number"!=typeof e){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function V(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function M(e){if("function"!=typeof e||"function"!=typeof e.create)throw TypeError("Hash must wrapped by utils.createHasher");if(B(e.outputLen),B(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function K(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function W(e,t){V(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function q(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function F(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function J(e,t){return e<<32-t|e>>>t}class Z{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(M(e),V(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),q(n)}update(e){return K(this),this.iHash.update(e),this}digestInto(e){K(this),W(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let G=((o=(e,t,r)=>new Z(e,t).update(r).digest()).create=(e,t)=>new Z(e,t),o),Q=Uint8Array.of(0),Y=Uint8Array.of();class X{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=F(this.buffer)}update(e){K(this),V(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let t=F(e);for(;n<=i-a;a+=n)this.process(t,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){K(this),W(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;t[a++]=128,q(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let e=a;e<n;e++)t[e]=0;r.setBigUint64(n-8,BigInt(8*this.length),i),this.process(r,0);let o=F(e),s=this.outputLen;if(s%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}let ee=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),et=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),er=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),en=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),ei=BigInt(0x100000000-1),ea=BigInt(32),eo=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]),es=new Uint32Array(64);class ec extends X{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:s}=this;return[e,t,r,n,i,a,o,s]}set(e,t,r,n,i,a,o,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|a,this.G=0|o,this.H=0|s}process(e,t){for(let r=0;r<16;r++,t+=4)es[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=es[e-15],r=es[e-2],n=J(t,7)^J(t,18)^t>>>3,i=J(r,17)^J(r,19)^r>>>10;es[e]=i+es[e-7]+n+es[e-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){var d,u,p,f;let t=l+(J(o,6)^J(o,11)^J(o,25))+((d=o)&s^~d&c)+eo[e]+es[e]|0,h=(J(r,2)^J(r,13)^J(r,22))+((u=r)&(p=n)^u&(f=i)^p&f)|0;l=c,c=s,s=o,o=a+t|0,a=i,i=n,n=r,r=t+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,i,a,o,s,c,l)}roundClean(){q(es)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),q(this.buffer)}}class el extends ec{A=0|ee[0];B=0|ee[1];C=0|ee[2];D=0|ee[3];E=0|ee[4];F=0|ee[5];G=0|ee[6];H=0|ee[7];constructor(){super(32)}}let ed=function(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){let{h:r,l:o}=function(e,t=!1){return t?{h:Number(e&ei),l:Number(e>>ea&ei)}:{h:0|Number(e>>ea&ei),l:0|Number(e&ei)}}(e[a],t);[n[a],i[a]]=[r,o]}return[n,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),eu=ed[0],ep=ed[1],ef=new Uint32Array(80),eh=new Uint32Array(80),em=function(e,t={}){let r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}(()=>new el,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),ey=new TextEncoder,eg=new TextDecoder;function ew(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function eb(e,t,r){if(t<0||t>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function eA(e){let t=Math.floor(e/0x100000000),r=new Uint8Array(8);return eb(r,t,0),eb(r,e%0x100000000,4),r}function eE(e){let t=new Uint8Array(4);return eb(t,e),t}function ev(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function ek(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:eg.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=eg.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{var r=t;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);let e=atob(r),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function e_(e){let t=e;return("string"==typeof t&&(t=ey.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}e.s(["decode",0,ek,"encode",0,e_],797379);let eS=Symbol();function ex(e,t){if(e)throw TypeError(`${t} can only be called once`)}function eT(e,t,r){try{return ek(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}async function eR(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}let eI=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function eU(e,t){if(parseInt(e.hash.name.slice(4),10)!==t)throw eI(`SHA-${t}`,"algorithm.hash")}function eO(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function eP(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==e.algorithm.name)throw eI("AES-GCM");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw eI(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==e.algorithm.name)throw eI("AES-KW");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw eI(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw eI("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==e.algorithm.name)throw eI("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==e.algorithm.name)throw eI("RSA-OAEP");eU(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}eO(e,r)}function eC(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let eD=(e,...t)=>eC("Key must be ",e,...t),eL=(e,t,...r)=>eC(`Key for the ${e} algorithm must be `,t,...r);class ez extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class e$ extends ez{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class eN extends ez{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class ej extends ez{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class eH extends ez{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class eB extends ez{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class eV extends ez{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class eM extends ez{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class eK extends ez{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class eW extends ez{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class eq extends ez{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class eF extends ez{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class eJ extends ez{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class eZ extends ez{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class eG extends ez{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function eQ(e){if(!eY(e))throw Error("CryptoKey instance expected")}let eY=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},eX=e=>e?.[Symbol.toStringTag]==="KeyObject",e0=e=>eY(e)||eX(e);function e1(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new eH(`Unsupported JWE Algorithm: ${e}`)}}let e2=e=>crypto.getRandomValues(new Uint8Array(e1(e)>>3));function e6(e,t){let r=e.byteLength<<3;if(r!==t)throw new eV(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function e5(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new eH(`Unsupported JWE Algorithm: ${e}`)}}function e8(e,t){if(t.length<<3!==e5(e))throw new eV("Invalid Initialization Vector length")}async function e4(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(eD(t,"Uint8Array"));let n=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),macKey:await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]),keySize:n}}async function e3(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function e9(e,t,r,n,i){let{encKey:a,macKey:o,keySize:s}=await e4(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),l=ew(i,n,c,eA(i.length<<3));return{ciphertext:c,tag:await e3(o,l,s),iv:n}}async function e7(e,t){if(!(e instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,e)),a=new Uint8Array(await crypto.subtle.sign(r,n,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return 0===o}async function te(e,t,r,n,i,a){let o,s,{encKey:c,macKey:l,keySize:d}=await e4(e,t,"decrypt"),u=ew(a,n,r,eA(a.length<<3)),p=await e3(l,u,d);try{o=await e7(i,p)}catch{}if(!o)throw new eB;try{s=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!s)throw new eB;return s}async function tt(e,t,r,n,i){let a;r instanceof Uint8Array?a=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(eP(r,e,"encrypt"),a=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:n}}async function tr(e,t,r,n,i,a){let o;t instanceof Uint8Array?o=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(eP(t,e,"decrypt"),o=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},o,ew(r,i)))}catch{throw new eB}}let tn="Unsupported JWE Content Encryption Algorithm";async function ti(e,t,r,n,i){if(!eY(r)&&!(r instanceof Uint8Array))throw TypeError(eD(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n)e8(e,n);else n=crypto.getRandomValues(new Uint8Array(e5(e)>>3));switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&e6(r,parseInt(e.slice(-3),10)),e9(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&e6(r,parseInt(e.slice(1,4),10)),tt(e,t,r,n,i);default:throw new eH(tn)}}async function ta(e,t,r,n,i,a){if(!eY(t)&&!(t instanceof Uint8Array))throw TypeError(eD(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new eV("JWE Initialization Vector missing");if(!i)throw new eV("JWE Authentication Tag missing");switch(e8(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&e6(t,parseInt(e.slice(-3),10)),te(e,t,r,n,i,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&e6(t,parseInt(e.slice(1,4),10)),tr(e,t,r,n,i,a);default:throw new eH(tn)}}function to(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function ts(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(eP(e,t,r),e)}async function tc(e,t,r){let n=await ts(t,e,"wrapKey");to(n,e);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function tl(e,t,r){let n=await ts(t,e,"unwrapKey");to(n,e);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}function td(e){return ew(eE(e.length),e)}async function tu(e,t,r){let n=t>>3,i=Math.ceil(n/32),a=new Uint8Array(32*i);for(let t=1;t<=i;t++){let n=new Uint8Array(4+e.length+r.length);n.set(eE(t),0),n.set(e,4),n.set(r,4+e.length);let i=await eR("sha256",n);a.set(i,(t-1)*32)}return a.slice(0,n)}async function tp(e,t,r,n,i=new Uint8Array,a=new Uint8Array){var o;eP(e,"ECDH"),eP(t,"ECDH","deriveBits");let s=ew(td(ev(r)),td(i),td(a),eE(n),new Uint8Array);return tu(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,"X25519"===(o=e).algorithm.name?256:Math.ceil(parseInt(o.algorithm.namedCurve.slice(-3),10)/8)<<3)),n,s)}function tf(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===e.algorithm.name}}async function th(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new eV("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||1!==Math.sign(r))throw new eV("PBES2 Count Input must be a positive integer");let i=ew(ev(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},s=await (n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(eP(n,t,"deriveBits"),n));return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function tm(e,t,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await th(i,e,n,t);return{encryptedKey:await tc(e.slice(-6),a,r),p2c:n,p2s:e_(i)}}async function ty(e,t,r,n,i){let a=await th(i,e,n,t);return tl(e.slice(-6),a,r)}function tg(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function tw(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new eH(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function tb(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(eD(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}switch(e){case"HS256":case"HS384":case"HS512":if("HMAC"!==t.algorithm.name)throw eI("HMAC");eU(t.algorithm,parseInt(e.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==t.algorithm.name)throw eI("RSASSA-PKCS1-v1_5");eU(t.algorithm,parseInt(e.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==t.algorithm.name)throw eI("RSA-PSS");eU(t.algorithm,parseInt(e.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==t.algorithm.name)throw eI("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let n;if(n=t.algorithm,n.name!==e)throw eI(e);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==t.algorithm.name)throw eI("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(e);if(t.algorithm.namedCurve!==r)throw eI(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return eO(t,r),t}async function tA(e,t,r){let n=await tb(e,t,"sign");return tg(e,n),new Uint8Array(await crypto.subtle.sign(tw(e,n.algorithm),n,r))}async function tE(e,t,r,n){let i=await tb(e,t,"verify");tg(e,i);let a=tw(e,i.algorithm);try{return await crypto.subtle.verify(a,i,r,n)}catch{return!1}}let tv=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new eH(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function tk(e,t,r){return eP(t,e,"encrypt"),tg(e,t),new Uint8Array(await crypto.subtle.encrypt(tv(e),t,r))}async function t_(e,t,r){return eP(t,e,"decrypt"),tg(e,t),new Uint8Array(await crypto.subtle.decrypt(tv(e),t,r))}function tS(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function tx(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}let tT=e=>tS(e)&&"string"==typeof e.kty,tR='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function tI(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new eH(tR)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new eH(tR)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new eH(tR)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new eH(tR)}break;default:throw new eH('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let tU="given KeyObject instance cannot be used for this algorithm",tO=async(e,r,n,i=!1)=>{let a=(t||=new WeakMap).get(e);if(a?.[n])return a[n];let o=await tI({...r,alg:n});return i&&Object.freeze(e),a?a[n]=o:t.set(e,{[n]:o}),o};async function tP(e,r){if(e instanceof Uint8Array||eY(e))return e;if(eX(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,r)=>{let n,i=(t||=new WeakMap).get(e);if(i?.[r])return i[r];let a="public"===e.type,o=!!a;if("x25519"===e.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(tU)}n=e.toCryptoKey(e.asymmetricKeyType,o,a?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError(tU);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==e.asymmetricKeyType.toUpperCase())throw TypeError(tU);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(r){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError(tU)}if(r.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},o,a?["encrypt"]:["decrypt"]);n=e.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},o,[a?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError(tU);let i={ES256:"P-256",ES384:"P-384",ES512:"P-521"};i[r]&&t===i[r]&&(n=e.toCryptoKey({name:"ECDSA",namedCurve:t},o,[a?"verify":"sign"])),r.startsWith("ECDH-ES")&&(n=e.toCryptoKey({name:"ECDH",namedCurve:t},o,a?[]:["deriveBits"]))}if(!n)throw TypeError(tU);return i?i[r]=n:t.set(e,{[r]:n}),n})(e,r)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return tO(e,n,r)}if(tT(e))return e.k?ek(e.k):tO(e,e,r,!0);throw Error("unreachable")}async function tC(e,t,r){let n;if(!tS(e))throw TypeError("JWK must be an object");switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return ek(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new eH('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return tI({...e,alg:t,ext:n});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return tI({...e,ext:n});case"EC":case"OKP":return tI({...e,alg:t,ext:n});default:throw new eH('Unsupported "kty" (Key Type) Parameter value')}}async function tD(e){if(eX(e))if("secret"!==e.type)return e.export({format:"jwk"});else e=e.export();if(e instanceof Uint8Array)return{kty:"oct",k:e_(e)};if(!eY(e))throw TypeError(eD(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...a}=await crypto.subtle.exportKey("jwk",e);return"AKP"===a.kty&&(a.alg=n),a}async function tL(e){return tD(e)}async function tz(e,t,r,n){let i=e.slice(0,7),a=await ti(i,r,t,n,new Uint8Array);return{encryptedKey:a.ciphertext,iv:e_(a.iv),tag:e_(a.tag)}}async function t$(e,t,r,n,i){return ta(e.slice(0,7),t,r,n,i,new Uint8Array)}let tN='Invalid or unsupported "alg" (JWE Algorithm) header value';function tj(e){if(void 0===e)throw new eV("JWE Encrypted Key missing")}async function tH(e,t,r,n,i){switch(e){case"dir":if(void 0!==r)throw new eV("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new eV("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i,a;if(!tS(n.epk))throw new eV('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(eQ(t),!tf(t))throw new eH("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await tC(n.epk,e);if(eQ(o),void 0!==n.apu){if("string"!=typeof n.apu)throw new eV('JOSE Header "apu" (Agreement PartyUInfo) invalid');i=eT(n.apu,"apu",eV)}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new eV('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=eT(n.apv,"apv",eV)}let s=await tp(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?e1(n.enc):parseInt(e.slice(-5,-2),10),i,a);if("ECDH-ES"===e)return s;return tj(r),tl(e.slice(-6),s,r)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return tj(r),eQ(t),t_(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let a;if(tj(r),"number"!=typeof n.p2c)throw new eV('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new eV('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new eV('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return a=eT(n.p2s,"p2s",eV),ty(e,t,r,n.p2c,a)}case"A128KW":case"A192KW":case"A256KW":return tj(r),tl(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(tj(r),"string"!=typeof n.iv)throw new eV('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new eV('JOSE Header "tag" (Authentication Tag) missing or invalid');return t$(e,t,r,eT(n.iv,"iv",eV),eT(n.tag,"tag",eV));default:throw new eH(tN)}}async function tB(e,t,r,n,i={}){let a,o,s;switch(e){case"dir":s=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let c;if(eQ(r),!tf(r))throw new eH("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:l,apv:d}=i;c=i.epk?await tP(i.epk,e):(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:u,y:p,crv:f,kty:h}=await tL(c),m=await tp(r,c,"ECDH-ES"===e?t:e,"ECDH-ES"===e?e1(t):parseInt(e.slice(-5,-2),10),l,d);if(o={epk:{x:u,crv:f,kty:h}},"EC"===h&&(o.epk.y=p),l&&(o.apu=e_(l)),d&&(o.apv=e_(d)),"ECDH-ES"===e){s=m;break}s=n||e2(t);let y=e.slice(-6);a=await tc(y,m,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s=n||e2(t),eQ(r),a=await tk(e,r,s);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||e2(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await tm(e,r,s,c,l));break}case"A128KW":case"A192KW":case"A256KW":s=n||e2(t),a=await tc(e,r,s);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||e2(t);let{iv:c}=i;({encryptedKey:a,...o}=await tz(e,r,s,c));break}default:throw new eH(tN)}return{cek:s,encryptedKey:a,parameters:o}}function tV(e,t,r,n,i){let a;if(void 0!==i.crit&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let o of(a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,n.crit)){if(!a.has(o))throw new eH(`Extension Header Parameter "${o}" is not recognized`);if(void 0===i[o])throw new e(`Extension Header Parameter "${o}" is missing`);if(a.get(o)&&void 0===n[o])throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}let tM=e=>e?.[Symbol.toStringTag],tK=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&t.key_ops?.includes?.(n)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0};function tW(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(tT(t)){if("oct"===t.kty&&"string"==typeof t.k&&tK(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!e0(t))throw TypeError(eL(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${tM(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r);break;default:((e,t,r)=>{if(tT(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&tK(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&tK(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!e0(t))throw TypeError(eL(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${tM(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${tM(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${tM(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${tM(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${tM(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)}}function tq(e){if(void 0===globalThis[e])throw new eH(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function tF(e){tq("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],i=t.readable.getReader();for(;;){let{value:e,done:t}=await i.read();if(t)break;n.push(e)}return ew(...n)}async function tJ(e,t){tq("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let i=[],a=0,o=r.readable.getReader();for(;;){let{value:e,done:r}=await o.read();if(r)break;if(i.push(e),a+=e.byteLength,t!==1/0&&a>t)throw new eV("Decompressed plaintext exceeded the configured limit")}return ew(...i)}class tZ{#e;#t;#r;#n;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return ex(this.#s,"setKeyManagementParameters"),this.#s=e,this}setProtectedHeader(e){return ex(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return ex(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return ex(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return ex(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return ex(this.#o,"setInitializationVector"),this.#o=e,this}async encrypt(e,t){let r,n,i,a,o,s;if(!this.#t&&!this.#n&&!this.#r)throw new eV("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!tx(this.#t,this.#n,this.#r))throw new eV("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let c={...this.#t,...this.#n,...this.#r};if(tV(eV,new Map,t?.crit,this.#t,c),void 0!==c.zip&&"DEF"!==c.zip)throw new eH('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==c.zip&&!this.#t?.zip)throw new eV('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:l,enc:d}=c;if("string"!=typeof l||!l)throw new eV('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof d||!d)throw new eV('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#a&&("dir"===l||"ECDH-ES"===l))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);tW("dir"===l?d:l,e,"encrypt");{let i,a=await tP(e,l);({cek:n,encryptedKey:r,parameters:i}=await tB(l,d,a,this.#a,this.#s)),i&&(t&&eS in t?this.#n?this.#n={...this.#n,...i}:this.setUnprotectedHeader(i):this.#t?this.#t={...this.#t,...i}:this.setProtectedHeader(i))}if(this.#t?o=ev(a=e_(JSON.stringify(this.#t))):(a="",o=new Uint8Array),this.#i){let e=ev(s=e_(this.#i));i=ew(o,ev("."),e)}else i=o;let u=this.#e;"DEF"===c.zip&&(u=await tF(u).catch(e=>{throw new eV("Failed to compress plaintext",{cause:e})}));let{ciphertext:p,tag:f,iv:h}=await ti(d,u,n,this.#o,i),m={ciphertext:e_(p)};return h&&(m.iv=e_(h)),f&&(m.tag=e_(f)),r&&(m.encrypted_key=e_(r)),s&&(m.aad=s),this.#t&&(m.protected=a),this.#r&&(m.unprotected=this.#r),this.#n&&(m.header=this.#n),m}}class tG{#c;constructor(e){this.#c=new tZ(e)}setContentEncryptionKey(e){return this.#c.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#c.setInitializationVector(e),this}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#c.setKeyManagementParameters(e),this}async encrypt(e,t){let r=await this.#c.encrypt(e,t);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}let tQ=e=>Math.floor(e.getTime()/1e3),tY=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function tX(e){let t,r=tY.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let n=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*n);break;case"day":case"days":case"d":t=Math.round(86400*n);break;case"week":case"weeks":case"w":t=Math.round(604800*n);break;default:t=Math.round(0x1e187e0*n)}return"-"===r[1]||"ago"===r[4]?-t:t}function t0(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let t1=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;function t2(e,t,r={}){var n,i;let a,o;try{a=JSON.parse(eg.decode(t))}catch{}if(!tS(a))throw new eK("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||t1(e.typ)!==t1(s)))throw new e$('unexpected "typ" JWT header value',a,"typ","check_failed");let{requiredClaims:c=[],issuer:l,subject:d,audience:u,maxTokenAge:p}=r,f=[...c];for(let e of(void 0!==p&&f.push("iat"),void 0!==u&&f.push("aud"),void 0!==d&&f.push("sub"),void 0!==l&&f.push("iss"),new Set(f.reverse())))if(!(e in a))throw new e$(`missing required "${e}" claim`,a,e,"missing");if(l&&!(Array.isArray(l)?l:[l]).includes(a.iss))throw new e$('unexpected "iss" claim value',a,"iss","check_failed");if(d&&a.sub!==d)throw new e$('unexpected "sub" claim value',a,"sub","check_failed");if(u&&(n=a.aud,i="string"==typeof u?[u]:u,"string"==typeof n?!i.includes(n):!(Array.isArray(n)&&i.some(Set.prototype.has.bind(new Set(n))))))throw new e$('unexpected "aud" claim value',a,"aud","check_failed");switch(typeof r.clockTolerance){case"string":o=tX(r.clockTolerance);break;case"number":o=r.clockTolerance;break;case"undefined":o=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:h}=r,m=tQ(h||new Date);if((void 0!==a.iat||p)&&"number"!=typeof a.iat)throw new e$('"iat" claim must be a number',a,"iat","invalid");if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw new e$('"nbf" claim must be a number',a,"nbf","invalid");if(a.nbf>m+o)throw new e$('"nbf" claim timestamp check failed',a,"nbf","check_failed")}if(void 0!==a.exp){if("number"!=typeof a.exp)throw new e$('"exp" claim must be a number',a,"exp","invalid");if(a.exp<=m-o)throw new eN('"exp" claim timestamp check failed',a,"exp","check_failed")}if(p){let e=m-a.iat;if(e-o>("number"==typeof p?p:tX(p)))throw new eN('"iat" claim timestamp check failed (too far in the past)',a,"iat","check_failed");if(e<0-o)throw new e$('"iat" claim timestamp check failed (it should be in the past)',a,"iat","check_failed")}return a}class t6{#l;constructor(e){if(!tS(e))throw TypeError("JWT Claims Set MUST be an object");this.#l=structuredClone(e)}data(){return ey.encode(JSON.stringify(this.#l))}get iss(){return this.#l.iss}set iss(e){this.#l.iss=e}get sub(){return this.#l.sub}set sub(e){this.#l.sub=e}get aud(){return this.#l.aud}set aud(e){this.#l.aud=e}set jti(e){this.#l.jti=e}set nbf(e){"number"==typeof e?this.#l.nbf=t0("setNotBefore",e):e instanceof Date?this.#l.nbf=t0("setNotBefore",tQ(e)):this.#l.nbf=tQ(new Date)+tX(e)}set exp(e){"number"==typeof e?this.#l.exp=t0("setExpirationTime",e):e instanceof Date?this.#l.exp=t0("setExpirationTime",tQ(e)):this.#l.exp=tQ(new Date)+tX(e)}set iat(e){void 0===e?this.#l.iat=tQ(new Date):e instanceof Date?this.#l.iat=t0("setIssuedAt",tQ(e)):"string"==typeof e?this.#l.iat=t0("setIssuedAt",tQ(new Date)+tX(e)):this.#l.iat=t0("setIssuedAt",e)}}class t5{#a;#o;#s;#t;#d;#u;#p;#f;constructor(e={}){this.#f=new t6(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return ex(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return ex(this.#s,"setKeyManagementParameters"),this.#s=e,this}setContentEncryptionKey(e){return ex(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return ex(this.#o,"setInitializationVector"),this.#o=e,this}replicateIssuerAsHeader(){return this.#d=!0,this}replicateSubjectAsHeader(){return this.#u=!0,this}replicateAudienceAsHeader(){return this.#p=!0,this}async encrypt(e,t){let r=new tG(this.#f.data());return this.#t&&(this.#d||this.#u||this.#p)&&(this.#t={...this.#t,iss:this.#d?this.#f.iss:void 0,sub:this.#u?this.#f.sub:void 0,aud:this.#p?this.#f.aud:void 0}),r.setProtectedHeader(this.#t),this.#o&&r.setInitializationVector(this.#o),this.#a&&r.setContentEncryptionKey(this.#a),this.#s&&r.setKeyManagementParameters(this.#s),r.encrypt(e,t)}}class t8{#l;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#l=e}setProtectedHeader(e){return ex(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return ex(this.#n,"setUnprotectedHeader"),this.#n=e,this}async sign(e,t){let r,n,i,a;if(!this.#t&&!this.#n)throw new eM("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tx(this.#t,this.#n))throw new eM("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this.#t,...this.#n},s=tV(eM,new Map([["b64",!0]]),t?.crit,this.#t,o),c=!0;if(s.has("b64")&&"boolean"!=typeof(c=this.#t.b64))throw new eM('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=o;if("string"!=typeof l||!l)throw new eM('JWS "alg" (Algorithm) Header Parameter missing or invalid');tW(l,e,"sign"),c?n=ev(r=e_(this.#l)):(n=this.#l,r=""),this.#t?a=ev(i=e_(JSON.stringify(this.#t))):(i="",a=new Uint8Array);let d=ew(a,ev("."),n),u=await tP(e,l),p={signature:e_(await tA(l,u,d)),payload:r};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=i),p}}class t4{#c;constructor(e){this.#c=new t8(e)}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}async sign(e,t){let r=await this.#c.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}class t3{#t;#f;constructor(e={}){this.#f=new t6(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){let r=new t4(this.#f.data());if(r.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new eK("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var t9=e.i(797379),t9=t9;let t7=(e,t)=>{if("string"!=typeof e||!e)throw new eW(`${t} missing or invalid`)};async function re(e,t){let r,n;if(tT(e))r=e;else if(e0(e))r=await tL(e);else throw TypeError(eD(e,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(t??="sha256")&&"sha384"!==t&&"sha512"!==t)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(r.kty){case"AKP":t7(r.alg,'"alg" (Algorithm) Parameter'),t7(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":t7(r.crv,'"crv" (Curve) Parameter'),t7(r.x,'"x" (X Coordinate) Parameter'),t7(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":t7(r.crv,'"crv" (Subtype of Key Pair) Parameter'),t7(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":t7(r.e,'"e" (Exponent) Parameter'),t7(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":t7(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new eH('"kty" (Key Type) Parameter missing or unsupported')}let i=ev(JSON.stringify(n));return e_(await eR(t,i))}function rt(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(eg.decode(ek(t)));if(!tS(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}function rr(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}async function rn(e,t,r){let n,i,a,o,s,c;if(!tS(e))throw new eV("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new eV("JOSE Header missing");if(void 0!==e.iv&&"string"!=typeof e.iv)throw new eV("JWE Initialization Vector incorrect type");if("string"!=typeof e.ciphertext)throw new eV("JWE Ciphertext missing or incorrect type");if(void 0!==e.tag&&"string"!=typeof e.tag)throw new eV("JWE Authentication Tag incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new eV("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new eV("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new eV("JWE AAD incorrect type");if(void 0!==e.header&&!tS(e.header))throw new eV("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!tS(e.unprotected))throw new eV("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected)try{let t=ek(e.protected);n=JSON.parse(eg.decode(t))}catch{throw new eV("JWE Protected Header is invalid")}if(!tx(n,e.header,e.unprotected))throw new eV("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let l={...n,...e.header,...e.unprotected};if(tV(eV,new Map,r?.crit,n,l),void 0!==l.zip&&"DEF"!==l.zip)throw new eH('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==l.zip&&!n?.zip)throw new eV('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:d,enc:u}=l;if("string"!=typeof d||!d)throw new eV("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new eV("missing JWE Encryption Algorithm (enc) in JWE Header");let p=r&&rr("keyManagementAlgorithms",r.keyManagementAlgorithms),f=r&&rr("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(p&&!p.has(d)||!p&&d.startsWith("PBES2"))throw new ej('"alg" (Algorithm) Header Parameter value not allowed');if(f&&!f.has(u))throw new ej('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==e.encrypted_key&&(i=eT(e.encrypted_key,"encrypted_key",eV));let h=!1;"function"==typeof t&&(t=await t(n,e),h=!0),tW("dir"===d?u:d,t,"decrypt");let m=await tP(t,d);try{a=await tH(d,m,i,l,r)}catch(e){if(e instanceof TypeError||e instanceof eV||e instanceof eH)throw e;a=e2(u)}void 0!==e.iv&&(o=eT(e.iv,"iv",eV)),void 0!==e.tag&&(s=eT(e.tag,"tag",eV));let y=void 0!==e.protected?ev(e.protected):new Uint8Array;c=void 0!==e.aad?ew(y,ev("."),ev(e.aad)):y;let g=eT(e.ciphertext,"ciphertext",eV),w=await ta(u,a,g,o,s,c),b={plaintext:w};if("DEF"===l.zip){let e=r?.maxDecompressedLength??25e4;if(0===e)throw new eH('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");b.plaintext=await tJ(w,e).catch(e=>{if(e instanceof eV)throw e;throw new eV("Failed to decompress plaintext",{cause:e})})}return(void 0!==e.protected&&(b.protectedHeader=n),void 0!==e.aad&&(b.additionalAuthenticatedData=eT(e.aad,"aad",eV)),void 0!==e.unprotected&&(b.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(b.unprotectedHeader=e.header),h)?{...b,key:m}:b}async function ri(e,t,r){if(e instanceof Uint8Array&&(e=eg.decode(e)),"string"!=typeof e)throw new eV("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:a,3:o,4:s,length:c}=e.split(".");if(5!==c)throw new eV("Invalid Compact JWE");let l=await rn({ciphertext:o,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}async function ra(e,t,r){let n=await ri(e,t,r),i=t2(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(void 0!==a.iss&&a.iss!==i.iss)throw new e$('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(void 0!==a.sub&&a.sub!==i.sub)throw new e$('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(void 0!==a.aud&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new e$('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:a};return"function"==typeof t?{...o,key:n.key}:o}async function ro(e,t,r){if(!tS(e))throw new eM("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new eM('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new eM("JWS Protected Header incorrect type");if(void 0===e.payload)throw new eM("JWS Payload missing");if("string"!=typeof e.signature)throw new eM("JWS Signature missing or incorrect type");if(void 0!==e.header&&!tS(e.header))throw new eM("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let t=ek(e.protected);n=JSON.parse(eg.decode(t))}catch{throw new eM("JWS Protected Header is invalid")}if(!tx(n,e.header))throw new eM("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...e.header},a=tV(eM,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(a.has("b64")&&"boolean"!=typeof(o=n.b64))throw new eM('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=i;if("string"!=typeof s||!s)throw new eM('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&rr("algorithms",r.algorithms);if(c&&!c.has(s))throw new ej('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new eM("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new eM("JWS Payload must be a string or an Uint8Array instance");let l=!1;"function"==typeof t&&(t=await t(n,e),l=!0),tW(s,t,"verify");let d=ew(void 0!==e.protected?ev(e.protected):new Uint8Array,ev("."),"string"==typeof e.payload?o?ev(e.payload):ey.encode(e.payload):e.payload),u=eT(e.signature,"signature",eM),p=await tP(t,s);if(!await tE(s,p,u,d))throw new eG;let f={payload:o?eT(e.payload,"payload",eM):"string"==typeof e.payload?ey.encode(e.payload):e.payload};return(void 0!==e.protected&&(f.protectedHeader=n),void 0!==e.header&&(f.unprotectedHeader=e.header),l)?{...f,key:p}:f}async function rs(e,t,r){if(e instanceof Uint8Array&&(e=eg.decode(e)),"string"!=typeof e)throw new eM("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:a,length:o}=e.split(".");if(3!==o)throw new eM("Invalid Compact JWS");let s=await ro({payload:i,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}async function rc(e,t,r){let n=await rs(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new eK("JWTs MUST NOT use unencoded payload");let i={payload:t2(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}async function rl(e,t,r=3600){return await new t3(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function rd(e,t){try{return(await rc(e,new TextEncoder().encode(t))).payload}catch{return null}}let ru=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]),rp="A256CBC-HS512";function rf(e,t){var r,n,i;return r=new TextEncoder().encode(e),n=new TextEncoder().encode(t),function(e,t,r,n=32){M(e),B(n,"length"),V(t,void 0,"prk");let i=e.outputLen;if(t.length<i)throw Error('"prk" must be at least HashLen octets');if(n>255*i)throw Error("Length must be <= 255*HashLen");let a=Math.ceil(n/i);void 0===r?r=Y:V(r,void 0,"info");let o=new Uint8Array(a*i),s=G.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)Q[0]=e+1,c.update(0===e?Y:l).update(r).update(Q).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),q(l,Q),o.slice(0,n)}(em,(i=n,M(em),void 0===i&&(i=new Uint8Array(em.outputLen)),G(em,i,r)),ru,64)}function rh(e){if("string"==typeof e)return[{version:0,value:e}];let t=[];for(let[r,n]of e.keys)t.push({version:r,value:n});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function rm(e,t,r,n=3600){let i=rf(function(e){if("string"==typeof e)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}(t),r),a=await re({kty:"oct",k:t9.encode(i)},"sha256");return await new t5(e).setProtectedHeader({alg:"dir",enc:rp,kid:a}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+n).setJti(crypto.randomUUID()).encrypt(i)}let ry={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[rp,"A256GCM"]};async function rg(e,t,r){if(!e)return null;let n=!1;try{n=void 0!==rt(e).kid}catch{return null}try{let n=rh(t),{payload:i}=await ra(e,async e=>{let t=e.kid;if(void 0!==t){for(let e of n){let n=rf(e.value,r);if(t===await re({kty:"oct",k:t9.encode(n)},"sha256"))return n}throw Error("no matching decryption secret")}return n.length,rf(n[0].value,r)},ry);return i}catch{if(n)return null;let i=rh(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let n=i[t],{payload:a}=await ra(e,rf(n.value,r),ry);return a}catch{continue}return null}}var rw=e.i(163738);function rb(e,t){if(!e||!t)return e;let r=Object.entries(t).filter(([,{returned:e}])=>!1===e).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!r.includes(e)).reduce((e,[t,r])=>({...e,[t]:r}),{})}let rA=new WeakMap;function rE(e,t,r){let n=`${t}:${r}`;rA.has(e)||rA.set(e,new Map);let i=rA.get(e);if(i.has(n))return i.get(n);let a="output"===r?(0,y.getAuthTables)(e)[t]?.fields??{}:{},o="user"===t||"session"===t||"account"===t?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(s={...s,...r.schema[t].fields});return i.set(n,s),s}function rv(e,t){return rb(t,rE(e,"user","output"))}function rk(e,t){let r=rE(e,"user","output"),n={};for(let e in r){let i=r[e];!1!==i.returned&&(e in t&&void 0!==t[e]?n[e]=t[e]:void 0!==i.defaultValue?n[e]="function"==typeof i.defaultValue?i.defaultValue():i.defaultValue:i.required||(n[e]=null))}return"id"in t&&(n.id=t.id),n}function r_(e,t){return rb(t,rE(e,"session","output"))}function rS(e,t){let r=t.action||"create",n=t.fields,i=Object.create(null);for(let t in n){if(t in e){if(!1===n[t].input){if(void 0!==n[t].defaultValue&&"update"!==r){i[t]=n[t].defaultValue;continue}if(e[t])throw b.APIError.from("BAD_REQUEST",{...rw.BASE_ERROR_CODES.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(n[t].validator?.input&&void 0!==e[t]){let r=n[t].validator.input["~standard"].validate(e[t]);if(r instanceof Promise)throw b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in r&&r.issues)throw b.APIError.from("BAD_REQUEST",{...rw.BASE_ERROR_CODES.VALIDATION_ERROR,message:r.issues[0]?.message||"Validation Error"});i[t]=r.value;continue}if(n[t].transform?.input&&void 0!==e[t]){i[t]=n[t].transform?.input(e[t]);continue}i[t]=e[t];continue}if(void 0!==n[t].defaultValue&&"create"===r){if("function"==typeof n[t].defaultValue){i[t]=n[t].defaultValue();continue}i[t]=n[t].defaultValue;continue}if(n[t].required&&"create"===r)throw b.APIError.from("BAD_REQUEST",{...rw.BASE_ERROR_CODES.MISSING_FIELD,message:`${t} is required`})}return i}function rx(e,t={},r){return rS(t,{fields:rE(e,"user","input"),action:r})}let rT=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e)),rR=/^(\+|\-)? ?(\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 rI(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function rU(e){if(!e)return[];let t=[],r=0,n=0;for(;n<e.length;){if(","===e[n]){let i=n+1;for(;i<e.length&&" "===e[i];)i++;for(;i<e.length&&"="!==e[i]&&";"!==e[i]&&","!==e[i];)i++;if(i<e.length&&"="===e[i]){let i=e.slice(r,n).trim();for(i&&t.push(i),r=n+1;r<e.length&&" "===e[r];)r++;n=r;continue}}n++}let i=e.slice(r).trim();return i&&t.push(i),t}let rO=/^[\w!#$%&'*.^`|~+-]+$/,rP=/^[ !#-:<-[\]-~]*$/;function rC(e){return!(e.length<2)&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function rD(e){let t=0,r=e.length;for(;t<r;){let r=e.charCodeAt(t);if(32!==r&&9!==r)break;t++}for(;r>t;){let t=e.charCodeAt(r-1);if(32!==t&&9!==t)break;r--}return 0===t&&r===e.length?e:e.slice(t,r)}function rL(e){let t=new Map;if(e.length<2)return t;for(let r of e.split(";")){let e=r.indexOf("=");if(-1===e)continue;let n=rD(r.slice(0,e)),i=rC(rD(r.slice(e+1)));rO.test(n)&&rP.test(i)&&t.set(n,rI(i))}return t}var rz=e.i(858544);function r$(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class a extends i{}function o(e){var t;let i=r?.Parent?new a:this;for(let r of(n(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}Symbol("zod_brand");class rN extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class rj extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(h=globalThis).__zod_globalConfig??(h.__zod_globalConfig={});let rH=globalThis.__zod_globalConfig;function rB(e){return e&&Object.assign(rH,e),rH}function rV(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function rM(e,t){return"bigint"==typeof t?t.toString():t}function rK(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function rW(e){return null==e}function rq(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rF(e,t){let r=e/t,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}let rJ=Symbol("evaluating");function rZ(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==rJ)return void 0===n&&(n=rJ,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function rG(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rQ(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}function rY(e){return JSON.stringify(e)}function rX(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}let r0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function r1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let r2=rK(()=>{if(rH.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function r6(e){if(!1===r1(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==r1(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let r5=new Set(["string","number","symbol"]),r8=new Set(["string","number","bigint","boolean","symbol","undefined"]);function r4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function r3(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function r9(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function r7(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function ne(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let nt={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]},nr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nn(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ni(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function na(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function no(e){return"string"==typeof e?e:e?.message}function ns(e,t,r){let n=e.message?e.message:no(e.inst?._zod.def?.error?.(e))??no(t?.error?.(e))??no(r.customError?.(e))??no(r.localeError?.(e))??"Invalid input",{inst:i,continue:a,input:o,...s}=e;return s.path??(s.path=[]),s.message=n,t?.reportInput&&(s.input=o),s}function nc(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function nl(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function nd(...e){let[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function nu(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function np(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}e.s(["BIGINT_FORMAT_RANGES",0,nr,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,nt,"aborted",0,nn,"allowsEval",0,r2,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error("Unexpected value in exhaustive check")},"assertNotEqual",0,function(e){return e},"assignProp",0,rG,"base64ToUint8Array",0,nu,"base64urlToUint8Array",0,function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return nu(t+r)},"cached",0,rK,"captureStackTrace",0,r0,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,rq,"clone",0,r3,"cloneDef",0,function(e){return rQ(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,a)=>(t??(t=e()),Reflect.set(t,n,i,a)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})},"defineLazy",0,rZ,"esc",0,rY,"escapeRegex",0,r4,"explicitlyAborted",0,ni,"extend",0,function(e,t){if(!r6(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=rQ(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return rG(this,"shape",r),r}});return r3(e,n)},"finalizeIssue",0,ns,"floatSafeRemainder",0,rF,"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,rV,"getLengthableOrigin",0,nl,"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,nc,"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r},"isObject",0,r1,"isPlainObject",0,r6,"issue",0,nd,"joinValues",0,function(e,t="|"){return e.map(e=>r7(e)).join(t)},"jsonStringifyReplacer",0,rM,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rQ(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return rG(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return r3(e,r)},"mergeDefs",0,rQ,"normalizeParams",0,r9,"nullish",0,rW,"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=rQ(e._zod.def,{get shape(){let n={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return rG(this,"shape",n),n},checks:[]});return r3(e,i)},"optionalKeys",0,ne,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=rQ(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(let t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return rG(this,"shape",i),i},checks:[]});return r3(t,i)},"pick",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=rQ(e._zod.def,{get shape(){let e={};for(let n in t){if(!(n in r.shape))throw Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return rG(this,"shape",e),e},checks:[]});return r3(e,i)},"prefixIssues",0,na,"primitiveTypes",0,r8,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})},"propertyKeyTypes",0,r5,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let n=rQ(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(let t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return rG(this,"shape",i),i}});return r3(t,n)},"safeExtend",0,function(e,t){if(!r6(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=rQ(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return rG(this,"shape",r),r}});return r3(e,r)},"shallowClone",0,function(e){return r6(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e},"slugify",0,rX,"stringifyPrimitive",0,r7,"uint8ArrayToBase64",0,np,"uint8ArrayToBase64url",0,function(e){return np(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"uint8ArrayToHex",0,function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,no],202721);let nf=/^[cC][0-9a-z]{6,}$/,nh=/^[0-9a-z]+$/,nm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ny=/^[0-9a-vA-V]{20}$/,ng=/^[A-Za-z0-9]{27}$/,nw=/^[a-zA-Z0-9_-]{21}$/,nb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,nA=/^([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})$/,nE=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nv=nE(4),nk=nE(6),n_=nE(7),nS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nx=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;function nT(){return RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}let nR=/^(?:(?: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])$/,nI=/^(([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}|:))$/,nU=e=>{let t=r4(e??":");return RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},nO=/^((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])$/,nP=/^(([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])$/,nC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nD=/^[A-Za-z0-9_-]*$/,nL=/^https?$/,nz=/^\+[1-9]\d{6,14}$/,n$="(?:(?:\\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])))",nN=RegExp(`^${n$}$`);function nj(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function nH(e){return RegExp(`^${nj(e)}$`)}function nB(e){let t=nj({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return RegExp(`^${n$}T(?:${n})$`)}let nV=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},nM=/^-?\d+n?$/,nK=/^-?\d+$/,nW=/^-?\d+(?:\.\d+)?$/,nq=/^(?:true|false)$/i,nF=/^null$/i,nJ=/^undefined$/i,nZ=/^[^A-Z]*$/,nG=/^[^a-z]*$/;function nQ(e,t){return RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function nY(e){return RegExp(`^[A-Za-z0-9_-]{${e}}$`)}let nX=nQ(22,"=="),n0=nY(22),n1=nQ(27,"="),n2=nY(27),n6=nQ(43,"="),n5=nY(43),n8=nQ(64,""),n4=nY(64),n3=nQ(86,"=="),n9=nY(86);e.s(["base64",0,nC,"base64url",0,nD,"bigint",0,nM,"boolean",0,nq,"browserEmail",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"cidrv4",0,nO,"cidrv6",0,nP,"cuid",0,nf,"cuid2",0,nh,"date",0,nN,"datetime",0,nB,"domain",0,/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,"duration",0,nb,"e164",0,nz,"email",0,nS,"emoji",0,nT,"extendedDuration",0,/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,"guid",0,nA,"hex",0,/^[0-9a-fA-F]*$/,"hostname",0,/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,"html5Email",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"httpProtocol",0,nL,"idnEmail",0,nx,"integer",0,nK,"ipv4",0,nR,"ipv6",0,nI,"ksuid",0,ng,"lowercase",0,nZ,"mac",0,nU,"md5_base64",0,nX,"md5_base64url",0,n0,"md5_hex",0,/^[0-9a-fA-F]{32}$/,"nanoid",0,nw,"null",0,nF,"number",0,nW,"rfc5322Email",0,/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"sha1_base64",0,n1,"sha1_base64url",0,n2,"sha1_hex",0,/^[0-9a-fA-F]{40}$/,"sha256_base64",0,n6,"sha256_base64url",0,n5,"sha256_hex",0,/^[0-9a-fA-F]{64}$/,"sha384_base64",0,n8,"sha384_base64url",0,n4,"sha384_hex",0,/^[0-9a-fA-F]{96}$/,"sha512_base64",0,n3,"sha512_base64url",0,n9,"sha512_hex",0,/^[0-9a-fA-F]{128}$/,"string",0,nV,"time",0,nH,"ulid",0,nm,"undefined",0,nJ,"unicodeEmail",0,nx,"uppercase",0,nG,"uuid",0,nE,"uuid4",0,nv,"uuid6",0,nk,"uuid7",0,n_,"xid",0,ny],110107);let n7=r$("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ie={number:"number",bigint:"bigint",object:"date"},it=r$("$ZodCheckLessThan",(e,t)=>{n7.init(e,t);let r=ie[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ir=r$("$ZodCheckGreaterThan",(e,t)=>{n7.init(e,t);let r=ie[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ii=r$("$ZodCheckMultipleOf",(e,t)=>{n7.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===rF(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ia=r$("$ZodCheckNumberFormat",(e,t)=>{n7.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,a]=nt[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=a,r&&(n.pattern=nK)}),e._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?o.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}))}s<i&&o.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),io=r$("$ZodCheckBigIntFormat",(e,t)=>{n7.init(e,t);let[r,n]=nr[t.format];e._zod.onattach.push(e=>{let i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{let a=i.value;a<r&&i.issues.push({origin:"bigint",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>n&&i.issues.push({origin:"bigint",input:a,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),is=r$("$ZodCheckMaxSize",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;n.size<=t.maximum||r.issues.push({origin:nc(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ic=r$("$ZodCheckMinSize",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;n.size>=t.minimum||r.issues.push({origin:nc(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),il=r$("$ZodCheckSizeEquals",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let n=r.value,i=n.size;if(i===t.size)return;let a=i>t.size;r.issues.push({origin:nc(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),id=r$("$ZodCheckMaxLength",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;if(n.length<=t.maximum)return;let i=nl(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),iu=r$("$ZodCheckMinLength",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;if(n.length>=t.minimum)return;let i=nl(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ip=r$("$ZodCheckLengthEquals",(e,t)=>{var r;n7.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rW(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let n=r.value,i=n.length;if(i===t.length)return;let a=nl(n),o=i>t.length;r.issues.push({origin:a,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),ih=r$("$ZodCheckStringFormat",(e,t)=>{var r,n;n7.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),im=r$("$ZodCheckRegex",(e,t)=>{ih.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),iy=r$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=nZ),ih.init(e,t)}),ig=r$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=nG),ih.init(e,t)}),iw=r$("$ZodCheckIncludes",(e,t)=>{n7.init(e,t);let r=r4(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),ib=r$("$ZodCheckStartsWith",(e,t)=>{n7.init(e,t);let r=RegExp(`^${r4(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),iA=r$("$ZodCheckEndsWith",(e,t)=>{n7.init(e,t);let r=RegExp(`.*${r4(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});(e,t)=>{n7.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}};let iE=r$("$ZodCheckOverwrite",(e,t)=>{n7.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class iv{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}let ik=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,rM,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},i_=r$("$ZodError",ik),iS=r$("$ZodError",ik,{Parent:Error}),ix=e=>(t,r,n,i)=>{let a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new rN;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ns(e,a,rB())));throw r0(t,i?.callee),t}return o.value},iT=ix(iS),iR=e=>async(t,r,n,i)=>{let a=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ns(e,a,rB())));throw r0(t,i?.callee),t}return o.value},iI=iR(iS),iU=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new rN;return a.issues.length?{success:!1,error:new(e??i_)(a.issues.map(e=>ns(e,i,rB())))}:{success:!0,data:a.value}},iO=iU(iS),iP=e=>async(t,r,n)=>{let i=n?{...n,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>ns(e,i,rB())))}:{success:!0,data:a.value}},iC=iP(iS),iD={major:4,minor:4,patch:3},iL=r$("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=iD;let n=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&n.unshift(e),n))for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,i=nn(e);for(let a of t){if(a._zod.def.when){if(ni(e)||!a._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&r?.async===!1)throw new rN;if(n||o instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(i||(i=nn(e,t)))});else{if(e.issues.length===t)continue;i||(i=nn(e,t))}}return n?n.then(()=>e):e},r=(r,i,a)=>{if(nn(r))return r.aborted=!0,r;let o=t(i,n,a);if(o instanceof Promise){if(!1===a.async)throw new rN;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if("backward"===a.direction){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,a)):r(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(!1===a.async)throw new rN;return o.then(e=>t(e,n,a))}return t(o,n,a)}}rZ(e,"~standard",()=>({validate:t=>{try{let r=iO(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return iC(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),iz=r$("$ZodString",(e,t)=>{iL.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??nV(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),i$=r$("$ZodStringFormat",(e,t)=>{ih.init(e,t),iz.init(e,t)}),iN=r$("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=nA),i$.init(e,t)}),ij=r$("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nE(e))}else t.pattern??(t.pattern=nE());i$.init(e,t)}),iH=r$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nS),i$.init(e,t)}),iB=r$("$ZodURL",(e,t)=>{i$.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===nL.source&&!/^https?:\/\//i.test(n))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),iV=r$("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nT()),i$.init(e,t)}),iM=r$("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nw),i$.init(e,t)}),iK=r$("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=nf),i$.init(e,t)}),iW=r$("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=nh),i$.init(e,t)}),iq=r$("$ZodULID",(e,t)=>{t.pattern??(t.pattern=nm),i$.init(e,t)}),iF=r$("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ny),i$.init(e,t)}),iJ=r$("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ng),i$.init(e,t)}),iZ=r$("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=nB(t)),i$.init(e,t)}),iG=r$("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=nN),i$.init(e,t)}),iQ=r$("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=nH(t)),i$.init(e,t)}),iY=r$("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nb),i$.init(e,t)}),iX=r$("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=nR),i$.init(e,t),e._zod.bag.format="ipv4"}),i0=r$("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nI),i$.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),i1=((e,t)=>{t.pattern??(t.pattern=nU(t.delimiter)),i$.init(e,t),e._zod.bag.format="mac"},r$("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=nO),i$.init(e,t)})),i2=r$("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=nP),i$.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(2!==n.length)throw Error();let[e,t]=n;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function i6(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let i5=r$("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nC),i$.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{i6(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),i8=r$("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=nD),i$.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{!function(e){if(!nD.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return i6(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),i4=r$("$ZodE164",(e,t)=>{t.pattern??(t.pattern=nz),i$.init(e,t)}),i3=r$("$ZodJWT",(e,t)=>{i$.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),i9=((e,t)=>{i$.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}},r$("$ZodNumber",(e,t)=>{iL.init(e,t),e._zod.pattern=e._zod.bag.pattern??nW,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let a="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),r}})),i7=r$("$ZodNumberFormat",(e,t)=>{ia.init(e,t),i9.init(e,t)}),ae=r$("$ZodBoolean",(e,t)=>{iL.init(e,t),e._zod.pattern=nq,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),at=r$("$ZodBigInt",(e,t)=>{iL.init(e,t),e._zod.pattern=nM,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),ar=((e,t)=>{io.init(e,t),at.init(e,t)},r$("$ZodAny",(e,t)=>{iL.init(e,t),e._zod.parse=e=>e})),an=r$("$ZodUnknown",(e,t)=>{iL.init(e,t),e._zod.parse=e=>e}),ai=r$("$ZodNever",(e,t)=>{iL.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),aa=((e,t)=>{iL.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return void 0===n||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}},r$("$ZodDate",(e,t)=>{iL.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let i=r.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...a?{received:"Invalid Date"}:{},inst:e}),r}}));function ao(e,t,r){e.issues.length&&t.issues.push(...na(r,e.issues)),t.value[r]=e.value}let as=r$("$ZodArray",(e,t)=>{iL.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},n);s instanceof Promise?a.push(s.then(t=>ao(t,r,e))):ao(s,r,e)}return a.length?Promise.all(a).then(()=>r):r}});function ac(e,t,r,n,i,a){let o=r in n;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...na(r,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?o&&(t.value[r]=void 0):t.value[r]=e.value}function al(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=ne(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ad(e,t,r,n,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,d="optional"===c.optin,u="optional"===c.optout;for(let i in t){if("__proto__"===i||s.has(i))continue;if("never"===l){o.push(i);continue}let a=c.run({value:t[i],issues:[]},n);a instanceof Promise?e.push(a.then(e=>ac(e,r,i,t,d,u))):ac(a,r,i,t,d,u)}return(o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length)?Promise.all(e).then(()=>r):r}let au=r$("$ZodObject",(e,t)=>{let r;iL.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=rK(()=>al(t));rZ(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let n=e[t]._zod;if(n.values)for(let e of(r[t]??(r[t]=new Set),n.values))r[t].add(e)}return r});let a=t.catchall;e._zod.parse=(t,n)=>{r??(r=i.value);let o=t.value;if(!r1(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};let s=[],c=r.shape;for(let e of r.keys){let r=c[e],i="optional"===r._zod.optin,a="optional"===r._zod.optout,l=r._zod.run({value:o[e],issues:[]},n);l instanceof Promise?s.push(l.then(r=>ac(r,t,e,o,i,a))):ac(l,t,e,o,i,a)}return a?ad(s,o,t,n,i.value,e):s.length?Promise.all(s).then(()=>t):t}}),ap=r$("$ZodObjectJIT",(e,t)=>{let r,n;au.init(e,t);let i=e._zod.parse,a=rK(()=>al(t)),o=!rH.jitless,s=o&&r2.value,c=t.catchall;e._zod.parse=(l,d)=>{n??(n=a.value);let u=l.value;return r1(u)?o&&s&&d?.async===!1&&!0!==d.jitless?(r||(r=(e=>{let t=new iv(["shape","payload","ctx"]),r=a.value,n=e=>{let t=rY(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),o=0;for(let e of r.keys)i[e]=`key_${o++}`;for(let a of(t.write("const newResult = {};"),r.keys)){let r=i[a],o=rY(a),s=e[a],c=s?._zod?.optin==="optional",l=s?._zod?.optout==="optional";t.write(`const ${r} = ${n(a)};`),c&&l?t.write(`
|
|
2
|
-
if (${r}.issues.length) {
|
|
3
|
-
if (${o} in input) {
|
|
4
|
-
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
5
|
-
...iss,
|
|
6
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
7
|
-
})));
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
if (${r}.value === undefined) {
|
|
12
|
-
if (${o} in input) {
|
|
13
|
-
newResult[${o}] = undefined;
|
|
14
|
-
}
|
|
15
|
-
} else {
|
|
16
|
-
newResult[${o}] = ${r}.value;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
`):c?t.write(`
|
|
20
|
-
if (${r}.issues.length) {
|
|
21
|
-
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
22
|
-
...iss,
|
|
23
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
24
|
-
})));
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (${r}.value === undefined) {
|
|
28
|
-
if (${o} in input) {
|
|
29
|
-
newResult[${o}] = undefined;
|
|
30
|
-
}
|
|
31
|
-
} else {
|
|
32
|
-
newResult[${o}] = ${r}.value;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
`):t.write(`
|
|
36
|
-
const ${r}_present = ${o} in input;
|
|
37
|
-
if (${r}.issues.length) {
|
|
38
|
-
payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
|
|
39
|
-
...iss,
|
|
40
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
41
|
-
})));
|
|
42
|
-
}
|
|
43
|
-
if (!${r}_present && !${r}.issues.length) {
|
|
44
|
-
payload.issues.push({
|
|
45
|
-
code: "invalid_type",
|
|
46
|
-
expected: "nonoptional",
|
|
47
|
-
input: undefined,
|
|
48
|
-
path: [${o}]
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
if (${r}_present) {
|
|
53
|
-
if (${r}.value === undefined) {
|
|
54
|
-
newResult[${o}] = undefined;
|
|
55
|
-
} else {
|
|
56
|
-
newResult[${o}] = ${r}.value;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
`)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),l=r(l,d),c)?ad([],u,l,d,n,e):l:i(l,d):(l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l)}});function af(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!nn(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>ns(e,n,rB())))}),t)}let ah=r$("$ZodUnion",(e,t)=>{iL.init(e,t),rZ(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),rZ(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),rZ(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),rZ(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>rq(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(0===t.issues.length)return t;o.push(t)}}return a?Promise.all(o).then(t=>af(t,n,e,i)):af(o,n,e,i)}});function am(e,t,r,n){let i=e.filter(e=>0===e.issues.length);return 1===i.length?t.value=i[0].value:0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>ns(e,n,rB())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t}(e,t)=>{ah.init(e,t),t.inclusive=!1;let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);t instanceof Promise?(o.push(t),a=!0):o.push(t)}return a?Promise.all(o).then(t=>am(t,n,e,i)):am(o,n,e,i)}},(e,t)=>{t.inclusive=!1,ah.init(e,t);let r=e._zod.parse;rZ(e._zod,"propValues",()=>{let e={};for(let r of t.options){let n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(n))for(let n of(e[t]||(e[t]=new Set),r))e[t].add(n)}return e});let n=rK(()=>{let e=t.options,r=new Map;for(let n of e){let e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,a)=>{let o=i.value;if(!r1(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let s=n.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||"backward"===a.direction?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}};let ay=r$("$ZodIntersection",(e,t)=>{iL.init(e,t),e._zod.parse=(e,r)=>{let n=e.value,i=t.left._zod.run({value:n,issues:[]},r),a=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,r])=>ag(e,t,r)):ag(e,i,a)}});function ag(e,t,r){let n,i=new Map;for(let r of t.issues)if("unrecognized_keys"===r.code)for(let e of(n??(n=r),r.keys))i.has(e)||i.set(e,{}),i.get(e).l=!0;else e.issues.push(r);for(let t of r.issues)if("unrecognized_keys"===t.code)for(let e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);let a=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&n&&e.issues.push({...n,keys:a}),nn(e))return e;let o=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(r6(t)&&r6(r)){let n=Object.keys(r),i=Object.keys(t).filter(e=>-1!==n.indexOf(e)),a={...t,...r};for(let n of i){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};a[n]=i.data}return{valid:!0,data:a}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let aw=r$("$ZodTuple",(e,t)=>{iL.init(e,t);let r=t.items;e._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],s=ab(r,"optin"),c=ab(r,"optout");if(!t.rest){if(a.length<s)return n.issues.push({code:"too_small",minimum:s,inclusive:!0,input:a,inst:e,origin:"array"}),n;a.length>r.length&&n.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:a,inst:e,origin:"array"})}let l=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=r.length-1;for(let s of a.slice(r.length)){e++;let r=t.rest._zod.run({value:s,issues:[]},i);r instanceof Promise?o.push(r.then(t=>aA(t,n,e))):aA(r,n,e)}}return o.length?Promise.all(o).then(()=>aE(l,n,r,a,c)):aE(l,n,r,a,c)}});function ab(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function aA(e,t,r){e.issues.length&&t.issues.push(...na(r,e.issues)),t.value[r]=e.value}function aE(e,t,r,n,i){for(let a=0;a<r.length;a++){let r=e[a],o=a<n.length;if(r.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...na(a,r.issues))}t.value[a]=r.value}for(let e=t.value.length-1;e>=n.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}let av=r$("$ZodRecord",(e,t)=>{iL.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!r6(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let a=[],o=t.keyType._zod.values;if(o){let s;r.value={};let c=new Set;for(let s of o)if("string"==typeof s||"number"==typeof s||"symbol"==typeof s){c.add("number"==typeof s?s.toString():s);let o=t.keyType._zod.run({value:s,issues:[]},n);if(o instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>ns(e,n,rB())),input:s,path:[s],inst:e});continue}let l=o.value,d=t.valueType._zod.run({value:i[s],issues:[]},n);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&r.issues.push(...na(s,e.issues)),r.value[l]=e.value})):(d.issues.length&&r.issues.push(...na(s,d.issues)),r.value[l]=d.value)}for(let e in i)c.has(e)||(s=s??[]).push(e);s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:s})}else for(let o of(r.value={},Reflect.ownKeys(i))){if("__proto__"===o||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},n);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof o&&nW.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},n);if(e instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?r.value[o]=i[o]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>ns(e,n,rB())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&r.issues.push(...na(o,e.issues)),r.value[s.value]=e.value})):(c.issues.length&&r.issues.push(...na(o,c.issues)),r.value[s.value]=c.value)}return a.length?Promise.all(a).then(()=>r):r}});function ak(e,t,r,n,i,a,o){e.issues.length&&(r5.has(typeof n)?r.issues.push(...na(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:a,issues:e.issues.map(e=>ns(e,o,rB()))})),t.issues.length&&(r5.has(typeof n)?r.issues.push(...na(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:a,key:n,issues:t.issues.map(e=>ns(e,o,rB()))})),r.value.set(e.value,t.value)}function a_(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}(e,t)=>{iL.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let a=[];for(let[o,s]of(r.value=new Map,i)){let c=t.keyType._zod.run({value:o,issues:[]},n),l=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||l instanceof Promise?a.push(Promise.all([c,l]).then(([t,a])=>{ak(t,a,r,o,i,e,n)})):ak(c,l,r,o,i,e,n)}return a.length?Promise.all(a).then(()=>r):r}},(e,t)=>{iL.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let a=[];for(let e of(r.value=new Set,i)){let i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?a.push(i.then(e=>a_(e,r))):a_(i,r)}return a.length?Promise.all(a).then(()=>r):r}};let aS=r$("$ZodEnum",(e,t)=>{iL.init(e,t);let r=rV(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=RegExp(`^(${r.filter(e=>r5.has(typeof e)).map(e=>"string"==typeof e?r4(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{let a=t.value;return n.has(a)||t.issues.push({code:"invalid_value",values:r,input:a,inst:e}),t}}),ax=((e,t)=>{if(iL.init(e,t),0===t.values.length)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?r4(e):e?r4(e.toString()):String(e)).join("|")})$`),e._zod.parse=(n,i)=>{let a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}},r$("$ZodTransform",(e,t)=>{iL.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new rj(e.constructor.name);let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(r.value=e,r.fallback=!0,r));if(i instanceof Promise)throw new rN;return r.value=i,r.fallback=!0,r}}));function aT(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let aR=r$("$ZodOptional",(e,t)=>{iL.init(e,t),e._zod.optin="optional",e._zod.optout="optional",rZ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),rZ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${rq(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let n=e.value,i=t.innerType._zod.run(e,r);return i instanceof Promise?i.then(e=>aT(e,n)):aT(i,n)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),aI=r$("$ZodExactOptional",(e,t)=>{aR.init(e,t),rZ(e._zod,"values",()=>t.innerType._zod.values),rZ(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),aU=r$("$ZodNullable",(e,t)=>{iL.init(e,t),rZ(e._zod,"optin",()=>t.innerType._zod.optin),rZ(e._zod,"optout",()=>t.innerType._zod.optout),rZ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${rq(e.source)}|null)$`):void 0}),rZ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),aO=r$("$ZodDefault",(e,t)=>{iL.init(e,t),e._zod.optin="optional",rZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>aP(e,t)):aP(n,t)}});function aP(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let aC=r$("$ZodPrefault",(e,t)=>{iL.init(e,t),e._zod.optin="optional",rZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),aD=r$("$ZodNonOptional",(e,t)=>{iL.init(e,t),rZ(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>aL(t,e)):aL(i,e)}});function aL(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}(e,t)=>{iL.init(e,t),e._zod.parse=(e,r)=>{if("backward"===r.direction)throw new rj("ZodSuccess");let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}};let az=r$("$ZodCatch",(e,t)=>{iL.init(e,t),e._zod.optin="optional",rZ(e._zod,"optout",()=>t.innerType._zod.optout),rZ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ns(e,r,rB()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ns(e,r,rB()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),a$=((e,t)=>{iL.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)},r$("$ZodPipe",(e,t)=>{iL.init(e,t),rZ(e._zod,"values",()=>t.in._zod.values),rZ(e._zod,"optin",()=>t.in._zod.optin),rZ(e._zod,"optout",()=>t.out._zod.optout),rZ(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>aN(e,t.in,r)):aN(n,t.in,r)}let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>aN(e,t.out,r)):aN(n,t.out,r)}}));function aN(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function aj(e,t,r){if(e.issues.length)return e.aborted=!0,e;if("forward"===(r.direction||"forward")){let n=t.transform(e.value,e);return n instanceof Promise?n.then(n=>aH(e,n,t.out,r)):aH(e,n,t.out,r)}{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(n=>aH(e,n,t.in,r)):aH(e,n,t.in,r)}}function aH(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}(e,t)=>{iL.init(e,t),rZ(e._zod,"values",()=>t.in._zod.values),rZ(e._zod,"optin",()=>t.in._zod.optin),rZ(e._zod,"optout",()=>t.out._zod.optout),rZ(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("forward"===(r.direction||"forward")){let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>aj(e,t,r)):aj(n,t,r)}{let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>aj(e,t,r)):aj(n,t,r)}}},(e,t)=>{a$.init(e,t)};let aB=r$("$ZodReadonly",(e,t)=>{iL.init(e,t),rZ(e._zod,"propValues",()=>t.innerType._zod.propValues),rZ(e._zod,"values",()=>t.innerType._zod.values),rZ(e._zod,"optin",()=>t.innerType?._zod?.optin),rZ(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(aV):aV(n)}});function aV(e){return e.value=Object.freeze(e.value),e}(e,t)=>{iL.init(e,t);let r=[];for(let e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let n=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else if(null===e||r8.has(typeof e))r.push(r4(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>("string"!=typeof r.value?r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source})),r)},(e,t)=>{iL.init(e,t),rZ(e._zod,"innerType",()=>(t._cachedInner||(t._cachedInner=t.getter()),t._cachedInner)),rZ(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),rZ(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),rZ(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),rZ(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)};let aM=r$("$ZodCustom",(e,t)=>{n7.init(e,t),iL.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>aK(t,r,n,e));aK(i,r,n,e)}});function aK(e,t,r,n){if(!e){let e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(nd(e))}}Symbol("ZodOutput"),Symbol("ZodInput");(m=globalThis).__zod_globalRegistry??(m.__zod_globalRegistry=new class e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});let aW=globalThis.__zod_globalRegistry;function aq(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...r9(t)})}function aF(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...r9(t)})}function aJ(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...r9(t)})}function aZ(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...r9(t)})}function aG(e,t){return new it({check:"less_than",...r9(t),value:e,inclusive:!1})}function aQ(e,t){return new it({check:"less_than",...r9(t),value:e,inclusive:!0})}function aY(e,t){return new ir({check:"greater_than",...r9(t),value:e,inclusive:!1})}function aX(e,t){return new ir({check:"greater_than",...r9(t),value:e,inclusive:!0})}function a0(e,t){return new ii({check:"multiple_of",...r9(t),value:e})}function a1(e,t){return new id({check:"max_length",...r9(t),maximum:e})}function a2(e,t){return new iu({check:"min_length",...r9(t),minimum:e})}function a6(e,t){return new ip({check:"length_equals",...r9(t),length:e})}function a5(e){return new iE({check:"overwrite",tx:e})}e.i(110107);var a8=e.i(202721),a8=a8;function a4(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??aW,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function a3(e,t,r={path:[],schemaPath:[]}){var n;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,n);else{let r=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,r,n)}let a=e._zod.parent;a&&(o.ref||(o.ref=a),a3(a,t,n),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),"input"===t.io&&function e(t,r){let n=r??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let i=t._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return e(i.element,n);if("set"===i.type)return e(i.valueType,n);if("lazy"===i.type)return e(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return e(i.innerType,n);if("intersection"===i.type)return e(i.left,n)||e(i.right,n);if("record"===i.type||"map"===i.type)return e(i.keyType,n)||e(i.valueType,n);if("pipe"===i.type)return!!t._zod.traits.has("$ZodCodec")||e(i.in,n)||e(i.out,n);if("object"===i.type){for(let t in i.shape)if(e(i.shape[t],n))return!0;return!1}if("union"===i.type){for(let t of i.options)if(e(t,n))return!0;return!1}if("tuple"===i.type){for(let t of i.items)if(e(t,n))return!0;if(i.rest&&e(i.rest,n))return!0}return!1}(e)&&(delete o.schema.examples,delete o.schema.default),"input"===t.io&&"_prefault"in o.schema&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function a9(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=n.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let n=t[1],{ref:i,defId:a}=(t=>{let n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(r)return{ref:i(r)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i("__shared")}#/${n}/${a}`}}if(t[1]===r)return{ref:"#"};let i=`#/${n}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}})(t);n.def={...n.schema},a&&(n.defId=a);let o=n.schema;for(let e in o)delete o[e];o.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>
|
|
61
|
-
|
|
62
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let n=r[1];if(t===r[0]){i(r);continue}if(e.external){let n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){i(r);continue}}if(e.metadataRegistry.get(r[0])?.id||n.cycle||n.count>1&&"ref"===e.reused){i(r);continue}}}function a7(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,a={...i},o=r.ref;if(r.ref=null,o){n(o);let r=e.seen.get(o),s=r.schema;if(s.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in a||delete i[e]);if(s.$ref&&r.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){n(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())n(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let a=e.metadataRegistry.get(t)?.id;void 0!==a&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:oe(t,"input",e.processors),output:oe(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let oe=(e,t,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=a4({...i??{},target:a,io:t,processors:r});return a3(e,o),a9(o,e),a7(o,e)},ot={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},or=(e,t,r,n)=>{let i=e._zod.def;a3(i.innerType,t,n),t.seen.get(e).ref=i.innerType},on=r$("ZodISODateTime",(e,t)=>{iZ.init(e,t),ox.init(e,t)}),oi=r$("ZodISODate",(e,t)=>{iG.init(e,t),ox.init(e,t)}),oa=r$("ZodISOTime",(e,t)=>{iQ.init(e,t),ox.init(e,t)}),oo=r$("ZodISODuration",(e,t)=>{iY.init(e,t),ox.init(e,t)}),os=r$("ZodError",(e,t)=>{i_.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>(function(e,t=e=>e.message){let r={_errors:[]},n=(e,i=[])=>{for(let a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(e=>n({issues:e},[...i,...a.path]));else if("invalid_key"===a.code)n({issues:a.issues},[...i,...a.path]);else if("invalid_element"===a.code)n({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(0===e.length)r._errors.push(t(a));else{let n=r,i=0;for(;i<e.length;){let r=e[i];i===e.length-1?(n[r]=n[r]||{_errors:[]},n[r]._errors.push(t(a))):n[r]=n[r]||{_errors:[]},n=n[r],i++}}}};return n(e),r})(e,t)},flatten:{value:t=>(function(e,t=e=>e.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}})(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,rM,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,rM,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),oc=ix(os),ol=iR(os),od=iU(os),ou=iP(os),op=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return ix(os)(e,t,n)},of=(e,t,r)=>ix(os)(e,t,r),oh=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iR(os)(e,t,n)},om=async(e,t,r)=>iR(os)(e,t,r),oy=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iU(os)(e,t,n)},og=(e,t,r)=>iU(os)(e,t,r),ow=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iP(os)(e,t,n)},ob=async(e,t,r)=>iP(os)(e,t,r),oA=new WeakMap;function oE(e,t,r){let n=Object.getPrototypeOf(e),i=oA.get(n);if(i||(i=new Set,oA.set(n,i)),!i.has(t))for(let e in i.add(t),r){let t=r[e];Object.defineProperty(n,e,{configurable:!0,enumerable:!1,get(){let r=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:r}),r},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}let ov=r$("ZodType",(e,t)=>(iL.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:oe(e,"input"),output:oe(e,"output")}}),e.toJSONSchema=((e,t={})=>r=>{let n=a4({...r,processors:t});return a3(e,n),a9(n,e),a7(n,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,r)=>oc(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>od(e,t,r),e.parseAsync=async(t,r)=>ol(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>ou(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>op(e,t,r),e.decode=(t,r)=>of(e,t,r),e.encodeAsync=async(t,r)=>oh(e,t,r),e.decodeAsync=async(t,r)=>om(e,t,r),e.safeEncode=(t,r)=>oy(e,t,r),e.safeDecode=(t,r)=>og(e,t,r),e.safeEncodeAsync=async(t,r)=>ow(e,t,r),e.safeDecodeAsync=async(t,r)=>ob(e,t,r),oE(e,"ZodType",{check(...e){let t=this.def;return this.clone(a8.mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return r3(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return new sw({type:"custom",check:"custom",fn:e,...r9(t)})}(e,t))},superRefine(e,t){return this.check(function(e,t){var r;let n,i;return r=t=>(t.addIssue=e=>{"string"==typeof e?t.issues.push(nd(e,t.value,n._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=t.value),e.inst??(e.inst=n),e.continue??(e.continue=!n._zod.def.abort),t.issues.push(nd(e)))},e(t.value,t)),(i=new n7({check:"custom",...r9(t)}))._zod.check=r,n=i}(e,t))},overwrite(e){return this.check(a5(e))},optional(){return ss(this)},exactOptional(){var e;return e=this,new sc({type:"optional",innerType:e})},nullable(){return sd(this)},nullish(){return ss(sd(this))},nonoptional(e){var t,r;return t=this,r=e,new sf({type:"nonoptional",innerType:t,...a8.normalizeParams(r)})},array(){return o4(this)},or(e){return new o7({type:"union",options:[this,e],...a8.normalizeParams(void 0)})},and(e){var t;return t=this,new se({type:"intersection",left:t,right:e})},transform(e){return sy(this,new sa({type:"transform",transform:e}))},default(e){var t,r;return t=this,r=e,new su({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():a8.shallowClone(r)}})},prefault(e){var t,r;return t=this,r=e,new sp({type:"prefault",innerType:t,get defaultValue(){return"function"==typeof r?r():a8.shallowClone(r)}})},catch(e){var t,r;return t=this,new sh({type:"catch",innerType:t,catchValue:"function"==typeof(r=e)?r:()=>r})},pipe(e){return sy(this,e)},readonly(){var e;return e=this,new sg({type:"readonly",innerType:e})},describe(e){let t=this.clone();return aW.add(t,{description:e}),t},meta(...e){if(0===e.length)return aW.get(this);let t=this.clone();return aW.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>aW.get(e)?.description,configurable:!0}),e)),ok=r$("_ZodString",(e,t)=>{iz.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{r.type="string";let{minimum:i,maximum:a,format:o,patterns:s,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof a&&(r.maxLength=a),o&&(r.format=ot[o]??o,""===r.format&&delete r.format,"time"===o&&delete r.format),c&&(r.contentEncoding=c),s&&s.size>0){let e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,r,0);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,oE(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new im({check:"string_format",format:"regex",...r9(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new iw({check:"string_format",format:"includes",...r9(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new ib({check:"string_format",format:"starts_with",...r9(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new iA({check:"string_format",format:"ends_with",...r9(t),suffix:e})}(...e))},min(...e){return this.check(a2(...e))},max(...e){return this.check(a1(...e))},length(...e){return this.check(a6(...e))},nonempty(...e){return this.check(a2(1,...e))},lowercase(e){return this.check(new iy({check:"string_format",format:"lowercase",...r9(e)}))},uppercase(e){return this.check(new ig({check:"string_format",format:"uppercase",...r9(e)}))},trim(){return this.check(a5(e=>e.trim()))},normalize(...e){return this.check(function(e){return a5(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(a5(e=>e.toLowerCase()))},toUpperCase(){return this.check(a5(e=>e.toUpperCase()))},slugify(){return this.check(a5(e=>rX(e)))}})}),o_=r$("ZodString",(e,t)=>{iz.init(e,t),ok.init(e,t),e.email=t=>e.check(aq(oT,t)),e.url=t=>e.check(new oU({type:"string",format:"url",check:"string_format",abort:!1,...r9(t)})),e.jwt=t=>e.check(new oW({type:"string",format:"jwt",check:"string_format",abort:!1,...r9(t)})),e.emoji=t=>e.check(new oO({type:"string",format:"emoji",check:"string_format",abort:!1,...r9(t)})),e.guid=t=>e.check(aF(oR,t)),e.uuid=t=>e.check(new oI({type:"string",format:"uuid",check:"string_format",abort:!1,...r9(t)})),e.uuidv4=t=>e.check(new oI({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...r9(t)})),e.uuidv6=t=>e.check(new oI({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...r9(t)})),e.uuidv7=t=>e.check(new oI({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...r9(t)})),e.nanoid=t=>e.check(new oP({type:"string",format:"nanoid",check:"string_format",abort:!1,...r9(t)})),e.guid=t=>e.check(aF(oR,t)),e.cuid=t=>e.check(new oC({type:"string",format:"cuid",check:"string_format",abort:!1,...r9(t)})),e.cuid2=t=>e.check(new oD({type:"string",format:"cuid2",check:"string_format",abort:!1,...r9(t)})),e.ulid=t=>e.check(new oL({type:"string",format:"ulid",check:"string_format",abort:!1,...r9(t)})),e.base64=t=>e.check(new oV({type:"string",format:"base64",check:"string_format",abort:!1,...r9(t)})),e.base64url=t=>e.check(new oM({type:"string",format:"base64url",check:"string_format",abort:!1,...r9(t)})),e.xid=t=>e.check(new oz({type:"string",format:"xid",check:"string_format",abort:!1,...r9(t)})),e.ksuid=t=>e.check(new o$({type:"string",format:"ksuid",check:"string_format",abort:!1,...r9(t)})),e.ipv4=t=>e.check(aJ(oN,t)),e.ipv6=t=>e.check(aZ(oj,t)),e.cidrv4=t=>e.check(new oH({type:"string",format:"cidrv4",check:"string_format",abort:!1,...r9(t)})),e.cidrv6=t=>e.check(new oB({type:"string",format:"cidrv6",check:"string_format",abort:!1,...r9(t)})),e.e164=t=>e.check(new oK({type:"string",format:"e164",check:"string_format",abort:!1,...r9(t)})),e.datetime=t=>e.check(new on({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...r9(t)})),e.date=t=>e.check(new oi({type:"string",format:"date",check:"string_format",...r9(t)})),e.time=t=>e.check(new oa({type:"string",format:"time",check:"string_format",precision:null,...r9(t)})),e.duration=t=>e.check(new oo({type:"string",format:"duration",check:"string_format",...r9(t)}))});function oS(e){return new o_({type:"string",...r9(e)})}let ox=r$("ZodStringFormat",(e,t)=>{i$.init(e,t),ok.init(e,t)}),oT=r$("ZodEmail",(e,t)=>{iH.init(e,t),ox.init(e,t)}),oR=r$("ZodGUID",(e,t)=>{iN.init(e,t),ox.init(e,t)}),oI=r$("ZodUUID",(e,t)=>{ij.init(e,t),ox.init(e,t)}),oU=r$("ZodURL",(e,t)=>{iB.init(e,t),ox.init(e,t)}),oO=r$("ZodEmoji",(e,t)=>{iV.init(e,t),ox.init(e,t)}),oP=r$("ZodNanoID",(e,t)=>{iM.init(e,t),ox.init(e,t)}),oC=r$("ZodCUID",(e,t)=>{iK.init(e,t),ox.init(e,t)}),oD=r$("ZodCUID2",(e,t)=>{iW.init(e,t),ox.init(e,t)}),oL=r$("ZodULID",(e,t)=>{iq.init(e,t),ox.init(e,t)}),oz=r$("ZodXID",(e,t)=>{iF.init(e,t),ox.init(e,t)}),o$=r$("ZodKSUID",(e,t)=>{iJ.init(e,t),ox.init(e,t)}),oN=r$("ZodIPv4",(e,t)=>{iX.init(e,t),ox.init(e,t)}),oj=r$("ZodIPv6",(e,t)=>{i0.init(e,t),ox.init(e,t)}),oH=r$("ZodCIDRv4",(e,t)=>{i1.init(e,t),ox.init(e,t)}),oB=r$("ZodCIDRv6",(e,t)=>{i2.init(e,t),ox.init(e,t)}),oV=r$("ZodBase64",(e,t)=>{i5.init(e,t),ox.init(e,t)}),oM=r$("ZodBase64URL",(e,t)=>{i8.init(e,t),ox.init(e,t)}),oK=r$("ZodE164",(e,t)=>{i4.init(e,t),ox.init(e,t)}),oW=r$("ZodJWT",(e,t)=>{i3.init(e,t),ox.init(e,t)}),oq=r$("ZodNumber",(e,t)=>{i9.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let{minimum:i,maximum:a,format:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof o&&o.includes("int")?r.type="integer":r.type="number";let d="number"==typeof l&&l>=(i??-1/0),u="number"==typeof c&&c<=(a??1/0),p="draft-04"===t.target||"openapi-3.0"===t.target;d?p?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),u?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:"number"==typeof a&&(r.maximum=a),"number"==typeof s&&(r.multipleOf=s)})(e,t,r,0),oE(e,"ZodNumber",{gt(e,t){return this.check(aY(e,t))},gte(e,t){return this.check(aX(e,t))},min(e,t){return this.check(aX(e,t))},lt(e,t){return this.check(aG(e,t))},lte(e,t){return this.check(aQ(e,t))},max(e,t){return this.check(aQ(e,t))},int(e){return this.check(oZ(e))},safe(e){return this.check(oZ(e))},positive(e){return this.check(aY(0,e))},nonnegative(e){return this.check(aX(0,e))},negative(e){return this.check(aG(0,e))},nonpositive(e){return this.check(aQ(0,e))},multipleOf(e,t){return this.check(a0(e,t))},step(e,t){return this.check(a0(e,t))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??-1/0,r.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(r.maximum??1/0,r.exclusiveMaximum??1/0)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function oF(e){return new oq({type:"number",checks:[],...r9(e)})}let oJ=r$("ZodNumberFormat",(e,t)=>{i7.init(e,t),oq.init(e,t)});function oZ(e){return new oJ({type:"number",check:"number_format",abort:!1,format:"safeint",...r9(e)})}let oG=r$("ZodBoolean",(e,t)=>{ae.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.type="boolean"}});function oQ(e){return new oG({type:"boolean",...r9(e)})}let oY=r$("ZodBigInt",(e,t)=>{at.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")})(0,e,0,0),e.gte=(t,r)=>e.check(aX(t,r)),e.min=(t,r)=>e.check(aX(t,r)),e.gt=(t,r)=>e.check(aY(t,r)),e.gte=(t,r)=>e.check(aX(t,r)),e.min=(t,r)=>e.check(aX(t,r)),e.lt=(t,r)=>e.check(aG(t,r)),e.lte=(t,r)=>e.check(aQ(t,r)),e.max=(t,r)=>e.check(aQ(t,r)),e.positive=t=>e.check(aY(BigInt(0),t)),e.negative=t=>e.check(aG(BigInt(0),t)),e.nonpositive=t=>e.check(aQ(BigInt(0),t)),e.nonnegative=t=>e.check(aX(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(a0(t,r));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),oX=r$("ZodAny",(e,t)=>{ar.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function o0(){return new oX({type:"any"})}let o1=r$("ZodUnknown",(e,t)=>{an.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function o2(){return new o1({type:"unknown"})}let o6=r$("ZodNever",(e,t)=>{ai.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.not={}}}),o5=r$("ZodDate",(e,t)=>{aa.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")})(0,e,0,0),e.min=(t,r)=>e.check(aX(t,r)),e.max=(t,r)=>e.check(aQ(t,r));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null}),o8=r$("ZodArray",(e,t)=>{as.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(r.minItems=a),"number"==typeof o&&(r.maxItems=o),r.type="array",r.items=a3(i.element,t,{...n,path:[...n.path,"items"]})})(e,t,r,n),e.element=t.element,oE(e,"ZodArray",{min(e,t){return this.check(a2(e,t))},nonempty(e){return this.check(a2(1,e))},max(e,t){return this.check(a1(e,t))},length(e,t){return this.check(a6(e,t))},unwrap(){return this.element}})});function o4(e,t){return new o8({type:"array",element:e,...r9(t)})}let o3=r$("ZodObject",(e,t)=>{ap.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object",r.properties={};let a=i.shape;for(let e in a)r.properties[e]=a3(a[e],t,{...n,path:[...n.path,"properties",e]});let o=new Set([...new Set(Object.keys(a))].filter(e=>{let r=i.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));o.size>0&&(r.required=Array.from(o)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=a3(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)})(e,t,r,n),a8.defineLazy(e,"shape",()=>t.shape),oE(e,"ZodObject",{keyof(){return si(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:o2()})},loose(){return this.clone({...this._zod.def,catchall:o2()})},strict(){return this.clone({...this._zod.def,catchall:new o6({type:"never",...r9(void 0)})})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return a8.extend(this,e)},safeExtend(e){return a8.safeExtend(this,e)},merge(e){return a8.merge(this,e)},pick(e){return a8.pick(this,e)},omit(e){return a8.omit(this,e)},partial(...e){return a8.partial(so,this,e[0])},required(...e){return a8.required(sf,this,e[0])}})});function o9(e,t){return new o3({type:"object",shape:e??{},...a8.normalizeParams(t)})}let o7=r$("ZodUnion",(e,t)=>{ah.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{var i,a,o,s;let c,l,d;return i=e,a=t,o=r,s=n,l=!1===(c=i._zod.def).inclusive,d=c.options.map((e,t)=>a3(e,a,{...s,path:[...s.path,l?"oneOf":"anyOf",t]})),void(l?o.oneOf=d:o.anyOf=d)},e.options=t.options}),se=r$("ZodIntersection",(e,t)=>{ay.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o,s;return a=a3((i=e._zod.def).left,t,{...n,path:[...n.path,"allOf",0]}),o=a3(i.right,t,{...n,path:[...n.path,"allOf",1]}),void(r.allOf=[...(s=e=>"allOf"in e&&1===Object.keys(e).length)(a)?a.allOf:[a],...s(o)?o.allOf:[o]])}}),st=r$("ZodRecord",(e,t)=>{av.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object";let a=i.keyType,o=a._zod.bag,s=o?.patterns;if("loose"===i.mode&&s&&s.size>0){let e=a3(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});for(let t of(r.patternProperties={},s))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=a3(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=a3(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let c=a._zod.values;if(c){let e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}})(e,t,r,n),e.keyType=t.keyType,e.valueType=t.valueType});function sr(e,t,r){return new st(t&&t._zod?{type:"record",keyType:e,valueType:t,...a8.normalizeParams(r)}:{type:"record",keyType:oS(),valueType:e,...a8.normalizeParams(t)})}let sn=r$("ZodEnum",(e,t)=>{aS.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;(i=rV(e._zod.def.entries)).every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{let i={};for(let n of e)if(r.has(n))i[n]=t.entries[n];else throw Error(`Key ${n} not found in enum`);return new sn({...t,checks:[],...a8.normalizeParams(n),entries:i})},e.exclude=(e,n)=>{let i={...t.entries};for(let t of e)if(r.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new sn({...t,checks:[],...a8.normalizeParams(n),entries:i})}});function si(e,t){return new sn({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...a8.normalizeParams(t)})}let sa=r$("ZodTransform",(e,t)=>{ax.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")})(0,e,0,0),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new rj(e.constructor.name);r.addIssue=n=>{"string"==typeof n?r.issues.push(a8.issue(n,r.value,t)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),r.issues.push(a8.issue(n)))};let i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}}),so=r$("ZodOptional",(e,t)=>{aR.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>or(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function ss(e){return new so({type:"optional",innerType:e})}let sc=r$("ZodExactOptional",(e,t)=>{aI.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>or(e,t,r,n),e.unwrap=()=>e._zod.def.innerType}),sl=r$("ZodNullable",(e,t)=>{aU.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=a3((i=e._zod.def).innerType,t,n),o=t.seen.get(e),void("openapi-3.0"===t.target?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}])},e.unwrap=()=>e._zod.def.innerType});function sd(e){return new sl({type:"nullable",innerType:e})}let su=r$("ZodDefault",(e,t)=>{aO.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a3((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),sp=r$("ZodPrefault",(e,t)=>{aC.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a3((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},e.unwrap=()=>e._zod.def.innerType}),sf=r$("ZodNonOptional",(e,t)=>{aD.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a3((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType},e.unwrap=()=>e._zod.def.innerType}),sh=r$("ZodCatch",(e,t)=>{az.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i,a=e._zod.def;a3(a.innerType,t,n),t.seen.get(e).ref=a.innerType;try{i=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i})(e,t,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),sm=r$("ZodPipe",(e,t)=>{a$.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=(i=e._zod.def).in._zod.traits.has("$ZodTransform"),void(a3(o="input"===t.io?a?i.out:i.in:i.out,t,n),t.seen.get(e).ref=o)},e.in=t.in,e.out=t.out});function sy(e,t){return new sm({type:"pipe",in:e,out:t})}let sg=r$("ZodReadonly",(e,t)=>{aB.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a3((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.readOnly=!0},e.unwrap=()=>e._zod.def.innerType}),sw=r$("ZodCustom",(e,t)=>{aM.init(e,t),ov.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")})(0,e,0,0)});e.s(["bigint",0,function(e){return new oY({type:"bigint",coerce:!0,...r9(e)})},"boolean",0,function(e){return new oG({type:"boolean",coerce:!0,...r9(e)})},"date",0,function(e){return new o5({type:"date",coerce:!0,...r9(e)})},"number",0,function(e){return new oq({type:"number",coerce:!0,checks:[],...r9(e)})},"string",0,function(e){return new o_({type:"string",coerce:!0,...r9(e)})}],803099);var sb=e.i(803099),sb=sb;function sA(e){let t=e.split("."),r=parseInt(t[t.length-1]||"0",10);return isNaN(r)?0:r}function sE(e,t){let r={};for(let n in e)r[n]={name:n,value:"",attributes:{...t,maxAge:0}};return r}let sv=e=>(t,r,n)=>{let i=function(e,t){let r={};for(let[n,i]of rL(t.headers?.get("cookie")||""))n.startsWith(e)&&(r[n]=i);return r}(t,n),a=n.context.logger;return{getValue:()=>Object.keys(i).sort((e,t)=>sA(e)-sA(t)).map(e=>i[e]).join(""),hasChunks:()=>Object.keys(i).length>0,chunk(n,o){let s=sE(i,r);for(let e in i)delete i[e];for(let c of function(e,t,r,n){let i=Math.ceil(t.value.length/3896);if(1===i)return r[t.name]=t.value,[t];let a=[];for(let e=0;e<i;e++){let n=`${t.name}.${e}`,i=3896*e,o=t.value.substring(i,i+3896);a.push({...t,name:n,value:o}),r[n]=o}return n.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds allowed 4096 bytes.`,emptyCookieSize:200,valueSize:t.value.length,chunkCount:i,chunks:a.map(e=>e.value.length+200)}),a}(e,{name:t,value:n,attributes:{...r,...o}},i,a))s[c.name]=c;return Object.values(s)},clean(){let e=sE(i,r);for(let e in i)delete i[e];return Object.values(e)},setCookies(e){for(let t of e)n.setCookie(t.name,t.value,t.attributes)}}},sk=sv("Session"),s_=sv("Account");function sS(e,t){let r=e.getCookie(t);if(r)return r;let n=[],i=e.headers?.get("cookie");if(!i)return null;for(let[e,r]of rL(i))if(e.startsWith(t+".")){let t=parseInt(e.split(".").at(-1)||"0",10);isNaN(t)||n.push({index:t,value:r})}return n.length>0?(n.sort((e,t)=>e.index-t.index),n.map(e=>e.value).join("")):null}async function sx(e,t){let r=e.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await rm(t,e.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>4096){let t=s_(r.name,n,e),a=t.chunk(i,n);t.setCookies(a)}else{let t=s_(r.name,n,e);if(t.hasChunks()){let e=t.clean();t.setCookies(e)}e.setCookie(r.name,i,n)}}async function sT(e){let t=sS(e,e.context.authCookies.accountData.name);if(t){let r=(0,rz.safeJSONParse)(await rg(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}let sR=ss(o9({disableCookieCache:sb.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:sb.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function sI(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function sU(e,t,r){let n="",i=0,a=0;for(let r of e)for(i=i<<8|r,a+=8;a>=6;)a-=6,n+=t[i>>a&63];if(a>0&&(n+=t[i<<6-a&63]),r){let e=(4-n.length%4)%4;n+="=".repeat(e)}return n}function sO(e,t){let r=new Map;for(let e=0;e<t.length;e++)r.set(t[e],e);let n=[],i=0,a=0;for(let t of e){if("="===t)break;let e=r.get(t);if(void 0===e)throw Error(`Invalid Base64 character: ${t}`);i=i<<6|e,(a+=6)>=8&&(a-=8,n.push(i>>a&255))}return Uint8Array.from(n)}let sP={encode(e,t={}){let r=sI(!1);return sU("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){"string"!=typeof e&&(e=new TextDecoder().decode(e));let t=sI(e.includes("-")||e.includes("_"));return sO(e,t)}},sC={encode(e,t={}){let r=sI(!0);return sU("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){let t=sI(e.includes("-")||e.includes("_"));return sO(e,t)}},sD=new Map,sL={decode:(e,t="utf-8")=>(sD.has(t)||sD.set(t,new TextDecoder(t)),sD.get(t).decode(e)),encode:new TextEncoder().encode};function sz(){let e="u">typeof globalThis&&globalThis.crypto;if(e&&"object"==typeof e.subtle&&null!=e.subtle)return e.subtle;throw Error("crypto.subtle must be defined")}let s$=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>sz().importKey("raw","string"==typeof t?new TextEncoder().encode(t):t,{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,n)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let i=await sz().sign("HMAC",e,"string"==typeof n?new TextEncoder().encode(n):n);return"hex"===t?(e=>{if("string"==typeof e&&(e=new TextEncoder().encode(e)),0===e.byteLength)return"";let t=new Uint8Array(e),r="";for(let e of t)r+=e.toString(16).padStart(2,"0");return r})(i):"base64"===t||"base64url"===t||"base64urlnopad"===t?sC.encode(i,{padding:"base64urlnopad"!==t}):i},verify:async(e,n,i)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(i=(e=>{if(!e)return"";if("string"==typeof e){if(e.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(e))throw Error("Invalid hexadecimal string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)})(i)),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(i=await sP.decode(i)),sz().verify("HMAC",e,"string"==typeof i?new TextEncoder().encode(i):i,"string"==typeof n?new TextEncoder().encode(n):n))};return r};function sN(e){let t="string"==typeof e.baseURL?e.baseURL:void 0,r="object"==typeof e.baseURL&&null!==e.baseURL?e.baseURL.protocol:void 0,n=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:"https"===r||"http"!==r&&(t?t.startsWith("https://"):S.isProduction))?"__Secure-":"",i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!O(e.baseURL))throw new b.BetterAuthError("baseURL is required when crossSubdomainCookies are enabled.");return function(t,r={}){let o=e.advanced?.cookiePrefix||"better-auth",s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${n}${s}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...r,...c}}}}function sj(e){let t=sN(e),r=t("session_token",{maxAge:e.session?.expiresIn||Math.round(function(){let e,t=rR.exec("7d");if(!t||t[4]&&t[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let r=parseFloat(t[2]),n=t[3].toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":e=315576e5*r;break;case"months":case"month":case"mo":e=2592e6*r;break;case"weeks":case"week":case"w":e=6048e5*r;break;case"days":case"day":case"d":e=864e5*r;break;case"hours":case"hour":case"hrs":case"hr":case"h":e=36e5*r;break;case"minutes":case"minute":case"mins":case"min":case"m":e=6e4*r;break;case"seconds":case"second":case"secs":case"sec":case"s":e=1e3*r;break;default:throw TypeError(`Unknown time unit: "${n}"`)}return"-"===t[1]||"ago"===t[4]?-e:e}()/1e3)}),n=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),i=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),a=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function sH(e,t,r){let n;if(!e.context.options.session?.cookieCache?.enabled)return;let i=rb(t.session,e.context.options.session?.additionalFields),a=rv(e.context.options,t.user),o=e.context.options.session?.cookieCache?.version,s="1";if(o){if("string"==typeof o)s=o;else if("function"==typeof o){let e=o(t.session,t.user);s=L(e)?await e:e}}let c={session:i,user:a,updatedAt:Date.now(),version:s},l={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},d=rT(l.maxAge||60,"sec").getTime(),u=e.context.options.session?.cookieCache?.strategy||"compact";if((n="jwe"===u?await rm(c,e.context.secretConfig,"better-auth-session",l.maxAge||300):"jwt"===u?await rl(c,e.context.secret,l.maxAge||300):sC.encode(JSON.stringify({session:c,expiresAt:d,signature:await s$("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...c,expiresAt:d}))}),{padding:!1})).length>4093){let t=sk(e.context.authCookies.sessionData.name,l,e),r=t.chunk(n,l);t.setCookies(r)}else{let t=sk(e.context.authCookies.sessionData.name,l,e);if(t.hasChunks()){let e=t.clean();t.setCookies(e)}e.setCookie(e.context.authCookies.sessionData.name,n,l)}if(e.context.options.account?.storeAccountCookie){let t=await sT(e);t&&await sx(e,t)}}async function sB(e,t,r,n){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!i;let a=e.context.authCookies.sessionToken.attributes,o=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes),await sH(e,t,r),e.context.setNewSession(t)}function sV(e,t){!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let n=`${t}=`,i=`${t}.`;for(let e of r){let t="function"==typeof e.getSetCookie?e.getSetCookie():rU(e.get("set-cookie")||"");if(!t.length)continue;let r=t.filter(e=>!e.startsWith(n)&&!e.startsWith(i));if(r.length!==t.length)for(let t of(e.delete("set-cookie"),r))e.append("set-cookie",t)}}(e,t.name),e.setCookie(t.name,"",{...t.attributes,maxAge:0})}function sM(e,t){if(sV(e,e.context.authCookies.sessionToken),sV(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){sV(e,e.context.authCookies.accountData);let t=s_(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),r=t.clean();t.setCookies(r)}"cookie"===e.context.oauthConfig.storeStateStrategy&&sV(e,e.context.createAuthCookie("oauth_state"));let r=sk(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),n=r.clean();r.setCookies(n),t||sV(e,e.context.authCookies.dontRememberToken)}function sK(e){return aJ(oN,void 0).safeParse(e).success||aZ(oj,void 0).safeParse(e).success}function sW(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=Array(8-r.length-n.length).fill("0000");return[...r.map(e=>e.padStart(4,"0")),...i,...n.map(e=>e.padStart(4,"0"))]}return e.split(":").map(e=>e.padStart(4,"0"))}function sq(e,t={}){if(aJ(oN,void 0).safeParse(e).success||!aZ(oj,void 0).safeParse(e).success)return e.toLowerCase();let r=function(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let e=t.substring(7);if(aJ(oN,void 0).safeParse(e).success)return e}let r=e.split(":");if(7===r.length&&r[5]?.toLowerCase()==="ffff"){let e=r[6];if(e&&aJ(oN,void 0).safeParse(e).success)return e}if(t.includes("::ffff:")||t.includes(":ffff:")){let t=sW(e);if(8===t.length&&"0000"===t[0]&&"0000"===t[1]&&"0000"===t[2]&&"0000"===t[3]&&"0000"===t[4]&&"ffff"===t[5]&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}(e);if(r)return r.toLowerCase();var n=t.ipv6Subnet??64;let i=sW(e);if(void 0!==n&&n<128){let e=Math.max(0,Math.floor(n));return i.map(t=>{if(e<=0)return"0000";if(e>=16)return e-=16,t;let r=Number.parseInt(t,16)&(65535<<16-e&65535);return e=0,r.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return i.join(":").toLowerCase()}function sF(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="headers"in e?e.headers:e;for(let e of t.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"]){let n="get"in r?r.get(e):r[e];if("string"==typeof n){let e=n.split(",")[0].trim();if(sK(e))return sq(e,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet})}}return(0,S.isTest)()||(0,S.isDevelopment)()?"127.0.0.1":null}function sJ(e,t){return{digest:async r=>{let n=new TextEncoder,i="string"==typeof r?n.encode(r):r,a=await sz().digest(e,i);return"hex"===t?Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join(""):"base64"===t||"base64url"===t||"base64urlnopad"===t?t.includes("url")?sC.encode(a,{padding:"base64urlnopad"!==t}):sP.encode(a):a}}}let sZ=async e=>{let t=await sJ("SHA-256").digest(new TextEncoder().encode(e));return sC.encode(new Uint8Array(t),{padding:!1})};async function sG(e,t){return t&&"plain"!==t?"hashed"===t?sZ(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function sQ(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,n]of Object.entries(t.overrides))if(e.startsWith(r))return n}return t.default}return t}}let sY=Symbol.for("better-auth:global"),sX=null,s0={},s1="1.6.12";function s2(){return globalThis[sY]||(globalThis[sY]={version:s1,epoch:1,context:s0},sX=globalThis[sY]),(sX=globalThis[sY]).version!==s1&&(sX.version=s1,sX.epoch++),globalThis[sY]}let s6=import("node:async_hooks").then(e=>e.AsyncLocalStorage).catch(e=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;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"),e});async function s5(){let e=await s6;if(null!==e)return e;throw Error("getAsyncLocalStorage is only available in server code")}let s8=async()=>{let e=s2();if(!e.context.adapterAsyncStorage){let t=await s5();e.context.adapterAsyncStorage=new t}return e.context.adapterAsyncStorage},s4=async e=>s8().then(t=>t.getStore()?.adapter||e).catch(()=>e),s3=async(e,t)=>{let r=!1;return s8().then(async n=>{let i,a;r=!0;let o=[],s=!1;try{i=await n.run({adapter:e,pendingHooks:o},t)}catch(e){a=e,s=!0}for(let e of o)await e();if(s)throw a;return i}).catch(e=>{if(!r)return t();throw e})},s9=async(e,t)=>s8().then(async r=>{let n,i,a=[],o=!1;try{n=await e.transaction(async e=>r.run({adapter:e,pendingHooks:a},t))}catch(e){o=!0,i=e}for(let e of a)await e();if(o)throw i;return n}).catch(e=>{throw e}),s7=async e=>s8().then(t=>{let r=t.getStore();if(!r)return e();r.pendingHooks.push(e)}).catch(()=>e()),ce=async()=>{let e=s2();if(!e.context.endpointContextAsyncStorage){let t=await s5();e.context.endpointContextAsyncStorage=new t}return e.context.endpointContextAsyncStorage};async function ct(){let e=(await ce()).getStore();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function cr(e,t){return(await ce()).run(e,t)}var cn=e.i(897454);let ci="better_auth.operation_id",ca="better_auth.hook.type",co="better_auth.context";var cs=e.i(969746),cc=e.i(90750);function cl(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let cd=(e,t)=>{let r,n=t.logger,i=t.options,a=i.secondaryStorage,o=new Map,s=i.session?.expiresIn||604800,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:d,deleteWithHooks:u,deleteManyWithHooks:p,consumeOneWithHooks:f}=(r=t.hooks,{createWithHooks:async function(t,n,i){let a=await ct().catch(()=>null),o=t;for(let{source:e,hooks:t}of r){let r=t[n]?.create?.before;if(r){let t=await (0,cs.withSpan)(`db create.before ${n}`,{[ca]:"create.before",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:e},()=>r(o,a));if(!1===t)return null;"object"==typeof t&&"data"in t&&(o={...o,...t.data})}}let s=null;for(let{source:t,hooks:c}of((!i||i.executeMainFn)&&(s=await (await s4(e)).create({model:n,data:o,forceAllowId:!0})),i?.fn&&(s=await i.fn(s??o)),r)){let e=c[n]?.create?.after;e&&await s7(async()=>{await (0,cs.withSpan)(`db create.after ${n}`,{[ca]:"create.after",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:t},()=>e(s,a))})}return s},updateWithHooks:async function(t,n,i,a){let o=await ct().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,cs.withSpan)(`db update.before ${i}`,{[ca]:"update.before",[cn.ATTR_DB_COLLECTION_NAME]:i,[co]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await s4(e)).update({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await s7(async()=>{await (0,cs.withSpan)(`db update.after ${i}`,{[ca]:"update.after",[cn.ATTR_DB_COLLECTION_NAME]:i,[co]:e},()=>r(l,o))})}return l},updateManyWithHooks:async function(t,n,i,a){let o=await ct().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,cs.withSpan)(`db updateMany.before ${i}`,{[ca]:"updateMany.before",[cn.ATTR_DB_COLLECTION_NAME]:i,[co]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await s4(e)).updateMany({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await s7(async()=>{await (0,cs.withSpan)(`db updateMany.after ${i}`,{[ca]:"updateMany.after",[cn.ATTR_DB_COLLECTION_NAME]:i,[co]:e},()=>r(l,o))})}return l},deleteWithHooks:async function(t,n,i){let a=await ct().catch(()=>null),o=null;try{o=(await (await s4(e)).findMany({model:n,where:t,limit:1}))[0]||null}catch{}if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.before;if(r&&await (0,cs.withSpan)(`db delete.before ${n}`,{[ca]:"delete.before",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:e},()=>r(o,a))===!1)return null}let s=i?await i.fn(t):null,c=(!i||i.executeMainFn)&&o?await (await s4(e)).delete({model:n,where:t}):s;if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.after;r&&await s7(async()=>{await (0,cs.withSpan)(`db delete.after ${n}`,{[ca]:"delete.after",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:e},()=>r(o,a))})}return c},deleteManyWithHooks:async function(t,n,i){let a=await ct().catch(()=>null),o=[];try{o=await (await s4(e)).findMany({model:n,where:t})}catch{}for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.before;if(r&&await (0,cs.withSpan)(`db delete.before ${n}`,{[ca]:"delete.before",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:t},()=>r(e,a))===!1)return null}let s=i?await i.fn(t):null,c=!i||i.executeMainFn?await (await s4(e)).deleteMany({model:n,where:t}):s;for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.after;r&&await s7(async()=>{await (0,cs.withSpan)(`db delete.after ${n}`,{[ca]:"delete.after",[cn.ATTR_DB_COLLECTION_NAME]:n,[co]:t},()=>r(e,a))})}return c},consumeOneWithHooks:async function(t,n,i,a){let o=await ct().catch(()=>null),s=r.flatMap(({source:e,hooks:r})=>{let n=r[t]?.delete?.before;return n?[{source:e,fn:n}]:[]}),c=a??null;if(s.length){if(!c)try{c=(await (await s4(e)).findMany({model:t,where:n,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:r}of s)if(await (0,cs.withSpan)(`db delete.before ${t}`,{[ca]:"delete.before",[cn.ATTR_DB_COLLECTION_NAME]:t,[co]:e},()=>r(c,o))===!1)return null}}let l=await i();if(!l)return null;for(let{source:e,hooks:n}of r){let r=n[t]?.delete?.after;r&&await s7(async()=>{await (0,cs.withSpan)(`db delete.after ${t}`,{[ca]:"delete.after",[cn.ATTR_DB_COLLECTION_NAME]:t,[co]:e},()=>r(l,o))})}return l}});async function h(e){if(!a)return;let t=await a.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),n=((0,rz.safeJSONParse)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(n.map(async({token:t})=>{let n=await a.get(t);if(!n)return;let i=(0,rz.safeJSONParse)(n);if(!i)return;let o=cl(i.session.expiresAt,r);await a.set(t,JSON.stringify({session:i.session,user:e}),Math.floor(o))}))}async function m(e,t){let r,n=o.get(e)??Promise.resolve(),i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);o.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),o.get(e)===a&&o.delete(e)}}return{createOAuthUser:async(t,r)=>s9(e,async()=>{let e=await c({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);return{user:e,account:await c({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async e=>await c({createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()},"user",void 0),createAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,n)=>{if(a){let e=await a.get(`active-sessions-${r}`);if(!e)return[];let n=(0,rz.safeJSONParse)(e)||[],i=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:r}of n){if(r<=i||o.has(e))continue;o.add(e);let n=await a.get(e);if(n)try{let e="string"==typeof n?JSON.parse(n):n;if(!e?.session)continue;s.push(r_(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await s4(e)).findMany({model:"session",where:[{field:"userId",value:r},...n?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,n,i)=>await (await s4(e)).findMany({model:"user",limit:t,offset:r,sortBy:n,where:i}),countTotalUsers:async t=>{let r=await (await s4(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{(!a||i.session?.storeSessionInDatabase)&&await p([{field:"userId",value:e}],"session",void 0),await p([{field:"userId",value:e}],"account",void 0),await u([{field:"id",value:e}],"user",void 0)},createSession:async(r,n,o,l)=>{let d,u=await (async()=>{let e=await ct().catch(()=>null);return e?.headers||e?.request?.headers})(),p=i.session?.storeSessionInDatabase,{id:f,...h}=o||{};if(a&&!p){let e=t.generateId({model:"session"});d=!1!==e?e:(0,cc.generateId)()}let m=function(e){let t=rE(e,"session","input"),r={};for(let e in t)void 0!==t[e].defaultValue&&(r[e]="function"==typeof t[e].defaultValue?t[e].defaultValue():t[e].defaultValue);return r}(i),y={...d?{id:d}:{},ipAddress:u&&sF(u,i)||"",userAgent:u?.get("user-agent")||"",...h,expiresAt:n?rT(86400,"sec"):rT(s,"sec"),userId:r,token:(0,cc.generateId)(32),createdAt:new Date,updatedAt:new Date,...m,...l?h:{}};return await c(y,"session",a?{fn:async t=>{let n=await a.get(`active-sessions-${r}`),i=[],o=Date.now();n&&(i=(i=(0,rz.safeJSONParse)(n)||[]).filter(e=>e.expiresAt>o&&e.token!==y.token));let s=[...i,{token:y.token,expiresAt:y.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=cl(s.at(-1)?.expiresAt??y.expiresAt.getTime(),o);c>0&&await a.set(`active-sessions-${r}`,JSON.stringify(s),c);let l=await (await s4(e)).findOne({model:"user",where:[{field:"id",value:r}]}),d=cl(y.expiresAt,o);return d>0&&await a.set(y.token,JSON.stringify({session:t,user:l}),d),t},executeMainFn:p}:void 0)},findSession:async r=>{if(a){let e=await a.get(r);if(!e&&(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,rz.safeJSONParse)(e);return r?{session:r_(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:rv(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}:null}}let n=await (await s4(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!n)return null;let{user:o,...s}=n;return o?{session:r_(t.options,s),user:rv(t.options,o)}:null},findSessions:async(t,r)=>{if(a){let e=[];for(let n of t){let t=await a.get(n);if(t)try{let n="string"==typeof t?JSON.parse(t):t;if(!n)return[];let i=new Date(n.session.expiresAt);if(r?.onlyActiveSessions&&i<=new Date)continue;let a={session:{...n.session,expiresAt:new Date(n.session.expiresAt)},user:{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)}};e.push(a)}catch{continue}}return e}let n=await (await s4(e)).findMany({model:"session",where:[{field:"token",value:t,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!n.length||n.some(e=>!e.user)?[]:n.map(e=>{let{user:t,...r}=e;return{session:r,user:t}})},updateSession:async(e,r)=>await l(r,[{field:"token",value:e}],"session",a?{async fn(r){let n=await a.get(e);if(!n)return null;let i=(0,rz.safeJSONParse)(n);if(!i)return null;let o={...i.session,...r,expiresAt:new Date(r.expiresAt??i.session.expiresAt),createdAt:new Date(i.session.createdAt),updatedAt:new Date(r.updatedAt??i.session.updatedAt)},s=r_(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),d=cl(l,c);if(d>0){await a.set(e,JSON.stringify({session:s,user:i.user}),d);let t=`active-sessions-${s.userId}`,r=await a.get(t),n=(r&&(0,rz.safeJSONParse)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=n.at(-1)?.expiresAt;o&&o>c?await a.set(t,JSON.stringify(n),cl(o,c)):await a.delete(t)}return s},executeMainFn:i.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(a){let r=await a.get(e);if(r){let{session:t}=(0,rz.safeJSONParse)(r)??{};if(!t)return void n.error("Session not found in secondary storage");let i=t.userId,o=await a.get(`active-sessions-${i}`);if(o){let t=(0,rz.safeJSONParse)(o)||[],r=Date.now(),n=t.filter(t=>t.expiresAt>r&&t.token!==e),s=n.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;n.length>0&&s&&s>Date.now()?await a.set(`active-sessions-${i}`,JSON.stringify(n),cl(s,r)):await a.delete(`active-sessions-${i}`)}else n.error("Active sessions list not found in secondary storage")}if(await a.delete(e),!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await u([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await p([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await u([{field:"id",value:e}],"account",void 0)},deleteSessions:async e=>{if(a){if("string"==typeof e){let t=await a.get(`active-sessions-${e}`),r=t?(0,rz.safeJSONParse)(t):[];if(!r)return;for(let e of r)await a.delete(e.token);await a.delete(`active-sessions-${e}`)}else for(let t of e)await a.get(t)&&await a.delete(t);if(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await p([{field:Array.isArray(e)?"token":"userId",value:e,operator:Array.isArray(e)?"in":void 0}],"session",void 0)},findOAuthUser:async(t,r,n)=>{let i=await (await s4(e)).findOne({model:"account",where:[{value:r,field:"accountId"},{value:n,field:"providerId"}],join:{user:!0}});if(i)if(i.user)return{user:i.user,linkedAccount:i,accounts:[i]};else{let r=await (await s4(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:i,accounts:[i]}:null}{let r=await (await s4(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:null,accounts:await (await s4(e)).findMany({model:"account",where:[{value:r.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(t,r)=>{let n=await (await s4(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!n)return null;let{account:i,...a}=n;return{user:a,accounts:i??[]}},findUserById:async t=>t?await (await s4(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await h(r),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await h(r),r},updatePassword:async(e,t)=>{await d({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async t=>await (await s4(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findAccount:async t=>await (await s4(e)).findOne({model:"account",where:[{field:"accountId",value:t}]}),findAccountByProviderId:async(t,r)=>await (await s4(e)).findOne({model:"account",where:[{field:"accountId",value:t},{field:"providerId",value:r}]}),findAccountByUserId:async t=>await (await s4(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=sQ(e.identifier,i.verification?.storeIdentifier),r=await sG(e.identifier,t);return await c({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",a?{async fn(e){let t=cl(e.expiresAt);return t>0&&await a.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:i.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=sQ(t,i.verification?.storeIdentifier),n=await sG(t,r);if(a){let e=await a.get(`verification:${n}`);if(e){let t=(0,rz.safeJSONParse)(e);if(t)return t}if(r&&"plain"!==r){let e=await a.get(`verification:${t}`);if(e){let t=(0,rz.safeJSONParse)(e);if(t)return t}}if(!i.verification?.storeInDatabase)return null}let o=await s4(e);async function s(e){return o.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let c=await s(n);return!c.length&&r&&"plain"!==r&&(c=await s(t)),i.verification?.disableCleanup||await p([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await sG(e,sQ(e,i.verification?.storeIdentifier));a&&await a.delete(`verification:${t}`),(!a||i.verification?.storeInDatabase)&&await u([{field:"identifier",value:t}],"verification",void 0)},consumeVerificationValue:async t=>{let r=sQ(t,i.verification?.storeIdentifier),n=await sG(t,r),o=r&&"plain"!==r?[n,t]:[n],s=e=>{if(!e)return null;let t="string"==typeof e?(0,rz.safeJSONParse)(e):"object"==typeof e?e:null;if(!t)return null;let r=new Date(t.expiresAt);return Number.isFinite(r.getTime())?{...t,expiresAt:r}:null},c=null;if(a&&!i.verification?.storeInDatabase){let e=async e=>a.getAndDelete?s(await a.getAndDelete(e)):m(e,async()=>{let t=s(await a.get(e));return t?(await a.delete(e),t):null});for(let t of o){let r=await e(`verification:${t}`);if(r){await Promise.all(o.filter(e=>e!==t).map(e=>a.delete(`verification:${e}`))),c=r;break}}}else{let t=async t=>m(`verification:${t}`,()=>s9(e,async()=>{let r=await s4(e),n=[{field:"identifier",value:t}],i=(await r.findMany({model:"verification",where:n,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return i?f("verification",[{field:"id",value:i.id}],async()=>{let e=await r.consumeOne({model:"verification",where:[{field:"id",value:i.id}]});return e?(await r.deleteMany({model:"verification",where:n}),e):null},i):null}));for(let e of o)if(c=await t(e))break;c&&a&&await Promise.all(o.map(e=>a.delete(`verification:${e}`)))}return!c||c.expiresAt<new Date?null:c},updateVerificationByIdentifier:async(e,t)=>{let r=await sG(e,sQ(e,i.verification?.storeIdentifier));if(a){let e=await a.get(`verification:${r}`);if(e){let n=(0,rz.safeJSONParse)(e);if(n){let e={...n,...t},o=e.expiresAt??n.expiresAt,s=cl(o instanceof Date?o:new Date(o));if(s>0&&await a.set(`verification:${r}`,JSON.stringify(e),s),!i.verification?.storeInDatabase)return e}}}return!a||i.verification?.storeInDatabase?await l(t,[{field:"identifier",value:r}],"verification",void 0):t},refreshUserSessions:h}};function cu(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e))}function cp(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,n=".",i){if(!cu(r))return e(t,{},n,i);let a={...r};for(let r of Object.keys(t)){if("__proto__"===r||"constructor"===r)continue;let o=t[r];null!=o&&(i&&i(a,r,o,n)||(Array.isArray(o)&&Array.isArray(a[r])?a[r]=[...o,...a[r]]:cu(o)&&cu(a[r])?a[r]=e(o,a[r],(n?`${n}.`:"")+r.toString(),i):a[r]=o))}return a})(t,r,"",e),{})}let cf=cp();cp((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),cp((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0});let ch=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function cm(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function cy(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function cg(e,t,r){if(0===r)return!0;let n=32===r?0xffffffff:-1<<32-r>>>0;return(e&n)==(t&n)}function cw(e){if("0.0.0.0"===e)return"unspecified";if("255.255.255.255"===e)return"broadcast";let t=cy(e);return cg(t,cy("127.0.0.0"),8)?"loopback":cg(t,cy("10.0.0.0"),8)||cg(t,cy("172.16.0.0"),12)||cg(t,cy("192.168.0.0"),16)?"private":cg(t,cy("169.254.0.0"),16)?"linkLocal":cg(t,cy("100.64.0.0"),10)?"sharedAddressSpace":cg(t,cy("192.0.2.0"),24)||cg(t,cy("198.51.100.0"),24)||cg(t,cy("203.0.113.0"),24)?"documentation":cg(t,cy("198.18.0.0"),15)?"benchmarking":cg(t,cy("224.0.0.0"),4)?"multicast":cg(t,cy("0.0.0.0"),8)||cg(t,cy("192.0.0.0"),24)||cg(t,cy("240.0.0.0"),4)?"reserved":"public"}function cb(e,t,r={}){let n=5*t,i=Number.parseInt(e.slice(n,n+4),16),a=Number.parseInt(e.slice(n+5,n+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return r.xor&&(o=(0xffffffff^o)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${255&o}`}async function cA(e){let t=e.options,r=t.plugins||[],n=[],i=[];for(let a of r)if(a.init){let r,o=a.init(e);if("object"==typeof(r=L(o)?await o:o)){if(r.options){let{databaseHooks:e,trustedOrigins:o,...s}=r.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),o&&n.push(o),t=cf(t,s)}r.context&&Object.assign(e,r.context)}}if(n.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...n],r=e.filter(Array.isArray).flat(),i=e.filter(e=>"function"==typeof e);i.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(i.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&i.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=cd(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}async function cE(e,t){let r=[];if(O(e.baseURL)){let t=e.baseURL.allowedHosts,n=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(n&&"https"!==n&&"auto"!==n||r.push(`https://${e}`),("http"===n||"auto"===n||function(e){let t=function(e){var t,r;let n,i=(-1===(n=(r=(t=function(e){if(e.startsWith("[")){let t=e.indexOf("]");return -1===t?e:e.slice(0,t+1)}let t=e.indexOf(":");return -1===t||-1!==e.indexOf(":",t+1)?e:e.slice(0,t)}(e.trim())).length>=2&&t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t).indexOf("%"))?r:r.slice(0,n)).replace(/\.+$/,"").toLowerCase();if(""===i)return{kind:"reserved",literal:"fqdn",canonical:""};if(!sK(i))return"localhost"===i||i.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:i}:ch.has(i)?{kind:"cloudMetadata",literal:"fqdn",canonical:i}:{kind:"public",literal:"fqdn",canonical:i};if(cm(i))return{kind:cw(i),literal:"ipv4",canonical:i};let a=sq(i,{ipv6Subnet:128});return cm(a)?{kind:cw(a),literal:"ipv4",canonical:a}:{kind:function(e){if("0000:0000:0000:0000:0000:0000:0000:0000"===e)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===e)return"loopback";let t=Number.parseInt(e.slice(0,2),16),r=Number.parseInt(e.slice(2,4),16);if(255===t)return"multicast";if(254===t&&(192&r)==128)return"linkLocal";if((254&t)==252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2002:")){let t=cb(e,1);return t&&"public"!==cw(t)?"reserved":"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let t=cb(e,6);return t&&cw(t),"reserved"}if(e.startsWith("2001:0000:")){let t=cb(e,6,{xor:!0});return t&&cw(t),"reserved"}return e.startsWith("0100:0000:0000:0000:")?"reserved":"public"}(a),literal:"ipv6",canonical:a}}(e).kind;return"loopback"===t||"localhost"===t}(e))&&r.push(`http://${e}`));if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let n=I("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);n&&r.push(new URL(n).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let n=await e.trustedOrigins(t);r.push(...n)}let n=S.env.BETTER_AUTH_TRUSTED_ORIGINS;return n&&r.push(...n.split(",")),r.filter(e=>!!e)}function cv(e){return e.advanced?.trustedProxyHeaders??!0}async function ck(e,t,r){let n,i=e.options.baseURL,a=function(e,t,r,n,i){if(O(e)){if(r){let n=C(r,i);if(!n){if(e.fallback)return T(e.fallback,t);throw new b.BetterAuthError("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(e.allowedHosts.some(e=>((e,t)=>{if(!e||!t)return!1;let r=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?_(n)(r):r.toLowerCase()===n.toLowerCase()})(n,e)))return T(`${function(e,t,r){let n;if("http"===t||"https"===t)return t;let i=P(e)?e.headers:e;if(r){let e=i.get("x-forwarded-proto");if(e&&R(e,"proto"))return e}if(P(e))try{let t=new URL(e.url);if("http:"===t.protocol||"https:"===t.protocol)return t.protocol.slice(0,-1)}catch{}let a=C(e,r);return a&&("localhost"===(n=a.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||n.endsWith(".localhost")||"::1"===n||n.startsWith("127."))?"http":"https"}(r,e.protocol,i)}://${n}`,t);if(e.fallback)return T(e.fallback,t);throw new b.BetterAuthError(`Host "${n}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return e.fallback?T(e.fallback,t):I(void 0,t,void 0,n,i)}let a=P(r)?r:void 0;return"string"==typeof e?I(e,t,a,n,i):I(void 0,t,a,n,i)}(i,e.options.basePath||"/api/auth",t,void 0,r);if(!a)throw new b.BetterAuthError("Could not resolve base URL from request. Check your allowedHosts config.");let o=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));o.baseURL=a,o.options={...e.options,baseURL:U(a)||void 0};let s={...o.options,baseURL:i};return n="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?P(t)?t:t?new Request(a,{headers:t}):void 0:void 0,o.trustedOrigins=await cE(s,n),o.trustedProviders=await cS(o.options,n),e.options.advanced?.crossSubDomainCookies?.enabled&&(o.authCookies=sj(o.options),o.createAuthCookie=sN(o.options)),o}async function c_(e,t){if(e)for(let r of e){let e="function"==typeof r?await r():r;if(e[t.field??"id"]===t.value)return e}}async function cS(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}async function cx(e,t){let r=(await e.context.internalAdapter.findAccounts(t.userId))?.find(e=>"credential"===e.providerId),n=r?.password;return!!r&&!!n&&await e.context.password.verify({hash:n,password:t.password})}async function cT(e,t){let r=(await t.context.internalAdapter.findAccounts(e))?.find(e=>"credential"===e.providerId),n=r?.password,i=t.body.password;if(!r||!n||!i)throw i&&await t.context.password.hash(i),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD);if(!await t.context.password.verify({hash:n,password:i}))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD);return!0}var cR=e.i(329604);let cI=/^application\/([a-z0-9.+-]*\+)?json/i;async function cU(e,t){let r=e.headers.get("content-type")||"",n=r.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=n.split(";")[0].trim(),r=e.toLowerCase().trim();return t===r||t.includes(r)})){if(!n)throw new cR.APIError(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new cR.APIError(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(cI.test(n))return await e.json();if(n.includes("application/x-www-form-urlencoded")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e.toString()}),r}if(n.includes("multipart/form-data")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e}),r}return n.includes("text/plain")?await e.text():n.includes("application/octet-stream")?await e.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await e.blob():n.includes("application/stream")||e.body instanceof ReadableStream?e.body:await e.text()}}function cO(e){return e instanceof cR.APIError||e?.name==="APIError"}async function cP(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function cC(e){return e instanceof Request||"[object Request]"===Object.prototype.toString.call(e)}let cD=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 cL(e){for(let t of cD)e.delete(t)}function cz(e,t){if(e instanceof Response){if(t?.headers){let r=new Headers(t.headers);cL(r),r.forEach((t,r)=>{e.headers.set(r,t)})}return e}if(e&&"object"==typeof e&&"_flag"in e&&"json"===e._flag){let r=e.body,n=e.routerResponse;if(n instanceof Response)return n;let i=new Headers;if(n?.headers){let e=new Headers(n.headers);for(let[t,r]of e.entries())e.set(t,r)}if(e.headers)for(let[t,r]of new Headers(e.headers).entries())i.set(t,r);if(t?.headers){let e=new Headers(t.headers);for(let[t,r]of(cL(e),e.entries()))i.set(t,r)}return i.set("Content-Type","application/json"),new Response(JSON.stringify(r),{...n,headers:i,status:e.status??t?.status??n?.status,statusText:t?.statusText??n?.statusText})}if(cO(e))return cz(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,n=new Headers(t?.headers);if(cL(n),e){if("string"==typeof e)r=e,n.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,n.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,n.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,n.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,n.set("Content-Type","application/octet-stream");else if(function(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(e)){let t,i;t=0,i=new WeakMap,r=JSON.stringify(e,(e,r)=>{if("bigint"==typeof r)return r.toString();if("object"==typeof r&&null!==r){if(i.has(r))return`[Circular ref-${i.get(r)}]`;i.set(r,t++)}return r},void 0),n.set("Content-Type","application/json")}}else null===e&&(r=JSON.stringify(null)),n.set("content-type","application/json");return new Response(r,{...t,headers:n})}let c$={name:"HMAC",hash:"SHA-256"},cN=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await sz().importKey("raw",t,c$,!1,["sign","verify"])},cj=async(e,t,r)=>{try{let n=atob(e),i=new Uint8Array(n.length);for(let e=0,t=n.length;e<t;e++)i[e]=n.charCodeAt(e);return await sz().verify(c$,r,i,new TextEncoder().encode(t))}catch(e){return!1}},cH=async(e,t)=>{let r=await cN(t);return btoa(String.fromCharCode(...new Uint8Array(await sz().sign(c$.name,r,new TextEncoder().encode(e)))))},cB=async(e,t)=>{let r=await cH(e,t);return encodeURIComponent(e=`${e}.${r}`)},cV=(e,t)=>{let r=e;if(t)if("secure"===t)r="__Secure-"+e;else{if("host"!==t)return;r="__Host-"+e}return r},cM=(e,t,r={})=>{let n;if(n=r?.prefix==="secure"?`__Secure-${e}=${t}`:r?.prefix==="host"?`__Host-${e}=${t}`:`${e}=${t}`,e.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),e.startsWith("__Host-")&&(r.secure||(r.secure=!0),"/"!==r.path&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&"number"==typeof r.maxAge&&r.maxAge>=0){if(r.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&"host"!==r.prefix&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},cK=async(e,t,r,n)=>cM(e,t=await cB(t,r),n);async function cW(e,t={}){let r={body:t.body,query:t.query};if(e.body){let n=await e.body["~standard"].validate(t.body);if(n.issues)return{data:null,error:cq(n.issues,"body")};r.body=n.value}if(e.query){let n=await e.query["~standard"].validate(t.query);if(n.issues)return{data:null,error:cq(n.issues,"query")};r.query=n.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:"Headers is required",issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function cq(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>"object"==typeof e?e.key:e).join("."):t}] ${e.message}`).join("; "),issues:e}}let cF=async(e,{options:t,path:r})=>{let n,i=new Headers,{data:a,error:o}=await cW(t,e);if(o)throw new cR.ValidationError(o.message,o.issues);let s="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&cC(e.request)?e.request.headers:null,c=s?.get("cookie"),l=c?function(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let n=e.indexOf("=",r);if(-1===n)break;let i=e.indexOf(";",r);if(-1===i)i=e.length;else if(i<n){r=e.lastIndexOf(";",n-1)+1;continue}let a=e.slice(r,n).trim();if(!t.has(a)){let r=e.slice(n+1,i).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(a,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=i+1}return t}(c):void 0,d={...e,body:a.body,query:a.query,path:e.path||r||"virtual:",context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:"*"===t.method?"GET":t.method),setHeader:(e,t)=>{i.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let r=cV(e,t);return r&&l?.get(r)||null},getSignedCookie:async(e,t,r)=>{let n=cV(e,r);if(!n)return null;let i=l?.get(n);if(!i)return null;let a=i.lastIndexOf(".");if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return 44===s.length&&s.endsWith("=")?!!await cj(s,o,await cN(t))&&o:null},setCookie:(e,t,r)=>{var n;let a=cM(e,n=encodeURIComponent(n=t),r);return i.append("set-cookie",a),a},setSignedCookie:async(e,t,r,n)=>{let a=await cK(e,t,r,n);return i.append("set-cookie",a),a},redirect:e=>(i.set("location",e),new cR.APIError("FOUND",void 0,i)),error:(e,t,r)=>new cR.APIError(e,t,r),setStatus:e=>{n=e},json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:i,get responseStatus(){return n}};for(let e of t.use||[]){let t=await e({...d,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(d.context,t.response),t.headers&&t.headers.forEach((e,t)=>{d.responseHeaders.set(t,e)})}return d};function cJ(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r;if(("GET"===i.method||"HEAD"===i.method)&&i.body)throw new cR.BetterCallError("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new cR.BetterCallError("Path cannot contain consecutive slashes");let o=async(...e)=>{let t=e[0]||{},{data:r,error:o}=await cP(cF(t,{options:i,path:n}));if(o){if(!(o instanceof cR.ValidationError))throw o;throw i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new cR.APIError(400,{message:o.message,code:"VALIDATION_ERROR"})}let s=await a(r).catch(async e=>{if(cO(e)){let r=i.onAPIError;if(r&&await r(e),t.asResponse)return e}throw e}),c=r.responseHeaders,l=r.responseStatus;return t.asResponse?cz(s,{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=n,o}function cZ(e,t){let r=async r=>{let n="function"==typeof e?e:t,i=await cF(r,{options:"function"==typeof e?{}:e,path:"/"});if(!n)throw Error("handler must be defined");try{let e=await n(i),t=i.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw cO(e)&&Object.defineProperty(e,cR.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,get:()=>i.responseHeaders}),e}};return r.options="function"==typeof e?{}:e,r}cJ.create=e=>(t,r,n)=>cJ(t,{...r,use:[...r?.use||[],...e?.use||[]]},n),cZ.create=e=>function(t,r){if("function"==typeof t)return cZ({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return cZ({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)};let cG={};function cQ(e){switch(e.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function cY(e){let t=[];return e.metadata?.openapi?.parameters?t.push(...e.metadata.openapi.parameters):e.query instanceof o3&&Object.entries(e.query.shape).forEach(([e,r])=>{r instanceof o3&&t.push({name:e,in:"query",schema:{type:cQ(r),..."minLength"in r&&r.minLength?{minLength:r.minLength}:{},description:r.description}})}),t}function cX(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function c0(e,t){return Object.entries(e).forEach(([e,t])=>{let r=t.options;if(!(!t.path||r.metadata?.SERVER_ONLY)&&("GET"===r.method&&(cG[t.path]={get:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cY(r),responses:cX(r.metadata?.openapi?.responses)}}),"POST"===r.method)){let e=function(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof o3||e.body instanceof so)){let t=e.body.shape;if(!t)return;let r={},n=[];return Object.entries(t).forEach(([e,t])=>{t instanceof o3&&(r[e]={type:cQ(t),description:t.description},t instanceof so||n.push(e))}),{required:!(e.body instanceof so)&&!!e.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}(r);cG[t.path]={post:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cY(r),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:cX(r.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:cG}}let c1=((s=function(){}).prototype=Object.create(null),Object.freeze(s.prototype),s);function c2(){return{root:{key:""},static:new c1}}function c6(e){let[t,...r]=e.split("/");return""===r[r.length-1]?r.slice(0,-1):r}function c5(e,t){let r=new c1;for(let[n,i]of t){let t=n<0?e.slice(-(n+1)).join("/"):e[n];if("string"==typeof i)r[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)r[t]=e.groups[t]}}return r}function c8(e,t="",r,n){t=t.toUpperCase(),47!==r.charCodeAt(0)&&(r=`/${r}`);let i=c6(r=r.replace(/\\:/g,"%3A")),a=e.root,o=0,s=[],c=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.startsWith("**")){a.wildcard||(a.wildcard={key:"**"}),a=a.wildcard,s.push([-(e+1),t.split(":")[1]||"_",2===t.length]);break}if("*"===t||t.includes(":")){if(a.param||(a.param={key:"*"}),a=a.param,"*"===t)s.push([e,`_${o++}`,!0]);else if(t.includes(":",1)){let r=function(e){let t=e.replace(/:(\w+)/g,(e,t)=>`(?<${t}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${t}$`)}(t);c[e]=r,a.hasRegexParam=!0,s.push([e,r,!1])}else s.push([e,t.slice(1),!1]);continue}"\\*"===t?t=i[e]="*":"\\*\\*"===t&&(t=i[e]="**");let r=a.static?.[t];if(r)a=r;else{let e={key:t};a.static||(a.static=new c1),a.static[t]=e,a=e}}let l=s.length>0;a.methods||(a.methods=new c1),a.methods[t]??=[],a.methods[t].push({data:n||null,paramsRegexp:c,paramsMap:l?s:void 0}),l||(e.static["/"+i.join("/")]=a)}function c4(e){return e instanceof cR.APIError||e instanceof b.APIError||e?.name==="APIError"}let c3=cZ(async()=>({})),c9=cZ.create({use:[c3,cZ(async()=>({}))]}),c7=[c3];function le(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r,o=async e=>{try{return await cr(e,()=>a(e))}catch(r){var t;throw t=e.responseHeaders,c4(r)&&t&&Object.defineProperty(r,cR.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,value:t,writable:!1}),r}};return n?cJ(n,{...i,use:[...i?.use||[],...c7]},o):cJ({...i,use:[...i?.use||[],...c7]},o)}function lt(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}return"/"===t||""===t?r:r===t?"/":r.startsWith(t+"/")?r.slice(t.length).replace(/\/+$/,"")||"/":r}function lr(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function ln(e){let t=e.context.skipOriginCheck;if(!0===t)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,n=lt(e.request.url,r);return t.some(e=>n.startsWith(e))}catch{}return!1}let li=(p=function(){},c=!1,function(...e){return c||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),c=!0),p.apply(this,e)}),la=c9(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await ls(e),ln(e)))return;let{body:t,query:r}=e,n=t?.callbackURL||r?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,r)=>{if(t&&!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
63
|
-
`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),"origin"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw b.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};n&&s(n,"callbackURL"),i&&s(i,"redirectURL"),a&&s(a,"errorCallbackURL"),o&&s(o,"newUserCallbackURL")}),lo=e=>c9(async t=>{if(!t.request||ln(t))return;let r=e(t),n=(e,r)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:"origin"!==r})){if(t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config
|
|
64
|
-
`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),"origin"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw b.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};for(let e of Array.isArray(r)?r:[r])n(e,"callbackURL")});async function ls(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let n=r.get("origin")||r.get("referer")||"",i=r.has("cookie");if(e.context.skipCSRFCheck)return;if(lr(e)){e.context.options.advanced?.disableOriginCheck===!0&&li();return}if(ln(e)||!(t||i))return;if(!n||"null"===n)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN);let a=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!a.some(e=>D(n,e)))throw e.context.logger.error(`Invalid origin: ${n}`),e.context.logger.info(`If it's a valid URL, please add ${n} to trustedOrigins in your auth config
|
|
65
|
-
`,`Current list of trustedOrigins: ${a}`),b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.INVALID_ORIGIN)}let lc=c9(async e=>{e.request&&await ll(e)});async function ll(e){let t=e.request;if(!t||e.context.skipCSRFCheck||lr(e))return;let r=t.headers;if(r.has("cookie"))return await ls(e);let n=r.get("Sec-Fetch-Site"),i=r.get("Sec-Fetch-Mode"),a=r.get("Sec-Fetch-Dest");if(n&&n.trim()||i&&i.trim()||a&&a.trim()){if("cross-site"===n&&"navigate"===i)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:n,secFetchMode:i,secFetchDest:a}),b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await ls(e,!0)}}let ld=new Map;function lu(e,t){let r,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let i=e.rateLimit.storage;return"secondary-storage"===i?{get:async t=>{let r=await e.options.secondaryStorage?.get(t);return r?(0,rz.safeJSONParse)(r):null},set:async(r,n,i)=>{let a=t?.window??e.options.rateLimit?.window??10;await e.options.secondaryStorage?.set?.(r,JSON.stringify(n),a)}}:"memory"===i?{async get(e){let t=ld.get(e);return t?Date.now()>=t.expiresAt?(ld.delete(e),null):t.data:null},async set(r,n,i){let a=t?.window??e.options.rateLimit?.window??10,o=Date.now()+1e3*a;ld.set(r,{data:n,expiresAt:o})}}:(r="rateLimit",n=e.adapter,{get:async e=>{let t=(await n.findMany({model:r,where:[{field:"key",value:e}]}))[0];return"bigint"==typeof t?.lastRequest&&(t.lastRequest=Number(t.lastRequest)),t},set:async(t,i,a)=>{try{a?await n.updateMany({model:r,where:[{field:"key",value:t}],update:{count:i.count,lastRequest:i.lastRequest}}):await n.create({model:r,data:{key:t,count:i.count,lastRequest:i.lastRequest}})}catch(t){e.logger.error("Error setting rate limit",t)}}})}let lp=!1;async function lf(e,t){let r=new URL(t.baseURL).pathname,n=lt(e.url,r),i=t.rateLimit.window,a=t.rateLimit.max,o=sF(e,t.options);if(!o)return lp||(t.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."),lp=!0),null;let s=`${o}|${n}`,c=[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}].find(e=>e.pathMatcher(n));for(let e of(c&&(i=c.window,a=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(n));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?_(e)(n):e===n);if(r){let n=t.rateLimit.customRules[r],o="function"==typeof n?await n(e,{window:i,max:a}):n;if(o&&(i=o.window,a=o.max),!1===o)return null}}return{key:s,currentWindow:i,currentMax:a}}async function lh(e,t){var r,n;if(!t.rateLimit.enabled)return;let i=await lf(e,t);if(!i)return;let{key:a,currentWindow:o,currentMax:s}=i,c=await lu(t,{window:o}).get(a);if(c&&Date.now()-c.lastRequest<1e3*o&&c.count>=s)return r=c.lastRequest,n=Math.ceil((r+1e3*o-Date.now())/1e3),new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":n.toString()}})}async function lm(e,t){if(!t.rateLimit.enabled)return;let r=await lf(e,t);if(!r)return;let{key:n,currentWindow:i}=r,a=lu(t,{window:i}),o=await a.get(n),s=Date.now();o?s-o.lastRequest>1e3*i?await a.set(n,{...o,count:1,lastRequest:s},!0):await a.set(n,{...o,count:o.count+1,lastRequest:s},!0):await a.set(n,{key:n,count:1,lastRequest:s})}let ly=async()=>{let e=s2();if(!e.context.requestStateAsyncStorage){let t=await s5();e.context.requestStateAsyncStorage=new t}return e.context.requestStateAsyncStorage};async function lg(){return void 0!==(await ly()).getStore()}async function lw(){let e=(await ly()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function lb(e,t){return(await ly()).run(e,t)}function lA(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await lw();if(!r.has(t)){let n=await e();return r.set(t,n),n}return r.get(t)},async set(e){(await lw()).set(t,e)}}}let{get:lE,set:lv}=lA(()=>null),{get:lk,set:l_}=lA(()=>!1),lS=()=>le("/get-session",{method:["GET","POST"],operationId:"getSession",query:sR,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async e=>{let t=e.context.options.session?.deferSessionRefresh,r="POST"===e.method;if(r&&!t)throw b.APIError.from("METHOD_NOT_ALLOWED",rw.BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let n=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!n)return null;let i=sS(e,e.context.authCookies.sessionData.name),a=null;if(i){let t=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===t){let t=await rg(i,e.context.secretConfig,"better-auth-session");if(!t||!t.session||!t.user)return sV(e,e.context.authCookies.sessionData),e.json(null);a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}}else if("jwt"===t){let t=await rd(i,e.context.secret);if(!t||!t.session||!t.user)return sV(e,e.context.authCookies.sessionData),e.json(null);a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}}else{let t=(0,rz.safeJSONParse)(sL.decode(sC.decode(i)));if(t)if(!await s$("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...t.session,expiresAt:t.expiresAt}),t.signature))return sV(e,e.context.authCookies.sessionData),e.json(null);else a=t}}let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(a?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=a.session,r=e.context.options.session?.cookieCache?.version,n="1";if(r){if("string"==typeof r)n=r;else if("function"==typeof r){let e=r(t.session,t.user);n=e instanceof Promise?await e:e}}if((t.version||"1")!==n)sV(e,e.context.authCookies.sessionData);else{let r=new Date(t.session.expiresAt);if(a.expiresAt<Date.now()||r<new Date)sV(e,e.context.authCookies.sessionData);else{let r=e.context.sessionConfig.cookieRefreshCache;if(!1===r){e.context.session=t;let r=r_(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),n=rv(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:r,user:n})}let n=a.expiresAt-Date.now(),i=1e3*r.updateAge,s=await lk();if(n<i&&!s){let r={session:{...t.session},user:t.user,updatedAt:Date.now()};await sH(e,r,!1);let n=e.context.authCookies.sessionToken.attributes,i=o?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i});let a=r_(e.context.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),s=rv(e.context.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)});return e.context.session={session:a,user:s},e.json({session:a,user:s})}let c=r_(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=rv(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:c,user:l},e.json({session:c,user:l})}}}let s=await e.context.internalAdapter.findSession(n);if(e.context.session=s,!s||s.session.expiresAt<new Date)return sM(e),s&&(!t||r)&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh){let t=r_(e.context.options,s.session),r=rv(e.context.options,s.user);return e.json({session:t,user:r})}let c=e.context.sessionConfig.expiresIn,l=e.context.sessionConfig.updateAge,d=s.session.expiresAt.valueOf()-1e3*c+1e3*l<=Date.now(),u=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,p=await lk(),f=d&&!u&&!p;if(t&&!r){await sH(e,s,!!o);let t=r_(e.context.options,s.session),r=rv(e.context.options,s.user);return e.json({session:t,user:r,needsRefresh:f})}if(f){let t=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:rT(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)throw sM(e),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);let r=(t.expiresAt.valueOf()-Date.now())/1e3;await sB(e,{session:t,user:s.user},!1,{maxAge:r});let n=r_(e.context.options,t),i=rv(e.context.options,s.user);return e.json({session:n,user:i})}await sH(e,s,!!o);let h=r_(e.context.options,s.session),m=rv(e.context.options,s.user);return e.json({session:h,user:m})}catch(t){if(c4(t))throw t;throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.FAILED_TO_GET_SESSION)}}),lx=async(e,t)=>{if(e.context.session)return e.context.session;let r=await lS()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query}}).catch(()=>null);return r?(r.headers&&r.headers.forEach((t,r)=>{e.context.responseHeaders?"set-cookie"===r.toLowerCase()?e.context.responseHeaders.append(r,t):e.context.responseHeaders.set(r,t):e.context.responseHeaders=new Headers({[r]:t})}),e.context.session=r.response,r.response):(e.context.session=null,null)},lT=c9(async e=>{let t=await lx(e);if(!t?.session)throw b.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),lR=c9(async e=>{let t=await lx(e,{disableCookieCache:!0});if(!t?.session)throw b.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});c9(async e=>{let t=await lx(e);if(!t?.session&&(e.request||e.headers))throw b.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});let lI=c9(async e=>{let t=await lx(e);if(!t?.session)throw b.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.SESSION_NOT_FRESH)}return{session:t}}),lU=le("/revoke-session",{method:"POST",body:o9({token:oS().meta({description:"The token to revoke"})}),use:[lR],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),b.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),lO=le("/revoke-sessions",{method:"POST",use:[lR],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),b.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),lP=le("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[lR],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw b.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(r.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function lC(e,t,r,n){let i=new URLSearchParams({error:r});n&&i.set("error_description",n);let a=t.includes("?")?"&":"?";throw e.redirect(`${t}${a}${i.toString()}`)}function lD(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}var lL=e.i(602118);let lz=(0,lL.createRandomStringGenerator)("a-z","0-9","A-Z","-_");function l$(e){if("boolean"!=typeof e)throw TypeError(`boolean expected, not ${e}`)}function lN(e){if("number"!=typeof e)throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function lj(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function lH(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function lB(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lV(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let lM=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],lK=e=>e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255,lW=lM?e=>e:e=>lK(e)>>>0,lq=lM?e=>e:e=>{for(let t=0;t<e.length;t++)e[t]=lK(e[t]);return e},lF="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,lJ=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function lZ(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function lG(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(lj(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!lQ(t))throw Error("invalid output, must be aligned");return t}function lQ(e){return e.byteOffset%4==0}function lY(e){return Uint8Array.from(lj(e))}function lX(e=32){lN(e);let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}function l0(e,t=lX){let{nonceLength:r}=e;lN(r);let n=(e,t,r)=>{let n=function(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];lj(n),t+=n.length}let r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}(e,t);return r.byteLength&&t.byteLength&&r.buffer===t.buffer&&r.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<r.byteOffset+r.byteLength||t.fill(0),n},i=(i,...a)=>({encrypt(o){lj(o);let s=t(r),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>n(s,e,o)):n(s,c,o)},decrypt(t){lj(t);let n=t.subarray(0,r),o=t.subarray(r);return e(i,n,...a).decrypt(o)}});return"blockSize"in e&&(i.blockSize=e.blockSize),"tagLength"in e&&(i.tagLength=e.tagLength),i}let l1=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),l2=lq(lB(l1("expand 16-byte k"))),l6=lq(lB(l1("expand 32-byte k")));function l5(e,t){return e<<t|e>>>32-t}let l8=0x100000000-1,l4=Uint32Array.of();function l3(e,t){return 255&e[t++]|(255&e[t++])<<8}class l9{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){const t=l3(e=lY(lj(e,32,"key")),0),r=l3(e,2),n=l3(e,4),i=l3(e,6),a=l3(e,8),o=l3(e,10),s=l3(e,12),c=l3(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=l3(e,16+2*t)}process(e,t,r=!1){let{h:n,r:i}=this,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],d=i[5],u=i[6],p=i[7],f=i[8],h=i[9],m=l3(e,t+0),y=l3(e,t+2),g=l3(e,t+4),w=l3(e,t+6),b=l3(e,t+8),A=l3(e,t+10),E=l3(e,t+12),v=l3(e,t+14),k=n[0]+(8191&m),_=n[1]+((m>>>13|y<<3)&8191),S=n[2]+((y>>>10|g<<6)&8191),x=n[3]+((g>>>7|w<<9)&8191),T=n[4]+((w>>>4|b<<12)&8191),R=n[5]+(b>>>1&8191),I=n[6]+((b>>>14|A<<2)&8191),U=n[7]+((A>>>11|E<<5)&8191),O=n[8]+((E>>>8|v<<8)&8191),P=n[9]+(v>>>5|2048*!r),C=0,D=0+k*a+5*h*_+5*f*S+5*p*x+5*u*T;C=D>>>13,D&=8191,D+=5*d*R+5*l*I+5*c*U+5*s*O+5*o*P,C+=D>>>13,D&=8191;let L=C+k*o+_*a+5*h*S+5*f*x+5*p*T;C=L>>>13,L&=8191,L+=5*u*R+5*d*I+5*l*U+5*c*O+5*s*P,C+=L>>>13,L&=8191;let z=C+k*s+_*o+S*a+5*h*x+5*f*T;C=z>>>13,z&=8191,z+=5*p*R+5*u*I+5*d*U+5*l*O+5*c*P,C+=z>>>13,z&=8191;let $=C+k*c+_*s+S*o+x*a+5*h*T;C=$>>>13,$&=8191,$+=5*f*R+5*p*I+5*u*U+5*d*O+5*l*P,C+=$>>>13,$&=8191;let N=C+k*l+_*c+S*s+x*o+T*a;C=N>>>13,N&=8191,N+=5*h*R+5*f*I+5*p*U+5*u*O+5*d*P,C+=N>>>13,N&=8191;let j=C+k*d+_*l+S*c+x*s+T*o;C=j>>>13,j&=8191,j+=R*a+5*h*I+5*f*U+5*p*O+5*u*P,C+=j>>>13,j&=8191;let H=C+k*u+_*d+S*l+x*c+T*s;C=H>>>13,H&=8191,H+=R*o+I*a+5*h*U+5*f*O+5*p*P,C+=H>>>13,H&=8191;let B=C+k*p+_*u+S*d+x*l+T*c;C=B>>>13,B&=8191,B+=R*s+I*o+U*a+5*h*O+5*f*P,C+=B>>>13,B&=8191;let V=C+k*f+_*p+S*u+x*d+T*l;C=V>>>13,V&=8191,V+=R*c+I*s+U*o+O*a+5*h*P,C+=V>>>13,V&=8191;let M=C+k*h+_*f+S*p+x*u+T*d;C=M>>>13,M&=8191,M+=R*l+I*c+U*s+O*o+P*a,C+=M>>>13,M&=8191,D=8191&(C=(C=(C<<2)+C|0)+D|0),C>>>=13,L+=C,n[0]=D,n[1]=L,n[2]=z,n[3]=$,n[4]=N,n[5]=j,n[6]=H,n[7]=B,n[8]=V,n[9]=M}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=65535&a;for(let r=1;r<8;r++)a=(e[r]+t[r]|0)+(a>>>16)|0,e[r]=65535&a;lV(r)}update(e){lH(this),lj(e);let{buffer:t,blockLen:r}=this,n=(e=lY(e)).length;for(let i=0;i<n;){let a=Math.min(r-this.pos,n-i);if(a===r){for(;r<=n-i;i+=r)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,lV(this.h,this.r,this.buffer,this.pad)}digestInto(e){lH(this),function(e,t,r=!1){lj(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!lQ(e))throw Error("invalid output, must be aligned")}(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=r[t]>>>0,e[i++]=r[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let l7=(f=e=>new l9(e),l=()=>[],(d=(e,t)=>f(t,...l(e)).update(e).digest()).outputLen=(u=f(new Uint8Array(32),...l(new Uint8Array(0)))).outputLen,d.blockLen=u.blockLen,d.create=(e,...t)=>f(e,...t),d),de=function(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:a,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return lN(i),lN(o),l$(a),l$(r),(t,s,c,l,d=0)=>{let u,p;if(lj(t,void 0,"key"),lj(s,void 0,"nonce"),lj(c,void 0,"data"),l=lG(c.length,l,!1),lN(d),d<0||d>=l8)throw Error("arx: counter overflow");let f=[],h=t.length;if(32===h)f.push(u=lY(t)),p=l6;else if(16===h&&r)(u=new Uint8Array(32)).set(t),u.set(t,16),p=l2,f.push(u);else throw lj(t,32,"arx key"),Error("invalid key size");lM&&lQ(s)||f.push(s=lY(s));let m=lB(u);if(n){if(24!==s.length)throw Error("arx: extended nonce must be 24 bytes");let e=s.subarray(0,16);if(lM)n(p,m,lB(e),m);else{let t=lq(Uint32Array.from(p));n(t,m,lB(e),m),lV(t),lq(m)}s=s.subarray(16)}else lM||lq(m);let y=16-i;if(y!==s.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let g=lq(lB(s));try{return!function(e,t,r,n,i,a,o,s){let c=i.length,l=new Uint8Array(64),d=lB(l),u=lM&&lQ(i)&&lQ(a),p=u?lB(i):l4,f=u?lB(a):l4;if(!lM){for(let u=0;u<c;o++){if(e(t,r,n,d,o,s),lq(d),o>=l8)throw Error("arx: counter overflow");let p=Math.min(64,c-u);for(let e=0,t;e<p;e++)a[t=u+e]=i[t]^l[e];u+=p}return}for(let h=0;h<c;o++){if(e(t,r,n,d,o,s),o>=l8)throw Error("arx: counter overflow");let m=Math.min(64,c-h);if(u&&64===m){let e=h/4;if(h%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)f[r=e+t]=p[r]^d[t];h+=64;continue}for(let e=0,t;e<m;e++)a[t=h+e]=i[t]^l[e];h+=m}}(e,p,m,g,c,l,d,o),l}finally{lV(...f)}}}(function(e,t,r,n,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],d=t[0],u=t[1],p=t[2],f=t[3],h=t[4],m=t[5],y=t[6],g=t[7],w=r[0],b=r[1],A=r[2],E=o,v=s,k=c,_=l,S=d,x=u,T=p,R=f,I=h,U=m,O=y,P=g,C=i,D=w,L=b,z=A;for(let e=0;e<a;e+=2)I=I+(C=l5(C^(E=E+S|0),16))|0,E=E+(S=l5(S^I,12))|0,I=I+(C=l5(C^E,8))|0,S=l5(S^I,7),U=U+(D=l5(D^(v=v+x|0),16))|0,v=v+(x=l5(x^U,12))|0,U=U+(D=l5(D^v,8))|0,x=l5(x^U,7),O=O+(L=l5(L^(k=k+T|0),16))|0,k=k+(T=l5(T^O,12))|0,O=O+(L=l5(L^k,8))|0,T=l5(T^O,7),P=P+(z=l5(z^(_=_+R|0),16))|0,_=_+(R=l5(R^P,12))|0,P=P+(z=l5(z^_,8))|0,R=l5(R^P,7),O=O+(z=l5(z^(E=E+x|0),16))|0,E=E+(x=l5(x^O,12))|0,O=O+(z=l5(z^E,8))|0,x=l5(x^O,7),P=P+(C=l5(C^(v=v+T|0),16))|0,v=v+(T=l5(T^P,12))|0,P=P+(C=l5(C^v,8))|0,T=l5(T^P,7),I=I+(D=l5(D^(k=k+R|0),16))|0,k=k+(R=l5(R^I,12))|0,I=I+(D=l5(D^k,8))|0,R=l5(R^I,7),U=U+(L=l5(L^(_=_+S|0),16))|0,_=_+(S=l5(S^U,12))|0,U=U+(L=l5(L^_,8))|0,S=l5(S^U,7);let $=0;n[$++]=o+E|0,n[$++]=s+v|0,n[$++]=c+k|0,n[$++]=l+_|0,n[$++]=d+S|0,n[$++]=u+x|0,n[$++]=p+T|0,n[$++]=f+R|0,n[$++]=h+I|0,n[$++]=m+U|0,n[$++]=y+O|0,n[$++]=g+P|0,n[$++]=i+C|0,n[$++]=w+D|0,n[$++]=b+L|0,n[$++]=A+z|0},{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let i=lW(e[0]),a=lW(e[1]),o=lW(e[2]),s=lW(e[3]),c=lW(t[0]),l=lW(t[1]),d=lW(t[2]),u=lW(t[3]),p=lW(t[4]),f=lW(t[5]),h=lW(t[6]),m=lW(t[7]),y=lW(r[0]),g=lW(r[1]),w=lW(r[2]),b=lW(r[3]);for(let e=0;e<20;e+=2)p=p+(y=l5(y^(i=i+c|0),16))|0,i=i+(c=l5(c^p,12))|0,p=p+(y=l5(y^i,8))|0,c=l5(c^p,7),f=f+(g=l5(g^(a=a+l|0),16))|0,a=a+(l=l5(l^f,12))|0,f=f+(g=l5(g^a,8))|0,l=l5(l^f,7),h=h+(w=l5(w^(o=o+d|0),16))|0,o=o+(d=l5(d^h,12))|0,h=h+(w=l5(w^o,8))|0,d=l5(d^h,7),m=m+(b=l5(b^(s=s+u|0),16))|0,s=s+(u=l5(u^m,12))|0,m=m+(b=l5(b^s,8))|0,u=l5(u^m,7),h=h+(b=l5(b^(i=i+l|0),16))|0,i=i+(l=l5(l^h,12))|0,h=h+(b=l5(b^i,8))|0,l=l5(l^h,7),m=m+(y=l5(y^(a=a+d|0),16))|0,a=a+(d=l5(d^m,12))|0,m=m+(y=l5(y^a,8))|0,d=l5(d^m,7),p=p+(g=l5(g^(o=o+u|0),16))|0,o=o+(u=l5(u^p,12))|0,p=p+(g=l5(g^o,8))|0,u=l5(u^p,7),f=f+(w=l5(w^(s=s+c|0),16))|0,s=s+(c=l5(c^f,12))|0,f=f+(w=l5(w^s,8))|0,c=l5(c^f,7);let A=0;n[A++]=i,n[A++]=a,n[A++]=o,n[A++]=s,n[A++]=y,n[A++]=g,n[A++]=w,n[A++]=b,lq(n)},allowShortKeys:!1}),dt=new Uint8Array(16),dr=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(dt.subarray(r))},dn=new Uint8Array(32);function di(e,t,r,n,i){var a,o;let s,c;void 0!==i&&lj(i,void 0,"AAD");let l=e(t,r,dn),d=(a=n.length,o=i?i.length:0,lN(a),lN(o),l$(!0),(c=new DataView((s=new Uint8Array(16)).buffer,s.byteOffset,s.byteLength)).setBigUint64(0,BigInt(o),!0),c.setBigUint64(8,BigInt(a),!0),s),u=l7.create(l);i&&dr(u,i),dr(u,n),u.update(d);let p=u.digest();return lV(l,d),p}let da=((e,t)=>{function r(n,...i){lj(n,void 0,"key"),void 0!==e.nonceLength&&lj(i[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let a=e.tagLength;a&&void 0!==i[1]&&lj(i[1],void 0,"AAD");let o=t(n,...i),s=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");lj(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,lj(e),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(lj(e),a&&e.length<a)throw Error('"ciphertext" expected length bigger than tagLength='+a);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16},(e,t,r)=>({encrypt(n,i){let a=n.length;(i=lG(a+16,i,!1)).set(n);let o=i.subarray(0,-16);de(e,t,o,o,1);let s=di(de,e,t,o,r);return i.set(s,a),lV(s),i},decrypt(n,i){i=lG(n.length-16,i,!1);let a=n.subarray(0,-16),o=n.subarray(-16),s=di(de,e,t,a,r);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(o,s))throw lV(s),Error("invalid tag");return i.set(n.subarray(0,-16)),de(e,t,i,i,1),lV(s),i}})),ds="$ba$";async function dc(e,t){let r=await sJ("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var i=l0(da)(new Uint8Array(r)).encrypt(n);if(lj(i),lF)return i.toHex();let a="";for(let e=0;e<i.length;e++)a+=lJ[i[e]];return a}async function dl(e,t){let r=await sJ("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("hex string expected, got "+typeof e);if(lF)try{return Uint8Array.fromHex(e)}catch(e){if(e instanceof SyntaxError)throw RangeError(e.message);throw e}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){let r=lZ(e.charCodeAt(i)),a=lZ(e.charCodeAt(i+1));if(void 0===r||void 0===a)throw RangeError('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);n[t]=16*r+a}return n}(t),i=l0(da)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}let dd=async({key:e,data:t})=>{var r;if("string"==typeof e)return dc(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let i=await dc(n,t);return r=e.currentVersion,`${ds}${r}$${i}`},du=async({key:e,data:t})=>{if("string"==typeof e)return dl(e,t);let r=function(e){if(!e.startsWith(ds))return null;let t=e.indexOf("$",4);if(-1===t)return null;let r=parseInt(e.slice(4,t),10);return!Number.isInteger(r)||r<0?null:{version:r,ciphertext:e.slice(t+1)}}(t);if(r){let t=e.keys.get(r.version);if(!t)throw Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return dl(t,r.ciphertext)}if(e.legacySecret)return dl(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};var dp=b,sb=sb;let df=new o3({type:"object",shape:{callbackURL:oS(),codeVerifier:oS(),errorURL:oS().optional(),newUserURL:oS().optional(),expiresAt:oF(),oauthState:oS().optional(),link:o9({email:oS(),userId:sb.string()}).optional(),requestSignUp:oQ().optional()},catchall:o2(),...a8.normalizeParams(void 0)});var dh=class extends dp.BetterAuthError{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function dm(e,t,r){let n=lz(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let i={...t,oauthState:n},a=await dd({key:e.context.secretConfig,data:JSON.stringify(i)}),o=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:n,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(i.name,n,e.context.secret,i.attributes);let a=new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:n}),identifier:n,expiresAt:a}))throw new dh("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:t.codeVerifier}}async function dy(e,t,r){let n;if(!t)throw new dh("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let i=e.context.createAuthCookie(r?.cookieName??"oauth_state"),a=e.getCookie(i.name);if(!a)throw new dh("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await du({key:e.context.secretConfig,data:a});n=df.parse(JSON.parse(t))}catch(e){throw new dh("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!n.oauthState||n.oauthState!==t)throw new dh("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});sV(e,i)}else{let i=await e.context.internalAdapter.findVerificationValue(t);if(!i)throw new dh("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(n=df.parse(JSON.parse(i.value))).oauthState&&n.oauthState!==t)throw new dh("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});let a=e.context.createAuthCookie(r?.cookieName??"state"),o=await e.getSignedCookie(a.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new dh("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});sV(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(t)}if(n.expiresAt<Date.now())throw new dh("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:n.expiresAt},errorURL:n.errorURL});return n}async function dg(e,t,r){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.CALLBACK_URL_REQUIRED);let i=lz(128),a={...r||{},callbackURL:n,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp};await lv(a);try{return dm(e,a)}catch(t){throw e.context.logger.error("Failed to create verification",t),new b.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function dw(e){let t,r=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await dy(e,r)}catch(i){e.context.logger.error("Failed to parse state",i);let t="internal_server_error",r=n;i instanceof dh&&(t="state_security_mismatch"===i.code?"state_mismatch":i.code,r=i.errorURL??n),lC(e,r,t)}return t.errorURL||(t.errorURL=n),t&&await lv(t),t}function db(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens)return e.startsWith("$ba$")||e.length%2==0&&/^[0-9a-f]+$/i.test(e)?du({key:t.secretConfig,data:e}):e;return e}function dA(e,t){return t.options.account?.encryptOAuthTokens&&e?dd({key:t.secretConfig,data:e}):e}function dE(e){let t=e=>new Date(new Date().getTime()+1e3*e);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:e?.scope?"string"==typeof e.scope?e.scope.split(" "):e.scope:[],idToken:e.id_token,raw:e}}function dv(e){let t=Array.isArray(e)?e[0]:e;return"string"==typeof t&&t.length>0?t:void 0}async function dk(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return sC.encode(new Uint8Array(r),{padding:!1})}async function d_({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:d,responseType:u,display:p,loginHint:f,hd:h,responseMode:m,additionalParams:y,scopeJoiner:g}){let w=new URL((t="function"==typeof t?await t():t).authorizationEndpoint||r);w.searchParams.set("response_type",u||"code");let b=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;if(w.searchParams.set("client_id",b),w.searchParams.set("state",n),a&&w.searchParams.set("scope",a.join(g||" ")),w.searchParams.set("redirect_uri",t.redirectURI||s),c&&w.searchParams.set("duration",c),p&&w.searchParams.set("display",p),f&&w.searchParams.set("login_hint",f),l&&w.searchParams.set("prompt",l),h&&w.searchParams.set("hd",h),d&&w.searchParams.set("access_type",d),m&&w.searchParams.set("response_mode",m),i){let e=await dk(i);w.searchParams.set("code_challenge_method","S256"),w.searchParams.set("code_challenge",e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});w.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}return y&&Object.entries(y).forEach(([e,t])=>{w.searchParams.set(e,t)}),w}var dS=Object.defineProperty,dx=Object.defineProperties,dT=Object.getOwnPropertyDescriptors,dR=Object.getOwnPropertySymbols,dI=Object.prototype.hasOwnProperty,dU=Object.prototype.propertyIsEnumerable,dO=(e,t,r)=>t in e?dS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,dP=(e,t)=>{for(var r in t||(t={}))dI.call(t,r)&&dO(e,r,t[r]);if(dR)for(var r of dR(t))dU.call(t,r)&&dO(e,r,t[r]);return e},dC=(e,t)=>dx(e,dT(t)),dD=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},dL=async(e,t)=>{var r,n,i,a,o,s;let c=t||{},l={onRequest:[null==t?void 0:t.onRequest],onResponse:[null==t?void 0:t.onResponse],onSuccess:[null==t?void 0:t.onSuccess],onError:[null==t?void 0:t.onError],onRetry:[null==t?void 0:t.onRetry]};if(!t||!(null==t?void 0:t.plugins))return{url:e,options:c,hooks:l};for(let d of(null==t?void 0:t.plugins)||[]){if(d.init){let n=await (null==(r=d.init)?void 0:r.call(d,e.toString(),t));c=n.options||c,e=n.url}l.onRequest.push(null==(n=d.hooks)?void 0:n.onRequest),l.onResponse.push(null==(i=d.hooks)?void 0:i.onResponse),l.onSuccess.push(null==(a=d.hooks)?void 0:a.onSuccess),l.onError.push(null==(o=d.hooks)?void 0:o.onError),l.onRetry.push(null==(s=d.hooks)?void 0:s.onRetry)}return{url:e,options:c,hooks:l}},dz=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},d$=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}},dN=async e=>{let t={},r=async e=>"function"==typeof e?await e():e;if(null==e?void 0:e.auth){if("Bearer"===e.auth.type){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if("Basic"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!i)return t;t.authorization=`Basic ${btoa(`${n}:${i}`)}`}else if("Custom"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!i)return t;t.authorization=`${null!=n?n:""} ${i}`}}return t},dj=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function dH(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}function dB(e){try{return JSON.parse(e)}catch(t){return e}}async function dV(e){let t=new Headers(null==e?void 0:e.headers);for(let[r,n]of Object.entries(await dN(e)||{}))t.set(r,n);if(!t.has("content-type")){let r=dH(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var dM=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function dK(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new dM(r.issues);return r.value}var dW=["get","post","put","patch","delete"],dq=async(e,t)=>{var r,n,i,a,o,s,c,l;let d,{hooks:u,url:p,options:f}=await dL(e,t),h=function(e){if(null==e?void 0:e.customFetchImpl)return e.customFetchImpl;if("u">typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch;throw Error("No fetch implementation found")}(f),m=new AbortController,y=null!=(r=f.signal)?r:m.signal,g=function(e,t){let{baseURL:r,params:n,query:i}=t||{query:{},params:{},baseURL:""},a=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let t=e.toString().split("@")[1].split("/")[0];dW.includes(t)&&(e=e.replace(`@${t}/`,"/"))}a.endsWith("/")||(a+="/");let[o,s]=e.replace(a,"").split("?"),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){let r;if(null!=t){if("string"==typeof t)r=t;else if(Array.isArray(t)){for(let r of t)c.append(e,r);continue}else r=JSON.stringify(t);c.set(e,r)}}if(n)if(Array.isArray(n))for(let[e,t]of o.split("/").filter(e=>e.startsWith(":")).entries()){let r=n[e];o=o.replace(t,r)}else for(let[e,t]of Object.entries(n))o=o.replace(`:${e}`,String(t));(o=o.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(o=o.slice(1));let l=c.toString();return(l=l.length>0?`?${l}`.replace(/\+/g,"%20"):"",a.startsWith("http"))?new URL(`${o}${l}`,a):`${a}${o}${l}`}(p,f),w=function(e){if(!(null==e?void 0:e.body))return null;let t=new Headers(null==e?void 0:e.headers);if(dH(e.body)&&!t.has("content-type")){for(let[t,r]of Object.entries(null==e?void 0:e.body))r instanceof Date&&(e.body[t]=r.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&"application/x-www-form-urlencoded"===t.get("content-type")&&dH(e.body)?new URLSearchParams(e.body).toString():e.body}(f),b=await dV(f),A=function(e,t){var r;if(null==t?void 0:t.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=null==(r=e.split("@")[1])?void 0:r.split("/")[0];return dW.includes(n)?n.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}return(null==t?void 0:t.body)?"POST":"GET"}(p,f),E=dC(dP({},f),{url:g,headers:b,body:w,method:A,signal:y});for(let e of u.onRequest)if(e){let t=await e(E);"object"==typeof t&&null!==t&&(E=t)}("pipeTo"in E&&"function"==typeof E.pipeTo||"function"==typeof(null==(n=null==t?void 0:t.body)?void 0:n.pipe))&&!("duplex"in E)&&(E.duplex="half");let{clearTimeout:v}=(!(null==f?void 0:f.signal)&&(null==f?void 0:f.timeout)&&(d=setTimeout(()=>null==m?void 0:m.abort(),null==f?void 0:f.timeout)),{abortTimeout:d,clearTimeout:()=>{d&&clearTimeout(d)}}),k=await h(E.url,E);v();let _={response:k,request:E};for(let e of u.onResponse)if(e){let r=await e(dC(dP({},_),{response:(null==(i=null==t?void 0:t.hookOptions)?void 0:i.cloneResponse)?k.clone():k}));r instanceof Response?k=r:"object"==typeof r&&null!==r&&(k=r.response)}if(k.ok){if("HEAD"===E.method)return{data:"",error:null};let e=function(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";return dj.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}(k),r={data:null,response:k,request:E};if("json"===e||"text"===e){let e=await k.text(),t=null!=(a=E.jsonParser)?a:dB;r.data=await t(e)}else r.data=await k[e]();for(let e of((null==E?void 0:E.output)&&E.output&&!E.disableValidation&&(r.data=await dK(E.output,r.data)),u.onSuccess))e&&await e(dC(dP({},r),{response:(null==(o=null==t?void 0:t.hookOptions)?void 0:o.cloneResponse)?k.clone():k}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let S=null!=(s=null==t?void 0:t.jsonParser)?s:dB,x=await k.text(),T=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(x),R=T?await S(x):null,I={response:k,responseText:x,request:E,error:dC(dP({},R),{status:k.status,statusText:k.statusText})};for(let e of u.onError)e&&await e(dC(dP({},I),{response:(null==(c=null==t?void 0:t.hookOptions)?void 0:c.cloneResponse)?k.clone():k}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new dz({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new dz(e);case"exponential":return new d$(e);default:throw Error("Invalid retry strategy")}}(t.retry),n=null!=(l=t.retryAttempt)?l:0;if(await r.shouldAttemptRetry(n,k)){for(let e of u.onRetry)e&&await e(_);let i=r.getDelay(n);return await new Promise(e=>setTimeout(e,i)),await dq(e,dC(dP({},t),{retryAttempt:n+1}))}}if(null==t?void 0:t.throw)throw new dD(k.status,k.statusText,T?R:x);return{data:null,error:dC(dP({},R),{status:k.status,statusText:k.statusText})}};async function dF({refreshToken:e,options:t,tokenEndpoint:r,authentication:n,extraParams:i}){let{body:a,headers:o}=await function({refreshToken:e,options:t,authentication:r,extraParams:n,resource:i}){let a=new URLSearchParams,o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(a.set("grant_type","refresh_token"),a.set("refresh_token",e),"basic"===r){let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;e?o.authorization="Basic "+sP.encode(`${e}:${t.clientSecret??""}`):o.authorization="Basic "+sP.encode(`:${t.clientSecret??""}`)}else{let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;a.set("client_id",e),t.clientSecret&&a.set("client_secret",t.clientSecret)}if(i)if("string"==typeof i)a.append("resource",i);else for(let e of i)a.append("resource",e);if(n)for(let[e,t]of Object.entries(n))a.set(e,t);return{body:a,headers:o}}({refreshToken:e,options:t,authentication:n,extraParams:i}),{data:s,error:c}=await dq(r,{method:"POST",body:a,headers:o});if(c)throw c;let l={accessToken:s.access_token,refreshToken:s.refresh_token,tokenType:s.token_type,scopes:s.scope?.split(" "),idToken:s.id_token};return s.expires_in&&(l.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*s.expires_in)),s.refresh_token_expires_in&&(l.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*s.refresh_token_expires_in)),l}function dJ(e){return tS(e)}class dZ{#h;#m=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(dJ)}(e))throw new eq("JSON Web Key Set malformed");this.#h=structuredClone(e)}jwks(){return this.#h}async getKey(e,t){let{alg:r,kid:n}={...e,...t?.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new eH('Unsupported "alg" value for a JSON Web Key Set')}}(r),a=this.#h.keys.filter(e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&("string"==typeof e.alg||"AKP"===i)&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:o,length:s}=a;if(0===s)throw new eF;if(1!==s){let e=new eJ,t=this.#m;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await dG(t,e,r)}catch{}},e}return dG(this.#m,o,r)}}async function dG(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){let e=await tC({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new eq("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function dQ(e){let t=new dZ(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(r="jose/v6.2.3");let dY=Symbol();async function dX(e,t,r,n=fetch){let i=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{if("TimeoutError"===e.name)throw new eZ;throw e});if(200!==i.status)throw new ez("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new ez("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let d0=Symbol();class d1{#y;#g;#w;#b;#A;#E;#v;#k;#_;#S;constructor(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");this.#y=new URL(e.href),this.#g="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this.#w="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this.#b="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,this.#v=new Headers(t?.headers),r&&!this.#v.has("User-Agent")&&this.#v.set("User-Agent",r),this.#v.has("accept")||(this.#v.set("accept","application/json"),this.#v.append("accept","application/jwk-set+json")),this.#k=t?.[dY],t?.[d0]!==void 0&&(this.#S=t?.[d0],function(e,t){return!("object"!=typeof e||null===e||!("uat"in e)||"number"!=typeof e.uat||Date.now()-e.uat>=t)&&"jwks"in e&&!!tS(e.jwks)&&!!Array.isArray(e.jwks.keys)&&!!Array.prototype.every.call(e.jwks.keys,tS)}(t?.[d0],this.#b)&&(this.#A=this.#S.uat,this.#_=dQ(this.#S.jwks)))}pendingFetch(){return!!this.#E}coolingDown(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#w}fresh(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#b}jwks(){return this.#_?.jwks()}async getKey(e,t){this.#_&&this.fresh()||await this.reload();try{return await this.#_(e,t)}catch(r){if(r instanceof eF&&!1===this.coolingDown())return await this.reload(),this.#_(e,t);throw r}}async reload(){this.#E&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#E=void 0),this.#E||=dX(this.#y.href,this.#v,AbortSignal.timeout(this.#g),this.#k).then(e=>{this.#_=dQ(e),this.#S&&(this.#S.uat=Date.now(),this.#S.jwks=e),this.#A=Date.now(),this.#E=void 0}).catch(e=>{throw this.#E=void 0,e}),await this.#E}}async function d2({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){return d6({code:e,codeVerifier:t,redirectURI:r,options:n="function"==typeof n?await n():n,authentication:i,deviceId:a,headers:o,additionalParams:s,resource:c})}function d6({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){let l=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),n.clientKey&&l.set("client_key",n.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",n.redirectURI||r),c)if("string"==typeof c)l.append("resource",c);else for(let e of c)l.append("resource",e);if("basic"===i){let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;d.authorization=`Basic ${sP.encode(`${e}:${n.clientSecret??""}`)}`}else{let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;l.set("client_id",e),n.clientSecret&&l.set("client_secret",n.clientSecret)}for(let[e,t]of Object.entries(s))l.has(e)||l.append(e,t);return{body:l,headers:d}}async function d5({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:i,authentication:a,deviceId:o,headers:s,additionalParams:c={},resource:l}){let{body:d,headers:u}=await d2({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:a,deviceId:o,headers:s,additionalParams:c,resource:l}),{data:p,error:f}=await dq(i,{method:"POST",body:d,headers:u});if(f)throw f;return dE(p)}function d8(e){let t,r;if("string"!=typeof e)throw new eK("JWTs must use Compact JWS serialization, JWT must be a string");let{1:n,length:i}=e.split(".");if(5===i)throw new eK("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new eK("Invalid JWT");if(!n)throw new eK("JWTs must contain a payload");try{t=ek(n)}catch{throw new eK("Failed to base64url decode the payload")}try{r=JSON.parse(eg.decode(t))}catch{throw new eK("Failed to parse the decoded payload as JSON")}if(!tS(r))throw new eK("Invalid JWT Claims Set");return r}async function d4(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function d3(e,t){return"string"==typeof e&&(e===t||e===await d4(t))}let d9=async e=>{let{data:t}=await dq("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new b.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tC(r,r.alg)},d7=async(e,t,r)=>{let n=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await dq(n);if(!t?.keys)throw new b.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tC(r,r.alg)}catch(e){throw g.logger.error("Failed to fetch Cognito public key:",e),e}},ue=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),ut=async e=>{let{data:t}=await dq("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new b.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tC(r,r.alg)},ur=async(e,t,r)=>{let{data:n}=await dq(`${r}/${t}/discovery/v2.0/keys`);if(!n?.keys)throw new b.APIError("BAD_REQUEST",{message:"Keys not found"});let i=n.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await tC(i,i.alg)},un="https://backboard.railway.com/oauth/token",ui={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:t,scopes:r,redirectURI:n}){if(!dv(e.clientId)||!e.clientSecret)throw g.logger.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let i=e.disableDefaultScope?[]:["email","name"];return e.scope&&i.push(...e.scope),r&&i.push(...r),await d_({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:i,state:t,redirectURI:n,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rt(t);if(!n||!i)return!1;let{payload:a}=await rc(t,await d9(n),{algorithms:[i],issuer:"https://appleid.apple.com",audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(e=>{void 0!==a[e]&&(a[e]=!!a[e])}),r&&!await d3(a.nonce,r))return!1;return!!a}catch{return!1}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=d8(t.idToken);if(!n)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():n.name||"";let i="boolean"==typeof n.email_verified?n.email_verified:"true"===n.email_verified,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{id:n.sub,name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw g.logger.error("Client Id and Secret are required for Atlassian"),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new b.BetterAuthError("codeVerifier is required for Atlassian");let a=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,additionalParams:{audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:r}=await dq("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...n},data:r}}catch(e){return g.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw g.logger.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new b.BetterAuthError("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,n=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!dv(e.clientId))throw g.logger.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw g.logger.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new b.BetterAuthError("CLIENT_SECRET_REQUIRED");let o=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&o.push(...e.scope),n&&o.push(...n);let s=await d_({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt}),c=s.searchParams.get("scope");if(c){s.searchParams.delete("scope");let e=encodeURIComponent(c),t=s.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d5({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rt(t);if(!n||!i)return!1;let a=await d7(n,e.region,e.userPoolId),o=`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,{payload:s}=await rc(t,a,{algorithms:[i],issuer:o,audience:e.clientId,maxTokenAge:"1h"});if(r&&s.nonce!==r)return!1;return!0}catch(e){return g.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=d8(t.idToken);if(!r)return null;let n=r.name||r.given_name||r.username||"",i={...r,name:n},a=await e.mapProfileToUser?.(i);return{user:{id:r.sub,name:i.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:i}}catch(e){g.logger.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await dq(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:r.email_verified,...t},data:r}}}catch(e){g.logger.error("Failed to fetch user info from Cognito:",e)}return null},options:e}},discord:e=>{let t="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identify","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=i.includes("bot")&&void 0!==e.permissions?`&permissions=${e.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}${a}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(null===r.avatar)r.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===r.discriminator?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5}.png`;else{let e=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${e}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n,loginHint:i}){if(!dv(e.clientId)||!e.clientSecret)throw g.logger.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let a=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d_({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:a,state:t,redirectURI:n,loginHint:i,additionalParams:e.configId?{config_id:e.configId}:{}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>d5({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);if(3===t.split(".").length)try{var n;let i,a,{payload:o}=await rc(t,(n=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),i=new d1(n,void 0),a=async(e,t)=>i.getKey(e,t),Object.defineProperties(a,{coolingDown:{get:()=>i.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>i.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>i.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>i.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>i.jwks(),enumerable:!0,configurable:!1,writable:!1}}),a),{algorithms:["RS256"],audience:e.clientId,issuer:"https://www.facebook.com"});if(r&&o.nonce!==r)return!1;return!!o}catch{return!1}return!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&3===t.idToken.split(".").length){let r=d8(t.idToken),n={id:r.sub,name:r.name,email:r.email,picture:{data:{url:r.picture,height:100,width:100,is_silhouette:!1}}},i=await e.mapProfileToUser?.({...n,email_verified:!1});return{user:{...n,emailVerified:!1,...i},data:r}}let{data:r,error:n}=await dq("https://graph.facebook.com/me?fields="+["id","name","email","picture",...e?.fields||[]].join(","),{auth:{type:"Bearer",token:t.accessToken}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified??!1,...i},data:r}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw g.logger.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new b.BetterAuthError("codeVerifier is required for Figma");let a=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d_({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await dq("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return g.logger.error("Failed to fetch user from Figma"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...n},data:r}}catch(e){return g.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},github:e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:r,loginHint:n,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),d_({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:o,state:t,codeVerifier:i,redirectURI:a,loginHint:n,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>{let{body:a,headers:o}=d6({code:r,codeVerifier:n,redirectURI:i,options:e}),{data:s,error:c}=await dq(t,{method:"POST",body:a,headers:o});return c?(g.logger.error("GitHub OAuth token exchange failed:",c),null):"error"in s?(g.logger.error("GitHub OAuth token exchange failed:",s),null):dE(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i}=await dq("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&i&&(r.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===r.email)?.verified??!1,o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:a,...o},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com",n=`${r}/${t}/oauth2/v2.0/authorize`,i=`${r}/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(t){if(!dv(e.clientId))throw g.logger.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),d_({id:"microsoft",options:e,authorizationEndpoint:n,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:n})=>d5({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:i}),async verifyIdToken(n,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(n,i);try{let{kid:a,alg:o}=rt(n);if(!a||!o)return!1;let s=await ur(a,t,r),c={algorithms:[o],audience:e.clientId,maxTokenAge:"1h"};"common"!==t&&"organizations"!==t&&"consumers"!==t&&(c.issuer=`${r}/${t}/v2.0`);let{payload:l}=await rc(n,s,c);if(i&&l.nonce!==i)return!1;return!0}catch(e){return g.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d8(t.idToken),n=e.profilePhotoSize||48;await dq(`https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(t){if(!e.disableProfilePhoto&&t.response.ok)try{let e=await t.response.clone().arrayBuffer();r.picture=`data:image/jpeg;base64, ${sP.encode(e)}`}catch(e){g.logger.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let i=await e.mapProfileToUser?.(r),a=void 0!==r.email_verified?r.email_verified:!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:a,...i},data:r}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),dF({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:i})},options:e}},google:e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a,display:o}){if(!dv(e.clientId)||!e.clientSecret)throw g.logger.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new b.BetterAuthError("codeVerifier is required for Google");let s=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await d_({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:s,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d5({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rt(t);if(!n||!i)return!1;let{payload:a}=await rc(t,await ut(n),{algorithms:[i],issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,maxTokenAge:"1h"});if(r&&a.nonce!==r)return!1;return!0}catch{return!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d8(t.idToken),n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=new URL("https://slack.com/openid/connect/authorize");return a.searchParams.set("scope",i.join(" ")),a.searchParams.set("response_type","code"),a.searchParams.set("client_id",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r["https://slack.com/user_id"],name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...i},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d_({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return g.logger.error("No idToken found in token"),null;let n=d8(r),i=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:n.email_verified,...i},data:n}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),d_({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,authentication:"basic",redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i,error:a}=await dq("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(r.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.email||r.data.username||null,image:r.data.profile_image_url,emailVerified:o,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:r,codeVerifier:n,redirectURI:i})=>{let a=e.disableDefaultScope?[]:["account_info.read"];e.scope&&a.push(...e.scope),r&&a.push(...r);let o={};return e.accessType&&(o.token_access_type=e.accessType),await d_({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>await d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...i},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",createAuthorizationURL({state:t,scopes:r,redirectURI:n,codeVerifier:i}){let a=e.disableDefaultScope?[]:["user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"kick",redirectURI:n,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:a,codeVerifier:i,state:t})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:n})=>d5({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=r.data[0],a=await e.mapProfileToUser?.(i);return{user:{id:i.user_id,name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
66
|
-
query {
|
|
67
|
-
viewer {
|
|
68
|
-
id
|
|
69
|
-
name
|
|
70
|
-
email
|
|
71
|
-
avatarUrl
|
|
72
|
-
active
|
|
73
|
-
createdAt
|
|
74
|
-
updatedAt
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
`})});if(n||!r?.data?.viewer)return null;let i=r.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{id:r.data.viewer.id,name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:r,redirectURI:n,loginHint:i})=>{let a=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await d_({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:a,state:t,loginHint:i,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>await d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...i},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:n,userinfoEndpoint:i}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:ue(`${t}/oauth/authorize`),tokenEndpoint:ue(`${t}/oauth/token`),userinfoEndpoint:ue(`${t}/api/v4/user`)}),a="gitlab";return{id:a,name:"Gitlab",createAuthorizationURL:async({state:t,scopes:n,codeVerifier:i,loginHint:o,redirectURI:s})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),n&&c.push(...n),await d_({id:a,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:i,loginHint:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>d5({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq(i,{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||"active"!==r.state||r.locked)return null;let a=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/";return{id:"tiktok",name:"TikTok",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user.info.profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${i.join(",")}&response_type=code&client_key=${e.clientKey}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:e.redirectURI||n,options:{clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"post",extraParams:{client_key:e.clientKey}}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return n?null:{user:{email:r.data.user.email||r.data.user.username,id:r.data.user.open_id,name:r.data.user.display_name||r.data.user.username||"",image:r.data.user.avatar_large_url,emailVerified:!1},data:r}},options:e}},reddit:e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identity"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d_({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),{data:i,error:a}=await dq("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 ${sP.encode(`${e.clientId}:${e.clientSecret}`)}`},body:n.toString()});if(a)throw a;return dE(i)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:"https://www.reddit.com/api/v1/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}},options:e}),roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"select_account consent"}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.nickname||r.preferred_username||"",image:r.picture,email:r.preferred_username||null,emailVerified:!1,...i},data:{...r}}},options:e}},salesforce:e=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!e.clientId||!e.clientSecret)throw g.logger.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new b.BetterAuthError("codeVerifier is required for Salesforce");let o=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&o.push(...e.scope),n&&o.push(...n),d_({id:"salesforce",options:e,authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:e.redirectURI||a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d5({code:t,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await dq(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return g.logger.error("Failed to fetch user info from Salesforce"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.user_id,name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...n},data:r}}catch(e){return g.logger.error("Failed to fetch user info from Salesforce:",e),null}},options:e}},vk:e=>{let t="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["email","phone"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i,deviceId:a})=>d5({code:r,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:n,error:i}=await dq("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(i)return null;let a=await e.mapProfileToUser?.(n);return n.user.email||a?.email?{user:{id:n.user.user_id,first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...a},data:n}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:n})=>{let i=new URLSearchParams({response_type:"code",redirect_uri:t.redirectURI?t.redirectURI:r,client_id:t.clientId,state:e});if(t.pkce){let e=await dk(n);i.set("code_challenge_method","S256"),i.set("code_challenge",e)}let a=new URL("https://zoom.us/oauth/authorize");return a.search=i.toString(),a},validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:n})=>d5({code:e,redirectURI:t.redirectURI||r,codeVerifier:n,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>dF({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:r,error:n}=await dq("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(n)return null;let i=await t.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...i},data:{...r}}}}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=(e.disableDefaultScope,[]);return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n,additionalParams:{owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(n||!r)return null;let i=r.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name||"",email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d_({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r),a=r.kakao_account||{},o=a.profile||{};return{user:{id:String(r.id),name:o.nickname||a.name||"",email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["profile","email"];return e.scope&&i.push(...e.scope),r&&i.push(...r),d_({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d5({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r||"00"!==r.resultcode)return null;let i=await e.mapProfileToUser?.(r),a=r.response||{};return{user:{id:a.id,name:a.name||a.nickname||"",email:a.email,image:a.profile_image,emailVerified:!1,...i},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),await d_({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:o,state:t,codeVerifier:n,redirectURI:i,loginHint:a})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=new URLSearchParams;n.set("id_token",t),n.set("client_id",e.clientId),r&&n.set("nonce",r);let{data:i,error:a}=await dq("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n});return!a&&!!i&&i.aud===e.clientId&&(!i.nonce||i.nonce===r)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=d8(t.idToken)}catch{}if(!r){let{data:e}=await dq("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let n=await e.mapProfileToUser?.(r),i=r.sub||r.userId,a=r.name||r.displayName||"",o=r.picture||r.pictureUrl||void 0;return{user:{id:i,name:a,email:r.email,image:o,emailVerified:!1,...n},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,n=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a,loginHint:o}){if(!e.clientId||!e.clientSecret)throw g.logger.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new b.BetterAuthError("codeVerifier is required for Paybin");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),n&&s.push(...n),await d_({id:"paybin",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d5({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d8(t.idToken),n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...n},data:r}},options:e}},paypal:e=>{let t="sandbox"===(e.environment||"sandbox"),r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",n=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo";return{id:"paypal",name:"PayPal",async createAuthorizationURL({state:t,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw g.logger.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new b.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");return await d_({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let i=sP.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await dq(n,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r}).toString()});if(!e.data)throw new b.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN");let a=e.data;return{accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?new Date(Date.now()+1e3*a.expires_in):void 0,idToken:a.id_token}}catch(e){throw g.logger.error("PayPal token exchange failed:",e),new b.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=sP.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await dq(n,{method:"POST",headers:{Authorization:`Basic ${r}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t}).toString()});if(!e.data)throw new b.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN");let i=e.data;return{accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:i.expires_in?new Date(Date.now()+1e3*i.expires_in):void 0}}catch(e){throw g.logger.error("PayPal token refresh failed:",e),new b.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{return!!d8(t).sub}catch(e){return g.logger.error("Failed to verify PayPal ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return g.logger.error("Access token is required to fetch PayPal user info"),null;try{let r=await dq(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return g.logger.error("Failed to fetch user info from PayPal"),null;let n=r.data,a=await e.mapProfileToUser?.(n);return{user:{id:n.user_id,name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:n}}catch(e){return g.logger.error("Failed to fetch user info from PayPal:",e),null}},options:e}},polar:e=>{let t="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d5({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dF({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),d_({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d5({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:un,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dF({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:un,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}),vercel:e=>({id:"vercel",name:"Vercel",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a;if(!n)throw new b.BetterAuthError("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(a=[],e.scope&&a.push(...e.scope),r&&a.push(...r)),d_({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d5({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dq("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}),wechat:e=>({id:"wechat",name:"WeChat",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&i.push(...e.scope),r&&i.push(...r);let a=new URL("https://open.weixin.qq.com/connect/qrconnect");return a.searchParams.set("scope",i.join(",")),a.searchParams.set("response_type","code"),a.searchParams.set("appid",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a.searchParams.set("lang",e.lang||"cn"),a.hash="wechat_redirect",a},validateAuthorizationCode:async({code:t})=>{let{data:r,error:n}=await dq("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:r,error:n}=await dq("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:e.clientId,grant_type:"refresh_token",refresh_token:t}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let{data:n,error:i}=await dq("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!n||n.errcode)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.unionid||n.openid||r,name:n.nickname,email:n.email||null,image:n.headimgurl,emailVerified:!1,...a},data:n}},options:e})},ua=si(Object.keys(ui)).or(oS()),uo=le("/list-accounts",{method:"GET",use:[lT],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(t=>{let{scope:r,...n}=function(e,t){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=rb(t,rE(e,"account","output"));return c}(e.context.options,t);return{...n,scopes:r?.split(",")||[]}}))}),us=le("/link-social",{method:"POST",requireHeaders:!0,body:o9({callbackURL:oS().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:ua,idToken:o9({token:oS(),nonce:oS().optional(),accessToken:oS().optional(),refreshToken:oS().optional(),scopes:o4(oS()).optional()}).optional(),requestSignUp:oQ().optional(),scopes:o4(oS()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:oS().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:oQ().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),additionalData:sr(oS(),o0()).optional()}),use:[lT],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=await c_(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:i}=e.body.idToken;if(!await r.verifyIdToken(n,i))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_TOKEN);let a=await r.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let o=String(a.user.id);if(!a.user.email)throw e.context.logger.error(lD(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);if((await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>e.providerId===r.id&&e.accountId===o))return e.json({url:"",status:!0,redirect:!1});if(!e.context.trustedProviders.includes(r.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw b.APIError.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw b.APIError.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:r.id,accountId:o,accessToken:e.body.idToken.accessToken,idToken:n,refreshToken:e.body.idToken.refreshToken,scope:e.body.idToken.scopes?.join(",")})}catch(e){throw b.APIError.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{await e.context.internalAdapter.updateUser(t.user.id,{name:a.user?.name,image:a.user?.image})}catch(e){console.warn("Could not update user - "+e.toString())}return e.json({url:"",status:!0,redirect:!1})}let n=await dg(e,{userId:t.user.id,email:t.user.email},e.body.additionalData),i=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),uc=le("/unlink-account",{method:"POST",body:o9({providerId:oS(),accountId:oS().optional()}),use:[lI],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{providerId:t,accountId:r}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===n.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=n.find(e=>r?e.accountId===r&&e.providerId===t:e.providerId===t);if(!i)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})}),ul=le("/get-access-token",{method:"POST",body:o9({providerId:oS().meta({description:"The provider ID for the OAuth provider"}),accountId:oS().meta({description:"The account ID associated with the refresh token"}).optional(),userId:oS().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let t,{providerId:r,accountId:n,userId:i}=e.body||{},a=e.request,o=await lx(e);if(a&&!o)throw e.error("UNAUTHORIZED");let s=o?.user?.id||i;if(!s)throw e.error("UNAUTHORIZED");let c=await c_(e.context.socialProviders,{value:r});if(!c)throw b.APIError.from("BAD_REQUEST",{message:`Provider ${r} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});let l=await sT(e);if(!(t=l&&l.userId===s&&r===l.providerId&&(!n||l.accountId===n)?l:(await e.context.internalAdapter.findAccounts(s)).find(e=>n?e.accountId===n&&e.providerId===r:e.providerId===r)))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);try{let r=null,n=t.accessTokenExpiresAt&&new Date(t.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(t.refreshToken&&n&&c.refreshAccessToken){let n=await db(t.refreshToken,e.context);r=await c.refreshAccessToken(n);let i={accessToken:await dA(r?.accessToken,e.context),accessTokenExpiresAt:r?.accessTokenExpiresAt,refreshToken:r?.refreshToken?await dA(r.refreshToken,e.context):t.refreshToken,refreshTokenExpiresAt:r?.refreshTokenExpiresAt??t.refreshTokenExpiresAt,idToken:r?.idToken||t.idToken},a=null;t.id&&(a=await e.context.internalAdapter.updateAccount(t.id,i)),e.context.options.account?.storeAccountCookie&&await sx(e,{...t,...a??i})}let i=r?.accessTokenExpiresAt?"string"==typeof r.accessTokenExpiresAt?new Date(r.accessTokenExpiresAt):r.accessTokenExpiresAt:t.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:void 0,a={accessToken:r?.accessToken??await db(t.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:t.scope?.split(",")??[],idToken:r?.idToken??t.idToken??void 0};return e.json(a)}catch(e){throw b.APIError.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}),ud=le("/refresh-token",{method:"POST",body:o9({providerId:oS().meta({description:"The provider ID for the OAuth provider"}),accountId:oS().meta({description:"The account ID associated with the refresh token"}).optional(),userId:oS().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let t,r,{providerId:n,accountId:i,userId:a}=e.body,o=e.request,s=await lx(e);if(o&&!s)throw e.error("UNAUTHORIZED");let c=s?.user?.id||a;if(!c)throw b.APIError.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});let l=await c_(e.context.socialProviders,{value:n});if(!l)throw b.APIError.from("BAD_REQUEST",{message:`Provider ${n} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!l.refreshAccessToken)throw b.APIError.from("BAD_REQUEST",{message:`Provider ${n} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let d=await sT(e);if(!(t=d&&d.userId===c&&(!n||n===d?.providerId)?d:(await e.context.internalAdapter.findAccounts(c)).find(e=>i?e.accountId===i&&e.providerId===n:e.providerId===n)))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);if(!(r=d&&n===d.providerId?d.refreshToken??void 0:t.refreshToken??void 0))throw b.APIError.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let i=await db(r,e.context),a=await l.refreshAccessToken(i),o=a.refreshToken?await dA(a.refreshToken,e.context):r,s=a.refreshTokenExpiresAt??t.refreshTokenExpiresAt;if(t.id){let r={...t||{},accessToken:await dA(a.accessToken,e.context),refreshToken:o,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||t.scope,idToken:a.idToken||t.idToken};await e.context.internalAdapter.updateAccount(t.id,r)}return d&&n===d.providerId&&e.context.options.account?.storeAccountCookie&&await sx(e,{...d,accessToken:await dA(a.accessToken,e.context),refreshToken:o,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||d.scope,idToken:a.idToken||d.idToken}),e.json({accessToken:a.accessToken,refreshToken:a.refreshToken??i,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||t.scope,idToken:a.idToken||t.idToken,providerId:t.providerId,accountId:t.accountId})}catch(e){throw b.APIError.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),uu=le("/account-info",{method:"GET",use:[lT],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:ss(o9({accountId:oS().meta({description:"The provider given account id for which to get the account info"}).optional()}))},async e=>{let t,r=e.query?.accountId;if(r){let n=await e.context.internalAdapter.findAccount(r);n&&(t=n)}else if(e.context.options.account?.storeAccountCookie){let r=await sT(e);r&&(t=r)}if(!t||t.userId!==e.context.session.user.id)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);let n=await c_(e.context.socialProviders,{value:t.providerId});if(!n)throw b.APIError.from("INTERNAL_SERVER_ERROR",{message:`Provider account provider is ${t.providerId} but it is not configured`,code:"PROVIDER_NOT_CONFIGURED"});let i=await ul({...e,method:"POST",body:{accountId:t.accountId,providerId:t.providerId},returnHeaders:!1,returnStatus:!1});if(!i.accessToken)throw b.APIError.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let a=await n.getUserInfo({...i,accessToken:i.accessToken});return e.json(a)});async function up(e,t,r,n=3600,i){return await rl({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...i},e,n)}async function uf(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let r=await up(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:r},e.request?.clone()))}let uh=le("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:o9({email:aq(oT,void 0).meta({description:"The email to send the verification email to"}),callbackURL:oS().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await lx(e);if(!r){let r=await e.context.internalAdapter.findUserByEmail(t);return!r||r.user.emailVerified?await up(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn):await uf(e,r.user),e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.EMAIL_MISMATCH);if(r?.user.emailVerified)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED);return await uf(e,r.user),e.json({status:!0})}),um=le("/verify-email",{method:"GET",operationId:"verifyEmail",query:o9({token:oS().meta({description:"The token to verify the email"}),callbackURL:oS().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[lo(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){if(e.query.callbackURL.includes("?"))throw e.redirect(`${e.query.callbackURL}&error=${t.code}`);throw e.redirect(`${e.query.callbackURL}?error=${t.code}`)}throw b.APIError.from("UNAUTHORIZED",t)}let{token:n}=e.query;try{t=await rc(n,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof eN)return r(rw.BASE_ERROR_CODES.TOKEN_EXPIRED);return r(rw.BASE_ERROR_CODES.INVALID_TOKEN)}let i=o9({email:aq(oT,void 0),updateTo:oS().optional(),requestType:oS().optional()}).parse(t.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return r(rw.BASE_ERROR_CODES.USER_NOT_FOUND);if(i.updateTo){let t=await lx(e);if(t&&t.user.email!==i.email)return r(rw.BASE_ERROR_CODES.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let t=await up(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),r=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),n=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:n,token:t},e.request?.clone())),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),await sB(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:rv(e.context.options,n)})}default:{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await up(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},e.request?.clone())),await sB(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:rv(e.context.options,n)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await lx(e);if(t&&t.user.email===i.email)await sB(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);await sB(e,{session:t,user:{...a.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function uy(e,t){let{userInfo:r,account:n,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=await e.context.internalAdapter.findOAuthUser(r.email.toLowerCase(),n.accountId,n.providerId).catch(t=>{g.logger.error("Better auth was unable to query your database.\nError: ",t),lC(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,"internal_server_error")}),c=s?.user,l=!c;if(s){let i=s.linkedAccount??s.accounts.find(e=>e.providerId===n.providerId&&e.accountId===n.accountId);if(i){let t=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({idToken:n.idToken,accessToken:await dA(n.accessToken,e.context),refreshToken:await dA(n.refreshToken,e.context),accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope}).filter(([e,t])=>void 0!==t)):{};e.context.options.account?.storeAccountCookie&&await sx(e,{...i,...t}),Object.keys(t).length>0&&await e.context.internalAdapter.updateAccount(i.id,t),r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||e.context.trustedProviders.includes(n.providerId),o=i?.requireLocalEmailVerified??!0;if(!a&&!r.emailVerified||o&&!s.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0)return(0,S.isDevelopment)()&&g.logger.warn(`User already exist but account isn't linked to ${n.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:n.providerId,accountId:r.id.toString(),userId:s.user.id,accessToken:await dA(n.accessToken,e.context),refreshToken:await dA(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope})}catch(e){return g.logger.error("Unable to link account",e),{error:"unable to link account",data:null}}r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0})}if(o){let{id:t,...n}=r;c=await e.context.internalAdapter.updateUser(s.user.id,{...n,email:r.email.toLowerCase(),emailVerified:r.email.toLowerCase()===s.user.email&&s.user.emailVerified||r.emailVerified})}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:t,...a}=r,o={accessToken:await dA(n.accessToken,e.context),refreshToken:await dA(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope,providerId:n.providerId,accountId:r.id.toString()},{user:s,account:l}=await e.context.internalAdapter.createOAuthUser({...a,email:r.email.toLowerCase()},o);if(c=s,e.context.options.account?.storeAccountCookie&&await sx(e,l),!r.emailVerified&&c&&e.context.options.emailVerification?.sendOnSignUp&&e.context.options.emailVerification?.sendVerificationEmail){let t=await up(e.context.secret,c.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${encodeURIComponent(i||"/")}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:c,url:r,token:t},e.request))}}catch(e){if(g.logger.error(e),c4(e))return{error:e.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!c)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(c.id);return d?{data:{session:d,user:c},error:null,isRegister:l}:{error:"unable to create session",data:null,isRegister:!1}}let ug={scope:"server"},uw=o9({code:oS().optional(),error:oS().optional(),device_id:oS().optional(),error_description:oS().optional(),state:oS().optional(),user:oS().optional()}),ub=le("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:uw.optional(),query:uw.optional(),metadata:{...ug,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,n,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?uw.parse(e.body):{},r=e.query?uw.parse(e.query):{},n=uw.parse({...t,...r}),i=new URLSearchParams;for(let[e,t]of Object.entries(n))null!=t&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if("GET"===e.method)t=uw.parse(e.query);else if("POST"===e.method)t=uw.parse(e.body);else throw Error("Unsupported method")}catch(t){e.context.logger.error("INVALID_CALLBACK_REQUEST",t),lC(e,a,"invalid_callback_request")}let{code:o,error:s,error_description:c,device_id:l,user:d}=t,{codeVerifier:u,callbackURL:p,link:f,errorURL:h,newUserURL:m,requestSignUp:y}=await dw(e),g=h??a;s&&lC(e,g,s,c),o||(e.context.logger.error("Code not found"),lC(e,g,"no_code"));let w=await c_(e.context.socialProviders,{value:e.params.id});w||(e.context.logger.error("Oauth provider with id",e.params.id,"not found"),lC(e,g,"oauth_provider_not_found"));try{r=await w.validateAuthorizationCode({code:o,codeVerifier:u,deviceId:l,redirectURI:`${e.context.baseURL}/callback/${w.id}`})}catch(t){e.context.logger.error("",t),lC(e,g,"invalid_code")}r||lC(e,g,"invalid_code");let b=d?(0,rz.safeJSONParse)(d):null,A=await w.getUserInfo({...r,user:b??void 0}).then(e=>e?.user);A&&void 0!==A.id&&null!==A.id||(e.context.logger.error("Unable to get user info"),lC(e,g,"unable_to_get_user_info"));let E=String(A.id);if(p||(e.context.logger.error("No callback URL found"),lC(e,g,"no_callback_url")),f){let t;(e.context.trustedProviders.includes(w.id)||A.emailVerified)&&e.context.options.account?.accountLinking?.enabled!==!1||(e.context.logger.error("Unable to link account - untrusted provider"),lC(e,g,"unable_to_link_account")),A.email?.toLowerCase()!==f.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0&&lC(e,g,"email_doesn't_match");let n=await e.context.internalAdapter.findAccountByProviderId(E,w.id);if(n){n.userId.toString()!==f.userId.toString()&&lC(e,g,"account_already_linked_to_different_user");let t=Object.fromEntries(Object.entries({accessToken:await dA(r.accessToken,e.context),refreshToken:await dA(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scopes?.join(",")}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(n.id,t)}else await e.context.internalAdapter.createAccount({userId:f.userId,providerId:w.id,accountId:E,...r,accessToken:await dA(r.accessToken,e.context),refreshToken:await dA(r.refreshToken,e.context),scope:r.scopes?.join(",")})||lC(e,g,"unable_to_link_account");try{t=p.toString()}catch{t=p}throw e.redirect(t)}A.email||(e.context.logger.error(lD(w.id)),lC(e,g,"email_not_found"));let v={providerId:w.id,accountId:E,...r,scope:r.scopes?.join(",")};try{n=await uy(e,{userInfo:{...A,id:E,email:A.email,name:A.name||""},account:v,callbackURL:p,disableSignUp:w.disableImplicitSignUp&&!y||w.options?.disableSignUp,overrideUserInfo:w.options?.overrideUserInfoOnSignIn})}catch(t){throw c4(t)&&t.body?.code&&lC(e,g,t.body.code,t.body.message),t}n.error&&(e.context.logger.error(n.error.split(" ").join("_")),lC(e,g,n.error.split(" ").join("_")));let{session:k,user:_}=n.data;await sB(e,{session:k,user:_});try{i=(n.isRegister&&m||p).toString()}catch{i=n.isRegister&&m||p}throw e.redirect(i)});function uA(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&")}let uE=le("/error",{method:"GET",metadata:{...ug,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",n=t.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",a=n?uA(n):null,o=new URLSearchParams;o.set("error",i),n&&o.set("error_description",n);let s=e.context.options,c=s.onAPIError?.errorURL;return c?new Response(null,{status:302,headers:{Location:`${c}${c.includes("?")?"&":"?"}${o.toString()}`}}):S.isProduction&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let n=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
78
|
-
<html lang="en">
|
|
79
|
-
<head>
|
|
80
|
-
<meta charset="UTF-8" />
|
|
81
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
82
|
-
<title>Error</title>
|
|
83
|
-
<style>
|
|
84
|
-
* {
|
|
85
|
-
box-sizing: border-box;
|
|
86
|
-
}
|
|
87
|
-
body {
|
|
88
|
-
font-family: ${n?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
|
|
89
|
-
background: ${n?.colors?.background||"var(--background)"};
|
|
90
|
-
color: var(--foreground);
|
|
91
|
-
margin: 0;
|
|
92
|
-
}
|
|
93
|
-
:root,
|
|
94
|
-
:host {
|
|
95
|
-
--spacing: 0.25rem;
|
|
96
|
-
--container-md: 28rem;
|
|
97
|
-
--text-sm: ${n?.size?.textSm||"0.875rem"};
|
|
98
|
-
--text-sm--line-height: calc(1.25 / 0.875);
|
|
99
|
-
--text-2xl: ${n?.size?.text2xl||"1.5rem"};
|
|
100
|
-
--text-2xl--line-height: calc(2 / 1.5);
|
|
101
|
-
--text-4xl: ${n?.size?.text4xl||"2.25rem"};
|
|
102
|
-
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
103
|
-
--text-6xl: ${n?.size?.text6xl||"3rem"};
|
|
104
|
-
--text-6xl--line-height: 1;
|
|
105
|
-
--font-weight-medium: 500;
|
|
106
|
-
--font-weight-semibold: 600;
|
|
107
|
-
--font-weight-bold: 700;
|
|
108
|
-
--default-transition-duration: 150ms;
|
|
109
|
-
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
110
|
-
--radius: ${n?.size?.radiusSm||"0.625rem"};
|
|
111
|
-
--default-mono-font-family: ${n?.font?.monoFamily||"var(--font-geist-mono)"};
|
|
112
|
-
--primary: ${n?.colors?.primary||"black"};
|
|
113
|
-
--primary-foreground: ${n?.colors?.primaryForeground||"white"};
|
|
114
|
-
--background: ${n?.colors?.background||"white"};
|
|
115
|
-
--foreground: ${n?.colors?.foreground||"oklch(0.271 0 0)"};
|
|
116
|
-
--border: ${n?.colors?.border||"oklch(0.89 0 0)"};
|
|
117
|
-
--destructive: ${n?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
|
|
118
|
-
--muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.545 0 0)"};
|
|
119
|
-
--corner-border: ${n?.colors?.cornerBorder||"#404040"};
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
button, .btn {
|
|
123
|
-
cursor: pointer;
|
|
124
|
-
background: none;
|
|
125
|
-
border: none;
|
|
126
|
-
color: inherit;
|
|
127
|
-
font: inherit;
|
|
128
|
-
transition: all var(--default-transition-duration)
|
|
129
|
-
var(--default-transition-timing-function);
|
|
130
|
-
}
|
|
131
|
-
button:hover, .btn:hover {
|
|
132
|
-
opacity: 0.8;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
@media (prefers-color-scheme: dark) {
|
|
136
|
-
:root,
|
|
137
|
-
:host {
|
|
138
|
-
--primary: ${n?.colors?.primary||"white"};
|
|
139
|
-
--primary-foreground: ${n?.colors?.primaryForeground||"black"};
|
|
140
|
-
--background: ${n?.colors?.background||"oklch(0.15 0 0)"};
|
|
141
|
-
--foreground: ${n?.colors?.foreground||"oklch(0.98 0 0)"};
|
|
142
|
-
--border: ${n?.colors?.border||"oklch(0.27 0 0)"};
|
|
143
|
-
--destructive: ${n?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
|
|
144
|
-
--muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.65 0 0)"};
|
|
145
|
-
--corner-border: ${n?.colors?.cornerBorder||"#a0a0a0"};
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
@media (max-width: 640px) {
|
|
149
|
-
:root, :host {
|
|
150
|
-
--text-6xl: 2.5rem;
|
|
151
|
-
--text-2xl: 1.25rem;
|
|
152
|
-
--text-sm: 0.8125rem;
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
@media (max-width: 480px) {
|
|
156
|
-
:root, :host {
|
|
157
|
-
--text-6xl: 2rem;
|
|
158
|
-
--text-2xl: 1.125rem;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
</style>
|
|
162
|
-
</head>
|
|
163
|
-
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
164
|
-
<div
|
|
165
|
-
style="
|
|
166
|
-
display: flex;
|
|
167
|
-
flex-direction: column;
|
|
168
|
-
align-items: center;
|
|
169
|
-
justify-content: center;
|
|
170
|
-
gap: 1.5rem;
|
|
171
|
-
position: relative;
|
|
172
|
-
width: 100%;
|
|
173
|
-
min-height: 100vh;
|
|
174
|
-
padding: 1rem;
|
|
175
|
-
"
|
|
176
|
-
>
|
|
177
|
-
${n?.disableBackgroundGrid?"":`
|
|
178
|
-
<div
|
|
179
|
-
style="
|
|
180
|
-
position: absolute;
|
|
181
|
-
inset: 0;
|
|
182
|
-
background-image: linear-gradient(to right, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
|
|
183
|
-
linear-gradient(to bottom, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
|
|
184
|
-
background-size: 40px 40px;
|
|
185
|
-
opacity: 0.6;
|
|
186
|
-
pointer-events: none;
|
|
187
|
-
width: 100vw;
|
|
188
|
-
height: 100vh;
|
|
189
|
-
"
|
|
190
|
-
></div>
|
|
191
|
-
<div
|
|
192
|
-
style="
|
|
193
|
-
position: absolute;
|
|
194
|
-
inset: 0;
|
|
195
|
-
display: flex;
|
|
196
|
-
align-items: center;
|
|
197
|
-
justify-content: center;
|
|
198
|
-
background: ${n?.colors?.background||"var(--background)"};
|
|
199
|
-
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
200
|
-
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
201
|
-
pointer-events: none;
|
|
202
|
-
"
|
|
203
|
-
></div>
|
|
204
|
-
`}
|
|
205
|
-
|
|
206
|
-
<div
|
|
207
|
-
style="
|
|
208
|
-
position: relative;
|
|
209
|
-
z-index: 10;
|
|
210
|
-
border: 2px solid var(--border);
|
|
211
|
-
background: ${n?.colors?.cardBackground||"var(--background)"};
|
|
212
|
-
padding: 1.5rem;
|
|
213
|
-
max-width: 42rem;
|
|
214
|
-
width: 100%;
|
|
215
|
-
"
|
|
216
|
-
>
|
|
217
|
-
${n?.disableCornerDecorations?"":`
|
|
218
|
-
<!-- Corner decorations -->
|
|
219
|
-
<div
|
|
220
|
-
style="
|
|
221
|
-
position: absolute;
|
|
222
|
-
top: -2px;
|
|
223
|
-
left: -2px;
|
|
224
|
-
width: 2rem;
|
|
225
|
-
height: 2rem;
|
|
226
|
-
border-top: 4px solid var(--corner-border);
|
|
227
|
-
border-left: 4px solid var(--corner-border);
|
|
228
|
-
"
|
|
229
|
-
></div>
|
|
230
|
-
<div
|
|
231
|
-
style="
|
|
232
|
-
position: absolute;
|
|
233
|
-
top: -2px;
|
|
234
|
-
right: -2px;
|
|
235
|
-
width: 2rem;
|
|
236
|
-
height: 2rem;
|
|
237
|
-
border-top: 4px solid var(--corner-border);
|
|
238
|
-
border-right: 4px solid var(--corner-border);
|
|
239
|
-
"
|
|
240
|
-
></div>
|
|
241
|
-
|
|
242
|
-
<div
|
|
243
|
-
style="
|
|
244
|
-
position: absolute;
|
|
245
|
-
bottom: -2px;
|
|
246
|
-
left: -2px;
|
|
247
|
-
width: 2rem;
|
|
248
|
-
height: 2rem;
|
|
249
|
-
border-bottom: 4px solid var(--corner-border);
|
|
250
|
-
border-left: 4px solid var(--corner-border);
|
|
251
|
-
"
|
|
252
|
-
></div>
|
|
253
|
-
<div
|
|
254
|
-
style="
|
|
255
|
-
position: absolute;
|
|
256
|
-
bottom: -2px;
|
|
257
|
-
right: -2px;
|
|
258
|
-
width: 2rem;
|
|
259
|
-
height: 2rem;
|
|
260
|
-
border-bottom: 4px solid var(--corner-border);
|
|
261
|
-
border-right: 4px solid var(--corner-border);
|
|
262
|
-
"
|
|
263
|
-
></div>`}
|
|
264
|
-
|
|
265
|
-
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
266
|
-
<div style="margin-bottom: 1.5rem;">
|
|
267
|
-
<div
|
|
268
|
-
style="
|
|
269
|
-
display: inline-block;
|
|
270
|
-
border: 2px solid ${n?.disableTitleBorder?"transparent":n?.colors?.titleBorder||"var(--destructive)"};
|
|
271
|
-
padding: 0.375rem 1rem;
|
|
272
|
-
"
|
|
273
|
-
>
|
|
274
|
-
<h1
|
|
275
|
-
style="
|
|
276
|
-
font-size: var(--text-6xl);
|
|
277
|
-
font-weight: var(--font-weight-semibold);
|
|
278
|
-
color: ${n?.colors?.titleColor||"var(--foreground)"};
|
|
279
|
-
letter-spacing: -0.02em;
|
|
280
|
-
margin: 0;
|
|
281
|
-
"
|
|
282
|
-
>
|
|
283
|
-
ERROR
|
|
284
|
-
</h1>
|
|
285
|
-
</div>
|
|
286
|
-
<div
|
|
287
|
-
style="
|
|
288
|
-
height: 2px;
|
|
289
|
-
background-color: var(--border);
|
|
290
|
-
width: calc(100% + 3rem);
|
|
291
|
-
margin-left: -1.5rem;
|
|
292
|
-
margin-top: 1.5rem;
|
|
293
|
-
"
|
|
294
|
-
></div>
|
|
295
|
-
</div>
|
|
296
|
-
|
|
297
|
-
<h2
|
|
298
|
-
style="
|
|
299
|
-
font-size: var(--text-2xl);
|
|
300
|
-
font-weight: var(--font-weight-semibold);
|
|
301
|
-
color: var(--foreground);
|
|
302
|
-
margin: 0 0 1rem;
|
|
303
|
-
"
|
|
304
|
-
>
|
|
305
|
-
Something went wrong
|
|
306
|
-
</h2>
|
|
307
|
-
|
|
308
|
-
<div
|
|
309
|
-
style="
|
|
310
|
-
display: inline-flex;
|
|
311
|
-
align-items: center;
|
|
312
|
-
gap: 0.5rem;
|
|
313
|
-
border: 2px solid var(--border);
|
|
314
|
-
background-color: var(--muted);
|
|
315
|
-
padding: 0.375rem 0.75rem;
|
|
316
|
-
margin: 0 0 1rem;
|
|
317
|
-
flex-wrap: wrap;
|
|
318
|
-
justify-content: center;
|
|
319
|
-
"
|
|
320
|
-
>
|
|
321
|
-
<span
|
|
322
|
-
style="
|
|
323
|
-
font-size: 0.75rem;
|
|
324
|
-
color: var(--muted-foreground);
|
|
325
|
-
font-weight: var(--font-weight-semibold);
|
|
326
|
-
"
|
|
327
|
-
>
|
|
328
|
-
CODE:
|
|
329
|
-
</span>
|
|
330
|
-
<span
|
|
331
|
-
style="
|
|
332
|
-
font-size: var(--text-sm);
|
|
333
|
-
font-family: var(--default-mono-font-family, monospace);
|
|
334
|
-
color: var(--foreground);
|
|
335
|
-
word-break: break-all;
|
|
336
|
-
"
|
|
337
|
-
>
|
|
338
|
-
${uA(t)}
|
|
339
|
-
</span>
|
|
340
|
-
</div>
|
|
341
|
-
|
|
342
|
-
<p
|
|
343
|
-
style="
|
|
344
|
-
color: var(--muted-foreground);
|
|
345
|
-
max-width: 28rem;
|
|
346
|
-
margin: 0 auto;
|
|
347
|
-
font-size: var(--text-sm);
|
|
348
|
-
line-height: 1.5;
|
|
349
|
-
text-wrap: pretty;
|
|
350
|
-
"
|
|
351
|
-
>
|
|
352
|
-
${!r?`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:r}
|
|
353
|
-
</p>
|
|
354
|
-
</div>
|
|
355
|
-
|
|
356
|
-
<div
|
|
357
|
-
style="
|
|
358
|
-
display: flex;
|
|
359
|
-
gap: 0.75rem;
|
|
360
|
-
margin-top: 1.5rem;
|
|
361
|
-
justify-content: center;
|
|
362
|
-
flex-wrap: wrap;
|
|
363
|
-
"
|
|
364
|
-
>
|
|
365
|
-
<a
|
|
366
|
-
href="/"
|
|
367
|
-
style="
|
|
368
|
-
text-decoration: none;
|
|
369
|
-
"
|
|
370
|
-
>
|
|
371
|
-
<div
|
|
372
|
-
style="
|
|
373
|
-
border: 2px solid var(--border);
|
|
374
|
-
background: var(--primary);
|
|
375
|
-
color: var(--primary-foreground);
|
|
376
|
-
padding: 0.5rem 1rem;
|
|
377
|
-
border-radius: 0;
|
|
378
|
-
white-space: nowrap;
|
|
379
|
-
"
|
|
380
|
-
class="btn"
|
|
381
|
-
>
|
|
382
|
-
Go Home
|
|
383
|
-
</div>
|
|
384
|
-
</a>
|
|
385
|
-
<a
|
|
386
|
-
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
|
|
387
|
-
target="_blank"
|
|
388
|
-
rel="noopener noreferrer"
|
|
389
|
-
style="
|
|
390
|
-
text-decoration: none;
|
|
391
|
-
"
|
|
392
|
-
>
|
|
393
|
-
<div
|
|
394
|
-
style="
|
|
395
|
-
border: 2px solid var(--border);
|
|
396
|
-
background: transparent;
|
|
397
|
-
color: var(--foreground);
|
|
398
|
-
padding: 0.5rem 1rem;
|
|
399
|
-
border-radius: 0;
|
|
400
|
-
white-space: nowrap;
|
|
401
|
-
"
|
|
402
|
-
class="btn"
|
|
403
|
-
>
|
|
404
|
-
Ask AI
|
|
405
|
-
</div>
|
|
406
|
-
</a>
|
|
407
|
-
</div>
|
|
408
|
-
</div>
|
|
409
|
-
</div>
|
|
410
|
-
</body>
|
|
411
|
-
</html>`})(e.context.options,i,a),{headers:{"Content-Type":"text/html"}})}),uv=le("/ok",{method:"GET",metadata:{...ug,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0}));function uk(e,t,r){let n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href}let u_=le("/request-password-reset",{method:"POST",body:o9({email:aq(oT,void 0).meta({description:"The email address of the user to send a password reset email to"}),redirectTo:oS().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:[lo(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),b.APIError.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return(0,cc.generateId)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=rT(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),a=(0,cc.generateId)(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:s,token:a},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),uS=le("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:o9({callbackURL:oS().meta({description:"The URL to redirect the user to reset their password"})}),use:[lo(e=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let n,{token:i}=e.params,{callbackURL:a}=e.query;if(!i||!a)throw e.redirect(uk(e.context,a,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);if(!o||o.expiresAt<new Date)throw e.redirect(uk(e.context,a,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:i},n=new URL(a,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href))}),ux=le("/reset-password",{method:"POST",operationId:"resetPassword",query:o9({token:oS().optional()}).optional(),body:o9({newPassword:oS().meta({description:"The new password to set"}),token:oS().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_TOKEN);let{newPassword:r}=e.body,n=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<n)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);if(r.length>i)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=`reset-password:${t}`,o=await e.context.internalAdapter.findVerificationValue(a);if(!o||o.expiresAt<new Date)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_TOKEN);let s=o.value,c=await e.context.password.hash(r);if((await e.context.internalAdapter.findAccounts(s)).find(e=>"credential"===e.providerId)?await e.context.internalAdapter.updatePassword(s,c):await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:c,accountId:s}),await e.context.internalAdapter.deleteVerificationByIdentifier(a),e.context.options.emailAndPassword?.onPasswordReset){let t=await e.context.internalAdapter.findUserById(s);t&&await e.context.options.emailAndPassword.onPasswordReset({user:t},e.request)}return e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteSessions(s),e.json({status:!0})}),uT=le("/verify-password",{method:"POST",body:o9({password:oS().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:[lR]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await cx(e,{password:t,userId:r.user.id}))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD);return e.json({status:!0})}),uR=o9({callbackURL:oS().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:oS().optional(),errorCallbackURL:oS().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:ua,disableRedirect:oQ().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:ss(o9({token:oS().meta({description:"ID token from the provider"}),nonce:oS().meta({description:"Nonce used to generate the token"}).optional(),accessToken:oS().meta({description:"Access token from the provider"}).optional(),refreshToken:oS().meta({description:"Refresh token from the provider"}).optional(),expiresAt:oF().meta({description:"Expiry date of the token"}).optional(),user:o9({name:o9({firstName:oS().optional(),lastName:oS().optional()}).optional(),email:oS().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:o4(oS()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:oQ().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:oS().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalData:sr(oS(),o0()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),uI=le("/sign-out",{method:"POST",operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}return sM(e),e.json({success:!0})}),uU=o9({name:oS(),email:aq(oT,void 0),password:oS().nonempty(),image:oS().optional(),callbackURL:oS().optional(),rememberMe:oQ().optional()}).and(sr(oS(),o0())),uO=sr(oS().meta({description:"Field name must be a string"}),o0()),uP=sr(oS().meta({description:"Field name must be a string"}),o0()),uC=le("/change-password",{method:"POST",operationId:"changePassword",body:o9({newPassword:oS().meta({description:"The new password to set"}),currentPassword:oS().meta({description:"The current password is required"}),revokeOtherSessions:oQ().meta({description:"Must be a boolean value"}).optional()}),use:[lR],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,i=e.context.session,a=e.context.password.config.minPasswordLength;if(t.length<a)throw e.context.logger.error("Password is too short"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.error("Password is too long"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!s||!s.password)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:r}))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD);await e.context.internalAdapter.updateAccount(s.id,{password:c});let l=null;if(n){await e.context.internalAdapter.deleteSessions(i.user.id);let t=await e.context.internalAdapter.createSession(i.user.id);if(!t)throw b.APIError.from("INTERNAL_SERVER_ERROR",rw.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);await sB(e,{session:t,user:i.user}),l=t.token}return e.json({token:l,user:rv(e.context.options,i.user)})}),uD=le({method:"POST",body:o9({newPassword:oS().meta({description:"The new password to set is required"})}),use:[lR]},async e=>{let{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(e=>"credential"===e.providerId&&e.password),o=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:o}),e.json({status:!0});throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_ALREADY_SET)}),uL=le("/delete-user",{method:"POST",use:[lR],body:o9({callbackURL:oS().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:oS().meta({description:"The password of the user is required to delete the user"}).optional(),token:oS().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),b.APIError.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){let r=(await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!r||!r.password)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD)}if(e.body.token)return await uz({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=lz(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let n=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:r},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),sM(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),uz=le("/delete-user/callback",{method:"GET",query:o9({token:oS().meta({description:"The token to verify the deletion request"}),callbackURL:oS().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[lo(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),b.APIError.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await lx(e);if(!t)throw b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date||r.value!==t.user.id)throw b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.INVALID_TOKEN);let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${e.query.token}`),sM(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),u$=le("/change-email",{method:"POST",body:o9({newEmail:aq(oT,void 0).meta({description:"The new email address to set must be a valid email address"}),callbackURL:oS().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[lR],metadata:{openapi:{operationId:"changeEmail",responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.error("Email is the same"),b.APIError.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,n=e.context.options.emailVerification?.sendVerificationEmail,i=n&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!i&&!n)throw e.context.logger.error("Verification email isn't enabled."),b.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await up(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t}),await sB(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),n){let r=await up(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:i,token:r},e.request))}return e.json({status:!0})}if(i){let r=await up(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:n,token:r},e.request)),e.json({status:!0})}if(!n)throw e.context.logger.error("Verification email isn't enabled."),b.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let a=await up(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),uN=cp((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),uj=new WeakMap;async function uH(e,t){if(e.baseURL)return e;let r=function(e){if(P(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has("host")||t.has("x-forwarded-host"))return t}(t),n=e.options.baseURL,i=O(n)&&!!n.fallback;if(void 0===r&&!i)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await ck(e,r,cv(e.options))}catch(e){if(e instanceof b.BetterAuthError)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}async function uB(e,t,r,n){let i={};for(let a of t){let t=!1;try{t=a.matcher(e)}catch(r){let t=uj.get(a.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${t} hook matcher execution:`,r),new b.APIError("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(t){let t=uj.get(a.handler)??"unknown",o=r.path??"/:virtual",s=await (0,cs.withSpan)(`hook before ${o} ${t}`,{[ca]:"before",[cn.ATTR_HTTP_ROUTE]:o,[co]:t,[ci]:n},()=>a.handler({...e,returnHeaders:!1})).catch(t=>{throw c4(t)&&(0,g.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),t});if(s&&"object"==typeof s){if("context"in s&&"object"==typeof s.context){let{headers:e,...t}=s.context;e instanceof Headers&&(i.headers?e.forEach((e,t)=>{i.headers?.set(t,e)}):i.headers=e),i=uN(t,i);continue}return s}}}return{context:i}}async function uV(e,t,r,n){for(let i of t)if(i.matcher(e)){let t=uj.get(i.handler)??"unknown",a=r.path??"/:virtual",o=await (0,cs.withSpan)(`hook after ${a} ${t}`,{[ca]:"after",[cn.ATTR_HTTP_ROUTE]:a,[co]:t,[ci]:n},()=>i.handler(e)).catch(t=>{if(c4(t)){let r=t[cR.kAPIErrorHeaderSymbol];return(0,g.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),{response:t,headers:r||(t.headers?new Headers(t.headers):null)}}throw t});o.headers&&o.headers.forEach((t,r)=>{e.context.responseHeaders?"set-cookie"===r.toLowerCase()?e.context.responseHeaders.append(r,t):e.context.responseHeaders.set(r,t):e.context.responseHeaders=new Headers({[r]:t})}),o.response&&(e.context.returned=o.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function uM(e,t){let r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},n=t.plugins?.map(t=>t.middlewares?.map(r=>{let n=async n=>{let i=await e;return(0,cs.withSpan)(`middleware ${r.path} ${t.id}`,{[ca]:"middleware",[cn.ATTR_HTTP_ROUTE]:r.path,[co]:`plugin:${t.id}`},()=>r.middleware({...n,context:{...i,...n.context}}))};return n.options=r.middleware.options,{path:r.path,middleware:n}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=async e=>{let r=function(e,t){if(!e?.options)return t;let r=e.options;return r.operationId??r.metadata?.openapi?.operationId??t}(i,n),a=i?.options?.method,o=Array.isArray(a)?a[0]:a,s=async()=>{let n=await t,a=e?.method??e?.request?.method??o??"?",s=i.path??"/:virtual",c=O(n.options.baseURL)?await uH(n,e):n,l={...e,context:{...c,returned:void 0,responseHeaders:void 0,session:null},path:i.path,headers:e?.headers?new Headers(e?.headers):void 0},d=P(e?.request),u=e?.asResponse??d;return(0,cs.withSpan)(`${a} ${s}`,{[cn.ATTR_HTTP_ROUTE]:s,[ci]:r},async()=>cr(l,async()=>{let{beforeHooks:t,afterHooks:n}=function(e){let t=e.options.plugins||[],r=[],n=[],i=e.options.hooks?.before;i&&(uj.set(i,"user"),r.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(uj.set(a,"user"),n.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(uj.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(uj.set(t.handler,`plugin:${e.id}`),t)));return o.length&&r.push(...o),s.length&&n.push(...s),{beforeHooks:r,afterHooks:n}}(c),a=await uB(l,t,i,r);if("context"in a&&a.context&&"object"==typeof a.context){let{headers:e,...t}=a.context;e&&e.forEach((e,t)=>{l.headers.set(t,e)}),l=uN(t,l)}else if(a)return u?cz(a,{headers:e?.headers}):e?.returnHeaders?{headers:e?.headers,response:a}:a;l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let o=await cr(l,()=>(0,cs.withSpan)(`handler ${s}`,{[cn.ATTR_HTTP_ROUTE]:s,[ci]:r},()=>i(l))).catch(e=>{if(c4(e)){let t=e[cR.kAPIErrorHeaderSymbol],r=e.headers&&e.headers!==t?new Headers(e.headers):null,n=null;return(t||r)&&(n=new Headers,t?.forEach((e,t)=>{n.append(t,e)}),r?.forEach((e,t)=>{"set-cookie"===t.toLowerCase()?n.append(t,e):n.set(t,e)})),{response:e,status:e.statusCode,headers:n}}throw e});if(o&&o instanceof Response)return o;l.context.returned=o.response,l.context.responseHeaders=o.headers;let d=await uV(l,n,i,r);if(d.response&&(o.response=d.response),c4(o.response)&&(0,g.shouldPublishLog)(c.logger.level,"debug")&&(o.response.stack=o.response.errorStack),c4(o.response)&&!u)throw o.headers&&Object.defineProperty(o.response,cR.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,writable:!1,value:o.headers}),o.response;return u?cz(o.response,{headers:o.headers,status:o.status}):e?.returnHeaders?e?.returnStatus?{headers:o.headers,response:o.response,status:o.status}:{headers:o.headers,response:o.response}:e?.returnStatus?{response:o.response,status:o.status}:o.response}))};return await lg()?s():lb(new WeakMap,s)},r[n].path=i.path,r[n].options=i.options;return r}({signInSocial:le("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:uR,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=await c_(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),b.APIError.from("NOT_FOUND",rw.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:n}=e.body.idToken;if(!await t.verifyIdToken(r,n))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_TOKEN);let i=await t.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user});if(!i||!i?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);if(!i.user.email)throw e.context.logger.error(lD(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);let a=await uy(e,{userInfo:{...i.user,email:i.user.email,id:String(i.user.id),name:i.user.name||"",image:i.user.image,emailVerified:i.user.emailVerified||!1},account:{providerId:t.id,accountId:String(i.user.id),accessToken:e.body.idToken.accessToken},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(a.error)throw b.APIError.from("UNAUTHORIZED",{message:a.error,code:"OAUTH_LINK_ERROR"});return await sB(e,a.data),e.json({redirect:!1,token:a.data.session.token,url:void 0,user:rv(e.context.options,a.data.user)})}let{codeVerifier:r,state:n}=await dg(e,void 0,e.body.additionalData),i=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:ub,getSession:lS(),signOut:uI,signUpEmail:le("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[lc],body:uU,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>s9(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw b.APIError.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:n,email:i,password:a,image:o,callbackURL:s,rememberMe:c,...l}=r;if(!aq(oT,void 0).safeParse(i).success)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_EMAIL);if(!a||"string"!=typeof a)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_PASSWORD);let d=e.context.password.config.minPasswordLength;if(a.length<d)throw e.context.logger.error("Password is too short"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let u=e.context.password.config.maxPasswordLength;if(a.length>u)throw e.context.logger.error("Password is too long"),b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let p=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,f=!1===e.context.options.emailAndPassword.autoSignIn||p,h=rx(e.context.options,l,"create"),m=i.toLowerCase(),y=await e.context.internalAdapter.findUserByEmail(m);if(y?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${i}`),p){let t;await e.context.password.hash(a),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:y.user},e.request?.clone()));let r=new Date,i=e.context.generateId({model:"user"})||(0,cc.generateId)(),s={name:n,email:m,emailVerified:!1,image:o??null,createdAt:r,updatedAt:r},c=e.context.options.emailAndPassword?.customSyntheticUser;if(c){let r=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of r)e in h&&(n[e]=h[e]);let a=c({coreFields:s,additionalFields:n,id:i});t=rk(e.context.options,a)}else t=rk(e.context.options,{...s,...h,id:i});return e.json({token:null,user:rv(e.context.options,t)})}throw b.APIError.from("UNPROCESSABLE_ENTITY",rw.BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let g=await e.context.password.hash(a);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:n,image:o,...h,emailVerified:!1})))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}catch(t){if((0,S.isDevelopment)()&&e.context.logger.error("Failed to create user",t),c4(t))throw t;throw e.context.logger?.error("Failed to create user",t),b.APIError.from("UNPROCESSABLE_ENTITY",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}if(!t)throw b.APIError.from("UNPROCESSABLE_ENTITY",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:g}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await up(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),i=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${i}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:n},e.request?.clone()))}if(f)return e.json({token:null,user:rv(e.context.options,t)});let w=await e.context.internalAdapter.createSession(t.id,!1===c);if(!w)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await sB(e,{session:w,user:t},!1===c),e.json({token:w.token,user:rv(e.context.options,t)})})),signInEmail:le("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[lc],cloneRequest:!0,body:o9({email:oS().meta({description:"Email of the user"}),password:oS().meta({description:"Password of the user"}),callbackURL:oS().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:oQ().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),b.APIError.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!aq(oT,void 0).safeParse(t).success)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.INVALID_EMAIL);let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let i=n.accounts.find(e=>"credential"===e.providerId);if(!i)throw await e.context.password.hash(r),e.context.logger.error("Credential account not found",{email:t}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let a=i?.password;if(!a)throw await e.context.password.hash(r),e.context.logger.error("Password not found",{email:t}),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.error("Invalid password"),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await up(e.context.secret,n.user.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:i,token:t},e.request?.clone()))}throw b.APIError.from("FORBIDDEN",rw.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED)}let o=await e.context.internalAdapter.createSession(n.user.id,!1===e.body.rememberMe);if(!o)throw e.context.logger.error("Failed to create session"),b.APIError.from("UNAUTHORIZED",rw.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await sB(e,{session:o,user:n.user},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:o.token,url:e.body.callbackURL,user:rv(e.context.options,n.user)})}),resetPassword:ux,verifyPassword:uT,verifyEmail:um,sendVerificationEmail:uh,changeEmail:u$,changePassword:uC,setPassword:uD,updateSession:le("/update-session",{method:"POST",operationId:"updateSession",body:uO,use:[lT],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{var t;let r=e.body;if("object"!=typeof r||Array.isArray(r))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,i=(t=e.context.options,rS(r,{fields:rE(t,"session","input"),action:"update"}));if(0===Object.keys(i).length)throw b.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(n.session.token,{...i,updatedAt:new Date})??{...n.session,...i,updatedAt:new Date};return await sB(e,{session:a,user:n.user}),e.json({session:r_(e.context.options,a)})}),updateUser:le("/update-user",{method:"POST",operationId:"updateUser",body:uP,use:[lT],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);if(t.email)throw b.APIError.from("BAD_REQUEST",rw.BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:n,...i}=t,a=e.context.session,o=rx(e.context.options,i,"update");if(void 0===n&&void 0===r&&0===Object.keys(o).length)throw b.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:r,image:n,...o})??{...a.user,...void 0!==r&&{name:r},...void 0!==n&&{image:n},...o};return await sB(e,{session:a.session,user:s}),e.json({status:!0})}),deleteUser:uL,requestPasswordReset:u_,requestPasswordResetCallback:uS,listSessions:le("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[lT],requireHeaders:!0,metadata:{openapi:{operationId:"listUserSessions",description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>r_(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),revokeSession:lU,revokeSessions:lO,revokeOtherSessions:lP,linkSocialAccount:us,listUserAccounts:uo,deleteUserCallback:uz,unlinkAccount:uc,refreshToken:ud,getAccessToken:ul,accountInfo:uu,...r,ok:uv,error:uE},e),middlewares:n}}var uK=e.i(902157),uW=e.i(912714),uq=e.i(660526),uF=e.i(750227);async function uJ(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let r=e.socialProviders?.[t];if(!r)return{};let n="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!n.mapProfileToUser,disableDefaultScope:!!n.disableDefaultScope,disableIdTokenSignIn:!!n.disableIdTokenSignIn,disableImplicitSignUp:n.disableImplicitSignUp,disableSignUp:n.disableSignUp,getUserInfo:!!n.getUserInfo,overrideUserInfoOnSignIn:!!n.overrideUserInfoOnSignIn,prompt:n.prompt,verifyIdToken:!!n.verifyIdToken,scope:n.scope,refreshAccessToken:!!n.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function uZ(e){let t=await sJ("SHA-256").digest(e);return sP.encode(t)}async function uG(){if(n)return n;try{let e=process.cwd();if(!e)return;let t=await uW.default.readFile(uF.default.join(e,"package.json"),"utf-8");return n=JSON.parse(t)}catch{}}async function uQ(e){if(n)return n.dependencies?.[e]||n.devDependencies?.[e]||n.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=uF.default.join(t,"node_modules",e,"package.json"),n=await uW.default.readFile(r,"utf-8");return JSON.parse(n).version||await uY(e)||void 0}catch{}return uY(e)}async function uY(e){let t=await uG();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function uX(){return(await uG())?.name}async function u0(){try{let e,t,r=uq.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":t("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":t("NETLIFY","NETLIFY_URL")?"netlify":t("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":t("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":t("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":t("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":t("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":t("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":t("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":t("DYNO","HEROKU_APP_NAME")?"heroku":t("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":t("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:uq.default.platform(),systemRelease:uq.default.release(),systemArchitecture:uq.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:uq.default.totalmem(),isWSL:await u4(),isDocker:await u6(),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 u1(){try{return uK.default.statSync("/.dockerenv"),!0}catch{return!1}}async function u2(){try{return uK.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function u6(){return void 0===i&&(i=await u1()||await u2()),i}let u5=async()=>{try{return uK.default.statSync("/run/.containerenv"),!0}catch{return!1}};async function u8(){return void 0===a&&(a=await u5()||await u6()),a}async function u4(){try{if(uq.default.release().toLowerCase().includes("microsoft")){if(await u8())return!1;return!0}return!!uK.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!await u8()}catch{return!1}}let u3=null;async function u9(e){if(u3)return u3;let t=await uX();return t?u3=await uZ(e?e+t:t):e?u3=await uZ(e):u3=(0,lL.createRandomStringGenerator)("a-z","A-Z","0-9")(32)}async function u7(){for(let[e,t]of Object.entries({pg:"postgresql",mysql:"mysql",mariadb:"mariadb",sqlite3:"sqlite","better-sqlite3":"sqlite","@prisma/client":"prisma",mongoose:"mongodb",mongodb:"mongodb","drizzle-orm":"drizzle"})){let r=await uQ(e);if(r)return{name:t,version:r}}}async function pe(){for(let[e,t]of Object.entries({next:"next",nuxt:"nuxt","react-router":"react-router",astro:"astro","@sveltejs/kit":"sveltekit","solid-start":"solid-start","tanstack-start":"tanstack-start",hono:"hono",express:"express",elysia:"elysia",expo:"expo"})){let r=await uQ(e);if(r)return{name:t,version:r}}}let pt=async function(){};async function pr(e,t){let r,n=e.telemetry?.debug||(0,S.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY_DEBUG",!1),i=S.ENV.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!i&&!t?.customTrack)return{publish:pt};let a=async e=>{t?.customTrack?await t.customTrack(e).catch(g.logger.error):i&&(n?g.logger.info("telemetry event",JSON.stringify(e,null,2)):await dq(i,{method:"POST",body:e}).catch(g.logger.error))},o=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,S.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,S.isTest)())},s=await o();return s&&(r=await u9("string"==typeof e.baseURL?e.baseURL:void 0),a({type:"init",payload:{config:await uJ(e,t),runtime:"u">typeof Deno?{name:"deno",version:Deno?.version?.deno??null}:"u">typeof Bun?{name:"bun",version:Bun?.version??null}:"u">typeof process&&process?.versions?.node?{name:"node",version:process.versions.node??null}:{name:"edge",version:null},database:await u7(),framework:await pe(),environment:"production"===(0,S.getEnvVar)("NODE_ENV")?"production":"false"!==S.env.CI&&("BUILD_ID"in S.env||"BUILD_NUMBER"in S.env||"CI"in S.env||"CI_APP_ID"in S.env||"CI_BUILD_ID"in S.env||"CI_BUILD_NUMBER"in S.env||"CI_NAME"in S.env||"CONTINUOUS_INTEGRATION"in S.env||"RUN_ID"in S.env)?"ci":(0,S.isTest)()?"test":"development",systemInfo:await u0(),packageManager:function(){let e=S.env.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),n=t.substring(0,r);return{name:"npminstall"===n?"cnpm":n,version:t.substring(r+1)}}()},anonymousId:r})),{publish:async t=>{s&&(r||(r=await u9("string"==typeof e.baseURL?e.baseURL:void 0)),await a({type:t.type,payload:t.payload,anonymousId:r}))}}}async function pn(e,t,r){let n,i,a,o;t.database||(t=cf(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}},account:{storeStateStrategy:"cookie",storeAccountCookie:!0}}));let s=t.plugins||[],c=(h=t,h.advanced?.crossSubDomainCookies?.enabled,[]),l=(0,g.createLogger)(t.logger),d=O(t.baseURL);if(O(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new b.BetterAuthError('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let u=d?void 0:I("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);u||d||l.warn("[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&l.error(`[better-auth] Misconfiguration detected.
|
|
412
|
-
You are using the memory DB with generateId: false.
|
|
413
|
-
This will cause no id to be generated for any model.
|
|
414
|
-
Most of the features of Better Auth will not work correctly.`);let p=t.secrets??((m=S.env.BETTER_AUTH_SECRETS)?m.split(",").map(e=>{let t=(e=e.trim()).indexOf(":");if(-1===t)throw new b.BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let r=parseInt(e.slice(0,t),10);if(!Number.isInteger(r)||r<0)throw new b.BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let n=e.slice(t+1).trim();if(!n)throw new b.BetterAuthError(`Empty secret value for version ${r} in BETTER_AUTH_SECRETS.`);return{version:r,value:n}}):null),f=t.secret||S.env.BETTER_AUTH_SECRET||S.env.AUTH_SECRET||"";if(p)!function(e,t){var r;let n;if(0===e.length)throw new b.BetterAuthError("`secrets` array must contain at least one entry.");let i=new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new b.BetterAuthError(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new b.BetterAuthError(`Empty secret value for version ${e} in \`secrets\`.`);if(i.has(e))throw new b.BetterAuthError(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);i.add(e)}let a=e[0];a.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${a.version}) should be at least 32 characters long for adequate security.`),120>(0===(n=new Set(r=a.value).size)?0:Math.log2(Math.pow(n,r.length)))&&t.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(p,l),n=p[0].value,i=function(e,t){let r=new Map;for(let t of e)r.set(parseInt(String(t.version),10),t.value);return{keys:r,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&"better-auth-secret-12345678901234567890"!==t?t:void 0}}(p,f);else{var h,m,w=n=f||"better-auth-secret-12345678901234567890";let e="better-auth-secret-12345678901234567890"===w;if(!(0,S.isTest)()){let t;if(e&&S.isProduction)throw new b.BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!w)throw new b.BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");w.length<32&&l.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),120>(0===(t=new Set(w).size)?0:Math.log2(Math.pow(t,w.length)))&&l.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}i=n}!function(e,t){let r=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,n]of Object.entries(e.endpoints))if(n&&"path"in n&&"string"==typeof n.path){let i=n.path,a=[];n.options&&"method"in n.options&&(Array.isArray(n.options.method)?a=n.options.method:"string"==typeof n.options.method&&(a=[n.options.method])),0===a.length&&(a=["*"]),r.has(i)||r.set(i,[]),r.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let n=[];for(let[e,t]of r.entries())if(t.length>1){let r=new Map,i=!1;for(let e of t)for(let n of e.methods)r.has(n)||r.set(n,[]),r.get(n).push(e.pluginId),r.get(n).length>1&&(i=!0),"*"===n&&t.length>1?i=!0:"*"!==n&&r.has("*")&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,n]of r.entries())(n.length>1||"*"===e&&t.length>1||"*"!==e&&r.has("*"))&&a.push(e);n.push({path:e,plugins:i,conflictingMethods:a})}}if(n.length>0){let e=n.map(e=>` - "${e.path}" [${e.conflictingMethods.join(", ")}] used by plugins: ${e.plugins.join(", ")}`).join("\n");t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
415
|
-
${e}
|
|
416
|
-
|
|
417
|
-
To resolve this, you can:
|
|
418
|
-
1. Use only one of the conflicting plugins
|
|
419
|
-
2. Configure the plugins to use different paths (if supported)
|
|
420
|
-
3. Ensure plugins use different HTTP methods for the same path
|
|
421
|
-
`)}}(t={...t,secret:n,baseURL:d?t.baseURL:u?new URL(u).origin:"",basePath:t.basePath||"/api/auth",plugins:s.concat(c)},l);let A=sj(t),E=(0,y.getAuthTables)(t),v=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let r="function"==typeof t?await t():t;if(null==r||!1===r.enabled)return null;r.clientId||l.warn(`Social provider ${e} is missing clientId or clientSecret`);let n=ui[e](r);return n.disableImplicitSignUp=r.disableImplicitSignUp,n}))).filter(e=>null!==e),k=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let n=t?.advanced?.database?.generateId;return"function"==typeof n?n({model:e,size:r}):"uuid"===n?crypto.randomUUID():"serial"!==n&&!1!==n&&(0,cc.generateId)(r)},{publish:_}=await pr(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),x=new Set(t.plugins.map(e=>e.id)),T=await cE(t),R=await cS(t),U={appName:t.appName||"Better Auth",baseURL:u||"",version:s2().version,socialProviders:v,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(t.database?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:E,trustedOrigins:T,trustedProviders:R,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>D(e,r,t))},sessionConfig:{updateAge:t.session?.updateAge!==void 0?t.session.updateAge:86400,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(a=t.session?.cookieCache?.refreshCache,o=t.session?.cookieCache?.maxAge||300,(t.database||t.secondaryStorage)&&a?(l.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==a&&void 0!==a&&(!0===a?{enabled:!0,updateAge:Math.floor(.2*o)}:{enabled:!0,updateAge:void 0!==a.updateAge?a.updateAge:Math.floor(.2*o)}))},secret:n,secretConfig:i,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??S.isProduction,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:A,logger:l,generateId:k,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||N,verify:t.emailAndPassword?.password?.verify||H,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:cT},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:cd(e,{options:t,logger:l,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:k}),createAuthCookie:sN(t),async runMigrations(){throw new b.BetterAuthError("runMigrations will be set by the specific init implementation")},publishTelemetry:_,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,S.isTest)(),runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{l.error("Failed to run background task:",e)})):await e}catch(e){l.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>x.has(e)},P=cA(U);return L(P)&&await P,U}var pi=e.i(877727);let pa=async e=>{let t=await A(e),r=await pn(t,e,e=>(0,pi.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new b.BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await (0,E.getMigrations)(e);await t()},r};e.s(["betterAuth",0,e=>((e,t)=>{let r=t(e),{api:n}=uM(r,e);return{handler:async t=>{let n,i=await r,a=i.options.basePath||"/api/auth";if(O(e.baseURL))n=await ck(i,t,cv(i.options));else{if(n=i,!i.options.baseURL){let e=I(void 0,a,t,void 0,i.options.advanced?.trustedProxyHeaders);if(e)i.baseURL=e,i.options.baseURL=U(i.baseURL)||void 0;else throw new b.BetterAuthError("Could not get base URL from request. Please provide a valid base URL.")}n.trustedOrigins=await cE(i.options,t),n.trustedProviders=await cS(i.options,t)}let{handler:o}=((e,t)=>{let{api:r,middlewares:n}=uM(e,t),i=new URL(e.baseURL).pathname;return((e,t)=>{if(!t?.openapi?.disabled){let r={path:"/api/reference",...t?.openapi};e.openapi=cJ(r.path,{method:"GET"},async t=>{let n,i;return new Response((n=await c0(e),i=r.scalar,`<!doctype html>
|
|
422
|
-
<html>
|
|
423
|
-
<head>
|
|
424
|
-
<title>Scalar API Reference</title>
|
|
425
|
-
<meta charset="utf-8" />
|
|
426
|
-
<meta
|
|
427
|
-
name="viewport"
|
|
428
|
-
content="width=device-width, initial-scale=1" />
|
|
429
|
-
</head>
|
|
430
|
-
<body>
|
|
431
|
-
<script
|
|
432
|
-
id="api-reference"
|
|
433
|
-
type="application/json">
|
|
434
|
-
${JSON.stringify(n)}
|
|
435
|
-
</script>
|
|
436
|
-
<script>
|
|
437
|
-
var configuration = {
|
|
438
|
-
favicon: ${i?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(i.logo)}`:void 0} ,
|
|
439
|
-
theme: ${i?.theme||"saturn"},
|
|
440
|
-
metaData: {
|
|
441
|
-
title: ${i?.title||"Open API Reference"},
|
|
442
|
-
description: ${i?.description||"Better Call Open API"},
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
document.getElementById('api-reference').dataset.configuration =
|
|
446
|
-
JSON.stringify(configuration)
|
|
447
|
-
</script>
|
|
448
|
-
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
449
|
-
</body>
|
|
450
|
-
</html>`),{headers:{"Content-Type":"text/html"}})})}let r=c2(),n=c2();for(let t of Object.values(e))if(!(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY))for(let e of Array.isArray(t.options?.method)?t.options.method:[t.options?.method])c8(r,e,t.path,t);if(t?.routerMiddleware?.length)for(let{path:e,middleware:r}of t.routerMiddleware)c8(n,"*",e,r);let i=async e=>{let i=new URL(e.url),a=i.pathname,o=t?.basePath&&"/"!==t.basePath?a.split(t.basePath).reduce((e,r,n)=>(0!==n&&(n>1?e.push(`${t.basePath}${r}`):e.push(r)),e),[]).join(""):i.pathname;if(!o?.length||/\/{2,}/.test(o))return new Response(null,{status:404,statusText:"Not Found"});let s=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=e.static[r];if(n&&n.methods){let e=n.methods[t]||n.methods[""];if(void 0!==e)return e[0]}let i=c6(r),a=function e(t,r,n,i,a){if(a===i.length){if(r.methods){let e=r.methods[n]||r.methods[""];if(e)return e}if(r.param&&r.param.methods){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}return}let o=i[a];if(r.static){let s=r.static[o];if(s){let r=e(t,s,n,i,a+1);if(r)return r}}if(r.param){let s=e(t,r.param,n,i,a+1);if(s){if(r.param.hasRegexParam){let e=s.find(e=>e.paramsRegexp[a]?.test(o))||s.find(e=>!e.paramsRegexp[a]);return e?[e]:void 0}return s}}if(r.wildcard&&r.wildcard.methods)return r.wildcard.methods[n]||r.wildcard.methods[""]}(e,e.root,t,i,0)?.[0];if(void 0!==a)return{data:a.data,params:a.paramsMap?c5(i,a.paramsMap):void 0}}(r,e.method,o);if(o.endsWith("/")!==s?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes||!s?.data)return new Response(null,{status:404,statusText:"Not Found"});let c={};i.searchParams.forEach((e,t)=>{t in c?Array.isArray(c[t])?c[t].push(e):c[t]=[c[t],e]:c[t]=e});let l=s.data;try{let r=l.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:o,method:e.method,headers:e.headers,params:s.params?JSON.parse(JSON.stringify(s.params)):{},request:e,body:l.options.disableBody?void 0:await cU(l.options.cloneRequest?e.clone():e,r),query:c,_flag:"router",asResponse:!0,context:t?.routerContext},a=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=c6(r);return(function e(t,r,n,i,a,o=[]){let s=i[a];if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];e&&o.push(...e)}if(r.param&&(e(t,r.param,n,i,a+1,o),a===i.length&&r.param.methods)){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;t?.[t?.length-1]?.[2]&&o.push(...e)}}let c=r.static?.[s];if(c&&e(t,c,n,i,a+1,o),a===i.length&&r.methods){let e=r.methods[n]||r.methods[""];e&&o.push(...e)}return o})(e,e.root,t,n,0).map(e=>({data:e.data,params:e.paramsMap?c5(n,e.paramsMap):void 0}))}(n,"*",o);if(a?.length)for(let{data:e,params:t}of a){let r=await e({...i,params:t,asResponse:!1});if(r instanceof Response)return r}return await l(i)}catch(r){if(t?.onError)try{let n=await t.onError(r,e);if(n instanceof Response)return cz(n)}catch(e){if(cO(e))return cz(e);throw e}if(t?.throwError)throw r;if(cO(r))return cz(r);return console.error("# SERVER_ERROR: ",r),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async e=>{let r=await t?.onRequest?.(e);if(r instanceof Response)return r;let n=cC(r)?r:e,a=await i(n),o=await t?.onResponse?.(a,n);return o instanceof Response?o:a},endpoints:e}})(r,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:"/**",middleware:la},...n],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],n=lt(t.url,i);if(r.includes(n))return new Response("Not Found",{status:404});let a=t;for(let t of e.options.plugins||[])if(t.onRequest){let r=await (0,cs.withSpan)(`onRequest ${t.id}`,{[ca]:"onRequest",[co]:`plugin:${t.id}`},()=>t.onRequest(a,e));if(r&&"response"in r)return r.response;r&&"request"in r&&(a=r.request)}let o=await lh(a,e);return o||a},async onResponse(t,r){for(let n of(await lm(r,e),e.options.plugins||[]))if(n.onResponse){let r=await (0,cs.withSpan)(`onResponse ${n.id}`,{[ca]:"onResponse",[co]:`plugin:${n.id}`,[cn.ATTR_HTTP_RESPONSE_STATUS_CODE]:t.status},()=>n.onResponse(t,e));if(r)return r.response}return t},onError(r){if(c4(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError)return void t.onAPIError.onError(r,e);let n=t.logger?.level,i="error"===n||"warn"===n||"debug"===n?g.logger:void 0;if(t.logger?.disabled!==!0){if(r&&"object"==typeof r&&"message"in r&&"string"==typeof r.message&&(r.message.includes("no column")||r.message.includes("column")||r.message.includes("relation")||r.message.includes("table")||r.message.includes("does not exist")))return void e.logger?.error(r.message);c4(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),i?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(n,e);return s3(n.adapter,()=>o(t))},api:n,options:e,$context:r,$ERROR_CODES:{...e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),...rw.BASE_ERROR_CODES}}})(e,pa)],223741),e.s(["nextCookies",0,()=>{let t=!1;return{id:"next-cookies",version:"1.6.12",hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:c9(async r=>{let n;if(t||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let n=r.findIndex(e=>e.id===t);-1===n||r.slice(n+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${t}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(r.context,"next-cookies"),t=!0),"_flag"in r&&"router"===r._flag)return;try{let{headers:t}=await e.A(84040);n=await t()}catch{return}let i="1"===n.get("RSC"),a=!!n.get("next-action");i&&!a&&await l_(!0)})}],after:[{matcher:e=>!0,handler:c9(async t=>{let r=t.context.responseHeaders;if((!("_flag"in t)||"router"!==t._flag)&&r instanceof Headers){let t,n,i=r?.get("set-cookie");if(!i)return;let a=(n=new Map,rU(i).forEach(e=>{let[t,...r]=e.split(";").map(e=>e.trim()),[i,...a]=(t||"").split("="),o=rC(a.join("="));if(!i)return;let s={value:rI(o)};r.forEach(e=>{let[t,...r]=e.split("="),n=r.join("="),i=t.trim().toLowerCase();switch(i){case"max-age":s["max-age"]=n?parseInt(n.trim(),10):void 0;break;case"expires":s.expires=n?new Date(n.trim()):void 0;break;case"domain":s.domain=n?n.trim():void 0;break;case"path":s.path=n?n.trim():void 0;break;case"secure":s.secure=!0;break;case"httponly":s.httponly=!0;break;case"samesite":s.samesite=n?n.trim().toLowerCase():void 0;break;case"partitioned":s.partitioned=!0;break;default:s[i]=!n||n.trim()}}),n.set(i,s)}),n);try{let{cookies:r}=await e.A(84040);t=await r()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}a.forEach((e,r)=>{if(r)try{t.set(r,e.value,{maxAge:e["max-age"],expires:e.expires,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httponly,sameSite:e.samesite,partitioned:e.partitioned})}catch{}});return}})}]}}},"toNextJsHandler",0,function(e){let t=async t=>"handler"in e?e.handler(t):e(t);return{GET:t,POST:t,PATCH:t,PUT:t,DELETE:t}}],473845)},798003,e=>{"use strict";var t=e.i(912714),r=e.i(660526),n=e.i(750227);function i(){return n.default.join(r.default.homedir(),".wiki-viewer","config.json")}async function a(){await (0,t.mkdir)(n.default.join(r.default.homedir(),".wiki-viewer"),{recursive:!0})}async function o(){try{let e=await (0,t.readFile)(i(),"utf8");return JSON.parse(e)}catch{return{}}}let s=Promise.resolve();function c(e){let t=s.then(e,e);return s=t.then(()=>void 0,()=>void 0),t}async function l(e){await a(),await (0,t.writeFile)(i(),JSON.stringify(e,null,2),"utf8")}async function d(e){return c(async()=>{let t=await o();await l({...t,...e})})}async function u(e){return c(async()=>{let t=e({...await o()});return await l(t),t})}e.s(["readConfig",0,o,"reposDir",0,function(){return n.default.join(r.default.homedir(),".wiki-viewer","repos")},"updateConfig",0,u,"writeConfig",0,d])},254226,860780,e=>{"use strict";let t,r;var n=e.i(223741),i=e.i(473845),a=e.i(286607),o=e.i(750227),s=e.i(660526),c=e.i(902157),l=e.i(666680),d=e.i(478500),u=e.i(798003);function p(e){return(e??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)}async function f(){let e=await (0,u.readConfig)();return{emails:e.allowedEmails&&e.allowedEmails.length>0?e.allowedEmails.map(e=>e.trim().toLowerCase()).filter(Boolean):p(process.env.AUTH_ALLOWED_EMAILS),domains:e.allowedDomains&&e.allowedDomains.length>0?e.allowedDomains.map(e=>e.trim().toLowerCase()).filter(Boolean):p(process.env.AUTH_ALLOWED_DOMAIN)}}async function h(e){let{emails:t,domains:r}=await f();if(0===t.length&&0===r.length)return!0;let n=e.toLowerCase();if(t.includes(n))return!0;let i=n.lastIndexOf("@");return!!(i>=0&&r.includes(n.slice(i+1)))}e.s(["getAllowlist",0,f,"isEmailAllowed",0,h],860780);let m=new d.AsyncLocalStorage;if("phase-production-build"!==process.env.NEXT_PHASE&&"1"!==process.env.WIKI_ALLOW_INSECURE){let e=process.env.BETTER_AUTH_URL??"";if(!e)throw Error("BETTER_AUTH_URL is required in production. Set it to https://your-domain so cookies and OAuth callbacks resolve correctly. Set WIKI_ALLOW_INSECURE=1 to bypass (development only).");if(!e.startsWith("https://"))throw Error(`BETTER_AUTH_URL must be https:// in production (got: ${e}). Set WIKI_ALLOW_INSECURE=1 to bypass (development only).`)}let y=o.default.join(process.env.HOME??s.default.homedir(),".wiki-viewer");(0,c.mkdirSync)(y,{recursive:!0});let g=o.default.join(y,"auth.db"),w=o.default.join(y,"auth.secret"),b=new a.default(g);b.pragma("journal_mode = WAL");let A={};process.env.GOOGLE_CLIENT_ID&&process.env.GOOGLE_CLIENT_SECRET&&(A.google={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET});let E=Object.keys(A).length>0,v="1"===process.env.AUTH_DISABLE_PASSWORD||"true"===process.env.AUTH_DISABLE_PASSWORD,k=!(v&&E);v&&!E&&console.warn("[wiki-viewer] AUTH_DISABLE_PASSWORD is set but no social provider is configured. Keeping email/password enabled so you are not locked out. Configure GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET to disable password auth.");let _=(process.env.AUTH_TRUSTED_PROVIDERS??"").split(",").map(e=>e.trim()).filter(Boolean),S=(0,n.betterAuth)({database:b,secret:function(){if(process.env.BETTER_AUTH_SECRET)return process.env.BETTER_AUTH_SECRET;if((0,c.existsSync)(w))return(0,c.readFileSync)(w,"utf-8").trim();let e=(0,l.randomBytes)(32).toString("base64");(0,c.writeFileSync)(w,e,{mode:384});try{(0,c.chmodSync)(w,384)}catch{}return e}(),baseURL:process.env.BETTER_AUTH_URL,account:{accountLinking:{enabled:!0,..._.length?{trustedProviders:_,requireLocalEmailVerified:!1}:{}}},emailAndPassword:{enabled:k,requireEmailVerification:!1,autoSignIn:!0},rateLimit:{enabled:!0,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:20},"/sign-up/email":{window:60,max:10}}},socialProviders:A,databaseHooks:{user:{create:{before:async e=>{if(!m.getStore()&&!await h(e.email))throw Error("SIGNUP_NOT_ALLOWED");return{data:e}}}}},plugins:[(0,i.nextCookies)()],trustedOrigins:(t=(process.env.WIKI_OWNER_HOSTS??"").split(",").map(e=>e.trim()).filter(Boolean),r=["",":3000",":3003"],Array.from(new Set(["http://localhost:3000","http://localhost:3003",...t.flatMap(e=>r.flatMap(t=>[`http://${e}${t}`,`https://${e}${t}`]))])))}),x=Symbol.for("wiki-viewer.better-auth.migration-promise"),T=globalThis;async function R(e){return S.api.getSession({headers:e.headers})}async function I(e){let t=await R(e);return t?.user?{ok:!0,user:{id:t.user.id,email:t.user.email,name:t.user.name}}:{ok:!1}}T[x]||(T[x]=(async()=>{let t=await e.A(427669),{runMigrations:r}=await t.getMigrations(S.options);await r()})()),e.s(["auth",0,S,"authReady",0,function(){return T[x]??Promise.resolve()},"db",0,b,"getSessionFromRequest",0,R,"passwordAuthEnabled",0,k,"requireUser",0,I,"withAdminUserCreate",0,function(e){return m.run(!0,e)}],254226)}];
|
|
451
|
-
|
|
452
|
-
//# sourceMappingURL=_0dr1r1g._.js.map
|