plaincrew 0.2.0 → 0.2.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/app-build/BUILD_ID +1 -1
- package/app-build/app-path-routes-manifest.json +1 -0
- package/app-build/build-manifest.json +3 -3
- package/app-build/diagnostics/route-bundle-stats.json +18 -18
- package/app-build/fallback-build-manifest.json +3 -3
- package/app-build/routes-manifest.json +8 -0
- package/app-build/server/app/_global-error.html +1 -1
- package/app-build/server/app/_global-error.rsc +1 -1
- package/app-build/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/app-build/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/app-build/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/app-build/server/app/_not-found.html +1 -1
- package/app-build/server/app/_not-found.rsc +1 -1
- package/app-build/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/app-build/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/app-build/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/app-build/server/app/api/account/ai/route.js +2 -2
- package/app-build/server/app/api/account/leaving/route.js +2 -2
- package/app-build/server/app/api/ais/models/route.js +2 -2
- package/app-build/server/app/api/attachments/route.js +2 -2
- package/app-build/server/app/api/auth/[...all]/route.js +2 -2
- package/app-build/server/app/api/cloud/enter/route.js +2 -2
- package/app-build/server/app/api/connect/[code]/approve/route.js +2 -2
- package/app-build/server/app/api/inngest/route.js +2 -2
- package/app-build/server/app/api/organization/route.js +2 -2
- package/app-build/server/app/api/projects/[id]/base/route.js +2 -2
- package/app-build/server/app/api/projects/[id]/github/route.js +11 -12
- package/app-build/server/app/api/projects/[id]/notes/[noteId]/route.js +2 -2
- package/app-build/server/app/api/projects/[id]/notes/route.js +2 -2
- package/app-build/server/app/api/projects/[id]/route.js +2 -2
- package/app-build/server/app/api/projects/[id]/site/route.js +2 -2
- package/app-build/server/app/api/projects/analyze/route.js +2 -2
- package/app-build/server/app/api/projects/route.js +2 -2
- package/app-build/server/app/api/projects/scratch/route.js +3 -3
- package/app-build/server/app/api/runs/[runId]/blocks/[blockId]/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/branch-name/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/cancel/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/connect-github/route.js +11 -12
- package/app-build/server/app/api/runs/[runId]/decision/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/delivery/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/events/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/failure/explain/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/failure/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/findings/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/follow-up/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/plan/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/preview/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/prompts/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/questions/[questionId]/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/review/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/ship/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/snapshots/[shot]/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/snapshots/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/throw-away/route/app-paths-manifest.json +3 -0
- package/app-build/server/app/api/runs/[runId]/throw-away/route/build-manifest.json +12 -0
- package/app-build/server/app/api/runs/[runId]/throw-away/route/server-reference-manifest.json +4 -0
- package/app-build/server/app/api/runs/[runId]/throw-away/route.js +27 -0
- package/app-build/server/app/api/runs/[runId]/throw-away/route_client-reference-manifest.js +3 -0
- package/app-build/server/app/api/runs/[runId]/versions/[n]/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/versions/[n]/site/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/versions/live/route.js +2 -2
- package/app-build/server/app/api/runs/[runId]/versions/route.js +2 -2
- package/app-build/server/app/api/system/choose-folder/route.js +2 -2
- package/app-build/server/app/api/workflows/[id]/draft/route.js +2 -2
- package/app-build/server/app/api/workflows/[id]/publish/route.js +2 -2
- package/app-build/server/app/api/workflows/[id]/runs/route.js +2 -2
- package/app-build/server/app/canvas/[workflowId]/page.js +2 -2
- package/app-build/server/app/canvas/[workflowId]/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/connect/page.js +2 -2
- package/app-build/server/app/connect/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/invite/[id]/page.js +2 -2
- package/app-build/server/app/invite/[id]/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/organization/new/page.js +2 -2
- package/app-build/server/app/organization/new/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/page.js +2 -2
- package/app-build/server/app/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/sign-in/page.js +2 -2
- package/app-build/server/app/sign-in/page_client-reference-manifest.js +1 -1
- package/app-build/server/app/sign-up/page.js +2 -2
- package/app-build/server/app/sign-up/page_client-reference-manifest.js +1 -1
- package/app-build/server/app-paths-manifest.json +1 -0
- package/app-build/server/chunks/1oeh_server_app_api_runs_[runId]_throw-away_route_actions_1a19gfw3nf1x2.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__09mx4_ihytiv9._.js → [root-of-the-server]__0-rma_dhn0mrx._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0qzwj14rh2ym2._.js → [root-of-the-server]__00222l-7v_pw1._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0-hf81cjc9miq._.js → [root-of-the-server]__01yfk7-22rke8._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__111rn2m71ahq1._.js → [root-of-the-server]__077j6jvkmfen-._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0j9vey56ni96j._.js → [root-of-the-server]__07u87ai27nhgy._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__0_use5ykfraw7._.js +11 -11
- package/app-build/server/chunks/{[root-of-the-server]__11vhj0obteagu._.js → [root-of-the-server]__0bwl79z8x10tg._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__1fg-66qrs9vmd._.js → [root-of-the-server]__0frjchnam0z0j._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__20oqzfu0t4513._.js → [root-of-the-server]__0h5zi4_dsk0d-._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__04bfm6aam99jr._.js → [root-of-the-server]__0k9ljvlsra_ty._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0drcpac0a5hru._.js → [root-of-the-server]__0o_g6qunr-flu._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__16_r5tdw4ji2s._.js → [root-of-the-server]__0pom1ni7il-px._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0hryxb3l1_c-b._.js → [root-of-the-server]__0pws17pv2c29c._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0d4dt0ywt1ow0._.js → [root-of-the-server]__0qjq8c0jw-mdw._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__1jwagne56rhyq._.js → [root-of-the-server]__0rw7-w7ggzp9w._.js} +2 -2
- package/app-build/server/chunks/[root-of-the-server]__0v0z73--8rq51._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__0w_5-09zlziz9._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__0ww92n3isnzm2._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__0xtbjsk_8ab4j._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__0j-5-xlcodeao._.js → [root-of-the-server]__0zxb48z34gqs1._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0fer144qqb0_6._.js → [root-of-the-server]__10o1v6vzm-1vx._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__1m9ci-2fhznpr._.js → [root-of-the-server]__13aehgyzs9lbd._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__15witsrnyg3dd._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__1a17c0kjajkbe._.js → [root-of-the-server]__17m5okwlzsyl1._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__0_wicg5sueifn._.js → [root-of-the-server]__17x6k6pitzk_5._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__18der_neib1_t._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__18hx5fasl2mue._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__1no1kg2v5558v._.js → [root-of-the-server]__18sbr3uygawkb._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__19vu74udpbi3u._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1a1-7v9-7r7z3._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1a87dgnjgqot2._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1ae3yidgvaczf._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1aje8j3jhgce_._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1aw9yt_bvxa4y._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__1j82aseh7oyg8._.js → [root-of-the-server]__1dg18go136mg2._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__083kealcx1eos._.js → [root-of-the-server]__1h4ao1cxtu9ct._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__1hynzq99iy2jv._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1hz3h385ra2_h._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1j1gi9vgjem2s._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1lb4spfx1cufp._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__01_h69z_7y8hj._.js → [root-of-the-server]__1m7zmx0c3d29a._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__1dx64weifqusv._.js → [root-of-the-server]__1mgzlhbtfm2s2._.js} +1 -1
- package/app-build/server/chunks/{[root-of-the-server]__04fo6q9-bmsqf._.js → [root-of-the-server]__1qrhu-f3_okvy._.js} +1 -1
- package/app-build/server/chunks/[root-of-the-server]__1sxtsguf6-rqn._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1uaaw183mgxvp._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__1vz7pyxbcxdam._.js +3 -0
- package/app-build/server/chunks/[root-of-the-server]__203b0tgsx02nt._.js +3 -0
- package/app-build/server/chunks/{[root-of-the-server]__1_67_outgzgho._.js → [root-of-the-server]__20u3cxne2g634._.js} +1 -1
- package/app-build/server/chunks/_0-spos-0d2krg._.js +19 -0
- package/app-build/server/chunks/_00_jnbz1zvwgx._.js +19 -0
- package/app-build/server/chunks/_00nvlapuy-n5u._.js +19 -0
- package/app-build/server/chunks/_02ydx-6i02-15._.js +19 -0
- package/app-build/server/chunks/_09ejh1dyvkto7._.js +1 -1
- package/app-build/server/chunks/_0acmw0tv499h0._.js +19 -0
- package/app-build/server/chunks/_0aw98t7vmjb88._.js +19 -0
- package/app-build/server/chunks/_0b2ridyy82jxe._.js +1 -1
- package/app-build/server/chunks/_0bhd3724mk5_8._.js +19 -0
- package/app-build/server/chunks/_0bsptjrzcu8a7._.js +19 -0
- package/app-build/server/chunks/_0d-t3ot63p6q4._.js +19 -0
- package/app-build/server/chunks/_0e2pq-eirvzjq._.js +1 -1
- package/app-build/server/chunks/_0et5mjk8ma941._.js +1 -1
- package/app-build/server/chunks/_0ety_xj8s9se5._.js +19 -0
- package/app-build/server/chunks/_0fbwelpje0vpp._.js +19 -0
- package/app-build/server/chunks/_0ipkjlo50tvzh._.js +19 -0
- package/app-build/server/chunks/_0j8and6kle-vr._.js +19 -0
- package/app-build/server/chunks/_0l56fyw-2mdap._.js +19 -0
- package/app-build/server/chunks/_0o-zfrg3y0fq7._.js +19 -0
- package/app-build/server/chunks/_0oh4tv1yn6ko-._.js +19 -0
- package/app-build/server/chunks/_0prtq3d1e3y27._.js +1 -1
- package/app-build/server/chunks/_0qgouuuv9x557._.js +19 -0
- package/app-build/server/chunks/_0r2znajb4c33_._.js +19 -0
- package/app-build/server/chunks/_0r7go8jj5dc5t._.js +4 -0
- package/app-build/server/chunks/_0uer66e27_rqy._.js +1 -1
- package/app-build/server/chunks/_0w3v4t4p9vsb-._.js +11 -11
- package/app-build/server/chunks/_0wi30r5c4hlyh._.js +19 -0
- package/app-build/server/chunks/_0yi75njq4zxzw._.js +2 -2
- package/app-build/server/chunks/_0yxx6fkquhd5h._.js +19 -0
- package/app-build/server/chunks/_1-l-baxl7r6o-._.js +19 -0
- package/app-build/server/chunks/_1-piaouq4au1v._.js +1 -1
- package/app-build/server/chunks/_12v43tznpol4u._.js +1 -1
- package/app-build/server/chunks/_153o0hrf0g3mk._.js +19 -0
- package/app-build/server/chunks/_155fw3g6f3-4h._.js +19 -0
- package/app-build/server/chunks/_19_0wmfnwvz9o._.js +1 -1
- package/app-build/server/chunks/_19q1zxel7pllh._.js +1 -1
- package/app-build/server/chunks/_1_mlvky6w1ov8._.js +19 -0
- package/app-build/server/chunks/_1bf1pcq2wtg91._.js +1 -1
- package/app-build/server/chunks/_1cq7469bqdm3u._.js +1 -1
- package/app-build/server/chunks/_1f610h-qim306._.js +19 -0
- package/app-build/server/chunks/_1h24vpftu-w_x._.js +19 -0
- package/app-build/server/chunks/_1hhnlf5x-a4y4._.js +19 -0
- package/app-build/server/chunks/_1nx8fwgx5ca29._.js +19 -0
- package/app-build/server/chunks/_1ob-6ym8mt48u._.js +1 -1
- package/app-build/server/chunks/_1uwtj6yrwszfe._.js +1 -1
- package/app-build/server/chunks/_1vb0vvvhh6nh7._.js +1 -1
- package/app-build/server/chunks/_1vfxvrhfw43y_._.js +3 -0
- package/app-build/server/chunks/_1w-v2i1f-t_3x._.js +19 -0
- package/app-build/server/chunks/_1wau1ee-6k-7o._.js +11 -11
- package/app-build/server/chunks/_1yho6hc7s0457._.js +11 -11
- package/app-build/server/chunks/_1zn_x1pv0cr9q._.js +19 -0
- package/app-build/server/chunks/src_1mb1qcardcu_6._.js +1 -1
- package/app-build/server/chunks/src_engine_ship_ts_1-sbwwj6ig7jv._.js +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__02fcbpwktzl0e._.js → [root-of-the-server]__0oas93cn5j9ig._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__1cu7ckiad_t58._.js → [root-of-the-server]__0xan19-2pz7sa._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__1ik_gvdjzwan6._.js → [root-of-the-server]__12-_-lnji2wdx._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__06kehcks298uq._.js → [root-of-the-server]__1flxwowggjg0y._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__0mpgsl517i3-0._.js → [root-of-the-server]__1g-692s4zsw6v._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__0ayx2k8e4n7yj._.js → [root-of-the-server]__1wvi-5c59hvhk._.js} +1 -1
- package/app-build/server/chunks/ssr/{[root-of-the-server]__07qbaxjilfrhb._.js → [root-of-the-server]__1xfbap5otqs7y._.js} +1 -1
- package/app-build/server/chunks/ssr/{_0plc10a4e_g26._.js → _0au36lf3n46hl._.js} +2 -2
- package/app-build/server/chunks/ssr/_14z-y2hqpv20w._.js +2 -2
- package/app-build/server/chunks/ssr/{_0vqiqfwum1eeq._.js → _1heqye3wc0a3t._.js} +2 -2
- package/app-build/server/chunks/ssr/{_15rry-mn1ylod._.js → _1mesxn8ux7m-b._.js} +2 -2
- package/app-build/server/chunks/ssr/{_1stfnmis3lpoq._.js → _1tl5r54a78aca._.js} +2 -2
- package/app-build/server/chunks/ssr/_212xzvdrw1r-3._.js +498 -0
- package/app-build/server/chunks/ssr/src_ui_0a7papum2y8_i._.js +1 -1
- package/app-build/server/chunks/ssr/src_ui_0dybjq718frlj._.js +1 -1
- package/app-build/server/chunks/ssr/src_ui_1lk_5nzn_qoqs._.js +1 -1
- package/app-build/server/chunks/ssr/src_ui_1pd2_lbqeputa._.js +1 -1
- package/app-build/server/chunks/ssr/src_ui_strings_ts_1es3352ykktl1._.js +1 -1
- package/app-build/server/middleware-build-manifest.js +3 -3
- package/app-build/server/pages/404.html +1 -1
- package/app-build/server/pages/500.html +1 -1
- package/app-build/static/chunks/13qqhom208k1g.js +5 -0
- package/app-build/static/chunks/2z0spwjyeqvjq.js +1 -0
- package/app-build/static/chunks/3sj18n0bki38_.js +1 -0
- package/app-build/trace-build +1 -1
- package/package.json +1 -1
- package/app-build/server/chunks/[root-of-the-server]__0o-3c4wjexyir._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0qwqrlb3b7i0y._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0qzb976d_qj48._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0rwo4zg_leice._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0tt48asd4bq_v._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0x8sjs-qr0fi-._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__0z7e3um13c2p0._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__11-p_3onzgf2e._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__15p8ahu4ip30q._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__16023he7o7zot._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__17z8-upkyjz-v._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1_2bvyen56qja._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1bbm3yv2mh0ob._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1ehsotx9v9v0-._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1ghp4gx3vslm5._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1irx63ehwr_32._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1n1otzmcc-pl-._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1rq-k_585r2e9._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1su62l6u2edkj._.js +0 -3
- package/app-build/server/chunks/[root-of-the-server]__1xodvnju6iwx3._.js +0 -3
- package/app-build/server/chunks/_04ipxobgytrai._.js +0 -19
- package/app-build/server/chunks/_06_bsixuw5t32._.js +0 -19
- package/app-build/server/chunks/_0_6-kjk5l5ckf._.js +0 -19
- package/app-build/server/chunks/_0_q5vorhn2m7p._.js +0 -19
- package/app-build/server/chunks/_0b15uwzi-_wuu._.js +0 -19
- package/app-build/server/chunks/_0fx9tvayvawom._.js +0 -19
- package/app-build/server/chunks/_0hfgolst82fo-._.js +0 -19
- package/app-build/server/chunks/_0mvcmkm58awy6._.js +0 -19
- package/app-build/server/chunks/_0p2av7ih_dhj4._.js +0 -19
- package/app-build/server/chunks/_0rnf-n0hrw3r0._.js +0 -19
- package/app-build/server/chunks/_0sqpau27sb7i_._.js +0 -19
- package/app-build/server/chunks/_0wuc81q3tth-g._.js +0 -19
- package/app-build/server/chunks/_0x2g7uj3hbyqa._.js +0 -19
- package/app-build/server/chunks/_1-bgcffz4bjus._.js +0 -19
- package/app-build/server/chunks/_1-yeinb4sdagg._.js +0 -19
- package/app-build/server/chunks/_108rver1pgqw-._.js +0 -19
- package/app-build/server/chunks/_13lb7kts14z5a._.js +0 -3
- package/app-build/server/chunks/_143_tdoh-o8r2._.js +0 -19
- package/app-build/server/chunks/_146_--s-6f_o-._.js +0 -19
- package/app-build/server/chunks/_190n79a8itd96._.js +0 -19
- package/app-build/server/chunks/_1fq2ezphtpgk3._.js +0 -19
- package/app-build/server/chunks/_1fv67kzffpbb_._.js +0 -19
- package/app-build/server/chunks/_1k79cnpkap3g1._.js +0 -19
- package/app-build/server/chunks/_1kwxo3qf7dky_._.js +0 -19
- package/app-build/server/chunks/_1oyjikbasms78._.js +0 -3
- package/app-build/server/chunks/_1p4epxp2kfwl3._.js +0 -19
- package/app-build/server/chunks/_1tqh-hw_2xsox._.js +0 -19
- package/app-build/server/chunks/_1u_phco4tax56._.js +0 -19
- package/app-build/server/chunks/_1unrzazajazmw._.js +0 -19
- package/app-build/server/chunks/_1vmf9gx675--i._.js +0 -19
- package/app-build/server/chunks/_20y-6xht4mb44._.js +0 -19
- package/app-build/server/chunks/ssr/_1uj-3d4t3_f-w._.js +0 -498
- package/app-build/static/chunks/04hu91jpixs3u.js +0 -1
- package/app-build/static/chunks/1wg6_v6094_ev.js +0 -1
- package/app-build/static/chunks/2ku8241h3kja_.js +0 -5
- /package/app-build/static/{r8bYBXboElhyfwYccuAh5 → HAjlyCK72AXHP41NT95Jp}/_buildManifest.js +0 -0
- /package/app-build/static/{r8bYBXboElhyfwYccuAh5 → HAjlyCK72AXHP41NT95Jp}/_clientMiddlewareManifest.js +0 -0
- /package/app-build/static/{r8bYBXboElhyfwYccuAh5 → HAjlyCK72AXHP41NT95Jp}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);var i=e.i(71045),a=e.i(94518),o=e.i(55659);let n={"Cache-Control":"no-store",Pragma:"no-cache"},s=(0,a.f)(async()=>({})),l=a.f.create({use:[s,(0,a.f)(async()=>({}))]}),c=i.f.create({use:[s]});function d(e,i){let a=i.metadata?.noStore===!0;return async i=>{if(a)for(let[e,t]of Object.entries(n))i.setHeader(e,t);try{return await (0,t.a)(i,()=>e(i))}catch(e){var s;throw s=i.responseHeaders,(0,r.f)(e)&&s&&Object.defineProperty(e,o.p,{enumerable:!1,configurable:!0,value:s,writable:!1}),e}}}function u(...e){if(3===e.length){let[t,r,i]=e;return c(t,r,d(i,r))}let[t,r]=e;return c(t,d(r,t))}u.serverOnly=(e,t)=>u({...e,metadata:{...e.metadata,SERVER_ONLY:!0}},t),e.s(["S",0,{scope:"server"},"p",0,n,"g",0,u,"a",0,l,"t",0,s])},95934,e=>{"use strict";let t,r=!1;async function i(){if(t)return t;let e=function(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}();if(e)return t??=e;try{let{AsyncLocalStorage:e}=await import("node:async_hooks");return t??=e}catch(i){let e=globalThis.AsyncLocalStorage;if("function"==typeof e)return t??=e;throw r||(r=!0,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://better-auth.com/docs/guides/cloudflare#nodejs-compatibility")),i}}e.s(["f",0,i])},97515,e=>{"use strict";var t=e.i(14268),r=e.i(95934);let i=async()=>{let e=(0,t.l)().context.endpointContextAsyncStorage;if(e)return e;let i=await (0,r.f)(),a=(0,t.l)().context;return a.endpointContextAsyncStorage??=new i};function a(){return(0,t.a)()}async function o(e,t){return(await i()).run(e,t)}e.s(["g",0,function(){let e=a();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e},"a",0,o,"G",0,a])},86198,96101,44336,30273,71045,94518,86097,18069,e=>{"use strict";let t;var r=e.i(71616),i=e.i(55659);function a(){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")}e.s(["f",0,a],96101);let o={name:"HMAC",hash:"SHA-256"},n=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await a().importKey("raw",t,o,!1,["sign","verify"])},s=async(e,t,r)=>{try{let i=atob(e),n=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)n[e]=i.charCodeAt(e);return await a().verify(o,r,n,new TextEncoder().encode(t))}catch{return!1}},l=async(e,t)=>{let r=await n(t);return btoa(String.fromCharCode(...new Uint8Array(await a().sign(o.name,r,new TextEncoder().encode(e)))))},c=async(e,t)=>{let r=await l(e,t);return encodeURIComponent(e=`${e}.${r}`)},d=/^application\/([a-z0-9.+-]*\+)?json/i;async function u(e,t){let r=e.headers.get("content-type")||"",a=r.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>a.split(";")[0].trim()===e.toLowerCase().trim())){if(!a)throw new i.E(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new i.E(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(d.test(a))try{return await e.json()}catch(e){if(e instanceof SyntaxError)throw new i.E(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw e}if(a.includes("application/x-www-form-urlencoded")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e.toString()}),r}if(a.includes("multipart/form-data")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e}),r}return a.includes("text/plain")?await e.text():a.includes("application/octet-stream")?await e.arrayBuffer():a.includes("application/pdf")||a.includes("image/")||a.includes("video/")?await e.blob():a.includes("application/stream")||e.body instanceof ReadableStream?e.body:await e.text()}}function f(e){return e instanceof i.E||e?.name==="APIError"}async function p(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function m(e){return e instanceof Request||"[object Request]"===Object.prototype.toString.call(e)}let h={secure:"__Secure-",host:"__Host-"},g=(e,t)=>t?"secure"===t||"host"===t?h[t]+e:void 0:e;function y(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let i=e.indexOf("=",r);if(-1===i)break;let a=e.indexOf(";",r);if(-1===a)a=e.length;else if(a<i){r=e.lastIndexOf(";",i-1)+1;continue}let o=e.slice(r,i).trim();if(!t.has(o)){let r=e.slice(i+1,a).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(o,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=a+1}return t}function w(e,t,r={}){let i=g(e,r.prefix)??e,a={...r},o=i.toLowerCase();return o.startsWith("__host-")?(a.secure=!0,a.path="/",a.domain=void 0):o.startsWith("__secure-")&&(a.secure=!0),(!0===a.partitioned||a.sameSite?.toLowerCase()==="none")&&(a.secure=!0),{name:i,value:t,options:a}}function b({name:e,value:t,options:r}){let i=`${e}=${t}`;if("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.");i+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&(i+=`; Domain=${r.domain}`),r.path&&(i+=`; 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.");i+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.sameSite&&(i+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(i+="; Partitioned"),i}let E=(e,t,r)=>b(w(e,t=encodeURIComponent(t),r)),A=async(e,t,r,i)=>b(w(e,t=await c(t,r),i));async function I(e,t={}){let r={body:t.body,query:t.query};if(e.body){let i=await e.body["~standard"].validate(t.body);if(i.issues)return{data:null,error:T(i.issues,"body")};r.body=i.value}if(e.query){let i=await e.query["~standard"].validate(t.query);if(i.issues)return{data:null,error:T(i.issues,"query")};r.query=i.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 T(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}}e.s(["K",0,g,"X",0,y,"j",0,E,"k",0,A],44336);let _=async(e,{options:t,path:r})=>{let a,o=new Headers,{data:l,error:c}=await I(t,e);if(c)throw new i.a(c.message,c.issues);let d=void 0!==e.headers?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&m(e.request)?e.request.headers:null,u=d?.get("cookie"),f=u?y(u):void 0,p={...e,body:l.body,query:l.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)=>{o.set(e,t)},getHeader:e=>d?d.get(e):null,getCookie:(e,t)=>{let r=g(e,t);return r&&f?.get(r)||null},getSignedCookie:async(e,t,r)=>{let i=g(e,r);if(!i)return null;let a=f?.get(i);if(!a)return null;let o=a.lastIndexOf(".");if(o<1)return null;let l=a.substring(0,o),c=a.substring(o+1);return 44===c.length&&c.endsWith("=")?!!await s(c,l,await n(t))&&l:null},setCookie:(e,t,r)=>{let i=E(e,t,r);return o.append("set-cookie",i),i},setSignedCookie:async(e,t,r,i)=>{let a=await A(e,t,r,i);return o.append("set-cookie",a),a},redirect:e=>(o.set("location",e),new i.E("FOUND",void 0,o)),error:(e,t,r)=>new i.E(e,t,r),setStatus:e=>{a=e},json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:o,get responseStatus(){return a}};for(let e of t.use||[]){let t=await e({...p,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(p.context,t.response),t.headers&&t.headers.forEach((e,t)=>{p.responseHeaders.set(t,e)})}return p},v=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 O(e){for(let t of v)e.delete(t)}function k(e,t){if(t)for(let[r,i]of new Headers(t).entries())"set-cookie"===r.toLowerCase()?e.append(r,i):e.set(r,i)}function R(e,t){if(e instanceof Response){if(t?.headers){let r=new Headers(t.headers);O(r),k(e.headers,r)}return e}if(e&&"object"==typeof e&&"_flag"in e&&"json"===e._flag){let r=e.body,i=e.routerResponse;if(i instanceof Response)return i;let a=new Headers;if(k(a,i?.headers),k(a,e.headers),t?.headers){let e=new Headers(t.headers);O(e),k(a,e)}a.set("Content-Type","application/json");let o=e.status??t?.status??i?.status,n=t?.statusText??i?.statusText;return new Response(JSON.stringify(r),{...i,headers:a,...void 0===o?{}:{status:o},...void 0===n?{}:{statusText:n}})}if(f(e))return R(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,i=new Headers(t?.headers);if(O(i),e){if("string"==typeof e)r=e,i.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,i.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,i.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,i.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,i.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,a,o;t=new WeakMap,a=new WeakMap,o=0,r=JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("object"==typeof r&&null!==r){if(((e,r)=>{let i=r;for(;i;){if(i===e)return!0;i=t.get(i)}return!1})(r,this))return`[Circular ref-${a.get(r)}]`;t.set(r,this),a.has(r)||a.set(r,o++)}return r}),i.set("Content-Type","application/json")}}else null===e&&(r=JSON.stringify(null)),i.set("content-type","application/json");return new Response(r,{...t,headers:i})}function x(e,t,r){let a="string"==typeof e?e:void 0,o="object"==typeof t?t:e,n="function"==typeof t?t:r;if(("GET"===o.method||"HEAD"===o.method)&&o.body)throw new i.n("Body is not allowed with GET or HEAD methods");if(a&&/\/{2,}/.test(a))throw new i.n("Path cannot contain consecutive slashes");let s=async(...e)=>{let t=e[0]||{},{data:r,error:s}=await p(_(t,{options:o,path:a}));if(s){if(!(s instanceof i.a))throw s;throw o.onValidationError&&await o.onValidationError({message:s.message,issues:s.issues}),new i.E(400,{message:s.message,code:"VALIDATION_ERROR"})}let l=await n(r).catch(async e=>{if(f(e)){let r=o.onAPIError;if(r&&await r(e),t.asResponse)return e}throw e}),c=r.responseHeaders,d=r.responseStatus;return t.asResponse?R(l,void 0===d?{headers:c}:{headers:c,status:d}):t.returnHeaders?t.returnStatus?{headers:c,response:l,status:d}:{headers:c,response:l}:t.returnStatus?{response:l,status:d}:l};return s.options=o,s.path=a,s}function S(e,t){return[...e??[],...t??[]]}function U(e,t){let r=async r=>{let a="function"==typeof e?e:t,o=await _(r,{options:"function"==typeof e?{}:e,path:"/"});if(!a)throw Error("handler must be defined");try{let e=await a(o),t=o.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw f(e)&&Object.defineProperty(e,i.p,{enumerable:!1,configurable:!0,get:()=>o.responseHeaders}),e}};return r.options="function"==typeof e?{}:e,r}e.s(["f",0,R],30273),x.create=e=>function(...t){if(3===t.length){let[r,i,a]=t;return x(r,{...i,use:S(i.use,e?.use)},a)}let[r,i]=t;return x({...r,use:S(r.use,e?.use)},i)},e.s(["f",0,x],71045),U.create=e=>function(t,r){if("function"==typeof t)return U({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return U({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)},e.s(["f",0,U],94518);var N=e.i(7855);let D={};function L(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 C(e){let t=[];return e.metadata?.openapi?.parameters?t.push(...e.metadata.openapi.parameters):e.query instanceof N.ZodObject&&Object.entries(e.query.shape).forEach(([e,r])=>{r instanceof N.ZodObject&&t.push({name:e,in:"query",schema:{type:L(r),..."minLength"in r&&r.minLength?{minLength:r.minLength}:{},description:r.description}})}),t}function z(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 j(e,t){return Object.entries(e).forEach(([e,t])=>{let r=t.options;if(!(!t.path||r.metadata?.SERVER_ONLY)&&("GET"===r.method&&(D[t.path]={get:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:C(r),responses:z(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 N.ZodObject||e.body instanceof N.ZodOptional)){let t=e.body.shape;if(!t)return;let r={},i=[];return Object.entries(t).forEach(([e,t])=>{t instanceof N.ZodObject&&(r[e]={type:L(t),description:t.description},t instanceof N.ZodOptional||i.push(e))}),{required:!(e.body instanceof N.ZodOptional)&&!!e.body,content:{"application/json":{schema:{type:"object",properties:r,required:i}}}}}}(r);D[t.path]={post:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:C(r),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:z(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:D}}let P=((t=function(){}).prototype=Object.create(null),Object.freeze(t.prototype),t);function B(){return{root:{key:""},static:new P}}function M(e){return`__rou3_unnamed_${e}`}function $(e){let t=e.split("/");return t.shift(),""===t[t.length-1]&&t.pop(),t}function q(e,t){let r=new P;for(let[i,a]of t){let t=i<0?e.slice(-(i+1)).join("/"):e[i];if("string"==typeof a)r[a]=t;else{let e=t.match(a);if(e)for(let t in e.groups)r[95!==t.charCodeAt(0)?t:t.startsWith("__rou3_esc_")?t.slice(11).replace(/__|_h/g,e=>"__"===e?"_":"-"):t.startsWith("__rou3_unnamed_")?t.slice(15):t]=e.groups[t]}}return r}function H(e,t="",r,i){var a,o;t=t.toUpperCase(),47!==r.charCodeAt(0)&&(r=`/${r}`);let n=function(e){if(!e.includes("{"))return;let t=function(e){let t=0,r=0;for(;t<e.length;t++){let i=e.charCodeAt(t);if(92===i)t++;else if(40===i)r++;else if(41===i&&r>0)r--;else if(123===i&&0===r)break}if(t>=e.length)return;let i=t+1;for(r=0;i<e.length;i++){let t=e.charCodeAt(i);if(92===t)i++;else if(40===t)r++;else if(41===t&&r>0)r--;else if(125===t&&0===r)break}if(i>=e.length)return;let a=e[i+1],o="?"===a||"+"===a||"*"===a;return[e.slice(0,t),e.slice(t+1,i),e.slice(i+(o?2:1)),o?a:void 0]}(e);if(!t)return;let[r,i,a,o]=t;if(!o)return[r+i+a];if("?"===o)return[r+i+a,r+a];if(i.includes("/"))throw Error("unsupported group repetition across segments");return[`${r}(?:${i})${o}${a}`]}(r);if(n){for(let r of n)H(e,t,r,i);return}let s=function(e){let t=$(e);for(;""===t[t.length-1];)t.pop();return t}(r=(a=r).includes("\\")?a.replace(/\\([:(){}])/g,(e,t)=>"�"+"ABCDE"[":(){}".indexOf(t)]):a),l=function(e){for(let t=0;t<e.length;t++){let r=e[t].charCodeAt(e[t].length-1);if(63!==r&&43!==r&&42!==r)continue;let i=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!i)continue;let a=e.slice(0,t),o=e.slice(t+1);if("?"===i[2])return["/"+a.concat(i[1]).concat(o).join("/"),"/"+a.concat(o).join("/")];let n=i[1].match(/:([\w-]+)/)?.[1]||"_",s="/"+[...a,`**:${n}`,...o].join("/"),l="/"+[...a,...o].join("/");return"+"===i[2]?[s]:[s,l]}}(s);if(l){for(let r of l)H(e,t,r,i);return}let c=e.root,d=0,u=[],f=[];for(let e=0;e<s.length;e++){let t=s[e],r=(o=t).startsWith("**")?2:"*"===o||o.includes(":")||o.includes("(")||function(e){let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(92===i){r++;continue}if(40===i){t++;continue}if(41===i&&t>0){t--;continue}if(42===i&&0===t)return!0}return!1}(o)?1:"\\*"===o?"*":"\\*\\*"===o?"**":o.includes("�")?o.replace(/\uFFFD([A-E])/g,(e,t)=>"A"===t?":":"B"===t?"(":"C"===t?")":"D"===t?"{":"}"):o;if(2===r){c.wildcard||(c.wildcard={key:"**"}),c=c.wildcard,u.push([-(e+1),t.split(":")[1]||"_",2===t.length]);break}if(1===r){if(c.param||(c.param={key:"*"}),c=c.param,"*"===t)u.push([e,String(d++),!0]);else if(t.includes("(")||t.includes(":",1)||!/^:[\w-]+$/.test(t)){let[r,i]=function(e,t=0){let r=t,i="",a=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(40===r)a++;else if(41===r&&a>0)a--;else if(92===r&&0===a&&t+1<e.length){let r=e[t+1];if(":"!==r&&"("!==r&&"*"!==r&&"\\"!==r){i+=""+r,t++;continue}}else if(46===r&&0===a){i+="\\.";continue}i+=e[t]}[i,r]=function(e,t,r=M){let i=0,a=t,o="";for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(92===n){o+=e[t],t+1<e.length&&(o+=e[++t]);continue}if(40===n){i++,o+=e[t];continue}if(41===n&&i>0){i--,o+=e[t];continue}if(42===n&&0===i){o+=`(?<${r(a++)}>[^/]*)`;continue}o+=e[t]}return[o,a]}(i,r);let o=i.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,r)=>`(?<${/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(t)?t:"__rou3_esc_"+t.replace(/[_-]/g,e=>"_"===e?"__":"_h")}>${r||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${M(r++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${o}$`),r]}(t,d);d=i,f[e]=r,c.hasRegexParam=!0,u.push([e,r,!1])}else u.push([e,t.slice(1),!1]);continue}t=s[e]=r;let i=c.static?.[t];if(i)c=i;else{let e={key:t};c.static||(c.static=new P),c.static[t]=e,c=e}}let p=u.length>0,m=c.methods??=new P;(m[t]??=[]).push({data:i||null,paramsRegexp:f,paramsMap:p?u:void 0}),p||(e.static["/"+s.join("/")]=c)}function F(e,t,r,i,a){let o,n=e[t]||e[""];if(!n)return;let s=n[0];if(1===n.length&&0===s.paramsRegexp.length){if(!a)return s;let e=s.paramsMap;return e?.[e.length-1]?.[2]?s:void 0}let l=-1;for(let e of n){let t=e.paramsMap,n=t?.[t.length-1]?.[2];if(a&&!n)continue;let s=i&&t&&!n?1:0,c=e.paramsRegexp;for(let e=0;e<c.length;e++)if(c[e]){if(!c[e].test(r[e])){s=-1;break}s++}s>l&&(o=e,l=s)}return o}function V(e,t,r){for(let i of(t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:i,paramsMap:a}=e;for(let e=0;e<i.length;e++)i[e]&&t++;return r&&a&&!a[a.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0])),t))e.push(i)}e.s(["f",0,(e,t)=>{if(!t?.openapi?.disabled){let r={path:"/api/reference",...t?.openapi};e.openapi=x(r.path,{method:"GET"},async t=>{let i,a;return new Response((i=await j(e),a=r.scalar,`<!doctype html>
|
|
1
|
+
module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);var i=e.i(71045),a=e.i(94518),o=e.i(55659);let n={"Cache-Control":"no-store",Pragma:"no-cache"},s=(0,a.f)(async()=>({})),l=a.f.create({use:[s,(0,a.f)(async()=>({}))]}),c=i.f.create({use:[s]});function d(e,i){let a=i.metadata?.noStore===!0;return async i=>{if(a)for(let[e,t]of Object.entries(n))i.setHeader(e,t);try{return await (0,t.a)(i,()=>e(i))}catch(e){var s;throw s=i.responseHeaders,(0,r.f)(e)&&s&&Object.defineProperty(e,o.p,{enumerable:!1,configurable:!0,value:s,writable:!1}),e}}}function u(...e){if(3===e.length){let[t,r,i]=e;return c(t,r,d(i,r))}let[t,r]=e;return c(t,d(r,t))}u.serverOnly=(e,t)=>u({...e,metadata:{...e.metadata,SERVER_ONLY:!0}},t),e.s(["S",0,{scope:"server"},"p",0,n,"g",0,u,"a",0,l,"t",0,s])},95934,e=>{"use strict";let t,r=!1;async function i(){if(t)return t;let e=function(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}();if(e)return t??=e;try{let{AsyncLocalStorage:e}=await import("node:async_hooks");return t??=e}catch(i){let e=globalThis.AsyncLocalStorage;if("function"==typeof e)return t??=e;throw r||(r=!0,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://better-auth.com/docs/guides/cloudflare#nodejs-compatibility")),i}}e.s(["f",0,i])},97515,e=>{"use strict";var t=e.i(14268),r=e.i(95934);let i=async()=>{let e=(0,t.l)().context.endpointContextAsyncStorage;if(e)return e;let i=await (0,r.f)(),a=(0,t.l)().context;return a.endpointContextAsyncStorage??=new i};function a(){return(0,t.a)()}async function o(e,t){return(await i()).run(e,t)}e.s(["g",0,function(){let e=a();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e},"a",0,o,"G",0,a])},86198,96101,44336,30273,71045,94518,86097,18069,e=>{"use strict";let t;var r=e.i(71616),i=e.i(55659);function a(){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")}e.s(["f",0,a],96101);let o={name:"HMAC",hash:"SHA-256"},n=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await a().importKey("raw",t,o,!1,["sign","verify"])},s=async(e,t,r)=>{try{let i=atob(e),n=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)n[e]=i.charCodeAt(e);return await a().verify(o,r,n,new TextEncoder().encode(t))}catch{return!1}},l=async(e,t)=>{let r=await n(t);return btoa(String.fromCharCode(...new Uint8Array(await a().sign(o.name,r,new TextEncoder().encode(e)))))},c=async(e,t)=>{let r=await l(e,t);return encodeURIComponent(e=`${e}.${r}`)},d=/^application\/([a-z0-9.+-]*\+)?json/i;async function u(e,t){let r=e.headers.get("content-type")||"",a=r.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>a.split(";")[0].trim()===e.toLowerCase().trim())){if(!a)throw new i.E(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new i.E(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(d.test(a))try{return await e.json()}catch(e){if(e instanceof SyntaxError)throw new i.E(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw e}if(a.includes("application/x-www-form-urlencoded")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e.toString()}),r}if(a.includes("multipart/form-data")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e}),r}return a.includes("text/plain")?await e.text():a.includes("application/octet-stream")?await e.arrayBuffer():a.includes("application/pdf")||a.includes("image/")||a.includes("video/")?await e.blob():a.includes("application/stream")||e.body instanceof ReadableStream?e.body:await e.text()}}function f(e){return e instanceof i.E||e?.name==="APIError"}async function p(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function m(e){return e instanceof Request||"[object Request]"===Object.prototype.toString.call(e)}let h={secure:"__Secure-",host:"__Host-"},g=(e,t)=>t?"secure"===t||"host"===t?h[t]+e:void 0:e;function y(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let i=e.indexOf("=",r);if(-1===i)break;let a=e.indexOf(";",r);if(-1===a)a=e.length;else if(a<i){r=e.lastIndexOf(";",i-1)+1;continue}let o=e.slice(r,i).trim();if(!t.has(o)){let r=e.slice(i+1,a).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(o,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=a+1}return t}function w(e,t,r={}){let i=g(e,r.prefix)??e,a={...r},o=i.toLowerCase();return o.startsWith("__host-")?(a.secure=!0,a.path="/",a.domain=void 0):o.startsWith("__secure-")&&(a.secure=!0),(!0===a.partitioned||a.sameSite?.toLowerCase()==="none")&&(a.secure=!0),{name:i,value:t,options:a}}function b({name:e,value:t,options:r}){let i=`${e}=${t}`;if("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.");i+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&(i+=`; Domain=${r.domain}`),r.path&&(i+=`; 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.");i+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.sameSite&&(i+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(i+="; Partitioned"),i}let E=(e,t,r)=>b(w(e,t=encodeURIComponent(t),r)),A=async(e,t,r,i)=>b(w(e,t=await c(t,r),i));async function I(e,t={}){let r={body:t.body,query:t.query};if(e.body){let i=await e.body["~standard"].validate(t.body);if(i.issues)return{data:null,error:T(i.issues,"body")};r.body=i.value}if(e.query){let i=await e.query["~standard"].validate(t.query);if(i.issues)return{data:null,error:T(i.issues,"query")};r.query=i.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 T(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}}e.s(["K",0,g,"X",0,y,"j",0,E,"k",0,A],44336);let _=async(e,{options:t,path:r})=>{let a,o=new Headers,{data:l,error:c}=await I(t,e);if(c)throw new i.a(c.message,c.issues);let d=void 0!==e.headers?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&m(e.request)?e.request.headers:null,u=d?.get("cookie"),f=u?y(u):void 0,p={...e,body:l.body,query:l.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)=>{o.set(e,t)},getHeader:e=>d?d.get(e):null,getCookie:(e,t)=>{let r=g(e,t);return r&&f?.get(r)||null},getSignedCookie:async(e,t,r)=>{let i=g(e,r);if(!i)return null;let a=f?.get(i);if(!a)return null;let o=a.lastIndexOf(".");if(o<1)return null;let l=a.substring(0,o),c=a.substring(o+1);return 44===c.length&&c.endsWith("=")?!!await s(c,l,await n(t))&&l:null},setCookie:(e,t,r)=>{let i=E(e,t,r);return o.append("set-cookie",i),i},setSignedCookie:async(e,t,r,i)=>{let a=await A(e,t,r,i);return o.append("set-cookie",a),a},redirect:e=>(o.set("location",e),new i.E("FOUND",void 0,o)),error:(e,t,r)=>new i.E(e,t,r),setStatus:e=>{a=e},json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:o,get responseStatus(){return a}};for(let e of t.use||[]){let t=await e({...p,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(p.context,t.response),t.headers&&t.headers.forEach((e,t)=>{p.responseHeaders.set(t,e)})}return p},v=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 O(e){for(let t of v)e.delete(t)}function R(e,t){if(t)for(let[r,i]of new Headers(t).entries())"set-cookie"===r.toLowerCase()?e.append(r,i):e.set(r,i)}function k(e,t){if(e instanceof Response){if(t?.headers){let r=new Headers(t.headers);O(r),R(e.headers,r)}return e}if(e&&"object"==typeof e&&"_flag"in e&&"json"===e._flag){let r=e.body,i=e.routerResponse;if(i instanceof Response)return i;let a=new Headers;if(R(a,i?.headers),R(a,e.headers),t?.headers){let e=new Headers(t.headers);O(e),R(a,e)}a.set("Content-Type","application/json");let o=e.status??t?.status??i?.status,n=t?.statusText??i?.statusText;return new Response(JSON.stringify(r),{...i,headers:a,...void 0===o?{}:{status:o},...void 0===n?{}:{statusText:n}})}if(f(e))return k(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,i=new Headers(t?.headers);if(O(i),e){if("string"==typeof e)r=e,i.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,i.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,i.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,i.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,i.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,a,o;t=new WeakMap,a=new WeakMap,o=0,r=JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("object"==typeof r&&null!==r){if(((e,r)=>{let i=r;for(;i;){if(i===e)return!0;i=t.get(i)}return!1})(r,this))return`[Circular ref-${a.get(r)}]`;t.set(r,this),a.has(r)||a.set(r,o++)}return r}),i.set("Content-Type","application/json")}}else null===e&&(r=JSON.stringify(null)),i.set("content-type","application/json");return new Response(r,{...t,headers:i})}function x(e,t,r){let a="string"==typeof e?e:void 0,o="object"==typeof t?t:e,n="function"==typeof t?t:r;if(("GET"===o.method||"HEAD"===o.method)&&o.body)throw new i.n("Body is not allowed with GET or HEAD methods");if(a&&/\/{2,}/.test(a))throw new i.n("Path cannot contain consecutive slashes");let s=async(...e)=>{let t=e[0]||{},{data:r,error:s}=await p(_(t,{options:o,path:a}));if(s){if(!(s instanceof i.a))throw s;throw o.onValidationError&&await o.onValidationError({message:s.message,issues:s.issues}),new i.E(400,{message:s.message,code:"VALIDATION_ERROR"})}let l=await n(r).catch(async e=>{if(f(e)){let r=o.onAPIError;if(r&&await r(e),t.asResponse)return e}throw e}),c=r.responseHeaders,d=r.responseStatus;return t.asResponse?k(l,void 0===d?{headers:c}:{headers:c,status:d}):t.returnHeaders?t.returnStatus?{headers:c,response:l,status:d}:{headers:c,response:l}:t.returnStatus?{response:l,status:d}:l};return s.options=o,s.path=a,s}function S(e,t){return[...e??[],...t??[]]}function U(e,t){let r=async r=>{let a="function"==typeof e?e:t,o=await _(r,{options:"function"==typeof e?{}:e,path:"/"});if(!a)throw Error("handler must be defined");try{let e=await a(o),t=o.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw f(e)&&Object.defineProperty(e,i.p,{enumerable:!1,configurable:!0,get:()=>o.responseHeaders}),e}};return r.options="function"==typeof e?{}:e,r}e.s(["f",0,k],30273),x.create=e=>function(...t){if(3===t.length){let[r,i,a]=t;return x(r,{...i,use:S(i.use,e?.use)},a)}let[r,i]=t;return x({...r,use:S(r.use,e?.use)},i)},e.s(["f",0,x],71045),U.create=e=>function(t,r){if("function"==typeof t)return U({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return U({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)},e.s(["f",0,U],94518);var N=e.i(7855);let D={};function L(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 C(e){let t=[];return e.metadata?.openapi?.parameters?t.push(...e.metadata.openapi.parameters):e.query instanceof N.ZodObject&&Object.entries(e.query.shape).forEach(([e,r])=>{r instanceof N.ZodObject&&t.push({name:e,in:"query",schema:{type:L(r),..."minLength"in r&&r.minLength?{minLength:r.minLength}:{},description:r.description}})}),t}function z(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 j(e,t){return Object.entries(e).forEach(([e,t])=>{let r=t.options;if(!(!t.path||r.metadata?.SERVER_ONLY)&&("GET"===r.method&&(D[t.path]={get:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:C(r),responses:z(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 N.ZodObject||e.body instanceof N.ZodOptional)){let t=e.body.shape;if(!t)return;let r={},i=[];return Object.entries(t).forEach(([e,t])=>{t instanceof N.ZodObject&&(r[e]={type:L(t),description:t.description},t instanceof N.ZodOptional||i.push(e))}),{required:!(e.body instanceof N.ZodOptional)&&!!e.body,content:{"application/json":{schema:{type:"object",properties:r,required:i}}}}}}(r);D[t.path]={post:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:C(r),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:z(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:D}}let P=((t=function(){}).prototype=Object.create(null),Object.freeze(t.prototype),t);function B(){return{root:{key:""},static:new P}}function M(e){return`__rou3_unnamed_${e}`}function $(e){let t=e.split("/");return t.shift(),""===t[t.length-1]&&t.pop(),t}function q(e,t){let r=new P;for(let[i,a]of t){let t=i<0?e.slice(-(i+1)).join("/"):e[i];if("string"==typeof a)r[a]=t;else{let e=t.match(a);if(e)for(let t in e.groups)r[95!==t.charCodeAt(0)?t:t.startsWith("__rou3_esc_")?t.slice(11).replace(/__|_h/g,e=>"__"===e?"_":"-"):t.startsWith("__rou3_unnamed_")?t.slice(15):t]=e.groups[t]}}return r}function H(e,t="",r,i){var a,o;t=t.toUpperCase(),47!==r.charCodeAt(0)&&(r=`/${r}`);let n=function(e){if(!e.includes("{"))return;let t=function(e){let t=0,r=0;for(;t<e.length;t++){let i=e.charCodeAt(t);if(92===i)t++;else if(40===i)r++;else if(41===i&&r>0)r--;else if(123===i&&0===r)break}if(t>=e.length)return;let i=t+1;for(r=0;i<e.length;i++){let t=e.charCodeAt(i);if(92===t)i++;else if(40===t)r++;else if(41===t&&r>0)r--;else if(125===t&&0===r)break}if(i>=e.length)return;let a=e[i+1],o="?"===a||"+"===a||"*"===a;return[e.slice(0,t),e.slice(t+1,i),e.slice(i+(o?2:1)),o?a:void 0]}(e);if(!t)return;let[r,i,a,o]=t;if(!o)return[r+i+a];if("?"===o)return[r+i+a,r+a];if(i.includes("/"))throw Error("unsupported group repetition across segments");return[`${r}(?:${i})${o}${a}`]}(r);if(n){for(let r of n)H(e,t,r,i);return}let s=function(e){let t=$(e);for(;""===t[t.length-1];)t.pop();return t}(r=(a=r).includes("\\")?a.replace(/\\([:(){}])/g,(e,t)=>"�"+"ABCDE"[":(){}".indexOf(t)]):a),l=function(e){for(let t=0;t<e.length;t++){let r=e[t].charCodeAt(e[t].length-1);if(63!==r&&43!==r&&42!==r)continue;let i=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!i)continue;let a=e.slice(0,t),o=e.slice(t+1);if("?"===i[2])return["/"+a.concat(i[1]).concat(o).join("/"),"/"+a.concat(o).join("/")];let n=i[1].match(/:([\w-]+)/)?.[1]||"_",s="/"+[...a,`**:${n}`,...o].join("/"),l="/"+[...a,...o].join("/");return"+"===i[2]?[s]:[s,l]}}(s);if(l){for(let r of l)H(e,t,r,i);return}let c=e.root,d=0,u=[],f=[];for(let e=0;e<s.length;e++){let t=s[e],r=(o=t).startsWith("**")?2:"*"===o||o.includes(":")||o.includes("(")||function(e){let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(92===i){r++;continue}if(40===i){t++;continue}if(41===i&&t>0){t--;continue}if(42===i&&0===t)return!0}return!1}(o)?1:"\\*"===o?"*":"\\*\\*"===o?"**":o.includes("�")?o.replace(/\uFFFD([A-E])/g,(e,t)=>"A"===t?":":"B"===t?"(":"C"===t?")":"D"===t?"{":"}"):o;if(2===r){c.wildcard||(c.wildcard={key:"**"}),c=c.wildcard,u.push([-(e+1),t.split(":")[1]||"_",2===t.length]);break}if(1===r){if(c.param||(c.param={key:"*"}),c=c.param,"*"===t)u.push([e,String(d++),!0]);else if(t.includes("(")||t.includes(":",1)||!/^:[\w-]+$/.test(t)){let[r,i]=function(e,t=0){let r=t,i="",a=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(40===r)a++;else if(41===r&&a>0)a--;else if(92===r&&0===a&&t+1<e.length){let r=e[t+1];if(":"!==r&&"("!==r&&"*"!==r&&"\\"!==r){i+=""+r,t++;continue}}else if(46===r&&0===a){i+="\\.";continue}i+=e[t]}[i,r]=function(e,t,r=M){let i=0,a=t,o="";for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(92===n){o+=e[t],t+1<e.length&&(o+=e[++t]);continue}if(40===n){i++,o+=e[t];continue}if(41===n&&i>0){i--,o+=e[t];continue}if(42===n&&0===i){o+=`(?<${r(a++)}>[^/]*)`;continue}o+=e[t]}return[o,a]}(i,r);let o=i.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,r)=>`(?<${/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(t)?t:"__rou3_esc_"+t.replace(/[_-]/g,e=>"_"===e?"__":"_h")}>${r||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${M(r++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${o}$`),r]}(t,d);d=i,f[e]=r,c.hasRegexParam=!0,u.push([e,r,!1])}else u.push([e,t.slice(1),!1]);continue}t=s[e]=r;let i=c.static?.[t];if(i)c=i;else{let e={key:t};c.static||(c.static=new P),c.static[t]=e,c=e}}let p=u.length>0,m=c.methods??=new P;(m[t]??=[]).push({data:i||null,paramsRegexp:f,paramsMap:p?u:void 0}),p||(e.static["/"+s.join("/")]=c)}function F(e,t,r,i,a){let o,n=e[t]||e[""];if(!n)return;let s=n[0];if(1===n.length&&0===s.paramsRegexp.length){if(!a)return s;let e=s.paramsMap;return e?.[e.length-1]?.[2]?s:void 0}let l=-1;for(let e of n){let t=e.paramsMap,n=t?.[t.length-1]?.[2];if(a&&!n)continue;let s=i&&t&&!n?1:0,c=e.paramsRegexp;for(let e=0;e<c.length;e++)if(c[e]){if(!c[e].test(r[e])){s=-1;break}s++}s>l&&(o=e,l=s)}return o}function V(e,t,r){for(let i of(t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:i,paramsMap:a}=e;for(let e=0;e<i.length;e++)i[e]&&t++;return r&&a&&!a[a.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0])),t))e.push(i)}e.s(["f",0,(e,t)=>{if(!t?.openapi?.disabled){let r={path:"/api/reference",...t?.openapi};e.openapi=x(r.path,{method:"GET"},async t=>{let i,a;return new Response((i=await j(e),a=r.scalar,`<!doctype html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<title>Scalar API Reference</title>
|
|
@@ -27,7 +27,7 @@ module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);
|
|
|
27
27
|
</script>
|
|
28
28
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
29
29
|
</body>
|
|
30
|
-
</html>`),{headers:{"Content-Type":"text/html"}})})}let r=B(),i=B();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])H(r,e,t.path,t);if(t?.routerMiddleware?.length)for(let{path:e,middleware:r}of t.routerMiddleware)H(i,"*",e,r);let a=t?.basePath&&"/"!==t.basePath?t.basePath.replace(/\/+$/,""):"",o=async e=>{let o,n=new URL(e.url),s=n.pathname;if(a){if(!s.startsWith(`${a}/`))return new Response(null,{status:404,statusText:"Not Found"});o=s.slice(a.length)}else o=s;if(0===o.length||/\/{2,}/.test(o))return new Response(null,{status:404,statusText:"Not Found"});let l=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let i=e.static[r];if(i&&i.methods){let e=i.methods[t]||i.methods[""];if(void 0!==e)return e[0]}let a=$(r),o=function e(t,r,i,a){if(a===i.length){if(t.methods){let e=F(t.methods,r,i,"*"===t.key,!1);if(e)return e}return t.param?.methods&&F(t.param.methods,r,i,!0,!0)||t.wildcard?.methods&&F(t.wildcard.methods,r,i,!0,!0)||void 0}let o=i[a];if(t.static){let n=t.static[o];if(n){let t=e(n,r,i,a+1);if(t)return t}}if(t.param){let o=e(t.param,r,i,a+1);if(o)return o}if(t.wildcard&&t.wildcard.methods)return F(t.wildcard.methods,r,i,!0,!1)}(e.root,t,a,0);if(void 0!==o)return{data:o.data,params:o.paramsMap?q(a,o.paramsMap):void 0}}(r,e.method,o);if(o.endsWith("/")!==l?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes||!l?.data)return new Response(null,{status:404,statusText:"Not Found"});let c={};n.searchParams.forEach((e,t)=>{t in c?Array.isArray(c[t])?c[t].push(e):c[t]=[c[t],e]:c[t]=e});let d=l.data;try{let r=d.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,a={path:o,method:e.method,headers:e.headers,params:l.params?{...l.params}:{},request:e,body:d.options.disableBody?void 0:await u(d.options.cloneRequest?e.clone():e,r),query:c,_flag:"router",asResponse:!0,context:{...t?.routerContext}},n=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let i=$(r);return(function e(t,r,i,a,o=[]){let n=i[a];if(t.wildcard&&t.wildcard.methods){let e=t.wildcard.methods[r]||t.wildcard.methods[""];if(e)if(a<i.length)V(o,e,!0);else{let t=[];for(let r of e){let e=r.paramsMap;e?.[e.length-1]?.[2]&&t.push(r)}V(o,t,!0)}}if(t.param){if(a<i.length){let s=o.length;if(e(t.param,r,i,a+1,o),t.param.hasRegexParam)for(let e=o.length-1;e>=s;e--)o[e].paramsRegexp[a]?.test(n)===!1&&o.splice(e,1)}else if(t.param.methods){let e=t.param.methods[r]||t.param.methods[""];if(e){let t=[];for(let r of e){let e=r.paramsMap;e?.[e.length-1]?.[2]&&t.push(r)}V(o,t,!0)}}}if(a<i.length){let s=t.static?.[n];s&&e(s,r,i,a+1,o)}if(a===i.length&&t.methods){let e=t.methods[r]||t.methods[""];e&&V(o,e,"*"===t.key)}return o})(e.root,t,i,0).map(e=>({data:e.data,params:e.paramsMap?q(i,e.paramsMap):void 0}))}(i,"*",o);if(n?.length)for(let{data:e,params:t}of n){let r=await e({...a,params:t?{...t}:{},asResponse:!1});if(r instanceof Response)return r}return await d(a)}catch(r){if(t?.onError)try{let i=await t.onError(r,e);if(i instanceof Response)return R(i)}catch(e){if(f(e))return R(e);throw e}if(t?.throwError)throw r;if(f(r))return R(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 i=m(r)?r:e,a=await o(i),n=await t?.onResponse?.(a,i);return n instanceof Response?n:a},endpoints:e}}],86097),e.s([],18069),e.s(["f",0,function(e){return e instanceof i.E||e instanceof r.E||e?.name==="APIError"}],86198)},36254,e=>{"use strict";var t=e.i(55281),r=e.i(69e3),i=e.i(4313),a=e.i(75225),o=e.i(44988),n=e.i(18899);let s=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;function l(e,t,r){return"pg"===r?(0,a.O)(e,t):n.B`LOWER(${e}) LIKE LOWER(${t})`}function c(e,t){return 0===t.length?n.B`false`:n.B`LOWER(${e}) IN (${n.B.join(t.map(e=>n.B`LOWER(${e})`),n.B`, `)})`}function d(e,t){return 0===t.length?n.B`true`:n.B`LOWER(${e}) NOT IN (${n.B.join(t.map(e=>n.B`LOWER(${e})`),n.B`, `)})`}function u(e,t){return n.B`LOWER(${e}) = LOWER(${t})`}function f(e,t){return n.B`LOWER(${e}) <> LOWER(${t})`}var p=e.i(4383),m=e.i(73278),h=e.i(90126),g=e.i(71616),y=e.i(56325),w=e.i(49129),b=e.i(60338);function E(e,t,r){let i=0;if(e&&"object"==typeof e&&"rowCount"in e?i=e.rowCount:e&&"object"==typeof e&&"number"==typeof e.count?i=e.count:Array.isArray(e)?i=e.length>0&&I(e[0])?A(e[0]):e.length:I(e)&&(i=A(e)),"number"!=typeof i||!Number.isFinite(i))throw h.y.error(`[Drizzle Adapter] The result of the ${t} operation is not a finite number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.`,{result:e,...r}),new g.p(`Drizzle adapter ${t} returned an invalid affected row count`);return i}function A(e){if(e&&"object"==typeof e){if("affectedRows"in e)return e.affectedRows;if("rowsAffected"in e)return e.rowsAffected;if("changes"in e)return e.changes;if("meta"in e){let t=e.meta;if(t&&"object"==typeof t&&"changes"in t)return t.changes}}}function I(e){return void 0!==A(e)}e.s(["f",0,(e,A)=>{let I,T=null,_=!1,v=()=>I??=function(e){let t=new Map;for(let[r,i]of Object.entries(e??{}))i.relations&&t.set(r,new Set(Object.keys(i.relations)));return t}(e._?.schema),O=(e,t=!1)=>({getFieldName:r,getDefaultFieldName:i,getDefaultModelName:s,options:p,schema:m})=>{function I(t){let r=A.schema||e._.fullSchema;if(!r)throw new g.p("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let i=r[t];if(!i)throw new g.p(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return i}"mysql"!==A.provider||p.advanced?.database?.generateId!==!1||_||(_=!0,h.y.warn('[Drizzle Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth\'s default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.'));let T=async(i,o,n,s,l)=>{if("mysql"!==A.provider)return(await n.returning())[0];let c=void 0===l&&p.advanced?.database?.generateId==="serial",d=c?await n.$returningId().execute():await n.execute(),u=I(i),f=n.config?.values;if(l?.length){let t=O(l.map(e=>void 0!==s[e.field]?{...e,value:s[e.field]}:e),i,o);return(await e.select().from(u).where(...t))[0]}let g=async e=>{let t=f?.[0]?.id?.value;if(t)return(await e.select().from(u).where((0,a.u)(u.id,t)).limit(1).execute())[0]??null;if(s.id)return(await e.select().from(u).where((0,a.u)(u.id,s.id)).limit(1).execute())[0]??null;let n=c?d?.[0]?.id:void 0;if(n&&u.id)return(await e.select().from(u).where((0,a.u)(u.id,n)).limit(1).execute())[0]??null;let l=m[o]?.fields;if(l)for(let[t,i]of Object.entries(l)){if(!i.unique)continue;let n=r({model:o,field:t}),l=s[n];if(null==l||!u[n])continue;let c=await e.select().from(u).where((0,a.u)(u[n],l)).limit(1).execute();if(c[0])return c[0]}let p=[];for(let[e,t]of Object.entries(s))void 0!==t&&u[e]&&p.push(null===t?(0,a.M)(u[e]):(0,a.u)(u[e],t));if(p.length>0){let t=(0,a.b)(...p);if(t){let r=await e.select().from(u).where(t).limit(2).execute();if(1===r.length)return r[0]}}return h.y.warn(`[Drizzle Adapter] Unable to safely identify the inserted "${i}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return t?g(e):e.transaction(g)};function O(e,t,i){let n=I(t),s=e=>{let a=r({model:i,field:e.field});if(!(0,o.f)(n[a],y.f))throw new g.p(`The field "${e.field}" does not exist in the schema for the model "${t}". Please update your schema.`);return a};if(!e)return[];if(1===e.length){let t=e[0];if(!t)return[];let r=s(t),i=(t.mode??"sensitive")==="insensitive"&&("string"==typeof t.value||Array.isArray(t.value)&&t.value.every(e=>"string"==typeof e));if("in"===t.operator){if(!Array.isArray(t.value))throw new g.p(`The value for the field "${t.field}" must be an array when using the "in" operator.`);return i?[c(n[r],t.value)]:[(0,a.y)(n[r],t.value)]}if("not_in"===t.operator){if(!Array.isArray(t.value))throw new g.p(`The value for the field "${t.field}" must be an array when using the "not_in" operator.`);return i?[d(n[r],t.value)]:[(0,a.$)(n[r],t.value)]}return"contains"===t.operator?i&&"string"==typeof t.value?[l(n[r],`%${t.value}%`,A.provider)]:[(0,a.D)(n[r],`%${t.value}%`)]:"starts_with"===t.operator?i&&"string"==typeof t.value?[l(n[r],`${t.value}%`,A.provider)]:[(0,a.D)(n[r],`${t.value}%`)]:"ends_with"===t.operator?i&&"string"==typeof t.value?[l(n[r],`%${t.value}`,A.provider)]:[(0,a.D)(n[r],`%${t.value}`)]:"lt"===t.operator?[(0,a.S)(n[r],t.value)]:"lte"===t.operator?[(0,a.n)(n[r],t.value)]:"ne"===t.operator?null===t.value?[(0,a.E)(n[r])]:i&&"string"==typeof t.value?[f(n[r],t.value)]:[(0,a.c)(n[r],t.value)]:"gt"===t.operator?[(0,a.H)(n[r],t.value)]:"gte"===t.operator?[(0,a.B)(n[r],t.value)]:null===t.value?[(0,a.M)(n[r])]:i&&"string"==typeof t.value?[u(n[r],t.value)]:[(0,a.u)(n[r],t.value)]}let p=e.filter(e=>"AND"===e.connector||!e.connector),m=e.filter(e=>"OR"===e.connector),h=(0,a.b)(...p.map(e=>{let t=s(e),r=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e));if("in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return r?c(n[t],e.value):(0,a.y)(n[t],e.value)}if("not_in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return r?d(n[t],e.value):(0,a.$)(n[t],e.value)}return"contains"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}%`,A.provider):(0,a.D)(n[t],`%${e.value}%`):"starts_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`${e.value}%`,A.provider):(0,a.D)(n[t],`${e.value}%`):"ends_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}`,A.provider):(0,a.D)(n[t],`%${e.value}`):"lt"===e.operator?(0,a.S)(n[t],e.value):"lte"===e.operator?(0,a.n)(n[t],e.value):"gt"===e.operator?(0,a.H)(n[t],e.value):"gte"===e.operator?(0,a.B)(n[t],e.value):"ne"===e.operator?null===e.value?(0,a.E)(n[t]):r&&"string"==typeof e.value?f(n[t],e.value):(0,a.c)(n[t],e.value):null===e.value?(0,a.M)(n[t]):r&&"string"==typeof e.value?u(n[t],e.value):(0,a.u)(n[t],e.value)})),w=(0,a.F)(...m.map(e=>{let t=s(e),r=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e));if("in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return r?c(n[t],e.value):(0,a.y)(n[t],e.value)}if("not_in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return r?d(n[t],e.value):(0,a.$)(n[t],e.value)}return"contains"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}%`,A.provider):(0,a.D)(n[t],`%${e.value}%`):"starts_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`${e.value}%`,A.provider):(0,a.D)(n[t],`${e.value}%`):"ends_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}`,A.provider):(0,a.D)(n[t],`%${e.value}`):"lt"===e.operator?(0,a.S)(n[t],e.value):"lte"===e.operator?(0,a.n)(n[t],e.value):"gt"===e.operator?(0,a.H)(n[t],e.value):"gte"===e.operator?(0,a.B)(n[t],e.value):"ne"===e.operator?null===e.value?(0,a.E)(n[t]):r&&"string"==typeof e.value?f(n[t],e.value):(0,a.c)(n[t],e.value):null===e.value?(0,a.M)(n[t]):r&&"string"==typeof e.value?u(n[t],e.value):(0,a.u)(n[t],e.value)}));return p.length&&m.length?[(0,a.b)(h,w)]:p.length?[h]:m.length?[w]:[]}function k(t){if(!e.query)return null;if(e.query[t])return t;if(A.usePlural){let r=`${t}s`;if(e.query[r])return r}if(A.schema){let r=A.schema[t];if(r){let t=e._.fullSchema;if(t){for(let i of Object.keys(e.query))if(t[i]===r)return i}}}return null}function R(e,t,r,i,a,o){return o?function({baseModel:e,joinModel:t,baseModelKey:r,joinModelKey:i,relationKeys:a,schema:o,getDefaultModelName:n}){let s=r??n(e),l=i??n(t),c=Object.values(o[l]?.fields??{}).some(e=>e.references?.model===s)?t:o[l]?.modelName??l;return a?.size?a.has(c)?c:a.has(t)?t:c:t}({baseModel:e,joinModel:t,baseModelKey:r,joinModelKey:i,relationKeys:a,schema:m,getDefaultModelName:s}):A.usePlural?t:`${t}s`}return{async create({model:t,modelKey:i=t,data:a}){let o=I(t);if(!o)throw new g.p("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");for(let e in a){let t;try{t=r({model:i,field:e})}catch{t=e}if(!o[t])throw new g.p(`The field "${e}" does not exist in the "${i}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}let n=e.insert(o).values(a);return await T(t,i,n,a)},async findOne({model:t,modelKey:i=t,where:a,select:o,join:n}){let s=I(t),l=O(a,t,i);if(n){let a=k(t);if(e.query&&a){let s,c=[],d=v().get(a);for(let[e,r]of(s={},Object.entries(n))){let a=r.limit??p.advanced?.database?.defaultFindManyLimit??100,o="one-to-one"===r.relation,n=R(t,e,i,r.modelKey??e,d,o);s[n]=!!o||{limit:a},n!==e&&c.push({key:n,target:e})}let u=await e.query[a].findFirst({where:l[0],columns:o?.length&&o.length>0?o.reduce((e,t)=>(e[r({model:i,field:t})]=!0,e),{}):void 0,with:s});if(u)for(let{key:e,target:t}of c)u[t]=u[e],delete u[e];return u}h.y.error(`[# Drizzle Adapter]: The model "${t}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),h.y.info("Falling back to regular query")}let c=await e.select(o?.length&&o.length>0?o.reduce((e,t)=>{let a=r({model:i,field:t});return{...e,[a]:s[a]}},{}):void 0).from(s).where(...l);return c.length?c[0]:null},async findMany({model:t,modelKey:i=t,where:a,sortBy:o,limit:n,select:s,offset:l,join:c}){let d=I(t),u=a?O(a,t,i):[],f=o?.direction==="desc"?w.A:w.M;if(c){let a=k(t);if(e.query&&a){let m,h,g=[],y=v().get(a);for(let[e,r]of(m={},Object.entries(c))){let a="one-to-one"===r.relation,o=r.limit??p.advanced?.database?.defaultFindManyLimit??100,n=R(t,e,i,r.modelKey??e,y,a);m[n]=!!a||{limit:o},n!==e&&g.push({key:n,target:e})}o?.field&&(h=[f(d[r({model:i,field:o?.field})])]);let w=await e.query[a].findMany({where:u[0],with:m,columns:s?.length&&s.length>0?s.reduce((e,t)=>(e[r({model:i,field:t})]=!0,e),{}):void 0,limit:n??100,offset:l??0,orderBy:h});if(w)for(let e of w)for(let{key:t,target:r}of g)e[r]=e[t],delete e[t];return w}h.y.error(`[# Drizzle Adapter]: The model "${t}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),h.y.info("Falling back to regular query")}let m=e.select(s?.length&&s.length>0?s.reduce((e,t)=>{let a=r({model:i,field:t});return{...e,[a]:d[a]}},{}):void 0).from(d);return void 0!==n&&(m=m.limit(n)),void 0!==l&&(m=m.offset(l)),o?.field&&(m=m.orderBy(f(d[r({model:i,field:o?.field})]))),await m.where(...u)},async count({model:t,modelKey:r=t,where:i}){let a=I(t),o=i?O(i,t,r):[];return(await e.select({count:(0,b.H)()}).from(a).where(...o))[0].count},async update({model:t,modelKey:r=t,where:i,update:a}){let o=I(t),n=O(i,t,r),s=e.update(o).set(a).where(...n);return await T(t,r,s,a,i)},async updateMany({model:t,modelKey:r=t,where:i,update:a}){let o=I(t),n=O(i,t,r);return E(await e.update(o).set(a).where(...n),"updateMany",{model:t,where:i})},async delete({model:t,modelKey:r=t,where:i}){let a=I(t),o=O(i,t,r);return await e.delete(a).where(...o)},async deleteMany({model:t,modelKey:r=t,where:i}){let a=I(t),o=O(i,t,r);return E(await e.delete(a).where(...o),"deleteMany",{model:t,where:i})},async consumeOne({model:i,modelKey:o=i,where:n}){let s=I(i),l=O(n,i,o),c=r({model:o,field:"id"}),d=s[c];if("mysql"===A.provider){let r=async e=>{let t=(await e.select().from(s).where(...l).for("update").limit(1))[0];if(!t)return null;let r=t[c]??t.id;return null!=r&&d&&E(await e.delete(s).where((0,a.u)(d,r)).execute(),"consumeOne",{model:i,where:n})>0?t:null};return t?r(e):e.transaction(r)}if(!d)return null;let u=e.select({id:d}).from(s).where(...l).limit(1);return(await e.delete(s).where((0,a.y)(d,u)).returning())[0]??null},async incrementOne({model:i,modelKey:o=i,where:s,increment:l,set:c}){let d=I(i),u=O(s,i,o),f=r({model:o,field:"id"}),p=d[f],m={};for(let[e,t]of Object.entries(l)){let a=r({model:o,field:e}),s=d[a];if(!s)throw new g.p(`The field "${e}" does not exist in the schema for the model "${i}". Please update your schema.`);m[a]=n.B`${s} + ${n.B.param(t)}`}if(c)for(let[e,t]of Object.entries(c)){let a=r({model:o,field:e});if(!d[a])throw new g.p(`The field "${e}" does not exist in the schema for the model "${i}". Please update your schema.`);m[a]=t}if("mysql"===A.provider){let r=async e=>{let t=(await e.select().from(d).where(...u).for("update").limit(1))[0];if(!t)return null;let r=t[f]??t.id;return null!=r&&p?(await e.update(d).set(m).where((0,a.u)(p,r)).execute(),(await e.select().from(d).where((0,a.u)(p,r)).limit(1).execute())[0]??null):null};return t?r(e):e.transaction(r)}if(!p)return null;let h=e.select({id:p}).from(d).where(...u).limit(1);return(await e.update(d).set(m).where((0,a.b)(...u,(0,a.y)(p,h))).returning())[0]??null},options:A}},k=null;k={config:{adapterId:"drizzle",adapterName:"Drizzle Adapter",usePlural:A.usePlural??!1,debugLogs:A.debugLogs??!1,supportsUUIDs:"pg"===A.provider,supportsJSON:"pg"===A.provider,supportsArrays:"pg"===A.provider,customTransformInput:({data:t,fieldAttributes:r,model:i,field:a})=>{if("date"!==r.type)return t;let o=A.schema||e._.fullSchema;return function(e,t,r){let i;if("string"!=typeof(i=t?.dataType)||"string"!==i.split(" ")[0])return e;let a=e=>{if(!(e instanceof Date))return e;let t=e.toISOString();return"mysql"===r?t.replace("T"," ").replace("Z",""):t};return Array.isArray(e)?e.map(a):a(e)}(t,o?.[i]?.[a],A.provider)},customTransformOutput:({data:e,fieldAttributes:t})=>{if("date"===t.type)return null==e?e:new Date("string"==typeof e&&s.test(e)?`${e.replace(" ","T")}Z`:e);return e},transaction:!!A.transaction&&(t=>e.transaction(e=>t((0,p.f)({config:{...k.config,transaction:!1},adapter:O(e,!0)})(T))))},adapter:O(e)};let R=(0,p.f)(k);return a=>{T=a;let n=R(a),s=(0,m.t)(()=>{var n,s;return n=A.schema??e._?.fullSchema??{},s=A.usePlural,(0,t.I)((0,t.w)(a,{usePlural:s}),function(e){let t=[];for(let[a,n]of Object.entries(e)){if(!(0,o.f)(n,r.s))continue;let e=Object.entries((0,i.q)(n)).map(([e,t])=>({name:e,nullable:!t.notNull,hasDefault:t.hasDefault||void 0!==t.generated||void 0!==t.generatedIdentity}));t.push({name:a,columns:e})}return t}(n))},"drizzle");return(0,m.E)(n,s,{runtimeEnabled:(0,m.S)(a)}),n}}],36254)},80849,24374,e=>{"use strict";var t=e.i(14268),r=e.i(95934);let i=async()=>{let e=(0,t.l)(),i=e.context.requestStateAsyncStorage;if(i)return i;let a=await (0,r.f)();return e.context.requestStateAsyncStorage??=new a,e.context.requestStateAsyncStorage};async function a(){return void 0!==(await i()).getStore()}async function o(){let e=(await i()).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 n(e,t){return(await i()).run(e,t)}function s(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await o();if(!r.has(t)){let i=await e();return r.set(t,i),i}return r.get(t)},async set(e){(await o()).set(t,e)}}}e.s(["z",0,s,"B",0,a,"O",0,n],24374);let{get:l,set:c}=s(()=>!1);e.s(["T",0,l,"w",0,c],80849)},4721,e=>{"use strict";let t,r,i,a,o,n,s;var l,c,d=e.i(69774),u=e.i(90126);async function f(t,r){let i;if(t.database)i="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,d.R)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:a}=await e.A(63921);i=a(r)(t)}return i.transaction||(u.y.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),i.transaction=async e=>e(i)),i}var p=e.i(71616);async function m(t){return f(t,async t=>{let{createKyselyAdapter:r,kyselyAdapter:i}=await e.A(46120),{kysely:a,databaseType:o,transaction:n}=await r(t);if(!a)throw new p.p("Failed to initialize database adapter");return i(a,{type:o||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:n})(t)})}var h=p,g=e.i(43638),y=e.i(46378),w=e.i(31139),b=e.i(55281),E=e.i(67409),A=e.i(73278),I=e.i(77113);let T={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","int8","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL","BIGINT"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function _(e,t){return`${(0,E.d)(e)}\0${(0,E.d)(t)}`}function v(e,t){return`${e}\0${t}`}function O(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,r)=>e===t.columns[r])}function k(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:"1"===e||e?.toLowerCase()==="true"||"t"===e}function R(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[_(e.table,e.name),{columns:t.flatMap(e=>null===e.name?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>null!==e.name&&e.fullLength)}]}))}async function x(e,t,r,i){let a;if(i)return R(await i(r));switch(t.type){case"sqlite":a=(await I.f`
|
|
30
|
+
</html>`),{headers:{"Content-Type":"text/html"}})})}let r=B(),i=B();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])H(r,e,t.path,t);if(t?.routerMiddleware?.length)for(let{path:e,middleware:r}of t.routerMiddleware)H(i,"*",e,r);let a=t?.basePath&&"/"!==t.basePath?t.basePath.replace(/\/+$/,""):"",o=async e=>{let o,n=new URL(e.url),s=n.pathname;if(a){if(!s.startsWith(`${a}/`))return new Response(null,{status:404,statusText:"Not Found"});o=s.slice(a.length)}else o=s;if(0===o.length||/\/{2,}/.test(o))return new Response(null,{status:404,statusText:"Not Found"});let l=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let i=e.static[r];if(i&&i.methods){let e=i.methods[t]||i.methods[""];if(void 0!==e)return e[0]}let a=$(r),o=function e(t,r,i,a){if(a===i.length){if(t.methods){let e=F(t.methods,r,i,"*"===t.key,!1);if(e)return e}return t.param?.methods&&F(t.param.methods,r,i,!0,!0)||t.wildcard?.methods&&F(t.wildcard.methods,r,i,!0,!0)||void 0}let o=i[a];if(t.static){let n=t.static[o];if(n){let t=e(n,r,i,a+1);if(t)return t}}if(t.param){let o=e(t.param,r,i,a+1);if(o)return o}if(t.wildcard&&t.wildcard.methods)return F(t.wildcard.methods,r,i,!0,!1)}(e.root,t,a,0);if(void 0!==o)return{data:o.data,params:o.paramsMap?q(a,o.paramsMap):void 0}}(r,e.method,o);if(o.endsWith("/")!==l?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes||!l?.data)return new Response(null,{status:404,statusText:"Not Found"});let c={};n.searchParams.forEach((e,t)=>{t in c?Array.isArray(c[t])?c[t].push(e):c[t]=[c[t],e]:c[t]=e});let d=l.data;try{let r=d.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,a={path:o,method:e.method,headers:e.headers,params:l.params?{...l.params}:{},request:e,body:d.options.disableBody?void 0:await u(d.options.cloneRequest?e.clone():e,r),query:c,_flag:"router",asResponse:!0,context:{...t?.routerContext}},n=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let i=$(r);return(function e(t,r,i,a,o=[]){let n=i[a];if(t.wildcard&&t.wildcard.methods){let e=t.wildcard.methods[r]||t.wildcard.methods[""];if(e)if(a<i.length)V(o,e,!0);else{let t=[];for(let r of e){let e=r.paramsMap;e?.[e.length-1]?.[2]&&t.push(r)}V(o,t,!0)}}if(t.param){if(a<i.length){let s=o.length;if(e(t.param,r,i,a+1,o),t.param.hasRegexParam)for(let e=o.length-1;e>=s;e--)o[e].paramsRegexp[a]?.test(n)===!1&&o.splice(e,1)}else if(t.param.methods){let e=t.param.methods[r]||t.param.methods[""];if(e){let t=[];for(let r of e){let e=r.paramsMap;e?.[e.length-1]?.[2]&&t.push(r)}V(o,t,!0)}}}if(a<i.length){let s=t.static?.[n];s&&e(s,r,i,a+1,o)}if(a===i.length&&t.methods){let e=t.methods[r]||t.methods[""];e&&V(o,e,"*"===t.key)}return o})(e.root,t,i,0).map(e=>({data:e.data,params:e.paramsMap?q(i,e.paramsMap):void 0}))}(i,"*",o);if(n?.length)for(let{data:e,params:t}of n){let r=await e({...a,params:t?{...t}:{},asResponse:!1});if(r instanceof Response)return r}return await d(a)}catch(r){if(t?.onError)try{let i=await t.onError(r,e);if(i instanceof Response)return k(i)}catch(e){if(f(e))return k(e);throw e}if(t?.throwError)throw r;if(f(r))return k(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 i=m(r)?r:e,a=await o(i),n=await t?.onResponse?.(a,i);return n instanceof Response?n:a},endpoints:e}}],86097),e.s([],18069),e.s(["f",0,function(e){return e instanceof i.E||e instanceof r.E||e?.name==="APIError"}],86198)},36254,e=>{"use strict";var t=e.i(55281),r=e.i(69e3),i=e.i(4313),a=e.i(75225),o=e.i(44988),n=e.i(18899);let s=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;function l(e,t,r){return"pg"===r?(0,a.O)(e,t):n.B`LOWER(${e}) LIKE LOWER(${t})`}function c(e,t){return 0===t.length?n.B`false`:n.B`LOWER(${e}) IN (${n.B.join(t.map(e=>n.B`LOWER(${e})`),n.B`, `)})`}function d(e,t){return 0===t.length?n.B`true`:n.B`LOWER(${e}) NOT IN (${n.B.join(t.map(e=>n.B`LOWER(${e})`),n.B`, `)})`}function u(e,t){return n.B`LOWER(${e}) = LOWER(${t})`}function f(e,t){return n.B`LOWER(${e}) <> LOWER(${t})`}var p=e.i(4383),m=e.i(73278),h=e.i(90126),g=e.i(71616),y=e.i(56325),w=e.i(49129),b=e.i(60338);function E(e,t,r){let i=0;if(e&&"object"==typeof e&&"rowCount"in e?i=e.rowCount:e&&"object"==typeof e&&"number"==typeof e.count?i=e.count:Array.isArray(e)?i=e.length>0&&I(e[0])?A(e[0]):e.length:I(e)&&(i=A(e)),"number"!=typeof i||!Number.isFinite(i))throw h.y.error(`[Drizzle Adapter] The result of the ${t} operation is not a finite number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.`,{result:e,...r}),new g.p(`Drizzle adapter ${t} returned an invalid affected row count`);return i}function A(e){if(e&&"object"==typeof e){if("affectedRows"in e)return e.affectedRows;if("rowsAffected"in e)return e.rowsAffected;if("changes"in e)return e.changes;if("meta"in e){let t=e.meta;if(t&&"object"==typeof t&&"changes"in t)return t.changes}}}function I(e){return void 0!==A(e)}e.s(["f",0,(e,A)=>{let I,T=null,_=!1,v=()=>I??=function(e){let t=new Map;for(let[r,i]of Object.entries(e??{}))i.relations&&t.set(r,new Set(Object.keys(i.relations)));return t}(e._?.schema),O=(e,t=!1)=>({getFieldName:r,getDefaultFieldName:i,getDefaultModelName:s,options:p,schema:m})=>{function I(t){let r=A.schema||e._.fullSchema;if(!r)throw new g.p("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let i=r[t];if(!i)throw new g.p(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return i}"mysql"!==A.provider||p.advanced?.database?.generateId!==!1||_||(_=!0,h.y.warn('[Drizzle Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth\'s default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.'));let T=async(i,o,n,s,l)=>{if("mysql"!==A.provider)return(await n.returning())[0];let c=void 0===l&&p.advanced?.database?.generateId==="serial",d=c?await n.$returningId().execute():await n.execute(),u=I(i),f=n.config?.values;if(l?.length){let t=O(l.map(e=>void 0!==s[e.field]?{...e,value:s[e.field]}:e),i,o);return(await e.select().from(u).where(...t))[0]}let g=async e=>{let t=f?.[0]?.id?.value;if(t)return(await e.select().from(u).where((0,a.u)(u.id,t)).limit(1).execute())[0]??null;if(s.id)return(await e.select().from(u).where((0,a.u)(u.id,s.id)).limit(1).execute())[0]??null;let n=c?d?.[0]?.id:void 0;if(n&&u.id)return(await e.select().from(u).where((0,a.u)(u.id,n)).limit(1).execute())[0]??null;let l=m[o]?.fields;if(l)for(let[t,i]of Object.entries(l)){if(!i.unique)continue;let n=r({model:o,field:t}),l=s[n];if(null==l||!u[n])continue;let c=await e.select().from(u).where((0,a.u)(u[n],l)).limit(1).execute();if(c[0])return c[0]}let p=[];for(let[e,t]of Object.entries(s))void 0!==t&&u[e]&&p.push(null===t?(0,a.M)(u[e]):(0,a.u)(u[e],t));if(p.length>0){let t=(0,a.b)(...p);if(t){let r=await e.select().from(u).where(t).limit(2).execute();if(1===r.length)return r[0]}}return h.y.warn(`[Drizzle Adapter] Unable to safely identify the inserted "${i}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return t?g(e):e.transaction(g)};function O(e,t,i){let n=I(t),s=e=>{let a=r({model:i,field:e.field});if(!(0,o.f)(n[a],y.f))throw new g.p(`The field "${e.field}" does not exist in the schema for the model "${t}". Please update your schema.`);return a};if(!e)return[];if(1===e.length){let t=e[0];if(!t)return[];let r=s(t),i=(t.mode??"sensitive")==="insensitive"&&("string"==typeof t.value||Array.isArray(t.value)&&t.value.every(e=>"string"==typeof e));if("in"===t.operator){if(!Array.isArray(t.value))throw new g.p(`The value for the field "${t.field}" must be an array when using the "in" operator.`);return i?[c(n[r],t.value)]:[(0,a.y)(n[r],t.value)]}if("not_in"===t.operator){if(!Array.isArray(t.value))throw new g.p(`The value for the field "${t.field}" must be an array when using the "not_in" operator.`);return i?[d(n[r],t.value)]:[(0,a.$)(n[r],t.value)]}return"contains"===t.operator?i&&"string"==typeof t.value?[l(n[r],`%${t.value}%`,A.provider)]:[(0,a.D)(n[r],`%${t.value}%`)]:"starts_with"===t.operator?i&&"string"==typeof t.value?[l(n[r],`${t.value}%`,A.provider)]:[(0,a.D)(n[r],`${t.value}%`)]:"ends_with"===t.operator?i&&"string"==typeof t.value?[l(n[r],`%${t.value}`,A.provider)]:[(0,a.D)(n[r],`%${t.value}`)]:"lt"===t.operator?[(0,a.S)(n[r],t.value)]:"lte"===t.operator?[(0,a.n)(n[r],t.value)]:"ne"===t.operator?null===t.value?[(0,a.E)(n[r])]:i&&"string"==typeof t.value?[f(n[r],t.value)]:[(0,a.c)(n[r],t.value)]:"gt"===t.operator?[(0,a.H)(n[r],t.value)]:"gte"===t.operator?[(0,a.B)(n[r],t.value)]:null===t.value?[(0,a.M)(n[r])]:i&&"string"==typeof t.value?[u(n[r],t.value)]:[(0,a.u)(n[r],t.value)]}let p=e.filter(e=>"AND"===e.connector||!e.connector),m=e.filter(e=>"OR"===e.connector),h=(0,a.b)(...p.map(e=>{let t=s(e),r=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e));if("in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return r?c(n[t],e.value):(0,a.y)(n[t],e.value)}if("not_in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return r?d(n[t],e.value):(0,a.$)(n[t],e.value)}return"contains"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}%`,A.provider):(0,a.D)(n[t],`%${e.value}%`):"starts_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`${e.value}%`,A.provider):(0,a.D)(n[t],`${e.value}%`):"ends_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}`,A.provider):(0,a.D)(n[t],`%${e.value}`):"lt"===e.operator?(0,a.S)(n[t],e.value):"lte"===e.operator?(0,a.n)(n[t],e.value):"gt"===e.operator?(0,a.H)(n[t],e.value):"gte"===e.operator?(0,a.B)(n[t],e.value):"ne"===e.operator?null===e.value?(0,a.E)(n[t]):r&&"string"==typeof e.value?f(n[t],e.value):(0,a.c)(n[t],e.value):null===e.value?(0,a.M)(n[t]):r&&"string"==typeof e.value?u(n[t],e.value):(0,a.u)(n[t],e.value)})),w=(0,a.F)(...m.map(e=>{let t=s(e),r=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e));if("in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return r?c(n[t],e.value):(0,a.y)(n[t],e.value)}if("not_in"===e.operator){if(!Array.isArray(e.value))throw new g.p(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return r?d(n[t],e.value):(0,a.$)(n[t],e.value)}return"contains"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}%`,A.provider):(0,a.D)(n[t],`%${e.value}%`):"starts_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`${e.value}%`,A.provider):(0,a.D)(n[t],`${e.value}%`):"ends_with"===e.operator?r&&"string"==typeof e.value?l(n[t],`%${e.value}`,A.provider):(0,a.D)(n[t],`%${e.value}`):"lt"===e.operator?(0,a.S)(n[t],e.value):"lte"===e.operator?(0,a.n)(n[t],e.value):"gt"===e.operator?(0,a.H)(n[t],e.value):"gte"===e.operator?(0,a.B)(n[t],e.value):"ne"===e.operator?null===e.value?(0,a.E)(n[t]):r&&"string"==typeof e.value?f(n[t],e.value):(0,a.c)(n[t],e.value):null===e.value?(0,a.M)(n[t]):r&&"string"==typeof e.value?u(n[t],e.value):(0,a.u)(n[t],e.value)}));return p.length&&m.length?[(0,a.b)(h,w)]:p.length?[h]:m.length?[w]:[]}function R(t){if(!e.query)return null;if(e.query[t])return t;if(A.usePlural){let r=`${t}s`;if(e.query[r])return r}if(A.schema){let r=A.schema[t];if(r){let t=e._.fullSchema;if(t){for(let i of Object.keys(e.query))if(t[i]===r)return i}}}return null}function k(e,t,r,i,a,o){return o?function({baseModel:e,joinModel:t,baseModelKey:r,joinModelKey:i,relationKeys:a,schema:o,getDefaultModelName:n}){let s=r??n(e),l=i??n(t),c=Object.values(o[l]?.fields??{}).some(e=>e.references?.model===s)?t:o[l]?.modelName??l;return a?.size?a.has(c)?c:a.has(t)?t:c:t}({baseModel:e,joinModel:t,baseModelKey:r,joinModelKey:i,relationKeys:a,schema:m,getDefaultModelName:s}):A.usePlural?t:`${t}s`}return{async create({model:t,modelKey:i=t,data:a}){let o=I(t);if(!o)throw new g.p("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");for(let e in a){let t;try{t=r({model:i,field:e})}catch{t=e}if(!o[t])throw new g.p(`The field "${e}" does not exist in the "${i}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}let n=e.insert(o).values(a);return await T(t,i,n,a)},async findOne({model:t,modelKey:i=t,where:a,select:o,join:n}){let s=I(t),l=O(a,t,i);if(n){let a=R(t);if(e.query&&a){let s,c=[],d=v().get(a);for(let[e,r]of(s={},Object.entries(n))){let a=r.limit??p.advanced?.database?.defaultFindManyLimit??100,o="one-to-one"===r.relation,n=k(t,e,i,r.modelKey??e,d,o);s[n]=!!o||{limit:a},n!==e&&c.push({key:n,target:e})}let u=await e.query[a].findFirst({where:l[0],columns:o?.length&&o.length>0?o.reduce((e,t)=>(e[r({model:i,field:t})]=!0,e),{}):void 0,with:s});if(u)for(let{key:e,target:t}of c)u[t]=u[e],delete u[e];return u}h.y.error(`[# Drizzle Adapter]: The model "${t}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),h.y.info("Falling back to regular query")}let c=await e.select(o?.length&&o.length>0?o.reduce((e,t)=>{let a=r({model:i,field:t});return{...e,[a]:s[a]}},{}):void 0).from(s).where(...l);return c.length?c[0]:null},async findMany({model:t,modelKey:i=t,where:a,sortBy:o,limit:n,select:s,offset:l,join:c}){let d=I(t),u=a?O(a,t,i):[],f=o?.direction==="desc"?w.A:w.M;if(c){let a=R(t);if(e.query&&a){let m,h,g=[],y=v().get(a);for(let[e,r]of(m={},Object.entries(c))){let a="one-to-one"===r.relation,o=r.limit??p.advanced?.database?.defaultFindManyLimit??100,n=k(t,e,i,r.modelKey??e,y,a);m[n]=!!a||{limit:o},n!==e&&g.push({key:n,target:e})}o?.field&&(h=[f(d[r({model:i,field:o?.field})])]);let w=await e.query[a].findMany({where:u[0],with:m,columns:s?.length&&s.length>0?s.reduce((e,t)=>(e[r({model:i,field:t})]=!0,e),{}):void 0,limit:n??100,offset:l??0,orderBy:h});if(w)for(let e of w)for(let{key:t,target:r}of g)e[r]=e[t],delete e[t];return w}h.y.error(`[# Drizzle Adapter]: The model "${t}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),h.y.info("Falling back to regular query")}let m=e.select(s?.length&&s.length>0?s.reduce((e,t)=>{let a=r({model:i,field:t});return{...e,[a]:d[a]}},{}):void 0).from(d);return void 0!==n&&(m=m.limit(n)),void 0!==l&&(m=m.offset(l)),o?.field&&(m=m.orderBy(f(d[r({model:i,field:o?.field})]))),await m.where(...u)},async count({model:t,modelKey:r=t,where:i}){let a=I(t),o=i?O(i,t,r):[];return(await e.select({count:(0,b.H)()}).from(a).where(...o))[0].count},async update({model:t,modelKey:r=t,where:i,update:a}){let o=I(t),n=O(i,t,r),s=e.update(o).set(a).where(...n);return await T(t,r,s,a,i)},async updateMany({model:t,modelKey:r=t,where:i,update:a}){let o=I(t),n=O(i,t,r);return E(await e.update(o).set(a).where(...n),"updateMany",{model:t,where:i})},async delete({model:t,modelKey:r=t,where:i}){let a=I(t),o=O(i,t,r);return await e.delete(a).where(...o)},async deleteMany({model:t,modelKey:r=t,where:i}){let a=I(t),o=O(i,t,r);return E(await e.delete(a).where(...o),"deleteMany",{model:t,where:i})},async consumeOne({model:i,modelKey:o=i,where:n}){let s=I(i),l=O(n,i,o),c=r({model:o,field:"id"}),d=s[c];if("mysql"===A.provider){let r=async e=>{let t=(await e.select().from(s).where(...l).for("update").limit(1))[0];if(!t)return null;let r=t[c]??t.id;return null!=r&&d&&E(await e.delete(s).where((0,a.u)(d,r)).execute(),"consumeOne",{model:i,where:n})>0?t:null};return t?r(e):e.transaction(r)}if(!d)return null;let u=e.select({id:d}).from(s).where(...l).limit(1);return(await e.delete(s).where((0,a.y)(d,u)).returning())[0]??null},async incrementOne({model:i,modelKey:o=i,where:s,increment:l,set:c}){let d=I(i),u=O(s,i,o),f=r({model:o,field:"id"}),p=d[f],m={};for(let[e,t]of Object.entries(l)){let a=r({model:o,field:e}),s=d[a];if(!s)throw new g.p(`The field "${e}" does not exist in the schema for the model "${i}". Please update your schema.`);m[a]=n.B`${s} + ${n.B.param(t)}`}if(c)for(let[e,t]of Object.entries(c)){let a=r({model:o,field:e});if(!d[a])throw new g.p(`The field "${e}" does not exist in the schema for the model "${i}". Please update your schema.`);m[a]=t}if("mysql"===A.provider){let r=async e=>{let t=(await e.select().from(d).where(...u).for("update").limit(1))[0];if(!t)return null;let r=t[f]??t.id;return null!=r&&p?(await e.update(d).set(m).where((0,a.u)(p,r)).execute(),(await e.select().from(d).where((0,a.u)(p,r)).limit(1).execute())[0]??null):null};return t?r(e):e.transaction(r)}if(!p)return null;let h=e.select({id:p}).from(d).where(...u).limit(1);return(await e.update(d).set(m).where((0,a.b)(...u,(0,a.y)(p,h))).returning())[0]??null},options:A}},R=null;R={config:{adapterId:"drizzle",adapterName:"Drizzle Adapter",usePlural:A.usePlural??!1,debugLogs:A.debugLogs??!1,supportsUUIDs:"pg"===A.provider,supportsJSON:"pg"===A.provider,supportsArrays:"pg"===A.provider,customTransformInput:({data:t,fieldAttributes:r,model:i,field:a})=>{if("date"!==r.type)return t;let o=A.schema||e._.fullSchema;return function(e,t,r){let i;if("string"!=typeof(i=t?.dataType)||"string"!==i.split(" ")[0])return e;let a=e=>{if(!(e instanceof Date))return e;let t=e.toISOString();return"mysql"===r?t.replace("T"," ").replace("Z",""):t};return Array.isArray(e)?e.map(a):a(e)}(t,o?.[i]?.[a],A.provider)},customTransformOutput:({data:e,fieldAttributes:t})=>{if("date"===t.type)return null==e?e:new Date("string"==typeof e&&s.test(e)?`${e.replace(" ","T")}Z`:e);return e},transaction:!!A.transaction&&(t=>e.transaction(e=>t((0,p.f)({config:{...R.config,transaction:!1},adapter:O(e,!0)})(T))))},adapter:O(e)};let k=(0,p.f)(R);return a=>{T=a;let n=k(a),s=(0,m.t)(()=>{var n,s;return n=A.schema??e._?.fullSchema??{},s=A.usePlural,(0,t.I)((0,t.w)(a,{usePlural:s}),function(e){let t=[];for(let[a,n]of Object.entries(e)){if(!(0,o.f)(n,r.s))continue;let e=Object.entries((0,i.q)(n)).map(([e,t])=>({name:e,nullable:!t.notNull,hasDefault:t.hasDefault||void 0!==t.generated||void 0!==t.generatedIdentity}));t.push({name:a,columns:e})}return t}(n))},"drizzle");return(0,m.E)(n,s,{runtimeEnabled:(0,m.S)(a)}),n}}],36254)},80849,24374,e=>{"use strict";var t=e.i(14268),r=e.i(95934);let i=async()=>{let e=(0,t.l)(),i=e.context.requestStateAsyncStorage;if(i)return i;let a=await (0,r.f)();return e.context.requestStateAsyncStorage??=new a,e.context.requestStateAsyncStorage};async function a(){return void 0!==(await i()).getStore()}async function o(){let e=(await i()).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 n(e,t){return(await i()).run(e,t)}function s(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await o();if(!r.has(t)){let i=await e();return r.set(t,i),i}return r.get(t)},async set(e){(await o()).set(t,e)}}}e.s(["z",0,s,"B",0,a,"O",0,n],24374);let{get:l,set:c}=s(()=>!1);e.s(["T",0,l,"w",0,c],80849)},4721,e=>{"use strict";let t,r,i,a,o,n,s;var l,c,d=e.i(69774),u=e.i(90126);async function f(t,r){let i;if(t.database)i="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,d.R)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:a}=await e.A(63921);i=a(r)(t)}return i.transaction||(u.y.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),i.transaction=async e=>e(i)),i}var p=e.i(71616);async function m(t){return f(t,async t=>{let{createKyselyAdapter:r,kyselyAdapter:i}=await e.A(46120),{kysely:a,databaseType:o,transaction:n}=await r(t);if(!a)throw new p.p("Failed to initialize database adapter");return i(a,{type:o||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:n})(t)})}var h=p,g=e.i(43638),y=e.i(46378),w=e.i(31139),b=e.i(55281),E=e.i(67409),A=e.i(73278),I=e.i(77113);let T={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","int8","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL","BIGINT"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function _(e,t){return`${(0,E.d)(e)}\0${(0,E.d)(t)}`}function v(e,t){return`${e}\0${t}`}function O(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,r)=>e===t.columns[r])}function R(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:"1"===e||e?.toLowerCase()==="true"||"t"===e}function k(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[_(e.table,e.name),{columns:t.flatMap(e=>null===e.name?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>null!==e.name&&e.fullLength)}]}))}async function x(e,t,r,i){let a;if(i)return k(await i(r));switch(t.type){case"sqlite":a=(await I.f`
|
|
31
31
|
SELECT
|
|
32
32
|
tables.name AS "tableName",
|
|
33
33
|
index_list.name AS "indexName",
|
|
@@ -99,7 +99,7 @@ module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);
|
|
|
99
99
|
WHERE table_schemas.name = ${t.schema}
|
|
100
100
|
AND indexes.name IS NOT NULL
|
|
101
101
|
AND index_columns.key_ordinal > 0
|
|
102
|
-
`.execute(e)).rows}let o=new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,r=e.indexName??e.index_name??e.INDEX_NAME??e.name,i=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!r)continue;let a=_(t,r),n=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=void 0===n?
|
|
102
|
+
`.execute(e)).rows}let o=new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,r=e.indexName??e.index_name??e.INDEX_NAME??e.name,i=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!r)continue;let a=_(t,r),n=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=void 0===n?R(e.isUnique??e.is_unique):!R(n),l=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),c={fullLength:null!=i&&(void 0===e.prefixLength||null===e.prefixLength),name:i??null,position:l},d=R(e.isPartial),u=!R(e.isDisabled)&&!R(e.isHypothetical)&&(void 0===e.isValid||R(e.isValid)),f=o.get(a);o.set(a,f?{...f,columns:[...f.columns,c],partial:f.partial||d,valid:f.valid&&u}:{columns:[c],name:r,partial:d,table:t,unique:s,valid:u})}return k([...o.values()])}async function S(e,t){let r;switch(t.type){case"postgres":case"sqlite":return new Map;case"mysql":r=(await I.f`
|
|
103
103
|
SELECT
|
|
104
104
|
table_name AS tableName,
|
|
105
105
|
column_name AS columnName,
|
|
@@ -117,10 +117,10 @@ module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);
|
|
|
117
117
|
INNER JOIN sys.schemas AS table_schemas
|
|
118
118
|
ON table_schemas.schema_id = tables.schema_id
|
|
119
119
|
WHERE table_schemas.name = ${t.schema}
|
|
120
|
-
`.execute(e)).rows}let i=new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,r=e.columnName??e.COLUMN_NAME;if(!t||!r)continue;let a=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(v(t,r),{maxIndexBytes:a<0?null:a})}return i}var U=class extends h.p{};async function N(e,t,r){let i=e.selectFrom(r).select(I.f`1`.as("present"));return(await ("mssql"===t?i.top(1):i.limit(1)).execute()).length>0}async function D(e,{throwOnUnsafe:t=!0}={}){let r,i,{schema:a,tables:o,referenceKeys:n}=function(e){let{indexesByTable:t,tables:r}=(0,d.j)(e),i=new Map,a={};for(let e in r){let t=r[e],o=t.fields,n={};if(Object.entries(o).forEach(([e,t])=>{let a=t.references,o=a?r[a.model]:void 0,s=a&&o?{...t,references:{...a,model:o.modelName}}:t;n[t.fieldName||e]=s,a&&i.set(s,{modelKey:a.model,fieldKey:a.field})}),a[t.modelName]){a[t.modelName].fields={...a[t.modelName].fields,...n},t.disableMigrations&&(a[t.modelName].disableMigrations=!0);continue}a[t.modelName]={fields:n,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,r]of t)a[e]&&(a[e].indexes=r);return{schema:a,tables:r,referenceKeys:i}}(e),s=(0,u.J)(e.logger),l=[],c=e=>{if(t)throw new U(e);l.push(e)},{kysely:f,databaseType:p,introspectIndexes:m,schemaName:k}=await (0,g.createKyselyAdapter)(e);switch(!p&&(s.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),p="sqlite"),!f&&(s.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1)),p){case"postgres":{let e=k??await (0,g.getPostgresSchema)(f);r={type:"postgres",schema:e},s.debug(`PostgreSQL migration: Using schema '${e}' (${k?"from database.schemaName":"from search_path"})`);try{(await f.introspection.getSchemas()).some(({name:t})=>t===e)||(k?s.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):s.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){s.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}i=(await (0,g.introspectPostgresTables)(f,[e])).filter(e=>!e.isView&&!e.isForeign),s.debug(`Found ${i.length} table(s) in schema '${e}': ${i.map(e=>e.name).join(", ")||"(none)"}`);break}case"mssql":{let e=await (0,g.getMssqlSchema)(f);r={type:"mssql",schema:e},s.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),i=(await f.introspection.getTables()).filter(t=>t.schema===e);break}case"mysql":r={type:"mysql"},i=await f.introspection.getTables();break;case"sqlite":r={type:"sqlite"},i=await f.introspection.getTables()}let R=await x(f,r,i.map(e=>e.name),m),L=await S(f,r),C=(0,b.I)((0,g.toPhysicalSchema)(f,a),(0,g.toIntrospectedTables)(i)).filter(e=>"unexpected-required-column"===e.kind).map(e=>(0,b.u)(e,"database")),z=[],j=[],P=[],B=new Map;for(let[e,t]of Object.entries(a)){if(t.disableMigrations)continue;let r=i.find(t=>t.name===e);for(let i of t.indexes??[]){let a=i.name,o=_(e,a),n=R.get(o);if(n){if(!O(n,i))throw new h.p(`Database index "${a}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if("sqlite"===p||"postgres"===p){let t=[...R.values()].find(t=>(0,E.d)(t.name)===(0,E.d)(a)&&(0,E.d)(t.table)!==(0,E.d)(e));if(t)throw new h.p(`Database index name "${a}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=B.get(o);if(s){if(!O({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},i))throw new h.p(`Database index name "${a}" identifies more than one index on table "${e}".`);continue}r&&("mysql"===p||"mssql"===p)&&function({columnBounds:e,dbType:t,existingColumns:r,fields:i,indexes:a,index:o,table:n}){let s="mysql"===t?3072:1700,l=0;for(let s of o.columns){let c=i[s];if(c)if("string"===c.type||Array.isArray(c.type)){if(!r.has(s)){l+=((0,E.e)({columnName:s,dialect:t,fields:i,indexes:a})??0)*("mysql"===t?4:1);continue}let c=e.get(v(n,s));if(!c?.maxIndexBytes)throw new h.p(`Cannot create database index "${o.name}" on existing table "${n}" because column "${s}" is not bounded for ${"mysql"===t?"MySQL":"SQL Server"}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);l+=c.maxIndexBytes}else l+=16}if(l>s)throw new h.p(`Cannot create database index "${o.name}" on existing table "${n}" because its columns can exceed ${"mysql"===t?"MySQL":"SQL Server"}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}({columnBounds:L,dbType:p,existingColumns:new Set(r.columns.map(e=>e.name)),fields:t.fields,index:i,indexes:t.indexes??[],table:e}),B.set(o,i),P.push({table:e,index:i,name:a})}if(!r){let r=z.findIndex(t=>t.table===e),i={table:e,fields:t.fields,order:t.order||1/0},a=z.findIndex(e=>(e.order||1/0)>i.order);-1===a?-1===r?z.push(i):z[r].fields={...z[r].fields,...t.fields}:z.splice(a,0,i);continue}let a={};for(let[i,o]of Object.entries(t.fields)){let t=r.columns.find(e=>e.name===i);if(!t){a[i]=o;continue}!1!==o.required&&t.isNullable&&s.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!function(e,t,r){if("string[]"===t||"number[]"===t)return e.toLowerCase().includes("json");let i=T[r];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(e.toLowerCase().split("(")[0].trim())}(t.dataType,o.type,p)&&s.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(a).length>0&&j.push({table:e,fields:a,order:t.order||1/0})}let M=[];k&&z.length>0&&M.push(f.schema.createSchema(k).ifNotExists());let $=e.advanced?.database?.generateId==="uuid",q=e.advanced?.database?.generateId==="serial";function H(e,t,r){let i=e.type,a=p||"sqlite",o={string:{sqlite:"text",postgres:"text",mysql:r?`varchar(${r})`:e.unique?"varchar(255)":e.references?"varchar(36)":e.sortable||e.index?"varchar(255)":"text",mssql:r?`varchar(${r})`:e.unique||e.sortable?"varchar(255)":e.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:e.bigint?"bigint":"integer",postgres:e.bigint?"bigint":"integer",mysql:e.bigint?"bigint":"integer",mssql:e.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:I.f`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:q?I.f`integer GENERATED BY DEFAULT AS IDENTITY`:$?"uuid":"text",mysql:q?"integer":"varchar(36)",mssql:q?"integer":"varchar(36)",sqlite:q?"integer":"text"},foreignKeyId:{postgres:q?"integer":$?"uuid":"text",mysql:q?"integer":"varchar(36)",mssql:q?"integer":"varchar(36)",sqlite:q?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===t||e.references?.field==="id")return"id"===t?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return"text";if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let F=(0,w.f)({schema:o,usePlural:!1}),V=(0,y.f)({schema:o,usePlural:!1});function W(e){let t=e.references;if(!t)throw new h.p("Cannot resolve a field without references.");let r=n.get(e);if(!r)throw new h.p(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${F(r.modelKey)}.${V({model:r.modelKey,field:r.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let K=[],G=(e,t)=>{if("mysql"!==p&&"mssql"!==p)return;let r=a[e];if(r)return(0,E.e)({columnName:t,dialect:p,fields:r.fields,indexes:r.indexes??[]})};if(j.length){let e=new Map;for(let t of j)for(let[r,i]of Object.entries(t.fields)){var J;let a=(J=p,"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===J||"mysql"===J||"mssql"===J)),o=!(i.unique&&!1===i.required)&&("string"===i.type||"number"===i.type||"boolean"===i.type)&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue;if(!1!==i.required&&!a&&!o){let a=e.get(t.table);if(void 0===a&&(a=await N(f,p,t.table),e.set(t.table,a)),a){let e="string"===i.type?" For a text column, every existing row ends up with the same empty string.":"";c(`Cannot add required column "${r}" to populated table "${t.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let n=H(i,r,G(t.table,r)),l=f.schema.alterTable(t.table);if(i.index||i.unique){let e=(0,E.j)(t.table,r,i.unique??!1),a=f.schema.createIndex(e).on(t.table).columns([r]);i.unique&&(a=a.unique(),!1===i.required&&"mssql"===p&&(a=a.where(r,"is not",null)),!1!==i.required&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue&&s.warn(`Adding unique column "${r}" to existing table "${t.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),K.push(a)}let d=l.addColumn(r,n,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(W(i)).onDelete(i.references.onDelete||"cascade")),a?e="mysql"===p?e.defaultTo(I.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(I.f`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo("boolean"==typeof i.defaultValue&&("sqlite"===p||"mssql"===p)?+!!i.defaultValue:i.defaultValue)),e));M.push(d)}}if(z.length)for(let e of z){let t=H({type:q?"number":"string"},"id"),r=f.schema.createTable(e.table).addColumn("id",t,e=>{if(q)return"postgres"===p?e.primaryKey().notNull():"sqlite"===p?e.primaryKey().notNull():"mssql"===p?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull();return $&&"postgres"===p?e.primaryKey().defaultTo(I.f`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull()});for(let[t,i]of Object.entries(e.fields)){let a=H(i,t,G(e.table,t));if(r=r.addColumn(t,a,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(W(i)).onDelete(i.references.onDelete||"cascade")),i.unique&&(e=e.unique()),"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===p||"mysql"===p||"mssql"===p)&&(e="mysql"===p?e.defaultTo(I.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(I.f`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let r=f.schema.createIndex((0,E.j)(e.table,t,!1)).on(e.table).columns([t]);K.push(r)}}M.push(r)}for(let{table:e,index:t,name:r}of P){let i=f.schema.createIndex(r).on(e).columns([...t.columns]);t.unique&&(i=i.unique()),K.push(i)}for(let e of K)M.push(e);return{toBeCreated:z,toBeAdded:j,toBeAddedIndexes:P,unsafeChanges:l,schemaProblems:C,runMigrations:async function(){try{for(let e of M)await e.execute()}finally{M.length&&e.database&&(0,A.P)(e.database)}},compileMigrations:async function(){return M.map(e=>e.compile().sql).join(";\n\n")+";"}}}var L=e.i(86198),C=e.i(90659),z=e.i(96481),j=e.i(76411),P=e.i(7855),B=e.i(15143);let M=/[\u0000-\u001f\u007f-\u009f]/,$="https://better-auth.invalid",q=/%2[fF]|%5[cC]/,H=/^(?=.*\d)[\d*?.]+$/,F=P.ipv4(),V=(e,t)=>{let[r=""]=e.split(":");if(!H.test(r))return!0;let[i=""]=t.split(":");return B.f(F,i)},W=(e,t=!1)=>{if(M.test(e))return null;let r=e.indexOf(":");if(r<=0)return null;let i=e.slice(0,r).toLowerCase(),a=e.slice(r+1),o="";if(a.startsWith("//")){let e=(a=a.slice(2)).search(t?/[/#]/:/[/?#]/);-1===e?(o=a,a=""):(o=a.slice(0,e),a=a.slice(e))}let n=a.search(t?/#/:/[?#]/),s=(e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let r=[];for(let e of t.split("/"))".."===e?r.pop():"."!==e&&""!==e&&r.push(e);return r.length>0?`/${r.join("/")}`:""})(-1===n?a:a.slice(0,n));return{scheme:i,authority:o.toLowerCase(),path:s}},K=(e,t,r)=>{if(e.startsWith("/"))return r?.allowRelativePaths===!0&&(e=>{if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||M.test(e))return!1;let t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t);if(q.test(r))return!1;try{return new URL(e,$).origin===$}catch{return!1}})(e);let i=t.includes("*")||t.includes("?");if(i&&!t.includes("://")){let r=(0,z.$)(e);return!!r&&(0,j.f)(t)(r)&&V(t,r)}let a=(0,z.Y)(e);if("http:"===a||"https:"===a||!a){if(!i)return t===(0,z.H)(e);let r=(0,z.H)(e);return null!==r&&!!(0,j.f)(t)(r)&&V(t.slice(t.indexOf("://")+3),r.slice(r.indexOf("://")+3))}let o=W(e),n=W(t,i);return!!o&&!!n&&o.scheme===n.scheme&&(i?!o.authority.includes("@")&&(!n.authority||!!((0,j.f)(n.authority)(o.authority)&&V(n.authority,o.authority)))&&(!n.path||(0,j.f)(n.path)(o.path||"/")):(!n.authority||o.authority===n.authority)&&(!n.path||o.path===n.path||o.path.startsWith(`${n.path}/`)))};var G=e.i(10228);function J(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let i=t.replace(/\/+$/,"");return""===i?r:r===i?"/":r.startsWith(i+"/")?r.slice(i.length).replace(/\/+$/,"")||"/":r}let Q="https://better-auth.invalid";function Y(e,t){let r=e.startsWith("/");if(e.startsWith("//")||e.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let i=r?new URL(e,Q):new URL(e);if(r&&i.origin!==Q)throw TypeError("Expected an absolute or root-relative URL");let a=t.toString();if(!a)return e;let o=i.search.endsWith("&")?"":"&";return i.search=i.search?`${i.search}${o}${a}`:a,r?i.href.slice(i.origin.length):i.href}function Z(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function X(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,i=J(e.request.url,r);return t.some(e=>{let t=e.replace(/\/+$/,"");return i===t||i.startsWith(`${t}/`)})}catch{}return!1}let ee=(l=function(){},a=!1,function(...e){return a||(((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."),a=!0),l.apply(this,e)}),et=(0,C.a)(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await ei(e),X(e)))return;let{body:t,query:r}=e,i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,o=t?.errorCallbackURL,n=t?.newUserCallbackURL,s=(t,r)=>{if(t){if("string"!=typeof t)throw p.E.fromStatus("BAD_REQUEST",{message:`Invalid ${r}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
120
|
+
`.execute(e)).rows}let i=new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,r=e.columnName??e.COLUMN_NAME;if(!t||!r)continue;let a=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(v(t,r),{maxIndexBytes:a<0?null:a})}return i}var U=class extends h.p{};async function N(e,t,r){let i=e.selectFrom(r).select(I.f`1`.as("present"));return(await ("mssql"===t?i.top(1):i.limit(1)).execute()).length>0}async function D(e,{throwOnUnsafe:t=!0}={}){let r,i,{schema:a,tables:o,referenceKeys:n}=function(e){let{indexesByTable:t,tables:r}=(0,d.j)(e),i=new Map,a={};for(let e in r){let t=r[e],o=t.fields,n={};if(Object.entries(o).forEach(([e,t])=>{let a=t.references,o=a?r[a.model]:void 0,s=a&&o?{...t,references:{...a,model:o.modelName}}:t;n[t.fieldName||e]=s,a&&i.set(s,{modelKey:a.model,fieldKey:a.field})}),a[t.modelName]){a[t.modelName].fields={...a[t.modelName].fields,...n},t.disableMigrations&&(a[t.modelName].disableMigrations=!0);continue}a[t.modelName]={fields:n,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,r]of t)a[e]&&(a[e].indexes=r);return{schema:a,tables:r,referenceKeys:i}}(e),s=(0,u.J)(e.logger),l=[],c=e=>{if(t)throw new U(e);l.push(e)},{kysely:f,databaseType:p,introspectIndexes:m,schemaName:R}=await (0,g.createKyselyAdapter)(e);switch(!p&&(s.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),p="sqlite"),!f&&(s.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1)),p){case"postgres":{let e=R??await (0,g.getPostgresSchema)(f);r={type:"postgres",schema:e},s.debug(`PostgreSQL migration: Using schema '${e}' (${R?"from database.schemaName":"from search_path"})`);try{(await f.introspection.getSchemas()).some(({name:t})=>t===e)||(R?s.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):s.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){s.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}i=(await (0,g.introspectPostgresTables)(f,[e])).filter(e=>!e.isView&&!e.isForeign),s.debug(`Found ${i.length} table(s) in schema '${e}': ${i.map(e=>e.name).join(", ")||"(none)"}`);break}case"mssql":{let e=await (0,g.getMssqlSchema)(f);r={type:"mssql",schema:e},s.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),i=(await f.introspection.getTables()).filter(t=>t.schema===e);break}case"mysql":r={type:"mysql"},i=await f.introspection.getTables();break;case"sqlite":r={type:"sqlite"},i=await f.introspection.getTables()}let k=await x(f,r,i.map(e=>e.name),m),L=await S(f,r),C=(0,b.I)((0,g.toPhysicalSchema)(f,a),(0,g.toIntrospectedTables)(i)).filter(e=>"unexpected-required-column"===e.kind).map(e=>(0,b.u)(e,"database")),z=[],j=[],P=[],B=new Map;for(let[e,t]of Object.entries(a)){if(t.disableMigrations)continue;let r=i.find(t=>t.name===e);for(let i of t.indexes??[]){let a=i.name,o=_(e,a),n=k.get(o);if(n){if(!O(n,i))throw new h.p(`Database index "${a}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if("sqlite"===p||"postgres"===p){let t=[...k.values()].find(t=>(0,E.d)(t.name)===(0,E.d)(a)&&(0,E.d)(t.table)!==(0,E.d)(e));if(t)throw new h.p(`Database index name "${a}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=B.get(o);if(s){if(!O({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},i))throw new h.p(`Database index name "${a}" identifies more than one index on table "${e}".`);continue}r&&("mysql"===p||"mssql"===p)&&function({columnBounds:e,dbType:t,existingColumns:r,fields:i,indexes:a,index:o,table:n}){let s="mysql"===t?3072:1700,l=0;for(let s of o.columns){let c=i[s];if(c)if("string"===c.type||Array.isArray(c.type)){if(!r.has(s)){l+=((0,E.e)({columnName:s,dialect:t,fields:i,indexes:a})??0)*("mysql"===t?4:1);continue}let c=e.get(v(n,s));if(!c?.maxIndexBytes)throw new h.p(`Cannot create database index "${o.name}" on existing table "${n}" because column "${s}" is not bounded for ${"mysql"===t?"MySQL":"SQL Server"}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);l+=c.maxIndexBytes}else l+=16}if(l>s)throw new h.p(`Cannot create database index "${o.name}" on existing table "${n}" because its columns can exceed ${"mysql"===t?"MySQL":"SQL Server"}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}({columnBounds:L,dbType:p,existingColumns:new Set(r.columns.map(e=>e.name)),fields:t.fields,index:i,indexes:t.indexes??[],table:e}),B.set(o,i),P.push({table:e,index:i,name:a})}if(!r){let r=z.findIndex(t=>t.table===e),i={table:e,fields:t.fields,order:t.order||1/0},a=z.findIndex(e=>(e.order||1/0)>i.order);-1===a?-1===r?z.push(i):z[r].fields={...z[r].fields,...t.fields}:z.splice(a,0,i);continue}let a={};for(let[i,o]of Object.entries(t.fields)){let t=r.columns.find(e=>e.name===i);if(!t){a[i]=o;continue}!1!==o.required&&t.isNullable&&s.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!function(e,t,r){if("string[]"===t||"number[]"===t)return e.toLowerCase().includes("json");let i=T[r];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(e.toLowerCase().split("(")[0].trim())}(t.dataType,o.type,p)&&s.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(a).length>0&&j.push({table:e,fields:a,order:t.order||1/0})}let M=[];R&&z.length>0&&M.push(f.schema.createSchema(R).ifNotExists());let $=e.advanced?.database?.generateId==="uuid",q=e.advanced?.database?.generateId==="serial";function H(e,t,r){let i=e.type,a=p||"sqlite",o={string:{sqlite:"text",postgres:"text",mysql:r?`varchar(${r})`:e.unique?"varchar(255)":e.references?"varchar(36)":e.sortable||e.index?"varchar(255)":"text",mssql:r?`varchar(${r})`:e.unique||e.sortable?"varchar(255)":e.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:e.bigint?"bigint":"integer",postgres:e.bigint?"bigint":"integer",mysql:e.bigint?"bigint":"integer",mssql:e.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:I.f`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:q?I.f`integer GENERATED BY DEFAULT AS IDENTITY`:$?"uuid":"text",mysql:q?"integer":"varchar(36)",mssql:q?"integer":"varchar(36)",sqlite:q?"integer":"text"},foreignKeyId:{postgres:q?"integer":$?"uuid":"text",mysql:q?"integer":"varchar(36)",mssql:q?"integer":"varchar(36)",sqlite:q?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===t||e.references?.field==="id")return"id"===t?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return"text";if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let F=(0,w.f)({schema:o,usePlural:!1}),V=(0,y.f)({schema:o,usePlural:!1});function W(e){let t=e.references;if(!t)throw new h.p("Cannot resolve a field without references.");let r=n.get(e);if(!r)throw new h.p(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${F(r.modelKey)}.${V({model:r.modelKey,field:r.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let K=[],G=(e,t)=>{if("mysql"!==p&&"mssql"!==p)return;let r=a[e];if(r)return(0,E.e)({columnName:t,dialect:p,fields:r.fields,indexes:r.indexes??[]})};if(j.length){let e=new Map;for(let t of j)for(let[r,i]of Object.entries(t.fields)){var J;let a=(J=p,"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===J||"mysql"===J||"mssql"===J)),o=!(i.unique&&!1===i.required)&&("string"===i.type||"number"===i.type||"boolean"===i.type)&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue;if(!1!==i.required&&!a&&!o){let a=e.get(t.table);if(void 0===a&&(a=await N(f,p,t.table),e.set(t.table,a)),a){let e="string"===i.type?" For a text column, every existing row ends up with the same empty string.":"";c(`Cannot add required column "${r}" to populated table "${t.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let n=H(i,r,G(t.table,r)),l=f.schema.alterTable(t.table);if(i.index||i.unique){let e=(0,E.j)(t.table,r,i.unique??!1),a=f.schema.createIndex(e).on(t.table).columns([r]);i.unique&&(a=a.unique(),!1===i.required&&"mssql"===p&&(a=a.where(r,"is not",null)),!1!==i.required&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue&&s.warn(`Adding unique column "${r}" to existing table "${t.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),K.push(a)}let d=l.addColumn(r,n,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(W(i)).onDelete(i.references.onDelete||"cascade")),a?e="mysql"===p?e.defaultTo(I.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(I.f`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo("boolean"==typeof i.defaultValue&&("sqlite"===p||"mssql"===p)?+!!i.defaultValue:i.defaultValue)),e));M.push(d)}}if(z.length)for(let e of z){let t=H({type:q?"number":"string"},"id"),r=f.schema.createTable(e.table).addColumn("id",t,e=>{if(q)return"postgres"===p?e.primaryKey().notNull():"sqlite"===p?e.primaryKey().notNull():"mssql"===p?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull();return $&&"postgres"===p?e.primaryKey().defaultTo(I.f`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull()});for(let[t,i]of Object.entries(e.fields)){let a=H(i,t,G(e.table,t));if(r=r.addColumn(t,a,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(W(i)).onDelete(i.references.onDelete||"cascade")),i.unique&&(e=e.unique()),"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===p||"mysql"===p||"mssql"===p)&&(e="mysql"===p?e.defaultTo(I.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(I.f`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let r=f.schema.createIndex((0,E.j)(e.table,t,!1)).on(e.table).columns([t]);K.push(r)}}M.push(r)}for(let{table:e,index:t,name:r}of P){let i=f.schema.createIndex(r).on(e).columns([...t.columns]);t.unique&&(i=i.unique()),K.push(i)}for(let e of K)M.push(e);return{toBeCreated:z,toBeAdded:j,toBeAddedIndexes:P,unsafeChanges:l,schemaProblems:C,runMigrations:async function(){try{for(let e of M)await e.execute()}finally{M.length&&e.database&&(0,A.P)(e.database)}},compileMigrations:async function(){return M.map(e=>e.compile().sql).join(";\n\n")+";"}}}var L=e.i(86198),C=e.i(90659),z=e.i(96481),j=e.i(76411),P=e.i(7855),B=e.i(15143);let M=/[\u0000-\u001f\u007f-\u009f]/,$="https://better-auth.invalid",q=/%2[fF]|%5[cC]/,H=/^(?=.*\d)[\d*?.]+$/,F=P.ipv4(),V=(e,t)=>{let[r=""]=e.split(":");if(!H.test(r))return!0;let[i=""]=t.split(":");return B.f(F,i)},W=(e,t=!1)=>{if(M.test(e))return null;let r=e.indexOf(":");if(r<=0)return null;let i=e.slice(0,r).toLowerCase(),a=e.slice(r+1),o="";if(a.startsWith("//")){let e=(a=a.slice(2)).search(t?/[/#]/:/[/?#]/);-1===e?(o=a,a=""):(o=a.slice(0,e),a=a.slice(e))}let n=a.search(t?/#/:/[?#]/),s=(e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let r=[];for(let e of t.split("/"))".."===e?r.pop():"."!==e&&""!==e&&r.push(e);return r.length>0?`/${r.join("/")}`:""})(-1===n?a:a.slice(0,n));return{scheme:i,authority:o.toLowerCase(),path:s}},K=(e,t,r)=>{if(e.startsWith("/"))return r?.allowRelativePaths===!0&&(e=>{if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||M.test(e))return!1;let t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t);if(q.test(r))return!1;try{return new URL(e,$).origin===$}catch{return!1}})(e);let i=t.includes("*")||t.includes("?");if(i&&!t.includes("://")){let r=(0,z.$)(e);return!!r&&(0,j.f)(t)(r)&&V(t,r)}let a=(0,z.Y)(e);if("http:"===a||"https:"===a||!a){if(!i)return t===(0,z.H)(e);let r=(0,z.H)(e);return null!==r&&!!(0,j.f)(t)(r)&&V(t.slice(t.indexOf("://")+3),r.slice(r.indexOf("://")+3))}let o=W(e),n=W(t,i);return!!o&&!!n&&o.scheme===n.scheme&&(i?!o.authority.includes("@")&&(!n.authority||!!((0,j.f)(n.authority)(o.authority)&&V(n.authority,o.authority)))&&(!n.path||(0,j.f)(n.path)(o.path||"/")):(!n.authority||o.authority===n.authority)&&(!n.path||o.path===n.path||o.path.startsWith(`${n.path}/`)))};var G=e.i(10228);function J(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let i=t.replace(/\/+$/,"");return""===i?r:r===i?"/":r.startsWith(i+"/")?r.slice(i.length).replace(/\/+$/,"")||"/":r}let Q="https://better-auth.invalid";function Y(e,t){let r=e.startsWith("/");if(e.startsWith("//")||e.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let i=r?new URL(e,Q):new URL(e);if(r&&i.origin!==Q)throw TypeError("Expected an absolute or root-relative URL");let a=t.toString();if(!a)return e;let o=i.search.endsWith("&")?"":"&";return i.search=i.search?`${i.search}${o}${a}`:a,r?i.href.slice(i.origin.length):i.href}function Z(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function X(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,i=J(e.request.url,r);return t.some(e=>{let t=e.replace(/\/+$/,"");return i===t||i.startsWith(`${t}/`)})}catch{}return!1}let ee=(l=function(){},a=!1,function(...e){return a||(((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."),a=!0),l.apply(this,e)}),et=(0,C.a)(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await ei(e),X(e)))return;let{body:t,query:r}=e,i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,o=t?.errorCallbackURL,n=t?.newUserCallbackURL,s=(t,r)=>{if(t){if("string"!=typeof t)throw p.E.fromStatus("BAD_REQUEST",{message:`Invalid ${r}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
121
121
|
`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),"origin"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_ORIGIN);if("callbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_CALLBACK_URL);if("redirectURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_NEW_USER_CALLBACK_URL);throw p.E.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}}};i&&s(i,"callbackURL"),a&&s(a,"redirectURL"),o&&s(o,"errorCallbackURL"),n&&s(n,"newUserCallbackURL")}),er=e=>(0,C.a)(async t=>{if(!t.request||X(t))return;let r=e(t),i=(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
|
|
122
122
|
`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),"origin"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_ORIGIN);if("callbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_CALLBACK_URL);if("redirectURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw p.E.from("FORBIDDEN",G.f.INVALID_NEW_USER_CALLBACK_URL);throw p.E.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};for(let e of Array.isArray(r)?r:[r])i(e,"callbackURL")});async function ei(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let i=r.get("origin"),a=i||r.get("referer")||"",o=r.has("cookie");if(e.context.skipCSRFCheck)return;if(Z(e)){e.context.options.advanced?.disableOriginCheck===!0&&ee();return}if(X(e)||!(t||o))return;let n="null"===i&&"same-origin"===r.get("sec-fetch-site")?(0,z.X)(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(n?(0,z.H)(n):void 0)??a;if(!s||"null"===s)throw p.E.from("FORBIDDEN",G.f.MISSING_OR_NULL_ORIGIN);let l=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!l.some(e=>K(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config
|
|
123
|
-
`,`Current list of trustedOrigins: ${l}`),p.E.from("FORBIDDEN",G.f.INVALID_ORIGIN)}let ea=(0,C.a)(async e=>{e.request&&await eo(e)});async function eo(e){let t=e.request;if(!t||e.context.skipCSRFCheck||Z(e))return;let r=t.headers;if(r.has("cookie"))return await ei(e);let i=r.get("Sec-Fetch-Site"),a=r.get("Sec-Fetch-Mode"),o=r.get("Sec-Fetch-Dest");if(i&&i.trim()||a&&a.trim()||o&&o.trim()){if("cross-site"===i&&"navigate"===a)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:i,secFetchMode:a,secFetchDest:o}),p.E.from("FORBIDDEN",G.f.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await ei(e,!0)}if(r.get("origin")||r.get("referer"))return await ei(e,!0)}var en=e.i(47391);let es=P.ipv4(),el=P.ipv6();function ec(e){return B.f(es,e)}function ed(e){return B.f(el,e)}function eu(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let e=t.substring(7);if(ec(e))return e}let r=e.split(":");if(7===r.length&&r[5]?.toLowerCase()==="ffff"){let e=r[6];if(e&&ec(e))return e}if(t.includes("::ffff:")||t.includes(":ffff:")){let t=ef(e);if(8===t.length&&"0000"===t[0]&&"0000"===t[1]&&"0000"===t[2]&&"0000"===t[3]&&"0000"===t[4]&&"ffff"===t[5]&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function ef(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],i=t[1]?t[1].split(":"):[],a=Array(8-r.length-i.length).fill("0000");return[...r.map(e=>e.padStart(4,"0")),...a,...i.map(e=>e.padStart(4,"0"))]}return e.split(":").map(e=>e.padStart(4,"0"))}function ep(e,t={}){if(ec(e)||!ed(e))return e.toLowerCase();let r=eu(e);if(r)return r.toLowerCase();var i=t.ipv6Subnet??64;let a=ef(e);if(void 0!==i&&i<128){let e=Math.max(0,Math.floor(i));return a.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 a.join(":").toLowerCase()}function em(e){if(ec(e))return Uint8Array.from(e.split(".").map(e=>Number(e)));if(!ed(e))return null;let t=eu(e);if(t)return Uint8Array.from(t.split(".").map(e=>Number(e)));let r=ef(e),i=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(r[e]??"0",16);i[2*e]=t>>8&255,i[2*e+1]=255&t}return i}let eh=/^\d+$/;function eg(e){let t=e.lastIndexOf("/"),r=em(-1===t?e:e.slice(0,t));if(!r)return null;let i=8*r.length;if(-1===t)return{bytes:r,prefix:i};let a=e.slice(t+1);if(!eh.test(a))return null;let o=Number(a);return o<=i?{bytes:r,prefix:o}:null}let ey=["x-forwarded-for"];function ew(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||ey){let i="get"in r?r.get(e):r[e];if("string"==typeof i){let e=function(e,t={}){let r=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===r.length)return null;let i=(t.trustedProxies??[]).map(eg).filter(e=>null!==e);if(i.length>0){for(let e=r.length-1;e>=0;e--){let a=r[e],o=a?em(a):null;if(!a||!o)break;if(!i.some(e=>(function(e,t){if(e.length!==t.bytes.length)return!1;let r=t.prefix;for(let i=0;i<e.length&&r>0;i++){let a=r>=8?8:r,o=8===a?255:255<<8-a&255;if(((e[i]??0)&o)!=((t.bytes[i]??0)&o))return!1;r-=8}return!0})(o,e)))return ep(a,{ipv6Subnet:t.ipv6Subnet})}return null}if(1!==r.length)return null;let a=r[0];return a&&(ec(a)||ed(a))?ep(a,{ipv6Subnet:t.ipv6Subnet}):null}(i,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return(0,en.s)()||(0,en.o)()?"127.0.0.1":null}let eb=new Map;function eE(e,t){return Math.ceil((e+1e3*t-Date.now())/1e3)}let eA=!1;async function eI(e,t){var r;let i=new URL(t.baseURL).pathname,a=J(e.url,i),o=t.rateLimit.window,n=t.rateLimit.max,s=ew(e,t.options);if(!s&&t.options.advanced?.ipAddress?.disableIpTracking)return null;s||eA||(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),eA=!0);let l=(r=s??"no-trusted-ip",`${r}|${a}`),c=e_().find(e=>e.pathMatcher(a));for(let e of(c&&(o=c.window,n=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(a));if(t){o=t.window,n=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?(0,j.f)(e)(a):e===a);if(r){let i=t.rateLimit.customRules[r],a="function"==typeof i?await i(e,{window:o,max:n}):i;if(a&&(o=a.window,n=a.max),!1===a)return null}}return{key:l,currentWindow:o,currentMax:n}}async function eT(e,t){if(!t.rateLimit.enabled)return;let r=await eI(e,t);if(!r)return;let{key:i,currentWindow:a,currentMax:o}=r,n=function(e){let t,r,i,a,o,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let s=e.rateLimit.storage;if("secondary-storage"===s){let t=e.options.secondaryStorage?.increment;if(!t)throw new p.p("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(r,i)=>await t(r,i.window??e.options.rateLimit?.window??10)<=i.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:i.window}}}return"memory"===s?{async consume(t,r){var i;let a;!function(){let e=Date.now();for(let[t,r]of eb)e>=r.expiresAt&&eb.delete(t);if(eb.size<=1e5)return;let t=eb.size-1e5,r=0;for(let e of eb.keys())if(eb.delete(e),++r>=t)break}();let o=Date.now(),n=eb.get(t),s=(i=n&&o<n.expiresAt?n.data:void 0,a=1e3*r.window,i?o-i.lastRequest>=a?{next:{...i,count:1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:i.count>=r.max?{next:i,update:!0,allowed:!1,retryAfter:eE(i.lastRequest,r.window)}:{next:{...i,count:i.count+1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:o},update:!1,allowed:!0,retryAfter:null});return s.allowed&&eb.set(t,{data:{...s.next,key:t},expiresAt:o+1e3*(r.window??e.options.rateLimit?.window??10)}),{allowed:s.allowed,retryAfter:s.retryAfter}}}:(t="rateLimit",r=e.adapter,i=Math.max(...function(e){let t=[e.rateLimit.window,...e_().map(e=>e.window)];for(let r of e.options.plugins||[])r.rateLimit&&t.push(...r.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let r of Object.values(e.rateLimit.customRules))r&&"function"!=typeof r&&t.push(r.window);let r=t.filter(e=>Number.isFinite(e)&&e>0);return r.length>0?r:[e.rateLimit.window]}(e)),a=async e=>{let i=(await r.findMany({model:t,where:[{field:"key",value:e}]}))[0];return i&&(i.lastRequest=Number(i.lastRequest)),i},o=async(e,s)=>{s.window>i&&(i=s.window);let l=1e3*s.window,c=await a(e),d=Date.now();if(!c)try{return await r.create({model:t,data:{key:e,count:1,lastRequest:d}}),{allowed:!0,retryAfter:null}}catch(t){if(!await a(e))throw t;return o(e,s)}if(d-c.lastRequest>=l)return await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"lte",value:c.lastRequest}],increment:{},set:{count:1,lastRequest:d}})?(await n(d),{allowed:!0,retryAfter:null}):o(e,s);let u=d-l;if(await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"gt",value:u},{field:"count",operator:"lt",value:s.max}],increment:{count:1},set:{lastRequest:d}}))return{allowed:!0,retryAfter:null};let f=await a(e);return!f||d-f.lastRequest>=l?o(e,s):{allowed:!1,retryAfter:eE(f.lastRequest,s.window)}},n=async a=>{let o=a-1e3*i;await e.runInBackgroundOrAwait(r.deleteMany({model:t,where:[{field:"lastRequest",operator:"lt",value:o}]}).then(()=>void 0).catch(t=>e.logger.error("Error pruning rate limit rows",t)))},{consume:o})}(t),{allowed:s,retryAfter:l}=await n.consume(i,{window:a,max:o});if(!s){var c;return c=l??a,new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":c.toString()}})}}function e_(){return[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}]}var ev=e.i(70728),eO=e.i(42158);function ek(e){if(!e?.method)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if("oauth"===e.method&&!e.oauth?.providerId)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if(("sso-oidc"===e.method||"sso-saml"===e.method)&&!e.sso?.providerId)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function eR(e,t){let r,i=e.context.options.user?.validateUserInfo;if(i){ek(t.source);try{r=await i(t,e)}catch(t){throw e.context.logger.error("validateUserInfo callback threw",t),new p.E("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(r?.error)throw new p.E("FORBIDDEN",{code:r.error,message:r.errorDescription||r.error})}}var ex=e.i(56023),eS=e.i(30501),eU=e.i(82318);let eN=async e=>{let t=await (0,eU.f)("SHA-256").digest(new TextEncoder().encode(e));return eS.W.encode(new Uint8Array(t),{padding:!1})};async function eD(e,t){return t&&"plain"!==t?"hashed"===t?eN(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function eL(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,i]of Object.entries(t.overrides))if(e.startsWith(r))return i}return t.default}return t}}var eC=e.i(73436),ez=e.i(97515),ej=e.i(13082),eP=e.i(33931),eB=e.i(87819),eM=e.i(18195),e$=e.i(30283),eq=e.i(24891);function eH(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let eF=(e,t)=>{let r,i,a=t.logger,o=t.options,n=o.secondaryStorage,s=new Map,l=0,c=o.session?.expiresIn||604800,d=!!n&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:u,updateWithHooks:f,updateManyWithHooks:m,deleteWithHooks:h,deleteManyWithHooks:g,consumeOneWithHooks:y}=(r=(0,eP.f)(t.options),i=t.hooks,{createWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=t;for(let{source:e,hooks:t}of i){let i=t[a]?.create?.before;if(i){let t=await r(`db create.before ${a}`,{[ej.A]:"create.before",[ej.d]:a,[ej.s]:e},()=>i(s,n));if(!1===t)return null;"object"==typeof t&&"data"in t&&(s={...s,...t.data})}}let l=null;for(let{source:t,hooks:c}of((!o||o.executeMainFn)&&(l=await (await (0,eC.g)(e)).create({model:a,data:s,forceAllowId:!0})),o?.fn&&(l=await o.fn(l??s)),i)){let e=c[a]?.create?.after;e&&await (0,eC.A)(async()=>{await r(`db create.after ${a}`,{[ej.A]:"create.after",[ej.d]:a,[ej.s]:t},()=>e(l,n))})}return l},updateWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db update.before ${o}`,{[ej.A]:"update.before",[ej.d]:o,[ej.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,eC.g)(e)).update({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,eC.A)(async()=>{await r(`db update.after ${o}`,{[ej.A]:"update.after",[ej.d]:o,[ej.s]:e},()=>i(d,s))})}return d},updateManyWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db updateMany.before ${o}`,{[ej.A]:"updateMany.before",[ej.d]:o,[ej.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,eC.g)(e)).updateMany({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,eC.A)(async()=>{await r(`db updateMany.after ${o}`,{[ej.A]:"updateMany.after",[ej.d]:o,[ej.s]:e},()=>i(d,s))})}return d},deleteWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=null;try{s=(await (await (0,eC.g)(e)).findMany({model:a,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[ej.A]:"delete.before",[ej.d]:a,[ej.s]:e},()=>i(s,n))===!1)return null}let l=o?await o.fn(t):null,c=(!o||o.executeMainFn)&&s?await (await (0,eC.g)(e)).delete({model:a,where:t}):l;if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${a}`,{[ej.A]:"delete.after",[ej.d]:a,[ej.s]:e},()=>i(s,n))})}return c},deleteManyWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=[];try{s=await (await (0,eC.g)(e)).findMany({model:a,where:t})}catch{}for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[ej.A]:"delete.before",[ej.d]:a,[ej.s]:t},()=>i(e,n))===!1)return null}let l=o?await o.fn(t):null,c=!o||o.executeMainFn?await (await (0,eC.g)(e)).deleteMany({model:a,where:t}):l;for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${a}`,{[ej.A]:"delete.after",[ej.d]:a,[ej.s]:t},()=>i(e,n))})}return c},consumeOneWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=i.flatMap(({source:e,hooks:r})=>{let i=r[t]?.delete?.before;return i?[{source:e,fn:i}]:[]}),c=n??null;if(l.length){if(!c)try{c=(await (await (0,eC.g)(e)).findMany({model:t,where:a,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:i}of l)if(await r(`db delete.before ${t}`,{[ej.A]:"delete.before",[ej.d]:t,[ej.s]:e},()=>i(c,s))===!1)return null}}let d=await o();if(!d)return null;for(let{source:e,hooks:a}of i){let i=a[t]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${t}`,{[ej.A]:"delete.after",[ej.d]:t,[ej.s]:e},()=>i(d,s))})}return d}}),w=(t,r)=>{let i=[...t,{field:"expiresAt",value:new Date,operator:"gt"}];return g(i,"session",{fn:async()=>{await (await (0,eC.g)(e)).updateMany({model:"session",where:i,update:{expiresAt:new Date}}),await r?.()},executeMainFn:!1})};async function b(e){if(!n)return;let t=await n.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),i=((0,e$.f)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(i.map(async({token:t})=>{let i=await n.get(t);if(!i)return;let a=(0,e$.f)(i);if(!a)return;let o=eH(a.session.expiresAt,r);await n.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function E(e){if(!n)return[];let t=await n.get(`active-sessions-${e}`);return t&&(0,e$.f)(t)||[]}async function A(e,t,r){if(!n)return;let i=[...t].sort((e,t)=>e.expiresAt-t.expiresAt),a=eH(i.at(-1)?.expiresAt??0,r);a>0?await n.set(`active-sessions-${e}`,JSON.stringify(i),a):await n.delete(`active-sessions-${e}`)}let I=e=>`revoked-sessions-before-${e}`,T=Math.max(c,86400,Number(o.plugins?.find(e=>"admin"===e.id)?.options?.impersonationSessionDuration)||0);async function _(e,t){if(!n)return!1;let r=t?.get(e.userId)??Number(await n.get(I(e.userId)));return t?.set(e.userId,r),new Date(e.createdAt).getTime()<r}async function v(e,t,r){if(!n)return;let i=Number(await n.get(I(e)));await n.set(I(e),String(Math.max(r,i||0)),T);let a=new Set(t.map(e=>e.token));for(let e of a)await n.delete(e);let o=await E(e),s=Date.now();await A(e,o.filter(e=>e.expiresAt>s&&!a.has(e.token)),s)}async function O(e,t){if(!n)return;let r=t??await E(e),i=Date.now();await (0,eC.A)(()=>v(e,r,i),{onError(e){a.error("Failed to delete committed user sessions from secondary storage",e)}})}async function k(e,t){let r;if((0,eB.p)())return t();let i=s.get(e)??Promise.resolve(),a=new Promise(e=>{r=e}),o=i.catch(()=>{}).then(()=>a);s.set(e,o),await i.catch(()=>{});try{return await t()}finally{r(),s.get(e)===o&&s.delete(e)}}return{createOAuthUser:async(t,r)=>(0,eC.n)(e,async()=>{let e=await u({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);if(!e)throw new p.E("BAD_REQUEST",{message:"Failed to create user"});return{user:e,account:await u({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(e,t)=>{let r={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(o.user?.validateUserInfo){let e,i={...t,action:"create-user"};ek(i);try{e=(0,ez.g)()}catch(e){throw a.error("Unable to run validateUserInfo: missing endpoint context",e),new p.E("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await eR(e,{user:r,source:i})}return await u(r,"user",void 0)},createAccount:async e=>await u({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,i)=>{if(d)return(await (await (0,eC.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},{field:"expiresAt",value:new Date,operator:"gt"}]})).map(e=>(0,ex.Q)(t.options,e));if(n){let e=await n.get(`active-sessions-${r}`);if(!e)return[];let i=(0,e$.f)(e)||[],a=Date.now(),o=new Set,s=[],l=new Map;for(let{token:e,expiresAt:r}of i){if(r<=a||o.has(e))continue;o.add(e);let i=await n.get(e);if(i)try{let e="string"==typeof i?JSON.parse(i):i;if(!e?.session||await _(e.session,l))continue;s.push((0,ex.Q)(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await (0,eC.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},...i?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,i,a)=>await (await (0,eC.g)(e)).findMany({model:"user",limit:t,offset:r,sortBy:i,where:a}),countTotalUsers:async t=>{let r=await (await (0,eC.g)(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{let t=await E(e);(!n||o.session?.storeSessionInDatabase)&&await g([{field:"userId",value:e}],"session",void 0),await g([{field:"userId",value:e}],"account",void 0),await h([{field:"id",value:e}],"user",void 0)!==null&&await O(e,t)},createSession:async(r,i,s,l,f)=>{let p,m=await (async()=>{let e=(0,ez.G)();return e?.headers||e?.request?.headers})(),h=o.session?.storeSessionInDatabase,g=f?.deferSecondaryStorageWrites===!0&&d,{id:y,...w}=s||{};if(n&&!h){let e=t.generateId({model:"session"});p=!1!==e?e:(0,eM.f)()}let b=(0,ex.P)(o),E={...p?{id:p}:{},ipAddress:m&&ew(m,o)||"",userAgent:m?.get("user-agent")||"",...w,expiresAt:i?(0,eO.f)(86400,"sec"):(0,eO.f)(c,"sec"),userId:r,token:(0,eM.f)(32),createdAt:new Date,updatedAt:new Date,...b,...l?w:{}},I=async t=>{if(!n)return t;let i=await n.get(`active-sessions-${r}`),a=[],o=Date.now();i&&(a=(a=(0,e$.f)(i)||[]).filter(e=>e.expiresAt>o&&e.token!==E.token)),await A(r,[...a,{token:E.token,expiresAt:E.expiresAt.getTime()}],o);let s=await (await (0,eC.g)(e)).findOne({model:"user",where:[{field:"id",value:r}]}),l=eH(E.expiresAt,o);return l>0&&await n.set(E.token,JSON.stringify({session:{...t,createdAt:E.createdAt},user:s}),l),t};return await u(E,"session",n?{fn:async e=>g?(await (0,eC.A)(async()=>{await I(e)},{onError(e){a.error("Failed to mirror committed session to secondary storage",e)}}),e):I(e),executeMainFn:h}:void 0)},findSession:async r=>{if(n){let e=await n.get(r);if(!e&&(!o.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,e$.f)(e);return!r||await _(r.session)?null:{session:(0,ex.Q)(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:(0,ex.$)(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}}}let i=await (await (0,eC.g)(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!i)return null;let{user:a,...s}=i;return a?{session:(0,ex.Q)(t.options,s),user:(0,ex.$)(t.options,a)}:null},findSessions:async(t,r)=>{let i=[...new Set(t)],a=new Map,o=[],s=new Map;if(n)for(let e of i){let t=await n.get(e);if(t)try{let i="string"==typeof t?JSON.parse(t):t;if(!i||await _(i.session,s))continue;let o=new Date(i.session.expiresAt);if(r?.onlyActiveSessions&&o<=new Date)continue;let n={session:{...i.session,expiresAt:new Date(i.session.expiresAt)},user:{...i.user,createdAt:new Date(i.user.createdAt),updatedAt:new Date(i.user.updatedAt)}};a.set(e,n)}catch{continue}else o.push(e)}let l=n?o:i;if(l.length>0&&(!n||d))for(let{user:t,...i}of(await (await (0,eC.g)(e)).findMany({model:"session",limit:l.length,where:[{field:"token",value:l,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}})))t&&a.set(i.token,{session:i,user:t});return i.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,r)=>await f(r,[{field:"token",value:e}],"session",n?{async fn(r){let i=await n.get(e);if(!i)return null;let a=(0,e$.f)(i);if(!a)return null;let o={...a.session,...r,expiresAt:new Date(r.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(r.updatedAt??a.session.updatedAt)},s=(0,ex.Q)(t.options,o),l=Date.now(),c=new Date(s.expiresAt).getTime(),d=eH(c,l);if(d>0){await n.set(e,JSON.stringify({session:s,user:a.user}),d);let t=`active-sessions-${s.userId}`,r=await n.get(t),i=(r&&(0,e$.f)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>l).concat([{token:e,expiresAt:c}]);await A(s.userId,i,l)}return s},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(n){let r=await n.get(e);if(r){let{session:t}=(0,e$.f)(r)??{};if(!t)return void a.error("Session not found in secondary storage");let i=t.userId,o=await n.get(`active-sessions-${i}`);if(o){let t=(0,e$.f)(o)||[],r=Date.now();await A(i,t.filter(t=>t.expiresAt>r&&t.token!==e),r)}else a.error("Active sessions list not found in secondary storage")}if(await n.delete(e),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await w([{field:"token",value:e}])}await h([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await g([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await h([{field:"id",value:e}],"account",void 0)},deleteUserSessions:async r=>{let i=await E(r);if(!n)return void await g([{field:"userId",value:r}],"session",void 0);if(!o.session?.storeSessionInDatabase)return void await O(r,i);let a=async()=>O(r,[...i,...await E(r)]);t.options.session?.preserveSessionInDatabase?await w([{field:"userId",value:r}],a):await g([{field:"userId",value:r}],"session",{fn:async t=>{let r=await (await (0,eC.g)(e)).deleteMany({model:"session",where:t});return await a(),r},executeMainFn:!1})},deleteSessions:async e=>{if(n){if(await Promise.all(e.map(e=>n.delete(e))),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await w([{field:"token",value:e,operator:"in"}])}await g([{field:"token",value:e,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"providerId",value:t},{field:"accountId",value:r}],limit:2,join:{user:!0}});if(i.length>1)throw new p.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let a=i[0];if(!a)return null;let{user:o,...n}=a;return o?{kind:"owned",user:o,account:n}:{kind:"orphaned",account:n}},findUserByEmail:async(t,r)=>{let i=await (await (0,eC.g)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!i)return null;let a=e=>e.normalize("NFC").toLowerCase();if(a(i.email)!==a(t))return null;let{account:o,...n}=i;return{user:n,accounts:o??[]}},findUserById:async t=>t?await (await (0,eC.g)(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await u({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await f({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await (0,eC.A)(()=>b(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updateUserByEmail:async(e,t)=>{let r=await f({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await (0,eC.A)(()=>b(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updatePassword:async(e,t)=>{await m({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"},{field:"accountId",value:e}],"account",void 0)},findAccounts:async t=>await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findCredentialAccount:async t=>(await (0,eC.g)(e)).findOne({model:"account",where:[{field:"userId",value:t},{field:"providerId",value:"credential"},{field:"accountId",value:t}]}),findAccountByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,eC.g)(e)).findMany({model:"account",limit:2,where:[{field:"providerId",value:t},{field:"accountId",value:r}]});if(i.length>1)throw new p.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return i[0]??null},findAccountByUserId:async t=>await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await f(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=eL(e.identifier,o.verification?.storeIdentifier),r=await eD(e.identifier,t);return await u({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",n?{async fn(e){let t=eH(e.expiresAt);return t>0&&await n.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=eL(t,o.verification?.storeIdentifier),i=await eD(t,r);if(n){let e=await n.get(`verification:${i}`);if(e){let t=(0,e$.f)(e);if(t)return t}if(r&&"plain"!==r){let e=await n.get(`verification:${t}`);if(e){let t=(0,e$.f)(e);if(t)return t}}if(!o.verification?.storeInDatabase)return null}let a=await (0,eC.g)(e);async function s(e){return a.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let c=await s(i);!c.length&&r&&"plain"!==r&&(c=await s(t));let d=Date.now();return!o.verification?.disableCleanup&&d>=l&&(l=d+6e4,await g([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0)),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=eL(e,o.verification?.storeIdentifier),r=await eD(e,t);n&&await n.delete(`verification:${r}`),(!n||o.verification?.storeInDatabase)&&await h([{field:"identifier",value:r}],"verification",void 0)},consumeVerificationValue:async t=>{let r=eL(t,o.verification?.storeIdentifier),i=await eD(t,r),a=r&&"plain"!==r?[i,t]:[i],s=null;if(n&&!o.verification?.storeInDatabase){let e=async e=>(e=>{if(!e)return null;let t="string"==typeof e?(0,e$.f)(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})(await n.getAndDelete(e));for(let t of a){let r=await e(`verification:${t}`);if(r){await Promise.all(a.filter(e=>e!==t).map(e=>n.delete(`verification:${e}`))),s=r;break}}}else{let t=async t=>k(`verification:${t}`,()=>(0,eC.n)(e,async()=>{let r=await (0,eC.g)(e),i=[{field:"identifier",value:t}],a=(await r.findMany({model:"verification",where:i,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return a?y("verification",[{field:"id",value:a.id}],async()=>(await r.deleteMany({model:"verification",where:[...i,{field:"id",operator:"ne",value:a.id},{field:"createdAt",operator:"lte",value:a.createdAt}]}),r.consumeOne({model:"verification",where:[{field:"id",value:a.id}]})),a):null}));for(let e of a)if(s=await t(e))break;s&&n&&await Promise.all(a.map(e=>n.delete(`verification:${e}`)))}return!s||s.expiresAt<new Date?null:s},reserveVerificationValue:async t=>{let r=(0,eq.$)(new Uint8Array(await (0,eU.f)("SHA-256").digest(new TextEncoder().encode("reserve:"+t.identifier))),o,{adapter:e,model:"verification"}),i=eL(t.identifier,o.verification?.storeIdentifier),a=await eD(t.identifier,i);if(n&&!o.verification?.storeInDatabase)throw new p.p("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await e.create({model:"verification",data:{id:r,identifier:a,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:"verification",where:[{field:"id",value:r}]}))return!1;throw t}if(n){let e=eH(t.expiresAt);e>0&&await n.set(`verification:${a}`,JSON.stringify({id:r,identifier:a,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let r=eL(e,o.verification?.storeIdentifier),i=await eD(e,r);if(n){let e=await n.get(`verification:${i}`);if(e){let r=(0,e$.f)(e);if(r){let e={...r,...t},a=e.expiresAt??r.expiresAt,s=eH(a instanceof Date?a:new Date(a));if(s>0&&await n.set(`verification:${i}`,JSON.stringify(e),s),!o.verification?.storeInDatabase)return e}}}return!n||o.verification?.storeInDatabase?await f(t,[{field:"identifier",value:i}],"verification",void 0):t},refreshUserSessions:b}};var eV=e.i(76660);function eW(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 eK(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,i=".",a){if(!eW(r))return e(t,{},i,a);let o={...r};for(let r of Object.keys(t)){if("__proto__"===r||"constructor"===r)continue;let n=t[r];null!=n&&(a&&a(o,r,n,i)||(Array.isArray(n)&&Array.isArray(o[r])?o[r]=[...n,...o[r]]:eW(n)&&eW(o[r])?o[r]=e(n,o[r],(i?`${i}.`:"")+r.toString(),a):o[r]=n))}return o})(t,r,"",e),{})}let eG=eK();eK((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),eK((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0});let eJ=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function eQ(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function eY(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function eZ(e,t,r){if(0===r)return!0;let i=32===r?0xffffffff:-1<<32-r>>>0;return(e&i)==(t&i)}function eX(e){if("0.0.0.0"===e)return"unspecified";if("255.255.255.255"===e)return"broadcast";let t=eY(e);return eZ(t,eY("127.0.0.0"),8)?"loopback":eZ(t,eY("10.0.0.0"),8)||eZ(t,eY("172.16.0.0"),12)||eZ(t,eY("192.168.0.0"),16)?"private":eZ(t,eY("169.254.0.0"),16)?"linkLocal":eZ(t,eY("100.64.0.0"),10)?"sharedAddressSpace":eZ(t,eY("192.0.2.0"),24)||eZ(t,eY("198.51.100.0"),24)||eZ(t,eY("203.0.113.0"),24)?"documentation":eZ(t,eY("198.18.0.0"),15)?"benchmarking":eZ(t,eY("224.0.0.0"),4)?"multicast":eZ(t,eY("0.0.0.0"),8)||eZ(t,eY("192.0.0.0"),24)||eZ(t,eY("192.88.99.0"),24)||eZ(t,eY("240.0.0.0"),4)?"reserved":"public"}function e0(e,t,r={}){let i=5*t,a=Number.parseInt(e.slice(i,i+4),16),o=Number.parseInt(e.slice(i+5,i+9),16);if(!Number.isFinite(a)||!Number.isFinite(o))return null;let n=(a<<16|o)>>>0;return r.xor&&(n=(0xffffffff^n)>>>0),`${n>>>24&255}.${n>>>16&255}.${n>>>8&255}.${255&n}`}async function e1(e){let t=e.options,r=t.plugins||[],i=[],a=[];for(let o of r)if(o.init){let r,n=o.init(e);if("object"==typeof(r=(0,eV.f)(n)?await n:n)){if(r.options){let{databaseHooks:e,trustedOrigins:n,...s}=r.options;e&&a.push({source:`plugin:${o.id}`,hooks:e}),n&&i.push(n),t=eG(t,s)}r.context&&Object.assign(e,r.context)}}if(i.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...i],r=e.filter(Array.isArray).flat(),a=e.filter(e=>"function"==typeof e);a.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(a.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&a.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=eF(e.adapter,{options:t,logger:e.logger,hooks:a,generateId:e.generateId}),e.options=t}async function e2(e,t){let r=[];if((0,z._)(e.baseURL)){let t=e.baseURL.allowedHosts,i=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(i&&"https"!==i&&"auto"!==i||r.push(`https://${e}`),("http"===i||"auto"===i||function(e){let t=function(e){var t,r;let i,a=(-1===(i=(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,i)).replace(/\.+$/,"").toLowerCase();if(""===a)return{kind:"reserved",literal:"fqdn",canonical:""};if(!(ec(a)||ed(a)))return"localhost"===a||a.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:a}:eJ.has(a)?{kind:"cloudMetadata",literal:"fqdn",canonical:a}:{kind:"public",literal:"fqdn",canonical:a};if(eQ(a))return{kind:eX(a),literal:"ipv4",canonical:a};let o=ep(a,{ipv6Subnet:128});return eQ(o)?{kind:eX(o),literal:"ipv4",canonical:o}:{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&&(192&r)==192)return"reserved";if((254&t)==252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2001:0002:0000:"))return"benchmarking";if(e.startsWith("2002:")){let t=e0(e,1);return t&&"public"!==eX(t)?"reserved":"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let t=e0(e,6);return t&&eX(t),"reserved"}if(e.startsWith("0064:ff9b:0001:"))return"reserved";if(e.startsWith("2001:0000:")){let t=e0(e,6,{xor:!0});return t&&eX(t),"reserved"}return e.startsWith("0100:0000:0000:0000:")?"reserved":e.startsWith("3fff:0")?"documentation":e.startsWith("5f00:")||e.startsWith("0000:0000:0000:0000:0000:0000:")?"reserved":"public"}(o),literal:"ipv6",canonical:o}}(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 i=(0,z.X)("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);i&&r.push(new URL(i).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let i=await e.trustedOrigins(t);r.push(...i)}let i=en.$.BETTER_AUTH_TRUSTED_ORIGINS;return i&&r.push(...i.split(",")),r.filter(e=>!!e)}function e5(e){return e.advanced?.trustedProxyHeaders??!1}async function e6(e,t,r){let i,a=e.options.baseURL,o=e.options.basePath||"/api/auth",n=(0,z.A)(a,o,t,void 0,r);if(!n)throw new p.p("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));s.baseURL=n,s.options={...e.options,baseURL:(0,z.H)(n)||void 0};let l={...s.options,baseURL:a};return i="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?(0,z.T)(t)?t:t?new Request(n,{headers:t}):void 0:void 0,s.trustedOrigins=await e2(l,i),s.trustedProviders=await e4(s.options,i),e.options.advanced?.crossSubDomainCookies?.enabled&&(s.authCookies=(0,ev.e)(s.options),s.createAuthCookie=(0,ev.g)(s.options)),s}async function e8(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 e4(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}var e3=e.i(67850),e9=e.i(96161),e7=e.i(75742),te=e.i(66680);function tt(e,t){return new Promise((r,i)=>{(0,te.scrypt)(e.normalize("NFKC"),t,64,{N:16384,r:16,p:1,maxmem:0x4000000},(e,t)=>{e?i(e):r(t)})})}async function tr(e){let t=(0,te.randomBytes)(16).toString("hex");return`${t}:${(await tt(e,t)).toString("hex")}`}async function ti(e,t){let[r,i]=e.split(":");if(!r||!i)throw Error("Invalid password hash");return(await tt(t,r)).toString("hex")===i}let ta=async({hash:e,password:t})=>ti(e,t);var to=e.i(39127);let tn=(0,to.f)("a-z","0-9","A-Z","-_");function ts(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT}e.i(96101);let tl=e=>e?`"${e}" `:"";function tc(e,t=""){if("boolean"!=typeof e)throw TypeError(tl(t)+"expected boolean, got type="+typeof e);return e}function td(e,t=""){if("number"!=typeof e)throw TypeError(tl(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(tl(t)+"expected integer >= 0, got "+e);return e}function tu(e,t,r=""){if(ts(e)&&(void 0===t||e.length===t))return e;void 0!==t&&td(t,"length");let i=ts(e),a=void 0!==t?` of length ${t}`:"",o=i?`length=${e.length}`:`type=${typeof e}`,n=tl(r)+"expected Uint8Array"+a+", got "+o;if(!i)throw TypeError(n);throw RangeError(n)}let tf=(e,t)=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw TypeError("object"===t?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function tp(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function tm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function th(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let tg=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],ty=tg?e=>e:function(e){for(let r=0;r<e.length;r++){var t;e[r]=(t=e[r])<<24&0xff000000|t<<8&0xff0000|t>>>8&65280|t>>>24&255}return e},tw="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,tb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function tE(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function tA(e,t){return!!e.byteLength&&!!t.byteLength&&e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function tI(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(tu(t,e,"output"),r&&!tT(t))throw Error("invalid output, must be aligned");return t}function tT(e){return e.byteOffset%4==0}function t_(e){return Uint8Array.from(tu(e))}function tv(e=32){td(e,"bytesLength");let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function tO(e,t=tv){if("function"!=typeof e)throw TypeError('"fn" expected cipher constructor, got type='+typeof e);if("function"!=typeof t)throw TypeError('"randomBytes_" expected function, got type='+typeof t);let{nonceLength:r}=e;td(r,"fn.nonceLength");let i=(e,t,r)=>{let i=function(...e){let t=0;for(let r=0;r<e.length;r++){let i=e[r];tu(i),t+=i.length}let r=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){let a=e[t];r.set(a,i),i+=a.length}return r}(e,t);return tA(r,t)||t.fill(0),i},a=(a,...o)=>({encrypt(n){tu(n,void 0,"data");let s=t(r),l=e(a,s,...o).encrypt(n);return l instanceof Promise?l.then(e=>i(s,e,n)):i(s,l,n)},decrypt(t){tu(t,void 0,"data");let i=t.subarray(0,r),n=t.subarray(r);return e(a,i,...o).decrypt(n)}});return"blockSize"in e&&(a.blockSize=e.blockSize),"tagLength"in e&&(a.tagLength=e.tagLength),"withAAD"in e&&(a.withAAD=e.withAAD),a}let tk=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),tR=ty(tm(tk("expand 16-byte k"))),tx=ty(tm(tk("expand 32-byte k")));function tS(e,t){return e<<t|e>>>32-t}let tU=Uint32Array.of();function tN(e,t){return 255&e[t++]|(255&e[t++])<<8}class tD{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){let t=tN(e=t_(tu(e,32,"key")),0),r=tN(e,2),i=tN(e,4),a=tN(e,6),o=tN(e,8),n=tN(e,10),s=tN(e,12),l=tN(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|a<<9)&8191,this.r[4]=(a>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|n<<2)&8191,this.r[7]=(n>>>11|s<<5)&8065,this.r[8]=(s>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=tN(e,16+2*t)}process(e,t,r=!1){let{h:i,r:a}=this,o=a[0],n=a[1],s=a[2],l=a[3],c=a[4],d=a[5],u=a[6],f=a[7],p=a[8],m=a[9],h=tN(e,t+0),g=tN(e,t+2),y=tN(e,t+4),w=tN(e,t+6),b=tN(e,t+8),E=tN(e,t+10),A=tN(e,t+12),I=tN(e,t+14),T=i[0]+(8191&h),_=i[1]+((h>>>13|g<<3)&8191),v=i[2]+((g>>>10|y<<6)&8191),O=i[3]+((y>>>7|w<<9)&8191),k=i[4]+((w>>>4|b<<12)&8191),R=i[5]+(b>>>1&8191),x=i[6]+((b>>>14|E<<2)&8191),S=i[7]+((E>>>11|A<<5)&8191),U=i[8]+((A>>>8|I<<8)&8191),N=i[9]+(I>>>5|2048*!r),D=0,L=0+T*o+5*m*_+5*p*v+5*f*O+5*u*k;D=L>>>13,L&=8191,L+=5*d*R+5*c*x+5*l*S+5*s*U+5*n*N,D+=L>>>13,L&=8191;let C=D+T*n+_*o+5*m*v+5*p*O+5*f*k;D=C>>>13,C&=8191,C+=5*u*R+5*d*x+5*c*S+5*l*U+5*s*N,D+=C>>>13,C&=8191;let z=D+T*s+_*n+v*o+5*m*O+5*p*k;D=z>>>13,z&=8191,z+=5*f*R+5*u*x+5*d*S+5*c*U+5*l*N,D+=z>>>13,z&=8191;let j=D+T*l+_*s+v*n+O*o+5*m*k;D=j>>>13,j&=8191,j+=5*p*R+5*f*x+5*u*S+5*d*U+5*c*N,D+=j>>>13,j&=8191;let P=D+T*c+_*l+v*s+O*n+k*o;D=P>>>13,P&=8191,P+=5*m*R+5*p*x+5*f*S+5*u*U+5*d*N,D+=P>>>13,P&=8191;let B=D+T*d+_*c+v*l+O*s+k*n;D=B>>>13,B&=8191,B+=R*o+5*m*x+5*p*S+5*f*U+5*u*N,D+=B>>>13,B&=8191;let M=D+T*u+_*d+v*c+O*l+k*s;D=M>>>13,M&=8191,M+=R*n+x*o+5*m*S+5*p*U+5*f*N,D+=M>>>13,M&=8191;let $=D+T*f+_*u+v*d+O*c+k*l;D=$>>>13,$&=8191,$+=R*s+x*n+S*o+5*m*U+5*p*N,D+=$>>>13,$&=8191;let q=D+T*p+_*f+v*u+O*d+k*c;D=q>>>13,q&=8191,q+=R*l+x*s+S*n+U*o+5*m*N,D+=q>>>13,q&=8191;let H=D+T*m+_*p+v*f+O*u+k*d;D=H>>>13,H&=8191,H+=R*c+x*l+S*s+U*n+N*o,D+=H>>>13,H&=8191,L=8191&(D=(D=(D<<2)+D|0)+L|0),D>>>=13,C+=D,i[0]=L,i[1]=C,i[2]=z,i[3]=j,i[4]=P,i[5]=B,i[6]=M,i[7]=$,i[8]=q,i[9]=H}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=i,i=e[t]>>>13,e[t]&=8191;e[0]+=5*i,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+i,i=r[t]>>>13,r[t]&=8191;r[9]-=8192;let a=(1^i)-1;for(let e=0;e<10;e++)r[e]&=a;a=~a;for(let t=0;t<10;t++)e[t]=e[t]&a|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 o=e[0]+t[0];e[0]=65535&o;for(let r=1;r<8;r++)o=(e[r]+t[r]|0)+(o>>>16)|0,e[r]=65535&o;th(r)}update(e){tp(this),tu(e);let{buffer:t,blockLen:r}=this,i=(e=t_(e)).length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){for(;r<=i-a;a+=r)this.process(e,a);continue}t.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,th(this.h,this.r,this.buffer,this.pad)}digestInto(e){tp(this);tu(e,void 0,"output");let t=this.outputLen;if(!(e.length>=t))throw RangeError('"output" expected length >= '+t);this.finished=!0;let{buffer:r,h:i}=this,{pos:a}=this;if(a){for(r[a++]=1;a<16;a++)r[a]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=i[t]>>>0,e[o++]=i[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let tL=(c=e=>new tD(e),o=()=>[],(n=(e,t)=>c(t,...o()).update(e).digest()).outputLen=(s=c(new Uint8Array(32),...o(new Uint8Array(0)))).outputLen,n.blockLen=s.blockLen,n.create=(e,...t)=>c(e,...t),n);function tC(e,t,r,i,a,o=20){let n=e[0],s=e[1],l=e[2],c=e[3],d=t[0],u=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],y=t[7],w=r[0],b=r[1],E=r[2],A=n,I=s,T=l,_=c,v=d,O=u,k=f,R=p,x=m,S=h,U=g,N=y,D=a,L=w,C=b,z=E;for(let e=0;e<o;e+=2)x=x+(D=tS(D^(A=A+v|0),16))|0,A=A+(v=tS(v^x,12))|0,x=x+(D=tS(D^A,8))|0,v=tS(v^x,7),S=S+(L=tS(L^(I=I+O|0),16))|0,I=I+(O=tS(O^S,12))|0,S=S+(L=tS(L^I,8))|0,O=tS(O^S,7),U=U+(C=tS(C^(T=T+k|0),16))|0,T=T+(k=tS(k^U,12))|0,U=U+(C=tS(C^T,8))|0,k=tS(k^U,7),N=N+(z=tS(z^(_=_+R|0),16))|0,_=_+(R=tS(R^N,12))|0,N=N+(z=tS(z^_,8))|0,R=tS(R^N,7),U=U+(z=tS(z^(A=A+O|0),16))|0,A=A+(O=tS(O^U,12))|0,U=U+(z=tS(z^A,8))|0,O=tS(O^U,7),N=N+(D=tS(D^(I=I+k|0),16))|0,I=I+(k=tS(k^N,12))|0,N=N+(D=tS(D^I,8))|0,k=tS(k^N,7),x=x+(L=tS(L^(T=T+R|0),16))|0,T=T+(R=tS(R^x,12))|0,x=x+(L=tS(L^T,8))|0,R=tS(R^x,7),S=S+(C=tS(C^(_=_+v|0),16))|0,_=_+(v=tS(v^S,12))|0,S=S+(C=tS(C^_,8))|0,v=tS(v^S,7);let j=0;i[j++]=n+A|0,i[j++]=s+I|0,i[j++]=l+T|0,i[j++]=c+_|0,i[j++]=d+v|0,i[j++]=u+O|0,i[j++]=f+k|0,i[j++]=p+R|0,i[j++]=m+x|0,i[j++]=h+S|0,i[j++]=g+U|0,i[j++]=y+N|0,i[j++]=a+D|0,i[j++]=w+L|0,i[j++]=b+C|0,i[j++]=E+z|0}let tz=function(e,t){var r;let{allowShortKeys:i,extendNonceFn:a,counterLength:o,counterRight:n,rounds:s}=(tf(r={allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},"defaults"),tf(t,"opts"),Object.assign(r,t));if("function"!=typeof e)throw Error("core must be a function");return td(o),td(s),tc(n),tc(i),(t,r,l,c,d=0)=>{let u,f;tu(t,void 0,"key"),tu(r,void 0,"nonce"),tu(l,void 0,"data");let p=l.length,m=void 0!==c;if(c=tI(p,c,!1),m&&function(e,t){if(tA(e,t)&&e.byteOffset<t.byteOffset)throw Error("complex overlap of input and output is not supported")}(l,c),td(d),d<0||d>=0xffffffff)throw Error("arx: counter overflow");let h=[],g=t.length;if(32===g)h.push(u=t_(t)),f=tx;else if(16===g&&i)(u=new Uint8Array(32)).set(t),u.set(t,16),f=tR,h.push(u);else throw tu(t,32,"arx key"),Error("invalid key size");tg&&tT(r)||h.push(r=t_(r));let y=tm(u);if(a){if(24!==r.length)throw Error("arx: extended nonce must be 24 bytes");let e=r.subarray(0,16);if(tg)a(f,y,tm(e),y);else{let t=ty(Uint32Array.from(f));a(t,y,tm(e),y),th(t),ty(y)}r=r.subarray(16)}else tg||ty(y);let w=16-o;if(w!==r.length)throw Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){let e=new Uint8Array(12);e.set(r,n?0:12-r.length),r=e,h.push(r)}let b=ty(tm(r));try{return!function(e,t,r,i,a,o,n,s){let l=a.length,c=new Uint8Array(64),d=tm(c),u=tg&&tT(a)&&tT(o),f=u?tm(a):tU,p=u?tm(o):tU;if(!tg){for(let u=0;u<l;n++){if(e(t,r,i,d,n,s),ty(d),n>=0xffffffff)throw Error("arx: counter overflow");let f=Math.min(64,l-u);for(let e=0,t;e<f;e++)o[t=u+e]=a[t]^c[e];u+=f}return}for(let m=0;m<l;n++){if(e(t,r,i,d,n,s),n>=0xffffffff)throw Error("arx: counter overflow");let h=Math.min(64,l-m);if(u&&64===h){let e=m/4;if(m%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)p[r=e+t]=f[r]^d[t];m+=64;continue}for(let e=0,t;e<h;e++)o[t=m+e]=a[t]^c[e];m+=h}}(e,f,y,b,l,c,d,s),c}finally{th(...h)}}}(tC,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,i){let a=tg?e:ty(e.slice(0,4)),o=tg?t:ty(t.slice(0,8)),n=tg?r:ty(r.slice(0,4)),s=new Uint32Array(16);tC(a,o,n.subarray(1),s,n[0]);let l=0;i[l++]=s[0]-a[0]|0,i[l++]=s[1]-a[1]|0,i[l++]=s[2]-a[2]|0,i[l++]=s[3]-a[3]|0,i[l++]=s[12]-n[0]|0,i[l++]=s[13]-n[1]|0,i[l++]=s[14]-n[2]|0,i[l++]=s[15]-n[3]|0,ty(i),tg||th(a,o,n),th(s)},allowShortKeys:!1}),tj=new Uint8Array(16),tP=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(tj.subarray(r))},tB=new Uint8Array(32);function tM(e,t,r,i,a){var o,n;let s,l;void 0!==a&&tu(a,void 0,"AAD");let c=e(t,r,tB),d=(o=i.length,n=a?a.length:0,td(o),td(n),tc(!0),(l=new DataView((s=new Uint8Array(16)).buffer,s.byteOffset,s.byteLength)).setBigUint64(0,BigInt(n),!0),l.setBigUint64(8,BigInt(o),!0),s),u=tL.create(c);a&&tP(u,a),tP(u,i),u.update(d);let f=u.digest();return th(c,d),f}let t$=((e,t)=>{function r(i,...a){tu(i,void 0,"key"),void 0!==e.nonceLength&&tu(a[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let o=e.tagLength,n=+(void 0!==e.nonceLength);if(!e.withAAD){for(let e=n;e<a.length;e++)if(ts(a[e]))throw Error("AAD not supported")}e.withAAD&&void 0!==a[n]&&tu(a[n],void 0,"AAD");let s=t(i,...a),l=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");tu(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,tu(e,void 0,"data"),l(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(tu(e,void 0,"data"),o&&e.length<o)throw Error('"ciphertext" expected length >= tagLength='+o);return l(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e,t,r)=>({encrypt(i,a){let o=i.length;(a=tI(o+16,a,!1)).set(i);let n=a.subarray(0,-16);tz(e,t,n,n,1);let s=tM(tz,e,t,n,r);return a.set(s,o),th(s),a},decrypt(i,a){a=tI(i.length-16,a,!1);let o=i.subarray(0,-16),n=i.subarray(-16),s=tM(tz,e,t,o,r);if(!function(e,t){if(e=tu(e),t=tu(t),e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}(n,s))throw th(s),Error("invalid tag");return a.set(i.subarray(0,-16)),tz(e,t,a,a,1),th(s),a}})),tq="$ba$";async function tH(e,t){let r=await (0,eU.f)("SHA-256").digest(e),i=function(e){if("string"!=typeof e)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var a=tO(t$)(new Uint8Array(r)).encrypt(i);if(tu(a),tw)return a.toHex();let o="";for(let e=0;e<a.length;e++)o+=tb[a[e]];return o}async function tF(e,t){let r=await (0,eU.f)("SHA-256").digest(e),i=function(e){if("string"!=typeof e)throw TypeError("hex string expected, got "+typeof e);if(tw)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 i=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){let r=tE(e.charCodeAt(a)),o=tE(e.charCodeAt(a+1));if(void 0===r||void 0===o)throw RangeError('hex string expected, got non-hex character "'+(e[a]+e[a+1])+'" at index '+a);i[t]=16*r+o}return i}(t),a=tO(t$)(new Uint8Array(r));return new TextDecoder().decode(a.decrypt(i))}let tV=async({key:e,data:t})=>{var r;if("string"==typeof e)return tH(e,t);let i=e.keys.get(e.currentVersion);if(!i)throw Error(`Secret version ${e.currentVersion} not found in keys`);let a=await tH(i,t);return r=e.currentVersion,`${tq}${r}$${a}`},tW=async({key:e,data:t})=>{if("string"==typeof e)return tF(e,t);let r=function(e){if(!e.startsWith(tq))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 tF(t,r.ciphertext)}if(e.legacySecret)return tF(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};var tK=e.i(69381),tG=e.i(1083),tJ=e.i(97858);let tQ=(0,tJ.k)("better-auth:oauth-encryption:v1");function tY(e,t){return(0,tJ.w)((0,tK.f)(tG.f,(0,tJ.k)(e),tQ,(0,tJ.k)(`better-auth:${t}:v1`),32))}function tZ(e,t){return"string"==typeof e?tY(e,t):{keys:new Map(Array.from(e.keys,([e,r])=>[e,tY(r,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:tY(e.legacySecret,t)}}}async function tX(e,t,r){let i=e.accountSubject,a=await i({tokens:t,profile:r}),o=String(a);if("number"==typeof a&&!Number.isFinite(a)||0===o.trim().length||"undefined"===o||"null"===o)throw new p.p("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:e.id,accountId:o}}async function t0(e,t,r){try{return await tX(e,t,r)}catch{throw p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO)}}let t1="invalid_code",t2="unable_to_get_user_info",t5="unable_to_link_account",t6="email_not_verified";function t8(e,t,r,i){let a=new URLSearchParams({error:r});i&&a.set("error_description",i);let o=Y(t,a);throw e.redirect(o)}function t4(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 create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}function t3(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}var t9=e.i(12996),t7=e.i(9939),re=e.i(65466);async function rt(e,t,r,i=3600,a){return await (0,e7.X)({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...a},e,i)}async function rr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),p.E.from("BAD_REQUEST",G.f.VERIFICATION_EMAIL_NOT_ENABLED);let r=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),i=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:r},e.request)}let ri=(0,C.g)("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:P.object({email:P.email().meta({description:"The email to send the verification email to"}),callbackURL:P.string().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."),p.E.from("BAD_REQUEST",G.f.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await (0,t9.D)(e);if(!r){let r,i=Date.now(),a=await e.context.internalAdapter.findUserByEmail(t);if(!a||a.user.emailVerified)await rt(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await rr(e,a.user)}catch(e){r=e}let o=500-(Date.now()-i);if(o>0&&await new Promise(e=>setTimeout(e,o)),r)throw r;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw p.E.from("BAD_REQUEST",G.f.EMAIL_MISMATCH);if(r?.user.emailVerified)throw p.E.from("BAD_REQUEST",G.f.EMAIL_ALREADY_VERIFIED);return await rr(e,r.user),e.json({status:!0})}),ra=(0,C.g)("/verify-email",{method:"GET",operationId:"verifyEmail",query:P.object({token:P.string().meta({description:"The token to verify the email"}),callbackURL:P.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[er(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){let r=new URLSearchParams({error:t.code}),i=Y(e.query.callbackURL,r);throw e.redirect(i)}throw p.E.from("UNAUTHORIZED",t)}let{token:i}=e.query;try{t=await (0,t7.f)(i,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof re.JWTExpired)return r(G.f.TOKEN_EXPIRED);return r(G.f.INVALID_TOKEN)}let a=P.object({email:P.email(),updateTo:P.string().optional(),requestType:P.string().optional(),userId:P.string().optional()}).parse(t.payload);if(a.updateTo){if(!a.userId)return r(G.f.INVALID_TOKEN);let t=await e.context.internalAdapter.findUserById(a.userId);if(!t)return r(G.f.USER_NOT_FOUND);if(t.email.toLowerCase()!==a.email)return r(G.f.INVALID_TOKEN);let i=await (0,t9.D)(e);if(i&&i.user.id!==t.id)return r(G.f.INVALID_USER);switch(a.requestType){case"change-email-confirmation":{let r=await rt(e.context.secret,a.email,a.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:t.id}),i=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...t,email:a.updateTo},url:o,token:r},t3(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t.emailVerified,o=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:r});if(r&&e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),i&&await (0,ev.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:r}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,ex.$)(e.context.options,o)})}default:{let r=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:!1}),o=await rt(e.context.secret,a.updateTo,void 0,void 0,{userId:t.id}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${n}`,token:o},t3(e.request))),i&&await (0,ev.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,ex.$)(e.context.options,r)})}}}let o=await e.context.internalAdapter.findUserByEmail(a.email);if(!o)return r(G.f.USER_NOT_FOUND);if(a.userId&&a.userId!==o.user.id)return r(G.f.INVALID_TOKEN);if(o.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(o.user,e.request);let n=await e.context.internalAdapter.updateUserByEmail(a.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await (0,t9.D)(e);if(t&&t.user.email===a.email)await (0,ev.V)(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(o.user.id);if(!t)throw p.E.from("INTERNAL_SERVER_ERROR",G.f.FAILED_TO_CREATE_SESSION);await (0,ev.V)(e,{session:t,user:{...o.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function ro(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)?tW({key:t.secretConfig,data:e}):e;return e}function rn(e,t){return t.options.account?.encryptOAuthTokens&&e?tV({key:t.secretConfig,data:e}):e}function rs(e){return e.callbackPath?e.callbackPath.startsWith("/")?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function rl(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?e.trim():"").filter(Boolean):"string"==typeof e?e.trim().split(/\s+/).filter(Boolean):[]}function rc(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:rl(e.scope),idToken:e.id_token,raw:e}}function rd(e){return!0===e||"true"===e||!1!==e&&"false"!==e&&void 0}function ru(e){let t=Array.isArray(e)?e[0]:e;return"string"==typeof t&&t.length>0?t:void 0}async function rf(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return eS.W.encode(new Uint8Array(r),{padding:!1})}function rp(e,t){return{linked:!1,error:{code:e,message:t}}}async function rm(e,t){if(!t.encryptedSessionToken||!(0,t9.f)(e))return!0;let r=await tW({key:tZ(e.context.secretConfig,"oauth-link-session-token"),data:t.encryptedSessionToken}).catch(()=>null);if(!r)return!1;let i=await e.context.internalAdapter.findSession(r);return!!i&&i.session.userId===t.userId&&i.session.expiresAt>new Date}async function rh(e,t){let{link:r,account:i,profile:a,scopes:o}=t,n={...t.userInfo,emailVerified:rd(t.userInfo.emailVerified)??!1};if(!await rm(e,r))return rp(t5);try{await eR(e,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:i.providerId,profile:a}}})}catch(e){if(!(0,L.f)(e)||!e.body?.code)throw e;return rp(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(i.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),rp(t5);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return rp("email_does_not_match");let s=await e.context.internalAdapter.findAccountByKey(i);if(s){var l;if(s.userId.toString()!==r.userId.toString())return rp("account_already_linked_to_different_user");let t=(l=s.scope,[...new Set([...l?l.split(",").map(e=>e.trim()).filter(Boolean):[],...(o??[]).map(e=>e.trim()).filter(Boolean)])].join(",")),a=Object.fromEntries(Object.entries({providerId:i.providerId,accessToken:await rn(i.accessToken,e.context),refreshToken:await rn(i.refreshToken,e.context),idToken:i.idToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:t||void 0}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(s.id,a)}else if(!await e.context.internalAdapter.createAccount({userId:r.userId,...i,accessToken:await rn(i.accessToken,e.context),refreshToken:await rn(i.refreshToken,e.context),scope:o?.join(",")??i.scope}))return rp(t5);return await rw(e,r.userId,n),{linked:!0}}async function rg(e,t){let{account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,n={...t.userInfo,emailVerified:rd(t.userInfo.emailVerified)??!1},s=t.source??{method:"oauth",oauth:{providerId:r.providerId}},l=!!t.selectedUser||!0===t.requireExactAccountBinding,c=null,d=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;t8(e,r,"internal_server_error")});if(d?.kind==="orphaned")return e.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let u=await (async()=>{if(d?.kind==="owned"){if(t.selectedUser&&d.user.id!==t.selectedUser.userId)throw new p.E("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:d.user,linkedAccount:d.account,accounts:[d.account]}}if(t.selectedUser){let r=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!r)throw new p.E("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:r,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if((0,L.f)(t))throw t;e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;t8(e,r,"internal_server_error")}),f=u?.user,m=!f;if(u){let i=u.linkedAccount??u.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await eR(e,{user:{...o,id:u.user.id,email:n.email.toLowerCase()},source:{...s,action:"sign-in"}});let d=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>void 0!==t)):{};if(e.context.options.account?.storeAccountCookie){let r={...i,...d};t.deferNonDatabaseWrites?c=r:await (0,e9.L)(e,r)}if(Object.keys(d).length>0){let a=await e.context.internalAdapter.updateAccount(i.id,d);if(!a)return{error:"unable to update account",data:null};if(l&&(a.accountId!==r.accountId||a.providerId!==r.providerId||a.userId!==u.user.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});t.deferNonDatabaseWrites&&c&&(c=a)}t.selectedUser||!n.emailVerified||u.user.emailVerified||n.email.toLowerCase()!==u.user.email||await e.context.internalAdapter.updateUser(u.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||!1!==t.trustProviderByName&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!u.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return(0,en.o)()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.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{let{id:i,...a}=n;await eR(e,{user:{...a,id:u.user.id,email:n.email.toLowerCase()},source:{...s,action:"link-account"}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:u.user.id,accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:"unable to link account",data:null};if(l&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==u.user.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=o:await (0,e9.L)(e,o))}catch(t){if((0,L.f)(t))throw t;return e.context.logger.error("Unable to link account",t),{error:"unable to link account",data:null}}t.selectedUser||!n.emailVerified||u.user.emailVerified||n.email.toLowerCase()!==u.user.email||await e.context.internalAdapter.updateUser(u.user.id,{emailVerified:!0}),t.selectedUser||(f=await rw(e,u.user.id,n)??f)}if(t.selectedUser?"update"===t.selectedUser.profile:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...l}=n,c=(0,ex.W)(e.context.options,l,"update"),d=await e.context.internalAdapter.updateUser(u.user.id,{name:o,image:s,...c,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===u.user.email&&u.user.emailVerified||n.emailVerified});if(null==d&&e.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session."),t.selectedUser&&d&&d.id!==t.selectedUser.userId)throw new p.E("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});f=d??f}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:d,image:u,...m}=n,h=(0,ex.W)(e.context.options,m,"create"),g={accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},y=await (0,eC.n)(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:d,image:u,...h,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return t?{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...g,userId:t.id})}:null});if(!y)return{error:"unable to create user",data:null,isRegister:!1};let{createdUser:w,createdAccount:b}=y;if(l&&(b.accountId!==r.accountId||b.providerId!==r.providerId||b.userId!==w.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});f=w,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=b:await (0,e9.L)(e,b))}catch(t){if((0,L.f)(t))throw t;return e.context.logger.error("Unable to create OAuth user",t),{error:"unable to create user",data:null,isRegister:!1}}}if(!f)return{error:"unable to create user",data:null,isRegister:!1};let h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await ry(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await ry(e,f,i,t.deferNonDatabaseWrites),{error:t6,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0===t.deferNonDatabaseWrites});if(!g)return{error:"unable to create session",data:null,isRegister:!1};if(l&&g.userId!==(t.selectedUser?.userId??f.id))throw new p.E("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:g,user:f},error:null,isRegister:m,accountCookie:c}}async function ry(e,t,r,i){let a=e.context.options.emailVerification?.sendVerificationEmail;if(!a)return;let o=async()=>{try{let i=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${encodeURIComponent(r||"/")}`;await e.context.runInBackgroundOrAwait(a({user:t,url:o,token:i},e.request))}catch(t){e.context.logger.error("Failed to send OAuth verification email",t)}};i?await (0,eC.A)(o):await o()}async function rw(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:i,emailVerified:a,name:o,image:n,...s}=r,l=(0,ex.W)(e.context.options,s,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:n,...l})}catch(t){e.context.logger.warn("Could not update user info on account link",t);return}}var rb=e.i(24374);let{get:rE,set:rA}=(0,rb.z)(()=>null),{get:rI,set:rT}=(0,rb.z)(()=>null);var r_=p,rv=e.i(54257);let rO=e=>`auth-state:${e}`,rk=P.looseObject({callbackURL:P.string(),codeVerifier:P.string(),errorURL:P.string().optional(),newUserURL:P.string().optional(),expiresAt:P.number(),oauthState:P.string().optional(),link:P.object({email:P.string(),userId:rv.f.string(),encryptedSessionToken:P.string().optional()}).optional(),requestSignUp:P.boolean().optional(),idTokenNonce:P.string().optional(),serverContext:P.record(P.string(),P.unknown()).optional()});new Set(Object.keys(rk.shape));var rR=class extends r_.p{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function rx(e,t,r){let i=tn(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let a={...t,oauthState:i},o=await tV({key:tZ(e.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),n=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(n.name,o,n.attributes),{state:i,codeVerifier:t.codeVerifier}}let a=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(a.name,i,e.context.secret,a.attributes);let o=new Date(Date.now()+6e5);if(!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:i}),identifier:rO(i),expiresAt:o}))throw new rR("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:i,codeVerifier:t.codeVerifier}}async function rS(e,t,r){let i;if(!t)throw new rR("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let a=e.context.createAuthCookie(r?.cookieName??"oauth_state"),o=e.getCookie(a.name);if(!o)throw new rR("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await tW({key:tZ(e.context.secretConfig,"oauth-state-cookie"),data:o});i=rk.parse(JSON.parse(t))}catch(e){throw new rR("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new rR("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,ev.c)(e,a)}else{let a=await e.context.internalAdapter.findVerificationValue(rO(t));if(!a)throw new rR("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(i=rk.parse(JSON.parse(a.value))).oauthState&&i.oauthState!==t)throw new rR("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});let o=e.context.createAuthCookie(r?.cookieName??"state"),n=await e.getSignedCookie(o.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!n||n!==t))throw new rR("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,ev.c)(e,o),await e.context.internalAdapter.deleteVerificationByIdentifier(rO(t))}if(i.expiresAt<Date.now())throw new rR("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function rU(e){return e.requiresIdTokenNonce?tn(32):void 0}async function rN(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw p.E.from("BAD_REQUEST",G.f.CALLBACK_URL_REQUIRED);let i=t?.codeVerifier??tn(128),a=await rI(),o=a&&Object.keys(a).length?a:void 0,n={...t?.additionalData?t.additionalData:{},callbackURL:r,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:o,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await rA(n);try{return rx(e,n)}catch(t){throw e.context.logger.error("Failed to create verification",t),new p.E("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function rD(e){let t,r=e.query.state||e.body?.state,i=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await rS(e,r)}catch(a){e.context.logger.error("Failed to parse state",a);let t="internal_server_error",r=i;a instanceof rR&&(t="state_security_mismatch"===a.code?"state_mismatch":a.code,r=a.errorURL||i),t8(e,r,t)}return t.errorURL||(t.errorURL=i),t&&await rA(t),t}let rL=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],rC=new Set(rL);async function rz({id:e,options:t,authorizationEndpoint:r,state:i,codeVerifier:a,scopes:o,claims:n,redirectURI:s,duration:l,prompt:c,accessType:d,responseType:u,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:y,scopeJoiner:w}){var b;let E;t="function"==typeof t?await t():t;let A=new URLSearchParams;A.set("response_type",u||"code");let I=ru(t.clientId);if(!I)throw Error("OAuth provider requires clientId");if(A.set("client_id",I),A.set("state",i),o?.length&&A.set("scope",o.join(w||" ")),A.set("redirect_uri",t.redirectURI||s),l&&A.set("duration",l),f&&A.set("display",f),p&&A.set("login_hint",p),m&&A.set("nonce",m),c&&A.set("prompt",c),h&&A.set("hd",h),d&&A.set("access_type",d),g&&A.set("response_mode",g),a){let e=await rf(a);A.set("code_challenge_method","S256"),A.set("code_challenge",e)}if(n){let e=n.reduce((e,t)=>(e[t]=null,e),{});A.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(y)for(let[e,t]of Object.entries(y))rC.has(e)||A.set(e,t);return new URL(Y((b=t.authorizationEndpoint||r,(E=new URL(b)).search=E.search.slice(1).split("&").filter(e=>{let[t]=new URLSearchParams(e).keys();return e&&void 0!==t&&!A.has(t)}).join("&"),E.href),A))}let rj=P.record(P.string(),P.string()).refine(e=>!Object.keys(e).some(e=>rC.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${rL.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional(),rP=["iss","sub","aud","exp","iat"];async function rB(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 rM(e,t,r="exact"){return"string"==typeof e&&(e===t||"exact-or-sha256"===r&&e===await rB(t))}async function r$(e,t,r){if(![t.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let i=await (0,t7.f)(e,t.jwks,{issuer:t.issuer,audience:t.audience,algorithms:t.algorithms,maxTokenAge:t.maxTokenAge,requiredClaims:rP,clockTolerance:30});if(r&&!await rM(i.payload.nonce,r,t.nonceComparison))throw Error("ID token nonce does not match");if(t.verifyClaims&&!t.verifyClaims(i.payload))throw Error("ID token claims were rejected");return i}function rq(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function rH(e,t,r,i){let a=e.options??{};if(a.disableIdTokenSignIn)return!1;try{if(a.verifyIdToken)return await a.verifyIdToken(t,r,i);let o=e.idToken;if(!o)return!1;if("verify"in o)return await o.verify(t,r,i);if(3!==t.split(".").length)return!0===o.allowOpaqueToken;return await r$(t,o,r),!0}catch{return!1}}var rF=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)}};let rV=async(e,t)=>{let r=t||{},i={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:r,hooks:i};for(let d of(null==t?void 0:t.plugins)||[]){var a,o,n,s,l,c;if(d.init){let t=await (null==(c=d.init)?void 0:c.call(d,e.toString(),r));r=t.options||r,e=t.url}i.onRequest.push(null==(a=d.hooks)?void 0:a.onRequest),i.onResponse.push(null==(o=d.hooks)?void 0:o.onResponse),i.onSuccess.push(null==(n=d.hooks)?void 0:n.onSuccess),i.onError.push(null==(s=d.hooks)?void 0:s.onError),i.onRetry.push(null==(l=d.hooks)?void 0:l.onRetry)}return{url:e,options:r,hooks:i}};var rW=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}},rK=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)}};let rG=["get","post","put","patch","delete"];function rJ(e){if(!e.startsWith("@"))return{method:void 0,path:e};let t=e.indexOf("/"),r=e.slice(1,-1===t?void 0:t);return rG.includes(r)?{method:r,path:-1===t?e:e.slice(t+1)}:{method:void 0,path:e}}let rQ=/^[a-z][a-z\d+.-]*:\/\/[^/?#]+/i,rY=/^\/+/;function rZ(e){let t=e.length;for(;t>0&&"/"===e[t-1];)t--;return e.slice(0,t)}function rX(e,t){let r=e.indexOf(t);return -1===r?[e,void 0]:[e.slice(0,r),e.slice(r+1)]}let r0=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 i=await r(e.auth.token);if(!i)return t;t.authorization=`Bearer ${i}`}else if("Basic"===e.auth.type){let[i,a]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!i||!a)return t;t.authorization=`Basic ${btoa(`${i}:${a}`)}`}else if("Custom"===e.auth.type){let[i,a]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!a)return t;t.authorization=`${null!=i?i:""} ${a}`}}return t},r1=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function r2(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 r5(e){try{return JSON.parse(e)}catch(t){return e}}async function r6(e){let t=new Headers(function(...e){let t={};for(let r of e)if(r)if(r instanceof Headers)r.forEach((e,r)=>{t[r]=e});else for(let[e,i]of Array.isArray(r)?r:Object.entries(r))null!=i&&(t[e]=i);return t}(null==e?void 0:e.headers,await r0(e)));if(!t.has("content-type")){let r=r2(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var r8=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function r4(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new r8(r.issues);return r.value}function r3(e){return(r3="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function r7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?r9(Object(r),!0).forEach(function(t){!function(e,t,r){var i;(i=function(e,t){if("object"!=r3(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=r3(i))return i;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==r3(i)?i:i+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):r9(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let ie=async(e,t)=>{var r,i,a,o,n,s,l,c;let d,{hooks:u,url:f,options:p}=await rV(e,t),m=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")}(p),h=new AbortController,g=null!=(r=p.signal)?r:h.signal,y=function(e,t){var r,i;let a,{baseURL:o,params:n,query:s}=t||{query:{},params:{},baseURL:""},{path:l}=rJ(e),c=l===e?e:`/${l}`,d=null==(r=c.match(rQ))?void 0:r[0],[u,f]=rX(d?c.slice(d.length):function(e,t){if(!t)return e;let r=`${rZ(t)}/`;return e.startsWith(r)?e.slice(r.length):e}(c,o),"?"),p=(a=function(e,t){let r=new Map;if(t)if(Array.isArray(t))for(let[i,a]of e.split("/").filter(e=>e.startsWith(":")).entries()){let e=t[i];r.set(a,String(e))}else for(let[e,i]of Object.entries(t))r.set(`:${e}`,String(i));return r}(u,n),u.split("/").map(e=>(function(e,t){let r=t.get(e);if(void 0===r)return e.split(":").map(e=>encodeURIComponent(e)).join(":");if("."===r||".."===r)throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(r)})(e,a)).join("/"));return function(e,t,r,i){let[a]=rX(e,"#"),[o,n=""]=rX(a,"?"),s=t.replace(rY,""),l=function(e,t){let r=new URLSearchParams(e);for(let[e,i]of Object.entries(t||{})){let t;if(null!=i){if("string"==typeof i)t=i;else if(Array.isArray(i)){for(let t of i)r.append(e,t);continue}else t=JSON.stringify(i);r.set(e,t)}}let i=r.toString();return i.length>0?`?${i}`.replace(/\+/g,"%20"):""}(`${n}&${null!=r?r:""}`,i),c=`${rZ(o)}/${s}${l}`;return rQ.test(c)?new URL(c):c}(null!=(i=null!=d?d:o)?i:"",p,f,s)}(f,p),w=await r6(p),b=function(e,t){let r,{body:i}=e;return i?r2(i)&&"string"!=typeof i?"application/x-www-form-urlencoded"===((r=t.get("content-type"))?r.split(";")[0].trim().toLowerCase():null)?new URLSearchParams(i).toString():JSON.stringify(i):i:null}(p,w),E=function(e,t){if(null==t?void 0:t.method)return t.method.toUpperCase();let{method:r}=rJ(e);return r?r.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}(f,p),A=r7(r7({},p),{},{url:y,headers:w,body:b,method:E,signal:g});for(let e of u.onRequest)if(e){let t=await e(A);"object"==typeof t&&null!==t&&Object.assign(A,t)}("pipeTo"in A&&"function"==typeof A.pipeTo||"function"==typeof(null==t||null==(i=t.body)?void 0:i.pipe))&&!("duplex"in A)&&(A.duplex="half");let{clearTimeout:I}=(!(null==p?void 0:p.signal)&&(null==p?void 0:p.timeout)&&(d=setTimeout(()=>null==h?void 0:h.abort(),null==p?void 0:p.timeout)),{abortTimeout:d,clearTimeout:()=>{d&&clearTimeout(d)}}),T=await m(A.url,A);I();let _={response:T,request:A};for(let e of u.onResponse)if(e){let r=await e(r7(r7({},_),{},{response:(null==t||null==(o=t.hookOptions)?void 0:o.cloneResponse)?T.clone():T}));r instanceof Response?T=r:"object"==typeof r&&null!==r&&(T=r.response)}if(T.ok){if("HEAD"===A.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 i=t.split(";").shift()||"";return r1.test(i)?"json":r.has(i)||i.startsWith("text/")?"text":"blob"}(T),r={data:null,response:T,request:A};if("json"===e||"text"===e){let e=await T.text();r.data=await (null!=(n=A.jsonParser)?n:r5)(e)}else r.data=await T[e]();for(let e of((null==A?void 0:A.output)&&A.output&&!A.disableValidation&&(r.data=await r4(A.output,r.data)),u.onSuccess))e&&await e(r7(r7({},r),{},{response:(null==t||null==(s=t.hookOptions)?void 0:s.cloneResponse)?T.clone():T}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let v=null!=(a=null==t?void 0:t.jsonParser)?a:r5,O=await T.text(),k=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(O),R=k?await v(O):null,x={response:T,responseText:O,request:A,error:r7(r7({},R),{},{status:T.status,statusText:T.statusText})};for(let e of u.onError)e&&await e(r7(r7({},x),{},{response:(null==t||null==(l=t.hookOptions)?void 0:l.cloneResponse)?T.clone():T}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new rW({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new rW(e);case"exponential":return new rK(e);default:throw Error("Invalid retry strategy")}}(t.retry),i=null!=(c=t.retryAttempt)?c:0;if(await r.shouldAttemptRetry(i,T)){for(let e of u.onRetry)e&&await e(_);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await ie(e,r7(r7({},t),{},{retryAttempt:i+1}))}}if(null==t?void 0:t.throw)throw new rF(T.status,T.statusText,k?R:O);return{data:null,error:r7(r7({},R),{},{status:T.status,statusText:T.statusText})}},it=new Set([301,302,303,307,308]);function ir(e){return new p.p(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function ii(e,t){let r=!1,i=t?.onError,a=await ie(e,{...t,redirect:"manual",async onError(e){var t;("opaqueredirect"===(t=e.response).type||it.has(t.status))&&(r=!0),await i?.(e)}}).catch(t=>{if(r)throw ir(e);throw t});if(r)throw ir(e);return a}function ia(e){return new URLSearchParams({v:e}).toString().slice(2)}e.i(27957);var io=e.i(97554);async function is({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"}}function il(e,t,r){if(t.clientSecret||r.has("client_secret"))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function ic(e,t){t&&e.set("client_id",t)}function id(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function iu(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function ip(e){if(e.has("client_assertion")!==e.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function im({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a,tokenEndpointAuth:o,authentication:n}){ip(e);let s=ru(r.clientId);if(e.has("client_assertion")){if(o)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");il("private_key_jwt",r,e),ic(e,s);return}let l=o??("basic"===n?{method:"client_secret_basic"}:r.clientSecret?{method:"client_secret_post"}:{method:"none"});if("custom"===l.method){let o,n;await l.customizeRequest({body:e,headers:(o=e=>"string"==typeof e?e.toLowerCase():e,n=e=>Object.prototype.hasOwnProperty.call(t,o(e))?o(e):e,new Proxy(t,{get:(e,t)=>Reflect.get(e,n(t)),set:(e,t,r)=>Reflect.set(e,o(t),r),has:(e,t)=>Reflect.has(e,n(t)),deleteProperty:(e,t)=>Reflect.deleteProperty(e,o(t)),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,n(t))})),options:r,tokenEndpoint:i,grantType:a}),ip(e);return}if("private_key_jwt"===l.method){if(il(l.method,r,e),iu(l.method,s),!i)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let t=await is({getClientAssertion:l.getClientAssertion,context:{clientId:s,tokenEndpoint:i,grantType:a}});for(let[r,i]of(ic(e,s),Object.entries(t)))e.set(r,i);return}if("none"===l.method){if(il(l.method,r,e),"client_credentials"===a)throw Error("none token endpoint authentication cannot be used with client_credentials grant");iu(l.method,s),ic(e,s);return}"client_secret_basic"===l.method?function({headers:e,options:t,clientId:r,body:i}){var a;let o;if(i.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");id("client_secret_basic",t),iu("client_secret_basic",r),a=t.clientSecret,o=`${ia(r)}:${ia(a)}`,e.authorization=`Basic ${eS.t.encode(o)}`}({headers:t,options:r,clientId:s,body:e}):function({body:e,options:t,clientId:r,requireClientSecret:i}){i&&id("client_secret_post",t),t.clientSecret&&(iu("client_secret_post",r),ic(e,r),e.set("client_secret",t.clientSecret))}({body:e,options:r,clientId:s,requireClientSecret:o?.method==="client_secret_post"})}let ih=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function ig({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:a,extraParams:o,resource:n,headers:s}){let l=function({refreshToken:e,options:t,extraParams:r,resource:i,headers:a}){let o=new URLSearchParams,n={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};for(let[e,t]of Object.entries(a??{}))n[e.toLowerCase()]=t;if(o.set("grant_type","refresh_token"),o.set("refresh_token",e),i)if("string"==typeof i)o.append("resource",i);else for(let e of i)o.append("resource",e);return r&&function(e,t){if(t)for(let[r,i]of Object.entries(t))ih.has(r)||e.set(r,i)}(o,r),{body:o,headers:n}}({refreshToken:e,options:t="function"==typeof t?await t():t,extraParams:o,resource:n,headers:s});return await im({body:l.body,headers:l.headers,options:t,tokenEndpoint:a??"",grantType:"refresh_token",tokenEndpointAuth:i,authentication:r}),l}async function iy({refreshToken:e,options:t,tokenEndpoint:r,authentication:i,tokenEndpointAuth:a,extraParams:o,resource:n,headers:s}){let{body:l,headers:c}=await ig({refreshToken:e,options:t,authentication:i,tokenEndpointAuth:a,tokenEndpoint:r,extraParams:o,resource:n,headers:s}),{data:d,error:u}=await ii(r,{method:"POST",body:l,headers:c});if(u)throw u;if("string"!=typeof d.access_token||!d.access_token)throw d;let f={accessToken:d.access_token,refreshToken:d.refresh_token,tokenType:d.token_type,scopes:rl(d.scope),idToken:d.id_token};return d.expires_in&&(f.accessTokenExpiresAt=new Date((new Date).getTime()+1e3*d.expires_in)),d.refresh_token_expires_in&&(f.refreshTokenExpiresAt=new Date((new Date).getTime()+1e3*d.refresh_token_expires_in)),f}e.i(1889),e.i(12319),e.i(41242),e.i(18069);var iw=e.i(55659),ib=e.i(63370),iE=e.i(83817);e.i(24472).C;var iA=e.i(92449),iI=e.i(16760);async function iT(e,t,r){let i=e.get(t)||e.set(t,{}).get(t),{alg:a}=r;if(void 0===i[a]){let e=(0,iA.f)(r,t,!0).then(e=>{if("public"!==e.type)throw new re.JWKSInvalid("JSON Web Key Set members must be public keys");return i[a]=e,e}).catch(t=>{throw i[a]===e&&delete i[a],t});i[a]=e}return i[a]}function i_(e){let t;try{t=structuredClone(e)}catch(e){throw new re.JWKSInvalid("JSON Web Key Set malformed",{cause:e})}if(!(0,iE.q)(t))throw new re.JWKSInvalid("JSON Web Key Set malformed");let r=t.keys.map(e=>{let t=(0,iA.C)(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),i=new WeakMap;return Object.defineProperty(async(e,a)=>{let{alg:o,kid:n}={...e,...a?.header},s="string"==typeof o?iI.K[o]:void 0;if(!s||s.secret)throw new re.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let l=t.keys.filter((e,t)=>(function(e,t,r,i){let{kty:a,key_ops:o,ext:n,kid:s,alg:l,use:c,crv:d}=e;return(void 0===n||"boolean"==typeof n)&&(void 0===o||Array.isArray(o)&&o.every((e,t)=>"string"==typeof e&&o.indexOf(e)===t)&&o.includes("verify"))&&t.kty.includes(a)&&(void 0===i||"string"==typeof i&&i===s)&&(void 0===l?"AKP"!==a:r===l)&&(void 0===c||"sig"===c)&&(!t.crv||d===t.crv)})(r[t],s,o,n)),{0:c,length:d}=l;if(!d)throw new re.JWKSNoMatchingKey;if(1!==d){let e=new re.JWKSMultipleMatchingKeys;throw e[Symbol.asyncIterator]=async function*(){for(let e of l)try{yield await iT(i,e,s)}catch{}},e}return iT(i,c,s)},"jwks",{value:()=>structuredClone(t)})}async function iv({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:a,tokenEndpointAuth:o,tokenEndpoint:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let u=function({code:e,codeVerifier:t,redirectURI:r,options:i,deviceId:a,headers:o,additionalParams:n={},resource:s}){let l=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};for(let[e,t]of Object.entries(o??{}))c[e.toLowerCase()]=t;if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),i.clientKey&&l.set("client_key",i.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",i.redirectURI||r),s)if("string"==typeof s)l.append("resource",s);else for(let e of s)l.append("resource",e);for(let[e,t]of Object.entries(n))l.has(e)||l.append(e,t);return{body:l,headers:c}}({code:e,codeVerifier:t,redirectURI:r,options:i="function"==typeof i?await i():i,deviceId:s,headers:l,additionalParams:c,resource:d});return await im({body:u.body,headers:u.headers,options:i,tokenEndpoint:n??"",grantType:"authorization_code",tokenEndpointAuth:o,authentication:a}),u}async function iO({code:e,codeVerifier:t,redirectURI:r,options:i,tokenEndpoint:a,authentication:o,tokenEndpointAuth:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let{body:u,headers:f}=await iv({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:o,tokenEndpointAuth:n,tokenEndpoint:a,deviceId:s,headers:l,additionalParams:c,resource:d}),{data:p,error:m}=await ii(a,{method:"POST",body:u,headers:f});if(m)throw m;return rc(p)}re.JWKSTimeout.code,re.JWKSInvalid.code,re.JWKSMultipleMatchingKeys.code;var ik=e.i(32802);function iR(e){let t,r;if("string"!=typeof e)throw new re.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:i,length:a}=e.split(".");if(5===a)throw new re.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==a)throw new re.JWTInvalid("Invalid JWT");if(!i)throw new re.JWTInvalid("JWTs must contain a payload");try{t=(0,ib.decode)(i)}catch(e){throw new re.JWTInvalid("Failed to base64url decode the payload",{cause:e})}try{r=JSON.parse(ik.L.decode(t))}catch(e){throw new re.JWTInvalid("Failed to parse the decoded payload as JSON",{cause:e})}if(!(0,iE.C)(r))throw new re.JWTInvalid("Invalid JWT Claims Set");return r}let ix=async e=>{let{data:t}=await ii("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new p.E("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 (0,io.g)(r,r.alg)},iS="https://dash.cloudflare.com/oauth2/token",iU=e=>e.tokenEndpointAuth??{method:e.tokenEndpointAuthMethod??(e.clientSecret?"client_secret_basic":"none")},iN=async(e,t,r)=>{let i=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await ii(i);if(!t?.keys)throw new p.E("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 (0,io.g)(r,r.alg)}catch(e){throw u.y.error("Failed to fetch Cognito public key:",e),e}};(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(t="jose/v6.2.17");let iD=Symbol();async function iL(e,t,r,i=fetch){let a=await i(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new re.JWKSTimeout(void 0,{cause:e}):e});if(200!==a.status)throw new re.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new re.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:e})}}let iC=Symbol();function iz(e,t){return Number.isFinite(e)&&Date.now()<e+t}function ij(e,t,r){if(Number.isNaN(e))throw TypeError(`"${r}" option must not be NaN`);if("number"==typeof e&&e<0)throw TypeError(`"${r}" option must not be negative`);return"number"==typeof e?e:t}async function iP(e,t){let r=ru(t.clientId);if(!r||!t.clientSecret)return null;let i=Array.isArray(t.clientId)?t.clientId:[t.clientId],a=`${r}|${t.clientSecret}`,{data:o,error:n}=await ii("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:a}});if(n||!o?.data)return null;let{is_valid:s,app_id:l,user_id:c}=o.data;return!0===s&&l&&i.includes(l)&&c?c:null}let iB=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),iM="RS256",i$=[iM],iq=(e,t)=>!e||"string"==typeof t&&!!t&&("*"===e||t===e),iH=async e=>{let[t]=await iF(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},iF=async e=>{let{data:t}=await ii("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new p.E("BAD_REQUEST",{message:"Keys not found"});let r=e?t.keys.filter(t=>t.kid===e):t.keys;if(!r.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(r.map(e=>(0,io.g)(e,iM)))},iV="9188040d-6c67-4c5b-b112-36a304b66dad",iW=async(e,t,r)=>{let{data:i}=await ii(`${r}/${t}/discovery/v2.0/keys`);if(!i?.keys)throw new p.E("BAD_REQUEST",{message:"Keys not found"});let a=i.keys.find(t=>t.kid===e);if(!a)throw Error(`JWK with kid ${e} not found`);return await (0,io.g)(a,a.alg??"RS256")},iK="https://backboard.railway.com/oauth/token";function iG({identifier:e,namespace:t}){let r=P.email().safeParse(`${e}@${t}.placeholder.invalid`);if(!r.success)throw TypeError("Invalid placeholder email");return r.data}let iJ={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a,codeVerifier:o}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","name"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:n,state:t,redirectURI:i,codeVerifier:o,responseMode:"form_post",responseType:"code id_token",additionalParams:a})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),idToken:{jwks:e=>ix(e.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let i=iR(t.idToken);if(!i)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():i.name||"";let a=rd(i.email_verified)??!1,o={...i,name:r},n=await e.mapProfileToUser?.(o);return{user:{name:o.name,emailVerified:a,email:i.email,...n},data:o}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Secret are required for Atlassian"),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Atlassian");let n=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:{...o??{},audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 ie("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}catch(e){return u.y.error("Failed to fetch user info from Atlassian:",e),null}},options:e}},cloudflare:e=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["user-details.read"];return e.scope?.length&&o.push(...e.scope),r?.length&&o.push(...r),rz({id:"cloudflare",options:e,authorizationEndpoint:"https://dash.cloudflare.com/oauth2/auth",scopes:o.length?[...new Set(o)]:void 0,state:t,codeVerifier:i,redirectURI:a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:iS,tokenEndpointAuth:iU(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:iS,tokenEndpointAuth:iU(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://api.cloudflare.com/client/v4/user",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r?.success||!r.result)return u.y.error("Failed to fetch user info from Cloudflare:",i??r?.errors),null;let a=r.result,o=[a.first_name,a.last_name].filter(Boolean).join(" ")||a.email,n=await e.mapProfileToUser?.(a);return{user:{name:o,email:a.email,emailVerified:!1,...n},data:a}},options:e}),cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw u.y.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new p.p("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,i=`https://${t}/oauth2/token`,a=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!ru(e.clientId))throw u.y.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw u.y.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new p.p("CLIENT_SECRET_REQUIRED");let s=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&s.push(...e.scope),i&&s.push(...i);let l=await rz({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...n??{}}}),c=l.searchParams.get("scope");if(c){l.searchParams.delete("scope");let e=encodeURIComponent(c),t=l.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return l},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),idToken:{jwks:t=>iN(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=iR(t.idToken);if(!r)return null;let i=r.name||r.given_name||r.username||"",a={...r,name:i},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:a}}catch(e){u.y.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await ie(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:rd(r.email_verified)??!1,...t},data:r}}}catch(e){u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identify","email"];r&&o.push(...r),e.scope&&o.push(...e.scope);let n=o.includes("bot");return rz({id:"discord",options:e,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"none",additionalParams:{...n&&void 0!==e.permissions?{permissions:String(e.permissions)}:{},...a??{}}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)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 a=await e.mapProfileToUser?.(r);return{user:{name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...a},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",accountSubject:({profile:e})=>"sub"in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:{...e.configId?{config_id:e.configId}:{},...o??{}}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>iO({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:function(e){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let r=new URL(e.href).href,i=(void 0)??{},a=i.timeoutDuration;if("number"==typeof a&&(!Number.isInteger(a)||a<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let o="number"==typeof a?a:5e3,n=ij(i.cooldownDuration,3e4,"cooldownDuration"),s=ij(i.cacheMaxAge,6e5,"cacheMaxAge"),l=new Headers(i.headers);t&&!l.has("User-Agent")&&l.set("User-Agent",t),l.has("accept")||l.set("accept","application/json, application/jwk-set+json");let c=i[iD],d=i[iC],u,f,p=0,m=0,h;if(d&&"object"==typeof d){let{uat:e,jwks:t}=d;iz(e,s)&&(0,iE.q)(t)&&(u=e,h=i_(t))}let g=async()=>{if(f&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(f=void 0),!f){let e=++p,t=f=iL(r,l,AbortSignal.timeout(o),c).then(t=>{let r=i_(t);if(e<=m)return;h=r;let i=Date.now();d&&(d.uat=i,d.jwks=t),u=i,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{h&&iz(u,s)||await g();try{return await h(e,t)}catch(r){if(r instanceof re.JWKSNoMatchingKey&&!iz(u,n))return await g(),h(e,t);throw r}},{coolingDown:{get:()=>iz(u,n),enumerable:!0},fresh:{get:()=>iz(u,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:e.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({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){let r=!!t.idToken&&3!==t.idToken.split(".").length,i=t.accessToken||(r?t.idToken:void 0);return i&&!await iP(i,e)?null:e.getUserInfo(t)}if(t.idToken&&3===t.idToken.split(".").length){let r=iR(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}let r=t.accessToken;if(!r)return null;let i=await iP(r,e);if(!i)return null;let a=["id","name","email","picture",...e?.fields||[]],{data:o,error:n}=await ie("https://graph.facebook.com/me?fields="+a.join(","),{auth:{type:"Bearer",token:r}});if(n||o.id!==i)return null;let s=await e.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified??!1,...s},data:o}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Figma");let n=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 ie("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return u.y.error("Failed to fetch user from Figma"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...i},data:r}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,codeVerifier:a,redirectURI:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),rz({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,codeVerifier:a,redirectURI:o,loginHint:i,prompt:e.prompt,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>{let{body:o,headers:n}=await iv({code:r,codeVerifier:i,redirectURI:a,options:e}),{data:s,error:l}=await ii(t,{method:"POST",body:o,headers:n});return l?(u.y.error("GitHub OAuth token exchange failed:",l),null):"error"in s?(u.y.error("GitHub OAuth token exchange failed:",s),null):rc(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a}=await ie("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&a&&(r.email=(a.find(e=>e.primary)??a[0])?.email);let o=a?.find(e=>e.email===r.email)?.verified??!1,n=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:o,...n},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";for(;r.endsWith("/");)r=r.slice(0,-1);let i=`${r}/${t}/oauth2/v2.0/authorize`,a=`${r}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new p.p("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let o=e.clientAssertion?{method:"private_key_jwt",getClientAssertion:e.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!ru(e.clientId))throw u.y.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new p.p("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),rz({id:"microsoft",options:e,authorizationEndpoint:i,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:a,tokenEndpointAuth:o}),idToken:{jwks:e=>iW(e.kid,t,r),algorithms:["RS256"],audience:e.clientId,maxTokenAge:"1h",issuer:"common"!==t&&"organizations"!==t&&"consumers"!==t?`${r}/${t}/v2.0`:void 0,verifyClaims:e=>{let i=e.tid;return"string"==typeof i&&e.iss===`${r}/${i}/v2.0`&&("organizations"!==t||i!==iV)&&("consumers"!==t||i===iV)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=iR(t.idToken);if("string"!=typeof r.oid||0===r.oid.trim().length)return u.y.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let i=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await ie(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer(),i=eS.t.encode(t);r.picture=`data:image/jpeg;base64, ${i}`}catch(e){u.y.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let a=await e.mapProfileToUser?.(r),o=void 0!==r.email_verified?rd(r.email_verified)??!1:!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:o,...a},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),iy({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:a,tokenEndpointAuth:o})},options:e}},google:e=>({id:"google",name:"Google",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,display:n,additionalParams:s}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Google");let l=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&l.push(...e.scope),r&&l.push(...r),await rz({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:l,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,accessType:e.accessType,display:n||e.display,loginHint:o,hd:e.hd,additionalParams:{...!1===e.includeGrantedScopes?{}:{include_granted_scopes:"true"},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:e=>iH(e.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,algorithms:i$,maxTokenAge:"1h",verifyClaims:e.hd?t=>iq(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=iR(t.idToken);if(!iq(e.hd,r.hd))return u.y.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",accountSubject:({profile:e})=>e["https://slack.com/user_id"],createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return r&&o.push(...r),e.scope&&o.push(...e.scope),rz({id:"slack",options:e,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...a},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...a},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"],additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 u.y.error("No idToken found in token"),null;let i=iR(r),a=await e.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...a},data:i}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",accountSubject:({profile:e})=>e.data.id,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),rz({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,authentication:"basic",redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a,error:o}=await ie("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),n=!1;!o&&a?.data?.confirmed_email&&(r.data.email=a.data.confirmed_email,n=!0);let s=await e.mapProfileToUser?.(r);return{user:{name:r.data.name,email:r.data.email||iG({identifier:r.data.id,namespace:"twitter"}),image:r.data.profile_image_url,emailVerified:n,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["account_info.read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...o??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>await iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...a},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,codeVerifier:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"kick",redirectURI:i,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:n,codeVerifier:a,state:t,additionalParams:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>iO({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({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:i}=await ie("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=r.data[0],o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.profile_picture,emailVerified:!1,...o},data:a}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
123
|
+
`,`Current list of trustedOrigins: ${l}`),p.E.from("FORBIDDEN",G.f.INVALID_ORIGIN)}let ea=(0,C.a)(async e=>{e.request&&await eo(e)});async function eo(e){let t=e.request;if(!t||e.context.skipCSRFCheck||Z(e))return;let r=t.headers;if(r.has("cookie"))return await ei(e);let i=r.get("Sec-Fetch-Site"),a=r.get("Sec-Fetch-Mode"),o=r.get("Sec-Fetch-Dest");if(i&&i.trim()||a&&a.trim()||o&&o.trim()){if("cross-site"===i&&"navigate"===a)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:i,secFetchMode:a,secFetchDest:o}),p.E.from("FORBIDDEN",G.f.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await ei(e,!0)}if(r.get("origin")||r.get("referer"))return await ei(e,!0)}var en=e.i(47391);let es=P.ipv4(),el=P.ipv6();function ec(e){return B.f(es,e)}function ed(e){return B.f(el,e)}function eu(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let e=t.substring(7);if(ec(e))return e}let r=e.split(":");if(7===r.length&&r[5]?.toLowerCase()==="ffff"){let e=r[6];if(e&&ec(e))return e}if(t.includes("::ffff:")||t.includes(":ffff:")){let t=ef(e);if(8===t.length&&"0000"===t[0]&&"0000"===t[1]&&"0000"===t[2]&&"0000"===t[3]&&"0000"===t[4]&&"ffff"===t[5]&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function ef(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],i=t[1]?t[1].split(":"):[],a=Array(8-r.length-i.length).fill("0000");return[...r.map(e=>e.padStart(4,"0")),...a,...i.map(e=>e.padStart(4,"0"))]}return e.split(":").map(e=>e.padStart(4,"0"))}function ep(e,t={}){if(ec(e)||!ed(e))return e.toLowerCase();let r=eu(e);if(r)return r.toLowerCase();var i=t.ipv6Subnet??64;let a=ef(e);if(void 0!==i&&i<128){let e=Math.max(0,Math.floor(i));return a.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 a.join(":").toLowerCase()}function em(e){if(ec(e))return Uint8Array.from(e.split(".").map(e=>Number(e)));if(!ed(e))return null;let t=eu(e);if(t)return Uint8Array.from(t.split(".").map(e=>Number(e)));let r=ef(e),i=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(r[e]??"0",16);i[2*e]=t>>8&255,i[2*e+1]=255&t}return i}let eh=/^\d+$/;function eg(e){let t=e.lastIndexOf("/"),r=em(-1===t?e:e.slice(0,t));if(!r)return null;let i=8*r.length;if(-1===t)return{bytes:r,prefix:i};let a=e.slice(t+1);if(!eh.test(a))return null;let o=Number(a);return o<=i?{bytes:r,prefix:o}:null}let ey=["x-forwarded-for"];function ew(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||ey){let i="get"in r?r.get(e):r[e];if("string"==typeof i){let e=function(e,t={}){let r=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===r.length)return null;let i=(t.trustedProxies??[]).map(eg).filter(e=>null!==e);if(i.length>0){for(let e=r.length-1;e>=0;e--){let a=r[e],o=a?em(a):null;if(!a||!o)break;if(!i.some(e=>(function(e,t){if(e.length!==t.bytes.length)return!1;let r=t.prefix;for(let i=0;i<e.length&&r>0;i++){let a=r>=8?8:r,o=8===a?255:255<<8-a&255;if(((e[i]??0)&o)!=((t.bytes[i]??0)&o))return!1;r-=8}return!0})(o,e)))return ep(a,{ipv6Subnet:t.ipv6Subnet})}return null}if(1!==r.length)return null;let a=r[0];return a&&(ec(a)||ed(a))?ep(a,{ipv6Subnet:t.ipv6Subnet}):null}(i,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return(0,en.s)()||(0,en.o)()?"127.0.0.1":null}let eb=new Map;function eE(e,t){return Math.ceil((e+1e3*t-Date.now())/1e3)}let eA=!1;async function eI(e,t){var r;let i=new URL(t.baseURL).pathname,a=J(e.url,i),o=t.rateLimit.window,n=t.rateLimit.max,s=ew(e,t.options);if(!s&&t.options.advanced?.ipAddress?.disableIpTracking)return null;s||eA||(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),eA=!0);let l=(r=s??"no-trusted-ip",`${r}|${a}`),c=e_().find(e=>e.pathMatcher(a));for(let e of(c&&(o=c.window,n=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(a));if(t){o=t.window,n=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?(0,j.f)(e)(a):e===a);if(r){let i=t.rateLimit.customRules[r],a="function"==typeof i?await i(e,{window:o,max:n}):i;if(a&&(o=a.window,n=a.max),!1===a)return null}}return{key:l,currentWindow:o,currentMax:n}}async function eT(e,t){if(!t.rateLimit.enabled)return;let r=await eI(e,t);if(!r)return;let{key:i,currentWindow:a,currentMax:o}=r,n=function(e){let t,r,i,a,o,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let s=e.rateLimit.storage;if("secondary-storage"===s){let t=e.options.secondaryStorage?.increment;if(!t)throw new p.p("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(r,i)=>await t(r,i.window??e.options.rateLimit?.window??10)<=i.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:i.window}}}return"memory"===s?{async consume(t,r){var i;let a;!function(){let e=Date.now();for(let[t,r]of eb)e>=r.expiresAt&&eb.delete(t);if(eb.size<=1e5)return;let t=eb.size-1e5,r=0;for(let e of eb.keys())if(eb.delete(e),++r>=t)break}();let o=Date.now(),n=eb.get(t),s=(i=n&&o<n.expiresAt?n.data:void 0,a=1e3*r.window,i?o-i.lastRequest>=a?{next:{...i,count:1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:i.count>=r.max?{next:i,update:!0,allowed:!1,retryAfter:eE(i.lastRequest,r.window)}:{next:{...i,count:i.count+1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:o},update:!1,allowed:!0,retryAfter:null});return s.allowed&&eb.set(t,{data:{...s.next,key:t},expiresAt:o+1e3*(r.window??e.options.rateLimit?.window??10)}),{allowed:s.allowed,retryAfter:s.retryAfter}}}:(t="rateLimit",r=e.adapter,i=Math.max(...function(e){let t=[e.rateLimit.window,...e_().map(e=>e.window)];for(let r of e.options.plugins||[])r.rateLimit&&t.push(...r.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let r of Object.values(e.rateLimit.customRules))r&&"function"!=typeof r&&t.push(r.window);let r=t.filter(e=>Number.isFinite(e)&&e>0);return r.length>0?r:[e.rateLimit.window]}(e)),a=async e=>{let i=(await r.findMany({model:t,where:[{field:"key",value:e}]}))[0];return i&&(i.lastRequest=Number(i.lastRequest)),i},o=async(e,s)=>{s.window>i&&(i=s.window);let l=1e3*s.window,c=await a(e),d=Date.now();if(!c)try{return await r.create({model:t,data:{key:e,count:1,lastRequest:d}}),{allowed:!0,retryAfter:null}}catch(t){if(!await a(e))throw t;return o(e,s)}if(d-c.lastRequest>=l)return await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"lte",value:c.lastRequest}],increment:{},set:{count:1,lastRequest:d}})?(await n(d),{allowed:!0,retryAfter:null}):o(e,s);let u=d-l;if(await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"gt",value:u},{field:"count",operator:"lt",value:s.max}],increment:{count:1},set:{lastRequest:d}}))return{allowed:!0,retryAfter:null};let f=await a(e);return!f||d-f.lastRequest>=l?o(e,s):{allowed:!1,retryAfter:eE(f.lastRequest,s.window)}},n=async a=>{let o=a-1e3*i;await e.runInBackgroundOrAwait(r.deleteMany({model:t,where:[{field:"lastRequest",operator:"lt",value:o}]}).then(()=>void 0).catch(t=>e.logger.error("Error pruning rate limit rows",t)))},{consume:o})}(t),{allowed:s,retryAfter:l}=await n.consume(i,{window:a,max:o});if(!s){var c;return c=l??a,new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":c.toString()}})}}function e_(){return[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}]}var ev=e.i(70728),eO=e.i(42158);function eR(e){if(!e?.method)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if("oauth"===e.method&&!e.oauth?.providerId)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if(("sso-oidc"===e.method||"sso-saml"===e.method)&&!e.sso?.providerId)throw new p.E("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function ek(e,t){let r,i=e.context.options.user?.validateUserInfo;if(i){eR(t.source);try{r=await i(t,e)}catch(t){throw e.context.logger.error("validateUserInfo callback threw",t),new p.E("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(r?.error)throw new p.E("FORBIDDEN",{code:r.error,message:r.errorDescription||r.error})}}var ex=e.i(56023),eS=e.i(30501),eU=e.i(82318);let eN=async e=>{let t=await (0,eU.f)("SHA-256").digest(new TextEncoder().encode(e));return eS.W.encode(new Uint8Array(t),{padding:!1})};async function eD(e,t){return t&&"plain"!==t?"hashed"===t?eN(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function eL(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,i]of Object.entries(t.overrides))if(e.startsWith(r))return i}return t.default}return t}}var eC=e.i(73436),ez=e.i(97515),ej=e.i(13082),eP=e.i(33931),eB=e.i(87819),eM=e.i(18195),e$=e.i(30283),eq=e.i(24891);function eH(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let eF=(e,t)=>{let r,i,a=t.logger,o=t.options,n=o.secondaryStorage,s=new Map,l=0,c=o.session?.expiresIn||604800,d=!!n&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:u,updateWithHooks:f,updateManyWithHooks:m,deleteWithHooks:h,deleteManyWithHooks:g,consumeOneWithHooks:y}=(r=(0,eP.f)(t.options),i=t.hooks,{createWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=t;for(let{source:e,hooks:t}of i){let i=t[a]?.create?.before;if(i){let t=await r(`db create.before ${a}`,{[ej.A]:"create.before",[ej.d]:a,[ej.s]:e},()=>i(s,n));if(!1===t)return null;"object"==typeof t&&"data"in t&&(s={...s,...t.data})}}let l=null;for(let{source:t,hooks:c}of((!o||o.executeMainFn)&&(l=await (await (0,eC.g)(e)).create({model:a,data:s,forceAllowId:!0})),o?.fn&&(l=await o.fn(l??s)),i)){let e=c[a]?.create?.after;e&&await (0,eC.A)(async()=>{await r(`db create.after ${a}`,{[ej.A]:"create.after",[ej.d]:a,[ej.s]:t},()=>e(l,n))})}return l},updateWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db update.before ${o}`,{[ej.A]:"update.before",[ej.d]:o,[ej.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,eC.g)(e)).update({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,eC.A)(async()=>{await r(`db update.after ${o}`,{[ej.A]:"update.after",[ej.d]:o,[ej.s]:e},()=>i(d,s))})}return d},updateManyWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db updateMany.before ${o}`,{[ej.A]:"updateMany.before",[ej.d]:o,[ej.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,eC.g)(e)).updateMany({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,eC.A)(async()=>{await r(`db updateMany.after ${o}`,{[ej.A]:"updateMany.after",[ej.d]:o,[ej.s]:e},()=>i(d,s))})}return d},deleteWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=null;try{s=(await (await (0,eC.g)(e)).findMany({model:a,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[ej.A]:"delete.before",[ej.d]:a,[ej.s]:e},()=>i(s,n))===!1)return null}let l=o?await o.fn(t):null,c=(!o||o.executeMainFn)&&s?await (await (0,eC.g)(e)).delete({model:a,where:t}):l;if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${a}`,{[ej.A]:"delete.after",[ej.d]:a,[ej.s]:e},()=>i(s,n))})}return c},deleteManyWithHooks:async function(t,a,o){let n=(0,ez.G)(),s=[];try{s=await (await (0,eC.g)(e)).findMany({model:a,where:t})}catch{}for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[ej.A]:"delete.before",[ej.d]:a,[ej.s]:t},()=>i(e,n))===!1)return null}let l=o?await o.fn(t):null,c=!o||o.executeMainFn?await (await (0,eC.g)(e)).deleteMany({model:a,where:t}):l;for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${a}`,{[ej.A]:"delete.after",[ej.d]:a,[ej.s]:t},()=>i(e,n))})}return c},consumeOneWithHooks:async function(t,a,o,n){let s=(0,ez.G)(),l=i.flatMap(({source:e,hooks:r})=>{let i=r[t]?.delete?.before;return i?[{source:e,fn:i}]:[]}),c=n??null;if(l.length){if(!c)try{c=(await (await (0,eC.g)(e)).findMany({model:t,where:a,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:i}of l)if(await r(`db delete.before ${t}`,{[ej.A]:"delete.before",[ej.d]:t,[ej.s]:e},()=>i(c,s))===!1)return null}}let d=await o();if(!d)return null;for(let{source:e,hooks:a}of i){let i=a[t]?.delete?.after;i&&await (0,eC.A)(async()=>{await r(`db delete.after ${t}`,{[ej.A]:"delete.after",[ej.d]:t,[ej.s]:e},()=>i(d,s))})}return d}}),w=(t,r)=>{let i=[...t,{field:"expiresAt",value:new Date,operator:"gt"}];return g(i,"session",{fn:async()=>{await (await (0,eC.g)(e)).updateMany({model:"session",where:i,update:{expiresAt:new Date}}),await r?.()},executeMainFn:!1})};async function b(e){if(!n)return;let t=await n.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),i=((0,e$.f)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(i.map(async({token:t})=>{let i=await n.get(t);if(!i)return;let a=(0,e$.f)(i);if(!a)return;let o=eH(a.session.expiresAt,r);await n.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function E(e){if(!n)return[];let t=await n.get(`active-sessions-${e}`);return t&&(0,e$.f)(t)||[]}async function A(e,t,r){if(!n)return;let i=[...t].sort((e,t)=>e.expiresAt-t.expiresAt),a=eH(i.at(-1)?.expiresAt??0,r);a>0?await n.set(`active-sessions-${e}`,JSON.stringify(i),a):await n.delete(`active-sessions-${e}`)}let I=e=>`revoked-sessions-before-${e}`,T=Math.max(c,86400,Number(o.plugins?.find(e=>"admin"===e.id)?.options?.impersonationSessionDuration)||0);async function _(e,t){if(!n)return!1;let r=t?.get(e.userId)??Number(await n.get(I(e.userId)));return t?.set(e.userId,r),new Date(e.createdAt).getTime()<r}async function v(e,t,r){if(!n)return;let i=Number(await n.get(I(e)));await n.set(I(e),String(Math.max(r,i||0)),T);let a=new Set(t.map(e=>e.token));for(let e of a)await n.delete(e);let o=await E(e),s=Date.now();await A(e,o.filter(e=>e.expiresAt>s&&!a.has(e.token)),s)}async function O(e,t){if(!n)return;let r=t??await E(e),i=Date.now();await (0,eC.A)(()=>v(e,r,i),{onError(e){a.error("Failed to delete committed user sessions from secondary storage",e)}})}async function R(e,t){let r;if((0,eB.p)())return t();let i=s.get(e)??Promise.resolve(),a=new Promise(e=>{r=e}),o=i.catch(()=>{}).then(()=>a);s.set(e,o),await i.catch(()=>{});try{return await t()}finally{r(),s.get(e)===o&&s.delete(e)}}return{createOAuthUser:async(t,r)=>(0,eC.n)(e,async()=>{let e=await u({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);if(!e)throw new p.E("BAD_REQUEST",{message:"Failed to create user"});return{user:e,account:await u({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(e,t)=>{let r={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(o.user?.validateUserInfo){let e,i={...t,action:"create-user"};eR(i);try{e=(0,ez.g)()}catch(e){throw a.error("Unable to run validateUserInfo: missing endpoint context",e),new p.E("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await ek(e,{user:r,source:i})}return await u(r,"user",void 0)},createAccount:async e=>await u({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,i)=>{if(d)return(await (await (0,eC.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},{field:"expiresAt",value:new Date,operator:"gt"}]})).map(e=>(0,ex.Q)(t.options,e));if(n){let e=await n.get(`active-sessions-${r}`);if(!e)return[];let i=(0,e$.f)(e)||[],a=Date.now(),o=new Set,s=[],l=new Map;for(let{token:e,expiresAt:r}of i){if(r<=a||o.has(e))continue;o.add(e);let i=await n.get(e);if(i)try{let e="string"==typeof i?JSON.parse(i):i;if(!e?.session||await _(e.session,l))continue;s.push((0,ex.Q)(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await (0,eC.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},...i?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,i,a)=>await (await (0,eC.g)(e)).findMany({model:"user",limit:t,offset:r,sortBy:i,where:a}),countTotalUsers:async t=>{let r=await (await (0,eC.g)(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{let t=await E(e);(!n||o.session?.storeSessionInDatabase)&&await g([{field:"userId",value:e}],"session",void 0),await g([{field:"userId",value:e}],"account",void 0),await h([{field:"id",value:e}],"user",void 0)!==null&&await O(e,t)},createSession:async(r,i,s,l,f)=>{let p,m=await (async()=>{let e=(0,ez.G)();return e?.headers||e?.request?.headers})(),h=o.session?.storeSessionInDatabase,g=f?.deferSecondaryStorageWrites===!0&&d,{id:y,...w}=s||{};if(n&&!h){let e=t.generateId({model:"session"});p=!1!==e?e:(0,eM.f)()}let b=(0,ex.P)(o),E={...p?{id:p}:{},ipAddress:m&&ew(m,o)||"",userAgent:m?.get("user-agent")||"",...w,expiresAt:i?(0,eO.f)(86400,"sec"):(0,eO.f)(c,"sec"),userId:r,token:(0,eM.f)(32),createdAt:new Date,updatedAt:new Date,...b,...l?w:{}},I=async t=>{if(!n)return t;let i=await n.get(`active-sessions-${r}`),a=[],o=Date.now();i&&(a=(a=(0,e$.f)(i)||[]).filter(e=>e.expiresAt>o&&e.token!==E.token)),await A(r,[...a,{token:E.token,expiresAt:E.expiresAt.getTime()}],o);let s=await (await (0,eC.g)(e)).findOne({model:"user",where:[{field:"id",value:r}]}),l=eH(E.expiresAt,o);return l>0&&await n.set(E.token,JSON.stringify({session:{...t,createdAt:E.createdAt},user:s}),l),t};return await u(E,"session",n?{fn:async e=>g?(await (0,eC.A)(async()=>{await I(e)},{onError(e){a.error("Failed to mirror committed session to secondary storage",e)}}),e):I(e),executeMainFn:h}:void 0)},findSession:async r=>{if(n){let e=await n.get(r);if(!e&&(!o.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,e$.f)(e);return!r||await _(r.session)?null:{session:(0,ex.Q)(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:(0,ex.$)(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}}}let i=await (await (0,eC.g)(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!i)return null;let{user:a,...s}=i;return a?{session:(0,ex.Q)(t.options,s),user:(0,ex.$)(t.options,a)}:null},findSessions:async(t,r)=>{let i=[...new Set(t)],a=new Map,o=[],s=new Map;if(n)for(let e of i){let t=await n.get(e);if(t)try{let i="string"==typeof t?JSON.parse(t):t;if(!i||await _(i.session,s))continue;let o=new Date(i.session.expiresAt);if(r?.onlyActiveSessions&&o<=new Date)continue;let n={session:{...i.session,expiresAt:new Date(i.session.expiresAt)},user:{...i.user,createdAt:new Date(i.user.createdAt),updatedAt:new Date(i.user.updatedAt)}};a.set(e,n)}catch{continue}else o.push(e)}let l=n?o:i;if(l.length>0&&(!n||d))for(let{user:t,...i}of(await (await (0,eC.g)(e)).findMany({model:"session",limit:l.length,where:[{field:"token",value:l,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}})))t&&a.set(i.token,{session:i,user:t});return i.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,r)=>await f(r,[{field:"token",value:e}],"session",n?{async fn(r){let i=await n.get(e);if(!i)return null;let a=(0,e$.f)(i);if(!a)return null;let o={...a.session,...r,expiresAt:new Date(r.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(r.updatedAt??a.session.updatedAt)},s=(0,ex.Q)(t.options,o),l=Date.now(),c=new Date(s.expiresAt).getTime(),d=eH(c,l);if(d>0){await n.set(e,JSON.stringify({session:s,user:a.user}),d);let t=`active-sessions-${s.userId}`,r=await n.get(t),i=(r&&(0,e$.f)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>l).concat([{token:e,expiresAt:c}]);await A(s.userId,i,l)}return s},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(n){let r=await n.get(e);if(r){let{session:t}=(0,e$.f)(r)??{};if(!t)return void a.error("Session not found in secondary storage");let i=t.userId,o=await n.get(`active-sessions-${i}`);if(o){let t=(0,e$.f)(o)||[],r=Date.now();await A(i,t.filter(t=>t.expiresAt>r&&t.token!==e),r)}else a.error("Active sessions list not found in secondary storage")}if(await n.delete(e),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await w([{field:"token",value:e}])}await h([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await g([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await h([{field:"id",value:e}],"account",void 0)},deleteUserSessions:async r=>{let i=await E(r);if(!n)return void await g([{field:"userId",value:r}],"session",void 0);if(!o.session?.storeSessionInDatabase)return void await O(r,i);let a=async()=>O(r,[...i,...await E(r)]);t.options.session?.preserveSessionInDatabase?await w([{field:"userId",value:r}],a):await g([{field:"userId",value:r}],"session",{fn:async t=>{let r=await (await (0,eC.g)(e)).deleteMany({model:"session",where:t});return await a(),r},executeMainFn:!1})},deleteSessions:async e=>{if(n){if(await Promise.all(e.map(e=>n.delete(e))),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await w([{field:"token",value:e,operator:"in"}])}await g([{field:"token",value:e,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"providerId",value:t},{field:"accountId",value:r}],limit:2,join:{user:!0}});if(i.length>1)throw new p.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let a=i[0];if(!a)return null;let{user:o,...n}=a;return o?{kind:"owned",user:o,account:n}:{kind:"orphaned",account:n}},findUserByEmail:async(t,r)=>{let i=await (await (0,eC.g)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!i)return null;let a=e=>e.normalize("NFC").toLowerCase();if(a(i.email)!==a(t))return null;let{account:o,...n}=i;return{user:n,accounts:o??[]}},findUserById:async t=>t?await (await (0,eC.g)(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await u({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await f({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await (0,eC.A)(()=>b(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updateUserByEmail:async(e,t)=>{let r=await f({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await (0,eC.A)(()=>b(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updatePassword:async(e,t)=>{await m({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"},{field:"accountId",value:e}],"account",void 0)},findAccounts:async t=>await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findCredentialAccount:async t=>(await (0,eC.g)(e)).findOne({model:"account",where:[{field:"userId",value:t},{field:"providerId",value:"credential"},{field:"accountId",value:t}]}),findAccountByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,eC.g)(e)).findMany({model:"account",limit:2,where:[{field:"providerId",value:t},{field:"accountId",value:r}]});if(i.length>1)throw new p.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return i[0]??null},findAccountByUserId:async t=>await (await (0,eC.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await f(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=eL(e.identifier,o.verification?.storeIdentifier),r=await eD(e.identifier,t);return await u({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",n?{async fn(e){let t=eH(e.expiresAt);return t>0&&await n.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=eL(t,o.verification?.storeIdentifier),i=await eD(t,r);if(n){let e=await n.get(`verification:${i}`);if(e){let t=(0,e$.f)(e);if(t)return t}if(r&&"plain"!==r){let e=await n.get(`verification:${t}`);if(e){let t=(0,e$.f)(e);if(t)return t}}if(!o.verification?.storeInDatabase)return null}let a=await (0,eC.g)(e);async function s(e){return a.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let c=await s(i);!c.length&&r&&"plain"!==r&&(c=await s(t));let d=Date.now();return!o.verification?.disableCleanup&&d>=l&&(l=d+6e4,await g([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0)),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=eL(e,o.verification?.storeIdentifier),r=await eD(e,t);n&&await n.delete(`verification:${r}`),(!n||o.verification?.storeInDatabase)&&await h([{field:"identifier",value:r}],"verification",void 0)},consumeVerificationValue:async t=>{let r=eL(t,o.verification?.storeIdentifier),i=await eD(t,r),a=r&&"plain"!==r?[i,t]:[i],s=null;if(n&&!o.verification?.storeInDatabase){let e=async e=>(e=>{if(!e)return null;let t="string"==typeof e?(0,e$.f)(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})(await n.getAndDelete(e));for(let t of a){let r=await e(`verification:${t}`);if(r){await Promise.all(a.filter(e=>e!==t).map(e=>n.delete(`verification:${e}`))),s=r;break}}}else{let t=async t=>R(`verification:${t}`,()=>(0,eC.n)(e,async()=>{let r=await (0,eC.g)(e),i=[{field:"identifier",value:t}],a=(await r.findMany({model:"verification",where:i,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return a?y("verification",[{field:"id",value:a.id}],async()=>(await r.deleteMany({model:"verification",where:[...i,{field:"id",operator:"ne",value:a.id},{field:"createdAt",operator:"lte",value:a.createdAt}]}),r.consumeOne({model:"verification",where:[{field:"id",value:a.id}]})),a):null}));for(let e of a)if(s=await t(e))break;s&&n&&await Promise.all(a.map(e=>n.delete(`verification:${e}`)))}return!s||s.expiresAt<new Date?null:s},reserveVerificationValue:async t=>{let r=(0,eq.$)(new Uint8Array(await (0,eU.f)("SHA-256").digest(new TextEncoder().encode("reserve:"+t.identifier))),o,{adapter:e,model:"verification"}),i=eL(t.identifier,o.verification?.storeIdentifier),a=await eD(t.identifier,i);if(n&&!o.verification?.storeInDatabase)throw new p.p("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await e.create({model:"verification",data:{id:r,identifier:a,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:"verification",where:[{field:"id",value:r}]}))return!1;throw t}if(n){let e=eH(t.expiresAt);e>0&&await n.set(`verification:${a}`,JSON.stringify({id:r,identifier:a,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let r=eL(e,o.verification?.storeIdentifier),i=await eD(e,r);if(n){let e=await n.get(`verification:${i}`);if(e){let r=(0,e$.f)(e);if(r){let e={...r,...t},a=e.expiresAt??r.expiresAt,s=eH(a instanceof Date?a:new Date(a));if(s>0&&await n.set(`verification:${i}`,JSON.stringify(e),s),!o.verification?.storeInDatabase)return e}}}return!n||o.verification?.storeInDatabase?await f(t,[{field:"identifier",value:i}],"verification",void 0):t},refreshUserSessions:b}};var eV=e.i(76660);function eW(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 eK(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,i=".",a){if(!eW(r))return e(t,{},i,a);let o={...r};for(let r of Object.keys(t)){if("__proto__"===r||"constructor"===r)continue;let n=t[r];null!=n&&(a&&a(o,r,n,i)||(Array.isArray(n)&&Array.isArray(o[r])?o[r]=[...n,...o[r]]:eW(n)&&eW(o[r])?o[r]=e(n,o[r],(i?`${i}.`:"")+r.toString(),a):o[r]=n))}return o})(t,r,"",e),{})}let eG=eK();eK((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),eK((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0});let eJ=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function eQ(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function eY(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function eZ(e,t,r){if(0===r)return!0;let i=32===r?0xffffffff:-1<<32-r>>>0;return(e&i)==(t&i)}function eX(e){if("0.0.0.0"===e)return"unspecified";if("255.255.255.255"===e)return"broadcast";let t=eY(e);return eZ(t,eY("127.0.0.0"),8)?"loopback":eZ(t,eY("10.0.0.0"),8)||eZ(t,eY("172.16.0.0"),12)||eZ(t,eY("192.168.0.0"),16)?"private":eZ(t,eY("169.254.0.0"),16)?"linkLocal":eZ(t,eY("100.64.0.0"),10)?"sharedAddressSpace":eZ(t,eY("192.0.2.0"),24)||eZ(t,eY("198.51.100.0"),24)||eZ(t,eY("203.0.113.0"),24)?"documentation":eZ(t,eY("198.18.0.0"),15)?"benchmarking":eZ(t,eY("224.0.0.0"),4)?"multicast":eZ(t,eY("0.0.0.0"),8)||eZ(t,eY("192.0.0.0"),24)||eZ(t,eY("192.88.99.0"),24)||eZ(t,eY("240.0.0.0"),4)?"reserved":"public"}function e0(e,t,r={}){let i=5*t,a=Number.parseInt(e.slice(i,i+4),16),o=Number.parseInt(e.slice(i+5,i+9),16);if(!Number.isFinite(a)||!Number.isFinite(o))return null;let n=(a<<16|o)>>>0;return r.xor&&(n=(0xffffffff^n)>>>0),`${n>>>24&255}.${n>>>16&255}.${n>>>8&255}.${255&n}`}async function e1(e){let t=e.options,r=t.plugins||[],i=[],a=[];for(let o of r)if(o.init){let r,n=o.init(e);if("object"==typeof(r=(0,eV.f)(n)?await n:n)){if(r.options){let{databaseHooks:e,trustedOrigins:n,...s}=r.options;e&&a.push({source:`plugin:${o.id}`,hooks:e}),n&&i.push(n),t=eG(t,s)}r.context&&Object.assign(e,r.context)}}if(i.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...i],r=e.filter(Array.isArray).flat(),a=e.filter(e=>"function"==typeof e);a.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(a.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&a.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=eF(e.adapter,{options:t,logger:e.logger,hooks:a,generateId:e.generateId}),e.options=t}async function e2(e,t){let r=[];if((0,z._)(e.baseURL)){let t=e.baseURL.allowedHosts,i=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(i&&"https"!==i&&"auto"!==i||r.push(`https://${e}`),("http"===i||"auto"===i||function(e){let t=function(e){var t,r;let i,a=(-1===(i=(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,i)).replace(/\.+$/,"").toLowerCase();if(""===a)return{kind:"reserved",literal:"fqdn",canonical:""};if(!(ec(a)||ed(a)))return"localhost"===a||a.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:a}:eJ.has(a)?{kind:"cloudMetadata",literal:"fqdn",canonical:a}:{kind:"public",literal:"fqdn",canonical:a};if(eQ(a))return{kind:eX(a),literal:"ipv4",canonical:a};let o=ep(a,{ipv6Subnet:128});return eQ(o)?{kind:eX(o),literal:"ipv4",canonical:o}:{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&&(192&r)==192)return"reserved";if((254&t)==252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2001:0002:0000:"))return"benchmarking";if(e.startsWith("2002:")){let t=e0(e,1);return t&&"public"!==eX(t)?"reserved":"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let t=e0(e,6);return t&&eX(t),"reserved"}if(e.startsWith("0064:ff9b:0001:"))return"reserved";if(e.startsWith("2001:0000:")){let t=e0(e,6,{xor:!0});return t&&eX(t),"reserved"}return e.startsWith("0100:0000:0000:0000:")?"reserved":e.startsWith("3fff:0")?"documentation":e.startsWith("5f00:")||e.startsWith("0000:0000:0000:0000:0000:0000:")?"reserved":"public"}(o),literal:"ipv6",canonical:o}}(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 i=(0,z.X)("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);i&&r.push(new URL(i).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let i=await e.trustedOrigins(t);r.push(...i)}let i=en.$.BETTER_AUTH_TRUSTED_ORIGINS;return i&&r.push(...i.split(",")),r.filter(e=>!!e)}function e5(e){return e.advanced?.trustedProxyHeaders??!1}async function e6(e,t,r){let i,a=e.options.baseURL,o=e.options.basePath||"/api/auth",n=(0,z.A)(a,o,t,void 0,r);if(!n)throw new p.p("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));s.baseURL=n,s.options={...e.options,baseURL:(0,z.H)(n)||void 0};let l={...s.options,baseURL:a};return i="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?(0,z.T)(t)?t:t?new Request(n,{headers:t}):void 0:void 0,s.trustedOrigins=await e2(l,i),s.trustedProviders=await e4(s.options,i),e.options.advanced?.crossSubDomainCookies?.enabled&&(s.authCookies=(0,ev.e)(s.options),s.createAuthCookie=(0,ev.g)(s.options)),s}async function e8(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 e4(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}var e3=e.i(67850),e9=e.i(96161),e7=e.i(75742),te=e.i(66680);function tt(e,t){return new Promise((r,i)=>{(0,te.scrypt)(e.normalize("NFKC"),t,64,{N:16384,r:16,p:1,maxmem:0x4000000},(e,t)=>{e?i(e):r(t)})})}async function tr(e){let t=(0,te.randomBytes)(16).toString("hex");return`${t}:${(await tt(e,t)).toString("hex")}`}async function ti(e,t){let[r,i]=e.split(":");if(!r||!i)throw Error("Invalid password hash");return(await tt(t,r)).toString("hex")===i}let ta=async({hash:e,password:t})=>ti(e,t);var to=e.i(39127);let tn=(0,to.f)("a-z","0-9","A-Z","-_");function ts(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT}e.i(96101);let tl=e=>e?`"${e}" `:"";function tc(e,t=""){if("boolean"!=typeof e)throw TypeError(tl(t)+"expected boolean, got type="+typeof e);return e}function td(e,t=""){if("number"!=typeof e)throw TypeError(tl(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(tl(t)+"expected integer >= 0, got "+e);return e}function tu(e,t,r=""){if(ts(e)&&(void 0===t||e.length===t))return e;void 0!==t&&td(t,"length");let i=ts(e),a=void 0!==t?` of length ${t}`:"",o=i?`length=${e.length}`:`type=${typeof e}`,n=tl(r)+"expected Uint8Array"+a+", got "+o;if(!i)throw TypeError(n);throw RangeError(n)}let tf=(e,t)=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw TypeError("object"===t?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function tp(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function tm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function th(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let tg=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],ty=tg?e=>e:function(e){for(let r=0;r<e.length;r++){var t;e[r]=(t=e[r])<<24&0xff000000|t<<8&0xff0000|t>>>8&65280|t>>>24&255}return e},tw="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,tb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function tE(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function tA(e,t){return!!e.byteLength&&!!t.byteLength&&e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function tI(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(tu(t,e,"output"),r&&!tT(t))throw Error("invalid output, must be aligned");return t}function tT(e){return e.byteOffset%4==0}function t_(e){return Uint8Array.from(tu(e))}function tv(e=32){td(e,"bytesLength");let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function tO(e,t=tv){if("function"!=typeof e)throw TypeError('"fn" expected cipher constructor, got type='+typeof e);if("function"!=typeof t)throw TypeError('"randomBytes_" expected function, got type='+typeof t);let{nonceLength:r}=e;td(r,"fn.nonceLength");let i=(e,t,r)=>{let i=function(...e){let t=0;for(let r=0;r<e.length;r++){let i=e[r];tu(i),t+=i.length}let r=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){let a=e[t];r.set(a,i),i+=a.length}return r}(e,t);return tA(r,t)||t.fill(0),i},a=(a,...o)=>({encrypt(n){tu(n,void 0,"data");let s=t(r),l=e(a,s,...o).encrypt(n);return l instanceof Promise?l.then(e=>i(s,e,n)):i(s,l,n)},decrypt(t){tu(t,void 0,"data");let i=t.subarray(0,r),n=t.subarray(r);return e(a,i,...o).decrypt(n)}});return"blockSize"in e&&(a.blockSize=e.blockSize),"tagLength"in e&&(a.tagLength=e.tagLength),"withAAD"in e&&(a.withAAD=e.withAAD),a}let tR=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),tk=ty(tm(tR("expand 16-byte k"))),tx=ty(tm(tR("expand 32-byte k")));function tS(e,t){return e<<t|e>>>32-t}let tU=Uint32Array.of();function tN(e,t){return 255&e[t++]|(255&e[t++])<<8}class tD{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){let t=tN(e=t_(tu(e,32,"key")),0),r=tN(e,2),i=tN(e,4),a=tN(e,6),o=tN(e,8),n=tN(e,10),s=tN(e,12),l=tN(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|a<<9)&8191,this.r[4]=(a>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|n<<2)&8191,this.r[7]=(n>>>11|s<<5)&8065,this.r[8]=(s>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=tN(e,16+2*t)}process(e,t,r=!1){let{h:i,r:a}=this,o=a[0],n=a[1],s=a[2],l=a[3],c=a[4],d=a[5],u=a[6],f=a[7],p=a[8],m=a[9],h=tN(e,t+0),g=tN(e,t+2),y=tN(e,t+4),w=tN(e,t+6),b=tN(e,t+8),E=tN(e,t+10),A=tN(e,t+12),I=tN(e,t+14),T=i[0]+(8191&h),_=i[1]+((h>>>13|g<<3)&8191),v=i[2]+((g>>>10|y<<6)&8191),O=i[3]+((y>>>7|w<<9)&8191),R=i[4]+((w>>>4|b<<12)&8191),k=i[5]+(b>>>1&8191),x=i[6]+((b>>>14|E<<2)&8191),S=i[7]+((E>>>11|A<<5)&8191),U=i[8]+((A>>>8|I<<8)&8191),N=i[9]+(I>>>5|2048*!r),D=0,L=0+T*o+5*m*_+5*p*v+5*f*O+5*u*R;D=L>>>13,L&=8191,L+=5*d*k+5*c*x+5*l*S+5*s*U+5*n*N,D+=L>>>13,L&=8191;let C=D+T*n+_*o+5*m*v+5*p*O+5*f*R;D=C>>>13,C&=8191,C+=5*u*k+5*d*x+5*c*S+5*l*U+5*s*N,D+=C>>>13,C&=8191;let z=D+T*s+_*n+v*o+5*m*O+5*p*R;D=z>>>13,z&=8191,z+=5*f*k+5*u*x+5*d*S+5*c*U+5*l*N,D+=z>>>13,z&=8191;let j=D+T*l+_*s+v*n+O*o+5*m*R;D=j>>>13,j&=8191,j+=5*p*k+5*f*x+5*u*S+5*d*U+5*c*N,D+=j>>>13,j&=8191;let P=D+T*c+_*l+v*s+O*n+R*o;D=P>>>13,P&=8191,P+=5*m*k+5*p*x+5*f*S+5*u*U+5*d*N,D+=P>>>13,P&=8191;let B=D+T*d+_*c+v*l+O*s+R*n;D=B>>>13,B&=8191,B+=k*o+5*m*x+5*p*S+5*f*U+5*u*N,D+=B>>>13,B&=8191;let M=D+T*u+_*d+v*c+O*l+R*s;D=M>>>13,M&=8191,M+=k*n+x*o+5*m*S+5*p*U+5*f*N,D+=M>>>13,M&=8191;let $=D+T*f+_*u+v*d+O*c+R*l;D=$>>>13,$&=8191,$+=k*s+x*n+S*o+5*m*U+5*p*N,D+=$>>>13,$&=8191;let q=D+T*p+_*f+v*u+O*d+R*c;D=q>>>13,q&=8191,q+=k*l+x*s+S*n+U*o+5*m*N,D+=q>>>13,q&=8191;let H=D+T*m+_*p+v*f+O*u+R*d;D=H>>>13,H&=8191,H+=k*c+x*l+S*s+U*n+N*o,D+=H>>>13,H&=8191,L=8191&(D=(D=(D<<2)+D|0)+L|0),D>>>=13,C+=D,i[0]=L,i[1]=C,i[2]=z,i[3]=j,i[4]=P,i[5]=B,i[6]=M,i[7]=$,i[8]=q,i[9]=H}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=i,i=e[t]>>>13,e[t]&=8191;e[0]+=5*i,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+i,i=r[t]>>>13,r[t]&=8191;r[9]-=8192;let a=(1^i)-1;for(let e=0;e<10;e++)r[e]&=a;a=~a;for(let t=0;t<10;t++)e[t]=e[t]&a|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 o=e[0]+t[0];e[0]=65535&o;for(let r=1;r<8;r++)o=(e[r]+t[r]|0)+(o>>>16)|0,e[r]=65535&o;th(r)}update(e){tp(this),tu(e);let{buffer:t,blockLen:r}=this,i=(e=t_(e)).length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){for(;r<=i-a;a+=r)this.process(e,a);continue}t.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,th(this.h,this.r,this.buffer,this.pad)}digestInto(e){tp(this);tu(e,void 0,"output");let t=this.outputLen;if(!(e.length>=t))throw RangeError('"output" expected length >= '+t);this.finished=!0;let{buffer:r,h:i}=this,{pos:a}=this;if(a){for(r[a++]=1;a<16;a++)r[a]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=i[t]>>>0,e[o++]=i[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let tL=(c=e=>new tD(e),o=()=>[],(n=(e,t)=>c(t,...o()).update(e).digest()).outputLen=(s=c(new Uint8Array(32),...o(new Uint8Array(0)))).outputLen,n.blockLen=s.blockLen,n.create=(e,...t)=>c(e,...t),n);function tC(e,t,r,i,a,o=20){let n=e[0],s=e[1],l=e[2],c=e[3],d=t[0],u=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],y=t[7],w=r[0],b=r[1],E=r[2],A=n,I=s,T=l,_=c,v=d,O=u,R=f,k=p,x=m,S=h,U=g,N=y,D=a,L=w,C=b,z=E;for(let e=0;e<o;e+=2)x=x+(D=tS(D^(A=A+v|0),16))|0,A=A+(v=tS(v^x,12))|0,x=x+(D=tS(D^A,8))|0,v=tS(v^x,7),S=S+(L=tS(L^(I=I+O|0),16))|0,I=I+(O=tS(O^S,12))|0,S=S+(L=tS(L^I,8))|0,O=tS(O^S,7),U=U+(C=tS(C^(T=T+R|0),16))|0,T=T+(R=tS(R^U,12))|0,U=U+(C=tS(C^T,8))|0,R=tS(R^U,7),N=N+(z=tS(z^(_=_+k|0),16))|0,_=_+(k=tS(k^N,12))|0,N=N+(z=tS(z^_,8))|0,k=tS(k^N,7),U=U+(z=tS(z^(A=A+O|0),16))|0,A=A+(O=tS(O^U,12))|0,U=U+(z=tS(z^A,8))|0,O=tS(O^U,7),N=N+(D=tS(D^(I=I+R|0),16))|0,I=I+(R=tS(R^N,12))|0,N=N+(D=tS(D^I,8))|0,R=tS(R^N,7),x=x+(L=tS(L^(T=T+k|0),16))|0,T=T+(k=tS(k^x,12))|0,x=x+(L=tS(L^T,8))|0,k=tS(k^x,7),S=S+(C=tS(C^(_=_+v|0),16))|0,_=_+(v=tS(v^S,12))|0,S=S+(C=tS(C^_,8))|0,v=tS(v^S,7);let j=0;i[j++]=n+A|0,i[j++]=s+I|0,i[j++]=l+T|0,i[j++]=c+_|0,i[j++]=d+v|0,i[j++]=u+O|0,i[j++]=f+R|0,i[j++]=p+k|0,i[j++]=m+x|0,i[j++]=h+S|0,i[j++]=g+U|0,i[j++]=y+N|0,i[j++]=a+D|0,i[j++]=w+L|0,i[j++]=b+C|0,i[j++]=E+z|0}let tz=function(e,t){var r;let{allowShortKeys:i,extendNonceFn:a,counterLength:o,counterRight:n,rounds:s}=(tf(r={allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},"defaults"),tf(t,"opts"),Object.assign(r,t));if("function"!=typeof e)throw Error("core must be a function");return td(o),td(s),tc(n),tc(i),(t,r,l,c,d=0)=>{let u,f;tu(t,void 0,"key"),tu(r,void 0,"nonce"),tu(l,void 0,"data");let p=l.length,m=void 0!==c;if(c=tI(p,c,!1),m&&function(e,t){if(tA(e,t)&&e.byteOffset<t.byteOffset)throw Error("complex overlap of input and output is not supported")}(l,c),td(d),d<0||d>=0xffffffff)throw Error("arx: counter overflow");let h=[],g=t.length;if(32===g)h.push(u=t_(t)),f=tx;else if(16===g&&i)(u=new Uint8Array(32)).set(t),u.set(t,16),f=tk,h.push(u);else throw tu(t,32,"arx key"),Error("invalid key size");tg&&tT(r)||h.push(r=t_(r));let y=tm(u);if(a){if(24!==r.length)throw Error("arx: extended nonce must be 24 bytes");let e=r.subarray(0,16);if(tg)a(f,y,tm(e),y);else{let t=ty(Uint32Array.from(f));a(t,y,tm(e),y),th(t),ty(y)}r=r.subarray(16)}else tg||ty(y);let w=16-o;if(w!==r.length)throw Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){let e=new Uint8Array(12);e.set(r,n?0:12-r.length),r=e,h.push(r)}let b=ty(tm(r));try{return!function(e,t,r,i,a,o,n,s){let l=a.length,c=new Uint8Array(64),d=tm(c),u=tg&&tT(a)&&tT(o),f=u?tm(a):tU,p=u?tm(o):tU;if(!tg){for(let u=0;u<l;n++){if(e(t,r,i,d,n,s),ty(d),n>=0xffffffff)throw Error("arx: counter overflow");let f=Math.min(64,l-u);for(let e=0,t;e<f;e++)o[t=u+e]=a[t]^c[e];u+=f}return}for(let m=0;m<l;n++){if(e(t,r,i,d,n,s),n>=0xffffffff)throw Error("arx: counter overflow");let h=Math.min(64,l-m);if(u&&64===h){let e=m/4;if(m%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)p[r=e+t]=f[r]^d[t];m+=64;continue}for(let e=0,t;e<h;e++)o[t=m+e]=a[t]^c[e];m+=h}}(e,f,y,b,l,c,d,s),c}finally{th(...h)}}}(tC,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,i){let a=tg?e:ty(e.slice(0,4)),o=tg?t:ty(t.slice(0,8)),n=tg?r:ty(r.slice(0,4)),s=new Uint32Array(16);tC(a,o,n.subarray(1),s,n[0]);let l=0;i[l++]=s[0]-a[0]|0,i[l++]=s[1]-a[1]|0,i[l++]=s[2]-a[2]|0,i[l++]=s[3]-a[3]|0,i[l++]=s[12]-n[0]|0,i[l++]=s[13]-n[1]|0,i[l++]=s[14]-n[2]|0,i[l++]=s[15]-n[3]|0,ty(i),tg||th(a,o,n),th(s)},allowShortKeys:!1}),tj=new Uint8Array(16),tP=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(tj.subarray(r))},tB=new Uint8Array(32);function tM(e,t,r,i,a){var o,n;let s,l;void 0!==a&&tu(a,void 0,"AAD");let c=e(t,r,tB),d=(o=i.length,n=a?a.length:0,td(o),td(n),tc(!0),(l=new DataView((s=new Uint8Array(16)).buffer,s.byteOffset,s.byteLength)).setBigUint64(0,BigInt(n),!0),l.setBigUint64(8,BigInt(o),!0),s),u=tL.create(c);a&&tP(u,a),tP(u,i),u.update(d);let f=u.digest();return th(c,d),f}let t$=((e,t)=>{function r(i,...a){tu(i,void 0,"key"),void 0!==e.nonceLength&&tu(a[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let o=e.tagLength,n=+(void 0!==e.nonceLength);if(!e.withAAD){for(let e=n;e<a.length;e++)if(ts(a[e]))throw Error("AAD not supported")}e.withAAD&&void 0!==a[n]&&tu(a[n],void 0,"AAD");let s=t(i,...a),l=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");tu(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,tu(e,void 0,"data"),l(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(tu(e,void 0,"data"),o&&e.length<o)throw Error('"ciphertext" expected length >= tagLength='+o);return l(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e,t,r)=>({encrypt(i,a){let o=i.length;(a=tI(o+16,a,!1)).set(i);let n=a.subarray(0,-16);tz(e,t,n,n,1);let s=tM(tz,e,t,n,r);return a.set(s,o),th(s),a},decrypt(i,a){a=tI(i.length-16,a,!1);let o=i.subarray(0,-16),n=i.subarray(-16),s=tM(tz,e,t,o,r);if(!function(e,t){if(e=tu(e),t=tu(t),e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}(n,s))throw th(s),Error("invalid tag");return a.set(i.subarray(0,-16)),tz(e,t,a,a,1),th(s),a}})),tq="$ba$";async function tH(e,t){let r=await (0,eU.f)("SHA-256").digest(e),i=function(e){if("string"!=typeof e)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var a=tO(t$)(new Uint8Array(r)).encrypt(i);if(tu(a),tw)return a.toHex();let o="";for(let e=0;e<a.length;e++)o+=tb[a[e]];return o}async function tF(e,t){let r=await (0,eU.f)("SHA-256").digest(e),i=function(e){if("string"!=typeof e)throw TypeError("hex string expected, got "+typeof e);if(tw)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 i=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){let r=tE(e.charCodeAt(a)),o=tE(e.charCodeAt(a+1));if(void 0===r||void 0===o)throw RangeError('hex string expected, got non-hex character "'+(e[a]+e[a+1])+'" at index '+a);i[t]=16*r+o}return i}(t),a=tO(t$)(new Uint8Array(r));return new TextDecoder().decode(a.decrypt(i))}let tV=async({key:e,data:t})=>{var r;if("string"==typeof e)return tH(e,t);let i=e.keys.get(e.currentVersion);if(!i)throw Error(`Secret version ${e.currentVersion} not found in keys`);let a=await tH(i,t);return r=e.currentVersion,`${tq}${r}$${a}`},tW=async({key:e,data:t})=>{if("string"==typeof e)return tF(e,t);let r=function(e){if(!e.startsWith(tq))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 tF(t,r.ciphertext)}if(e.legacySecret)return tF(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};var tK=e.i(69381),tG=e.i(1083),tJ=e.i(97858);let tQ=(0,tJ.k)("better-auth:oauth-encryption:v1");function tY(e,t){return(0,tJ.w)((0,tK.f)(tG.f,(0,tJ.k)(e),tQ,(0,tJ.k)(`better-auth:${t}:v1`),32))}function tZ(e,t){return"string"==typeof e?tY(e,t):{keys:new Map(Array.from(e.keys,([e,r])=>[e,tY(r,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:tY(e.legacySecret,t)}}}async function tX(e,t,r){let i=e.accountSubject,a=await i({tokens:t,profile:r}),o=String(a);if("number"==typeof a&&!Number.isFinite(a)||0===o.trim().length||"undefined"===o||"null"===o)throw new p.p("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:e.id,accountId:o}}async function t0(e,t,r){try{return await tX(e,t,r)}catch{throw p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO)}}let t1="invalid_code",t2="unable_to_get_user_info",t5="unable_to_link_account",t6="email_not_verified";function t8(e,t,r,i){let a=new URLSearchParams({error:r});i&&a.set("error_description",i);let o=Y(t,a);throw e.redirect(o)}function t4(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 create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}function t3(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}var t9=e.i(12996),t7=e.i(9939),re=e.i(65466);async function rt(e,t,r,i=3600,a){return await (0,e7.X)({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...a},e,i)}async function rr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),p.E.from("BAD_REQUEST",G.f.VERIFICATION_EMAIL_NOT_ENABLED);let r=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),i=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:r},e.request)}let ri=(0,C.g)("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:P.object({email:P.email().meta({description:"The email to send the verification email to"}),callbackURL:P.string().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."),p.E.from("BAD_REQUEST",G.f.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await (0,t9.D)(e);if(!r){let r,i=Date.now(),a=await e.context.internalAdapter.findUserByEmail(t);if(!a||a.user.emailVerified)await rt(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await rr(e,a.user)}catch(e){r=e}let o=500-(Date.now()-i);if(o>0&&await new Promise(e=>setTimeout(e,o)),r)throw r;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw p.E.from("BAD_REQUEST",G.f.EMAIL_MISMATCH);if(r?.user.emailVerified)throw p.E.from("BAD_REQUEST",G.f.EMAIL_ALREADY_VERIFIED);return await rr(e,r.user),e.json({status:!0})}),ra=(0,C.g)("/verify-email",{method:"GET",operationId:"verifyEmail",query:P.object({token:P.string().meta({description:"The token to verify the email"}),callbackURL:P.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[er(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){let r=new URLSearchParams({error:t.code}),i=Y(e.query.callbackURL,r);throw e.redirect(i)}throw p.E.from("UNAUTHORIZED",t)}let{token:i}=e.query;try{t=await (0,t7.f)(i,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof re.JWTExpired)return r(G.f.TOKEN_EXPIRED);return r(G.f.INVALID_TOKEN)}let a=P.object({email:P.email(),updateTo:P.string().optional(),requestType:P.string().optional(),userId:P.string().optional()}).parse(t.payload);if(a.updateTo){if(!a.userId)return r(G.f.INVALID_TOKEN);let t=await e.context.internalAdapter.findUserById(a.userId);if(!t)return r(G.f.USER_NOT_FOUND);if(t.email.toLowerCase()!==a.email)return r(G.f.INVALID_TOKEN);let i=await (0,t9.D)(e);if(i&&i.user.id!==t.id)return r(G.f.INVALID_USER);switch(a.requestType){case"change-email-confirmation":{let r=await rt(e.context.secret,a.email,a.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:t.id}),i=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...t,email:a.updateTo},url:o,token:r},t3(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t.emailVerified,o=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:r});if(r&&e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),i&&await (0,ev.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:r}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,ex.$)(e.context.options,o)})}default:{let r=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:!1}),o=await rt(e.context.secret,a.updateTo,void 0,void 0,{userId:t.id}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${n}`,token:o},t3(e.request))),i&&await (0,ev.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,ex.$)(e.context.options,r)})}}}let o=await e.context.internalAdapter.findUserByEmail(a.email);if(!o)return r(G.f.USER_NOT_FOUND);if(a.userId&&a.userId!==o.user.id)return r(G.f.INVALID_TOKEN);if(o.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(o.user,e.request);let n=await e.context.internalAdapter.updateUserByEmail(a.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await (0,t9.D)(e);if(t&&t.user.email===a.email)await (0,ev.V)(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(o.user.id);if(!t)throw p.E.from("INTERNAL_SERVER_ERROR",G.f.FAILED_TO_CREATE_SESSION);await (0,ev.V)(e,{session:t,user:{...o.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function ro(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)?tW({key:t.secretConfig,data:e}):e;return e}function rn(e,t){return t.options.account?.encryptOAuthTokens&&e?tV({key:t.secretConfig,data:e}):e}function rs(e){return e.callbackPath?e.callbackPath.startsWith("/")?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function rl(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?e.trim():"").filter(Boolean):"string"==typeof e?e.trim().split(/\s+/).filter(Boolean):[]}function rc(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:rl(e.scope),idToken:e.id_token,raw:e}}function rd(e){return!0===e||"true"===e||!1!==e&&"false"!==e&&void 0}function ru(e){let t=Array.isArray(e)?e[0]:e;return"string"==typeof t&&t.length>0?t:void 0}async function rf(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return eS.W.encode(new Uint8Array(r),{padding:!1})}function rp(e,t){return{linked:!1,error:{code:e,message:t}}}async function rm(e,t){if(!t.encryptedSessionToken||!(0,t9.f)(e))return!0;let r=await tW({key:tZ(e.context.secretConfig,"oauth-link-session-token"),data:t.encryptedSessionToken}).catch(()=>null);if(!r)return!1;let i=await e.context.internalAdapter.findSession(r);return!!i&&i.session.userId===t.userId&&i.session.expiresAt>new Date}async function rh(e,t){let{link:r,account:i,profile:a,scopes:o}=t,n={...t.userInfo,emailVerified:rd(t.userInfo.emailVerified)??!1};if(!await rm(e,r))return rp(t5);try{await ek(e,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:i.providerId,profile:a}}})}catch(e){if(!(0,L.f)(e)||!e.body?.code)throw e;return rp(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(i.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),rp(t5);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return rp("email_does_not_match");let s=await e.context.internalAdapter.findAccountByKey(i);if(s){var l;if(s.userId.toString()!==r.userId.toString())return rp("account_already_linked_to_different_user");let t=(l=s.scope,[...new Set([...l?l.split(",").map(e=>e.trim()).filter(Boolean):[],...(o??[]).map(e=>e.trim()).filter(Boolean)])].join(",")),a=Object.fromEntries(Object.entries({providerId:i.providerId,accessToken:await rn(i.accessToken,e.context),refreshToken:await rn(i.refreshToken,e.context),idToken:i.idToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:t||void 0}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(s.id,a)}else if(!await e.context.internalAdapter.createAccount({userId:r.userId,...i,accessToken:await rn(i.accessToken,e.context),refreshToken:await rn(i.refreshToken,e.context),scope:o?.join(",")??i.scope}))return rp(t5);return await rw(e,r.userId,n),{linked:!0}}async function rg(e,t){let{account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,n={...t.userInfo,emailVerified:rd(t.userInfo.emailVerified)??!1},s=t.source??{method:"oauth",oauth:{providerId:r.providerId}},l=!!t.selectedUser||!0===t.requireExactAccountBinding,c=null,d=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;t8(e,r,"internal_server_error")});if(d?.kind==="orphaned")return e.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let u=await (async()=>{if(d?.kind==="owned"){if(t.selectedUser&&d.user.id!==t.selectedUser.userId)throw new p.E("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:d.user,linkedAccount:d.account,accounts:[d.account]}}if(t.selectedUser){let r=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!r)throw new p.E("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:r,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if((0,L.f)(t))throw t;e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;t8(e,r,"internal_server_error")}),f=u?.user,m=!f;if(u){let i=u.linkedAccount??u.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await ek(e,{user:{...o,id:u.user.id,email:n.email.toLowerCase()},source:{...s,action:"sign-in"}});let d=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>void 0!==t)):{};if(e.context.options.account?.storeAccountCookie){let r={...i,...d};t.deferNonDatabaseWrites?c=r:await (0,e9.L)(e,r)}if(Object.keys(d).length>0){let a=await e.context.internalAdapter.updateAccount(i.id,d);if(!a)return{error:"unable to update account",data:null};if(l&&(a.accountId!==r.accountId||a.providerId!==r.providerId||a.userId!==u.user.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});t.deferNonDatabaseWrites&&c&&(c=a)}t.selectedUser||!n.emailVerified||u.user.emailVerified||n.email.toLowerCase()!==u.user.email||await e.context.internalAdapter.updateUser(u.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||!1!==t.trustProviderByName&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!u.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return(0,en.o)()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.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{let{id:i,...a}=n;await ek(e,{user:{...a,id:u.user.id,email:n.email.toLowerCase()},source:{...s,action:"link-account"}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:u.user.id,accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:"unable to link account",data:null};if(l&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==u.user.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=o:await (0,e9.L)(e,o))}catch(t){if((0,L.f)(t))throw t;return e.context.logger.error("Unable to link account",t),{error:"unable to link account",data:null}}t.selectedUser||!n.emailVerified||u.user.emailVerified||n.email.toLowerCase()!==u.user.email||await e.context.internalAdapter.updateUser(u.user.id,{emailVerified:!0}),t.selectedUser||(f=await rw(e,u.user.id,n)??f)}if(t.selectedUser?"update"===t.selectedUser.profile:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...l}=n,c=(0,ex.W)(e.context.options,l,"update"),d=await e.context.internalAdapter.updateUser(u.user.id,{name:o,image:s,...c,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===u.user.email&&u.user.emailVerified||n.emailVerified});if(null==d&&e.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session."),t.selectedUser&&d&&d.id!==t.selectedUser.userId)throw new p.E("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});f=d??f}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:d,image:u,...m}=n,h=(0,ex.W)(e.context.options,m,"create"),g={accessToken:await rn(r.accessToken,e.context),refreshToken:await rn(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},y=await (0,eC.n)(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:d,image:u,...h,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return t?{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...g,userId:t.id})}:null});if(!y)return{error:"unable to create user",data:null,isRegister:!1};let{createdUser:w,createdAccount:b}=y;if(l&&(b.accountId!==r.accountId||b.providerId!==r.providerId||b.userId!==w.id))throw new p.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});f=w,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=b:await (0,e9.L)(e,b))}catch(t){if((0,L.f)(t))throw t;return e.context.logger.error("Unable to create OAuth user",t),{error:"unable to create user",data:null,isRegister:!1}}}if(!f)return{error:"unable to create user",data:null,isRegister:!1};let h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await ry(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await ry(e,f,i,t.deferNonDatabaseWrites),{error:t6,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0===t.deferNonDatabaseWrites});if(!g)return{error:"unable to create session",data:null,isRegister:!1};if(l&&g.userId!==(t.selectedUser?.userId??f.id))throw new p.E("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:g,user:f},error:null,isRegister:m,accountCookie:c}}async function ry(e,t,r,i){let a=e.context.options.emailVerification?.sendVerificationEmail;if(!a)return;let o=async()=>{try{let i=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${encodeURIComponent(r||"/")}`;await e.context.runInBackgroundOrAwait(a({user:t,url:o,token:i},e.request))}catch(t){e.context.logger.error("Failed to send OAuth verification email",t)}};i?await (0,eC.A)(o):await o()}async function rw(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:i,emailVerified:a,name:o,image:n,...s}=r,l=(0,ex.W)(e.context.options,s,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:n,...l})}catch(t){e.context.logger.warn("Could not update user info on account link",t);return}}var rb=e.i(24374);let{get:rE,set:rA}=(0,rb.z)(()=>null),{get:rI,set:rT}=(0,rb.z)(()=>null);var r_=p,rv=e.i(54257);let rO=e=>`auth-state:${e}`,rR=P.looseObject({callbackURL:P.string(),codeVerifier:P.string(),errorURL:P.string().optional(),newUserURL:P.string().optional(),expiresAt:P.number(),oauthState:P.string().optional(),link:P.object({email:P.string(),userId:rv.f.string(),encryptedSessionToken:P.string().optional()}).optional(),requestSignUp:P.boolean().optional(),idTokenNonce:P.string().optional(),serverContext:P.record(P.string(),P.unknown()).optional()});new Set(Object.keys(rR.shape));var rk=class extends r_.p{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function rx(e,t,r){let i=tn(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let a={...t,oauthState:i},o=await tV({key:tZ(e.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),n=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(n.name,o,n.attributes),{state:i,codeVerifier:t.codeVerifier}}let a=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(a.name,i,e.context.secret,a.attributes);let o=new Date(Date.now()+6e5);if(!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:i}),identifier:rO(i),expiresAt:o}))throw new rk("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:i,codeVerifier:t.codeVerifier}}async function rS(e,t,r){let i;if(!t)throw new rk("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let a=e.context.createAuthCookie(r?.cookieName??"oauth_state"),o=e.getCookie(a.name);if(!o)throw new rk("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await tW({key:tZ(e.context.secretConfig,"oauth-state-cookie"),data:o});i=rR.parse(JSON.parse(t))}catch(e){throw new rk("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new rk("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,ev.c)(e,a)}else{let a=await e.context.internalAdapter.findVerificationValue(rO(t));if(!a)throw new rk("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(i=rR.parse(JSON.parse(a.value))).oauthState&&i.oauthState!==t)throw new rk("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});let o=e.context.createAuthCookie(r?.cookieName??"state"),n=await e.getSignedCookie(o.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!n||n!==t))throw new rk("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,ev.c)(e,o),await e.context.internalAdapter.deleteVerificationByIdentifier(rO(t))}if(i.expiresAt<Date.now())throw new rk("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function rU(e){return e.requiresIdTokenNonce?tn(32):void 0}async function rN(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw p.E.from("BAD_REQUEST",G.f.CALLBACK_URL_REQUIRED);let i=t?.codeVerifier??tn(128),a=await rI(),o=a&&Object.keys(a).length?a:void 0,n={...t?.additionalData?t.additionalData:{},callbackURL:r,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:o,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await rA(n);try{return rx(e,n)}catch(t){throw e.context.logger.error("Failed to create verification",t),new p.E("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function rD(e){let t,r=e.query.state||e.body?.state,i=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await rS(e,r)}catch(a){e.context.logger.error("Failed to parse state",a);let t="internal_server_error",r=i;a instanceof rk&&(t="state_security_mismatch"===a.code?"state_mismatch":a.code,r=a.errorURL||i),t8(e,r,t)}return t.errorURL||(t.errorURL=i),t&&await rA(t),t}let rL=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],rC=new Set(rL);async function rz({id:e,options:t,authorizationEndpoint:r,state:i,codeVerifier:a,scopes:o,claims:n,redirectURI:s,duration:l,prompt:c,accessType:d,responseType:u,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:y,scopeJoiner:w}){var b;let E;t="function"==typeof t?await t():t;let A=new URLSearchParams;A.set("response_type",u||"code");let I=ru(t.clientId);if(!I)throw Error("OAuth provider requires clientId");if(A.set("client_id",I),A.set("state",i),o?.length&&A.set("scope",o.join(w||" ")),A.set("redirect_uri",t.redirectURI||s),l&&A.set("duration",l),f&&A.set("display",f),p&&A.set("login_hint",p),m&&A.set("nonce",m),c&&A.set("prompt",c),h&&A.set("hd",h),d&&A.set("access_type",d),g&&A.set("response_mode",g),a){let e=await rf(a);A.set("code_challenge_method","S256"),A.set("code_challenge",e)}if(n){let e=n.reduce((e,t)=>(e[t]=null,e),{});A.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(y)for(let[e,t]of Object.entries(y))rC.has(e)||A.set(e,t);return new URL(Y((b=t.authorizationEndpoint||r,(E=new URL(b)).search=E.search.slice(1).split("&").filter(e=>{let[t]=new URLSearchParams(e).keys();return e&&void 0!==t&&!A.has(t)}).join("&"),E.href),A))}let rj=P.record(P.string(),P.string()).refine(e=>!Object.keys(e).some(e=>rC.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${rL.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional(),rP=["iss","sub","aud","exp","iat"];async function rB(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 rM(e,t,r="exact"){return"string"==typeof e&&(e===t||"exact-or-sha256"===r&&e===await rB(t))}async function r$(e,t,r){if(![t.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let i=await (0,t7.f)(e,t.jwks,{issuer:t.issuer,audience:t.audience,algorithms:t.algorithms,maxTokenAge:t.maxTokenAge,requiredClaims:rP,clockTolerance:30});if(r&&!await rM(i.payload.nonce,r,t.nonceComparison))throw Error("ID token nonce does not match");if(t.verifyClaims&&!t.verifyClaims(i.payload))throw Error("ID token claims were rejected");return i}function rq(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function rH(e,t,r,i){let a=e.options??{};if(a.disableIdTokenSignIn)return!1;try{if(a.verifyIdToken)return await a.verifyIdToken(t,r,i);let o=e.idToken;if(!o)return!1;if("verify"in o)return await o.verify(t,r,i);if(3!==t.split(".").length)return!0===o.allowOpaqueToken;return await r$(t,o,r),!0}catch{return!1}}var rF=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)}};let rV=async(e,t)=>{let r=t||{},i={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:r,hooks:i};for(let d of(null==t?void 0:t.plugins)||[]){var a,o,n,s,l,c;if(d.init){let t=await (null==(c=d.init)?void 0:c.call(d,e.toString(),r));r=t.options||r,e=t.url}i.onRequest.push(null==(a=d.hooks)?void 0:a.onRequest),i.onResponse.push(null==(o=d.hooks)?void 0:o.onResponse),i.onSuccess.push(null==(n=d.hooks)?void 0:n.onSuccess),i.onError.push(null==(s=d.hooks)?void 0:s.onError),i.onRetry.push(null==(l=d.hooks)?void 0:l.onRetry)}return{url:e,options:r,hooks:i}};var rW=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}},rK=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)}};let rG=["get","post","put","patch","delete"];function rJ(e){if(!e.startsWith("@"))return{method:void 0,path:e};let t=e.indexOf("/"),r=e.slice(1,-1===t?void 0:t);return rG.includes(r)?{method:r,path:-1===t?e:e.slice(t+1)}:{method:void 0,path:e}}let rQ=/^[a-z][a-z\d+.-]*:\/\/[^/?#]+/i,rY=/^\/+/;function rZ(e){let t=e.length;for(;t>0&&"/"===e[t-1];)t--;return e.slice(0,t)}function rX(e,t){let r=e.indexOf(t);return -1===r?[e,void 0]:[e.slice(0,r),e.slice(r+1)]}let r0=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 i=await r(e.auth.token);if(!i)return t;t.authorization=`Bearer ${i}`}else if("Basic"===e.auth.type){let[i,a]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!i||!a)return t;t.authorization=`Basic ${btoa(`${i}:${a}`)}`}else if("Custom"===e.auth.type){let[i,a]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!a)return t;t.authorization=`${null!=i?i:""} ${a}`}}return t},r1=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function r2(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 r5(e){try{return JSON.parse(e)}catch(t){return e}}async function r6(e){let t=new Headers(function(...e){let t={};for(let r of e)if(r)if(r instanceof Headers)r.forEach((e,r)=>{t[r]=e});else for(let[e,i]of Array.isArray(r)?r:Object.entries(r))null!=i&&(t[e]=i);return t}(null==e?void 0:e.headers,await r0(e)));if(!t.has("content-type")){let r=r2(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var r8=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function r4(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new r8(r.issues);return r.value}function r3(e){return(r3="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function r7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?r9(Object(r),!0).forEach(function(t){!function(e,t,r){var i;(i=function(e,t){if("object"!=r3(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=r3(i))return i;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==r3(i)?i:i+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):r9(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let ie=async(e,t)=>{var r,i,a,o,n,s,l,c;let d,{hooks:u,url:f,options:p}=await rV(e,t),m=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")}(p),h=new AbortController,g=null!=(r=p.signal)?r:h.signal,y=function(e,t){var r,i;let a,{baseURL:o,params:n,query:s}=t||{query:{},params:{},baseURL:""},{path:l}=rJ(e),c=l===e?e:`/${l}`,d=null==(r=c.match(rQ))?void 0:r[0],[u,f]=rX(d?c.slice(d.length):function(e,t){if(!t)return e;let r=`${rZ(t)}/`;return e.startsWith(r)?e.slice(r.length):e}(c,o),"?"),p=(a=function(e,t){let r=new Map;if(t)if(Array.isArray(t))for(let[i,a]of e.split("/").filter(e=>e.startsWith(":")).entries()){let e=t[i];r.set(a,String(e))}else for(let[e,i]of Object.entries(t))r.set(`:${e}`,String(i));return r}(u,n),u.split("/").map(e=>(function(e,t){let r=t.get(e);if(void 0===r)return e.split(":").map(e=>encodeURIComponent(e)).join(":");if("."===r||".."===r)throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(r)})(e,a)).join("/"));return function(e,t,r,i){let[a]=rX(e,"#"),[o,n=""]=rX(a,"?"),s=t.replace(rY,""),l=function(e,t){let r=new URLSearchParams(e);for(let[e,i]of Object.entries(t||{})){let t;if(null!=i){if("string"==typeof i)t=i;else if(Array.isArray(i)){for(let t of i)r.append(e,t);continue}else t=JSON.stringify(i);r.set(e,t)}}let i=r.toString();return i.length>0?`?${i}`.replace(/\+/g,"%20"):""}(`${n}&${null!=r?r:""}`,i),c=`${rZ(o)}/${s}${l}`;return rQ.test(c)?new URL(c):c}(null!=(i=null!=d?d:o)?i:"",p,f,s)}(f,p),w=await r6(p),b=function(e,t){let r,{body:i}=e;return i?r2(i)&&"string"!=typeof i?"application/x-www-form-urlencoded"===((r=t.get("content-type"))?r.split(";")[0].trim().toLowerCase():null)?new URLSearchParams(i).toString():JSON.stringify(i):i:null}(p,w),E=function(e,t){if(null==t?void 0:t.method)return t.method.toUpperCase();let{method:r}=rJ(e);return r?r.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}(f,p),A=r7(r7({},p),{},{url:y,headers:w,body:b,method:E,signal:g});for(let e of u.onRequest)if(e){let t=await e(A);"object"==typeof t&&null!==t&&Object.assign(A,t)}("pipeTo"in A&&"function"==typeof A.pipeTo||"function"==typeof(null==t||null==(i=t.body)?void 0:i.pipe))&&!("duplex"in A)&&(A.duplex="half");let{clearTimeout:I}=(!(null==p?void 0:p.signal)&&(null==p?void 0:p.timeout)&&(d=setTimeout(()=>null==h?void 0:h.abort(),null==p?void 0:p.timeout)),{abortTimeout:d,clearTimeout:()=>{d&&clearTimeout(d)}}),T=await m(A.url,A);I();let _={response:T,request:A};for(let e of u.onResponse)if(e){let r=await e(r7(r7({},_),{},{response:(null==t||null==(o=t.hookOptions)?void 0:o.cloneResponse)?T.clone():T}));r instanceof Response?T=r:"object"==typeof r&&null!==r&&(T=r.response)}if(T.ok){if("HEAD"===A.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 i=t.split(";").shift()||"";return r1.test(i)?"json":r.has(i)||i.startsWith("text/")?"text":"blob"}(T),r={data:null,response:T,request:A};if("json"===e||"text"===e){let e=await T.text();r.data=await (null!=(n=A.jsonParser)?n:r5)(e)}else r.data=await T[e]();for(let e of((null==A?void 0:A.output)&&A.output&&!A.disableValidation&&(r.data=await r4(A.output,r.data)),u.onSuccess))e&&await e(r7(r7({},r),{},{response:(null==t||null==(s=t.hookOptions)?void 0:s.cloneResponse)?T.clone():T}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let v=null!=(a=null==t?void 0:t.jsonParser)?a:r5,O=await T.text(),R=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(O),k=R?await v(O):null,x={response:T,responseText:O,request:A,error:r7(r7({},k),{},{status:T.status,statusText:T.statusText})};for(let e of u.onError)e&&await e(r7(r7({},x),{},{response:(null==t||null==(l=t.hookOptions)?void 0:l.cloneResponse)?T.clone():T}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new rW({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new rW(e);case"exponential":return new rK(e);default:throw Error("Invalid retry strategy")}}(t.retry),i=null!=(c=t.retryAttempt)?c:0;if(await r.shouldAttemptRetry(i,T)){for(let e of u.onRetry)e&&await e(_);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await ie(e,r7(r7({},t),{},{retryAttempt:i+1}))}}if(null==t?void 0:t.throw)throw new rF(T.status,T.statusText,R?k:O);return{data:null,error:r7(r7({},k),{},{status:T.status,statusText:T.statusText})}},it=new Set([301,302,303,307,308]);function ir(e){return new p.p(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function ii(e,t){let r=!1,i=t?.onError,a=await ie(e,{...t,redirect:"manual",async onError(e){var t;("opaqueredirect"===(t=e.response).type||it.has(t.status))&&(r=!0),await i?.(e)}}).catch(t=>{if(r)throw ir(e);throw t});if(r)throw ir(e);return a}function ia(e){return new URLSearchParams({v:e}).toString().slice(2)}e.i(27957);var io=e.i(97554);async function is({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"}}function il(e,t,r){if(t.clientSecret||r.has("client_secret"))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function ic(e,t){t&&e.set("client_id",t)}function id(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function iu(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function ip(e){if(e.has("client_assertion")!==e.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function im({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a,tokenEndpointAuth:o,authentication:n}){ip(e);let s=ru(r.clientId);if(e.has("client_assertion")){if(o)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");il("private_key_jwt",r,e),ic(e,s);return}let l=o??("basic"===n?{method:"client_secret_basic"}:r.clientSecret?{method:"client_secret_post"}:{method:"none"});if("custom"===l.method){let o,n;await l.customizeRequest({body:e,headers:(o=e=>"string"==typeof e?e.toLowerCase():e,n=e=>Object.prototype.hasOwnProperty.call(t,o(e))?o(e):e,new Proxy(t,{get:(e,t)=>Reflect.get(e,n(t)),set:(e,t,r)=>Reflect.set(e,o(t),r),has:(e,t)=>Reflect.has(e,n(t)),deleteProperty:(e,t)=>Reflect.deleteProperty(e,o(t)),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,n(t))})),options:r,tokenEndpoint:i,grantType:a}),ip(e);return}if("private_key_jwt"===l.method){if(il(l.method,r,e),iu(l.method,s),!i)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let t=await is({getClientAssertion:l.getClientAssertion,context:{clientId:s,tokenEndpoint:i,grantType:a}});for(let[r,i]of(ic(e,s),Object.entries(t)))e.set(r,i);return}if("none"===l.method){if(il(l.method,r,e),"client_credentials"===a)throw Error("none token endpoint authentication cannot be used with client_credentials grant");iu(l.method,s),ic(e,s);return}"client_secret_basic"===l.method?function({headers:e,options:t,clientId:r,body:i}){var a;let o;if(i.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");id("client_secret_basic",t),iu("client_secret_basic",r),a=t.clientSecret,o=`${ia(r)}:${ia(a)}`,e.authorization=`Basic ${eS.t.encode(o)}`}({headers:t,options:r,clientId:s,body:e}):function({body:e,options:t,clientId:r,requireClientSecret:i}){i&&id("client_secret_post",t),t.clientSecret&&(iu("client_secret_post",r),ic(e,r),e.set("client_secret",t.clientSecret))}({body:e,options:r,clientId:s,requireClientSecret:o?.method==="client_secret_post"})}let ih=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function ig({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:a,extraParams:o,resource:n,headers:s}){let l=function({refreshToken:e,options:t,extraParams:r,resource:i,headers:a}){let o=new URLSearchParams,n={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};for(let[e,t]of Object.entries(a??{}))n[e.toLowerCase()]=t;if(o.set("grant_type","refresh_token"),o.set("refresh_token",e),i)if("string"==typeof i)o.append("resource",i);else for(let e of i)o.append("resource",e);return r&&function(e,t){if(t)for(let[r,i]of Object.entries(t))ih.has(r)||e.set(r,i)}(o,r),{body:o,headers:n}}({refreshToken:e,options:t="function"==typeof t?await t():t,extraParams:o,resource:n,headers:s});return await im({body:l.body,headers:l.headers,options:t,tokenEndpoint:a??"",grantType:"refresh_token",tokenEndpointAuth:i,authentication:r}),l}async function iy({refreshToken:e,options:t,tokenEndpoint:r,authentication:i,tokenEndpointAuth:a,extraParams:o,resource:n,headers:s}){let{body:l,headers:c}=await ig({refreshToken:e,options:t,authentication:i,tokenEndpointAuth:a,tokenEndpoint:r,extraParams:o,resource:n,headers:s}),{data:d,error:u}=await ii(r,{method:"POST",body:l,headers:c});if(u)throw u;if("string"!=typeof d.access_token||!d.access_token)throw d;let f={accessToken:d.access_token,refreshToken:d.refresh_token,tokenType:d.token_type,scopes:rl(d.scope),idToken:d.id_token};return d.expires_in&&(f.accessTokenExpiresAt=new Date((new Date).getTime()+1e3*d.expires_in)),d.refresh_token_expires_in&&(f.refreshTokenExpiresAt=new Date((new Date).getTime()+1e3*d.refresh_token_expires_in)),f}e.i(1889),e.i(12319),e.i(41242),e.i(18069);var iw=e.i(55659),ib=e.i(63370),iE=e.i(83817);e.i(24472).C;var iA=e.i(92449),iI=e.i(16760);async function iT(e,t,r){let i=e.get(t)||e.set(t,{}).get(t),{alg:a}=r;if(void 0===i[a]){let e=(0,iA.f)(r,t,!0).then(e=>{if("public"!==e.type)throw new re.JWKSInvalid("JSON Web Key Set members must be public keys");return i[a]=e,e}).catch(t=>{throw i[a]===e&&delete i[a],t});i[a]=e}return i[a]}function i_(e){let t;try{t=structuredClone(e)}catch(e){throw new re.JWKSInvalid("JSON Web Key Set malformed",{cause:e})}if(!(0,iE.q)(t))throw new re.JWKSInvalid("JSON Web Key Set malformed");let r=t.keys.map(e=>{let t=(0,iA.C)(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),i=new WeakMap;return Object.defineProperty(async(e,a)=>{let{alg:o,kid:n}={...e,...a?.header},s="string"==typeof o?iI.K[o]:void 0;if(!s||s.secret)throw new re.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let l=t.keys.filter((e,t)=>(function(e,t,r,i){let{kty:a,key_ops:o,ext:n,kid:s,alg:l,use:c,crv:d}=e;return(void 0===n||"boolean"==typeof n)&&(void 0===o||Array.isArray(o)&&o.every((e,t)=>"string"==typeof e&&o.indexOf(e)===t)&&o.includes("verify"))&&t.kty.includes(a)&&(void 0===i||"string"==typeof i&&i===s)&&(void 0===l?"AKP"!==a:r===l)&&(void 0===c||"sig"===c)&&(!t.crv||d===t.crv)})(r[t],s,o,n)),{0:c,length:d}=l;if(!d)throw new re.JWKSNoMatchingKey;if(1!==d){let e=new re.JWKSMultipleMatchingKeys;throw e[Symbol.asyncIterator]=async function*(){for(let e of l)try{yield await iT(i,e,s)}catch{}},e}return iT(i,c,s)},"jwks",{value:()=>structuredClone(t)})}async function iv({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:a,tokenEndpointAuth:o,tokenEndpoint:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let u=function({code:e,codeVerifier:t,redirectURI:r,options:i,deviceId:a,headers:o,additionalParams:n={},resource:s}){let l=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};for(let[e,t]of Object.entries(o??{}))c[e.toLowerCase()]=t;if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),i.clientKey&&l.set("client_key",i.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",i.redirectURI||r),s)if("string"==typeof s)l.append("resource",s);else for(let e of s)l.append("resource",e);for(let[e,t]of Object.entries(n))l.has(e)||l.append(e,t);return{body:l,headers:c}}({code:e,codeVerifier:t,redirectURI:r,options:i="function"==typeof i?await i():i,deviceId:s,headers:l,additionalParams:c,resource:d});return await im({body:u.body,headers:u.headers,options:i,tokenEndpoint:n??"",grantType:"authorization_code",tokenEndpointAuth:o,authentication:a}),u}async function iO({code:e,codeVerifier:t,redirectURI:r,options:i,tokenEndpoint:a,authentication:o,tokenEndpointAuth:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let{body:u,headers:f}=await iv({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:o,tokenEndpointAuth:n,tokenEndpoint:a,deviceId:s,headers:l,additionalParams:c,resource:d}),{data:p,error:m}=await ii(a,{method:"POST",body:u,headers:f});if(m)throw m;return rc(p)}re.JWKSTimeout.code,re.JWKSInvalid.code,re.JWKSMultipleMatchingKeys.code;var iR=e.i(32802);function ik(e){let t,r;if("string"!=typeof e)throw new re.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:i,length:a}=e.split(".");if(5===a)throw new re.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==a)throw new re.JWTInvalid("Invalid JWT");if(!i)throw new re.JWTInvalid("JWTs must contain a payload");try{t=(0,ib.decode)(i)}catch(e){throw new re.JWTInvalid("Failed to base64url decode the payload",{cause:e})}try{r=JSON.parse(iR.L.decode(t))}catch(e){throw new re.JWTInvalid("Failed to parse the decoded payload as JSON",{cause:e})}if(!(0,iE.C)(r))throw new re.JWTInvalid("Invalid JWT Claims Set");return r}let ix=async e=>{let{data:t}=await ii("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new p.E("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 (0,io.g)(r,r.alg)},iS="https://dash.cloudflare.com/oauth2/token",iU=e=>e.tokenEndpointAuth??{method:e.tokenEndpointAuthMethod??(e.clientSecret?"client_secret_basic":"none")},iN=async(e,t,r)=>{let i=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await ii(i);if(!t?.keys)throw new p.E("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 (0,io.g)(r,r.alg)}catch(e){throw u.y.error("Failed to fetch Cognito public key:",e),e}};(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(t="jose/v6.2.17");let iD=Symbol();async function iL(e,t,r,i=fetch){let a=await i(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new re.JWKSTimeout(void 0,{cause:e}):e});if(200!==a.status)throw new re.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new re.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:e})}}let iC=Symbol();function iz(e,t){return Number.isFinite(e)&&Date.now()<e+t}function ij(e,t,r){if(Number.isNaN(e))throw TypeError(`"${r}" option must not be NaN`);if("number"==typeof e&&e<0)throw TypeError(`"${r}" option must not be negative`);return"number"==typeof e?e:t}async function iP(e,t){let r=ru(t.clientId);if(!r||!t.clientSecret)return null;let i=Array.isArray(t.clientId)?t.clientId:[t.clientId],a=`${r}|${t.clientSecret}`,{data:o,error:n}=await ii("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:a}});if(n||!o?.data)return null;let{is_valid:s,app_id:l,user_id:c}=o.data;return!0===s&&l&&i.includes(l)&&c?c:null}let iB=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),iM="RS256",i$=[iM],iq=(e,t)=>!e||"string"==typeof t&&!!t&&("*"===e||t===e),iH=async e=>{let[t]=await iF(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},iF=async e=>{let{data:t}=await ii("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new p.E("BAD_REQUEST",{message:"Keys not found"});let r=e?t.keys.filter(t=>t.kid===e):t.keys;if(!r.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(r.map(e=>(0,io.g)(e,iM)))},iV="9188040d-6c67-4c5b-b112-36a304b66dad",iW=async(e,t,r)=>{let{data:i}=await ii(`${r}/${t}/discovery/v2.0/keys`);if(!i?.keys)throw new p.E("BAD_REQUEST",{message:"Keys not found"});let a=i.keys.find(t=>t.kid===e);if(!a)throw Error(`JWK with kid ${e} not found`);return await (0,io.g)(a,a.alg??"RS256")},iK="https://backboard.railway.com/oauth/token";function iG({identifier:e,namespace:t}){let r=P.email().safeParse(`${e}@${t}.placeholder.invalid`);if(!r.success)throw TypeError("Invalid placeholder email");return r.data}let iJ={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a,codeVerifier:o}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","name"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:n,state:t,redirectURI:i,codeVerifier:o,responseMode:"form_post",responseType:"code id_token",additionalParams:a})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),idToken:{jwks:e=>ix(e.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let i=ik(t.idToken);if(!i)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():i.name||"";let a=rd(i.email_verified)??!1,o={...i,name:r},n=await e.mapProfileToUser?.(o);return{user:{name:o.name,emailVerified:a,email:i.email,...n},data:o}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Secret are required for Atlassian"),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Atlassian");let n=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:{...o??{},audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 ie("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}catch(e){return u.y.error("Failed to fetch user info from Atlassian:",e),null}},options:e}},cloudflare:e=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["user-details.read"];return e.scope?.length&&o.push(...e.scope),r?.length&&o.push(...r),rz({id:"cloudflare",options:e,authorizationEndpoint:"https://dash.cloudflare.com/oauth2/auth",scopes:o.length?[...new Set(o)]:void 0,state:t,codeVerifier:i,redirectURI:a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:iS,tokenEndpointAuth:iU(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:iS,tokenEndpointAuth:iU(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://api.cloudflare.com/client/v4/user",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r?.success||!r.result)return u.y.error("Failed to fetch user info from Cloudflare:",i??r?.errors),null;let a=r.result,o=[a.first_name,a.last_name].filter(Boolean).join(" ")||a.email,n=await e.mapProfileToUser?.(a);return{user:{name:o,email:a.email,emailVerified:!1,...n},data:a}},options:e}),cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw u.y.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new p.p("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,i=`https://${t}/oauth2/token`,a=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!ru(e.clientId))throw u.y.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw u.y.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new p.p("CLIENT_SECRET_REQUIRED");let s=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&s.push(...e.scope),i&&s.push(...i);let l=await rz({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...n??{}}}),c=l.searchParams.get("scope");if(c){l.searchParams.delete("scope");let e=encodeURIComponent(c),t=l.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return l},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),idToken:{jwks:t=>iN(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=ik(t.idToken);if(!r)return null;let i=r.name||r.given_name||r.username||"",a={...r,name:i},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:a}}catch(e){u.y.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await ie(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:rd(r.email_verified)??!1,...t},data:r}}}catch(e){u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identify","email"];r&&o.push(...r),e.scope&&o.push(...e.scope);let n=o.includes("bot");return rz({id:"discord",options:e,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"none",additionalParams:{...n&&void 0!==e.permissions?{permissions:String(e.permissions)}:{},...a??{}}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)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 a=await e.mapProfileToUser?.(r);return{user:{name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...a},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",accountSubject:({profile:e})=>"sub"in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:{...e.configId?{config_id:e.configId}:{},...o??{}}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>iO({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:function(e){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let r=new URL(e.href).href,i=(void 0)??{},a=i.timeoutDuration;if("number"==typeof a&&(!Number.isInteger(a)||a<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let o="number"==typeof a?a:5e3,n=ij(i.cooldownDuration,3e4,"cooldownDuration"),s=ij(i.cacheMaxAge,6e5,"cacheMaxAge"),l=new Headers(i.headers);t&&!l.has("User-Agent")&&l.set("User-Agent",t),l.has("accept")||l.set("accept","application/json, application/jwk-set+json");let c=i[iD],d=i[iC],u,f,p=0,m=0,h;if(d&&"object"==typeof d){let{uat:e,jwks:t}=d;iz(e,s)&&(0,iE.q)(t)&&(u=e,h=i_(t))}let g=async()=>{if(f&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(f=void 0),!f){let e=++p,t=f=iL(r,l,AbortSignal.timeout(o),c).then(t=>{let r=i_(t);if(e<=m)return;h=r;let i=Date.now();d&&(d.uat=i,d.jwks=t),u=i,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{h&&iz(u,s)||await g();try{return await h(e,t)}catch(r){if(r instanceof re.JWKSNoMatchingKey&&!iz(u,n))return await g(),h(e,t);throw r}},{coolingDown:{get:()=>iz(u,n),enumerable:!0},fresh:{get:()=>iz(u,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:e.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({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){let r=!!t.idToken&&3!==t.idToken.split(".").length,i=t.accessToken||(r?t.idToken:void 0);return i&&!await iP(i,e)?null:e.getUserInfo(t)}if(t.idToken&&3===t.idToken.split(".").length){let r=ik(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}let r=t.accessToken;if(!r)return null;let i=await iP(r,e);if(!i)return null;let a=["id","name","email","picture",...e?.fields||[]],{data:o,error:n}=await ie("https://graph.facebook.com/me?fields="+a.join(","),{auth:{type:"Bearer",token:r}});if(n||o.id!==i)return null;let s=await e.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified??!1,...s},data:o}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Figma");let n=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 ie("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return u.y.error("Failed to fetch user from Figma"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...i},data:r}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,codeVerifier:a,redirectURI:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),rz({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,codeVerifier:a,redirectURI:o,loginHint:i,prompt:e.prompt,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>{let{body:o,headers:n}=await iv({code:r,codeVerifier:i,redirectURI:a,options:e}),{data:s,error:l}=await ii(t,{method:"POST",body:o,headers:n});return l?(u.y.error("GitHub OAuth token exchange failed:",l),null):"error"in s?(u.y.error("GitHub OAuth token exchange failed:",s),null):rc(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a}=await ie("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&a&&(r.email=(a.find(e=>e.primary)??a[0])?.email);let o=a?.find(e=>e.email===r.email)?.verified??!1,n=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:o,...n},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";for(;r.endsWith("/");)r=r.slice(0,-1);let i=`${r}/${t}/oauth2/v2.0/authorize`,a=`${r}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new p.p("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let o=e.clientAssertion?{method:"private_key_jwt",getClientAssertion:e.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!ru(e.clientId))throw u.y.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new p.p("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),rz({id:"microsoft",options:e,authorizationEndpoint:i,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:a,tokenEndpointAuth:o}),idToken:{jwks:e=>iW(e.kid,t,r),algorithms:["RS256"],audience:e.clientId,maxTokenAge:"1h",issuer:"common"!==t&&"organizations"!==t&&"consumers"!==t?`${r}/${t}/v2.0`:void 0,verifyClaims:e=>{let i=e.tid;return"string"==typeof i&&e.iss===`${r}/${i}/v2.0`&&("organizations"!==t||i!==iV)&&("consumers"!==t||i===iV)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=ik(t.idToken);if("string"!=typeof r.oid||0===r.oid.trim().length)return u.y.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let i=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await ie(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer(),i=eS.t.encode(t);r.picture=`data:image/jpeg;base64, ${i}`}catch(e){u.y.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let a=await e.mapProfileToUser?.(r),o=void 0!==r.email_verified?rd(r.email_verified)??!1:!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:o,...a},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),iy({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:a,tokenEndpointAuth:o})},options:e}},google:e=>({id:"google",name:"Google",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,display:n,additionalParams:s}){if(!ru(e.clientId)||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new p.p("codeVerifier is required for Google");let l=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&l.push(...e.scope),r&&l.push(...r),await rz({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:l,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,accessType:e.accessType,display:n||e.display,loginHint:o,hd:e.hd,additionalParams:{...!1===e.includeGrantedScopes?{}:{include_granted_scopes:"true"},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:e=>iH(e.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,algorithms:i$,maxTokenAge:"1h",verifyClaims:e.hd?t=>iq(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=ik(t.idToken);if(!iq(e.hd,r.hd))return u.y.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",accountSubject:({profile:e})=>e["https://slack.com/user_id"],createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return r&&o.push(...r),e.scope&&o.push(...e.scope),rz({id:"slack",options:e,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...a},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...a},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"],additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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 u.y.error("No idToken found in token"),null;let i=ik(r),a=await e.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...a},data:i}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",accountSubject:({profile:e})=>e.data.id,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),rz({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,authentication:"basic",redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a,error:o}=await ie("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),n=!1;!o&&a?.data?.confirmed_email&&(r.data.email=a.data.confirmed_email,n=!0);let s=await e.mapProfileToUser?.(r);return{user:{name:r.data.name,email:r.data.email||iG({identifier:r.data.id,namespace:"twitter"}),image:r.data.profile_image_url,emailVerified:n,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["account_info.read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...o??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>await iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...a},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,codeVerifier:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"kick",redirectURI:i,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:n,codeVerifier:a,state:t,additionalParams:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>iO({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({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:i}=await ie("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=r.data[0],o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.profile_picture,emailVerified:!1,...o},data:a}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
124
124
|
query {
|
|
125
125
|
viewer {
|
|
126
126
|
id
|
|
@@ -132,7 +132,7 @@ module.exports=[90659,e=>{"use strict";var t=e.i(97515),r=e.i(86198);e.i(18069);
|
|
|
132
132
|
updatedAt
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
|
-
`})});if(i||!r?.data?.viewer)return null;let a=r.data.viewer,o=await e.mapProfileToUser?.(a);return{user:{name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...o},data:a}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:n,state:t,loginHint:a,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>await iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...a},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:i,userinfoEndpoint:a}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:iB(`${t}/oauth/authorize`),tokenEndpoint:iB(`${t}/oauth/token`),userinfoEndpoint:iB(`${t}/api/v4/user`)}),o="gitlab";return{id:o,name:"Gitlab",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:t,scopes:i,codeVerifier:a,loginHint:n,redirectURI:s,additionalParams:l})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),i&&c.push(...i),await rz({id:o,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:a,loginHint:n,additionalParams:l})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:a})=>iO({code:t,redirectURI:r,options:e,codeVerifier:a,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie(a,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||"active"!==r.state||r.locked)return null;let o=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...o},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/",r={method:"custom",customizeRequest({body:t}){t.set("client_key",e.clientKey),t.set("client_secret",e.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user.info.profile"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://www.tiktok.com/v2/auth/authorize");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("client_key",e.clientKey),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),a)for(let[e,t]of Object.entries(a))rC.has(e)||"client_key"!==e&&n.searchParams.set(e,t);return n},validateAuthorizationCode:async({code:i,codeVerifier:a,redirectURI:o})=>iO({code:i,codeVerifier:a,redirectURI:e.redirectURI||o,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>iy({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{email:r.data.user.email||iG({identifier:r.data.user.open_id,namespace:"tiktok"}),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=>{let t="https://www.reddit.com/api/v1/access_token",r={clientId:e.clientId,clientSecret:e.clientSecret},i={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identity"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:i,duration:e.duration,additionalParams:a})},validateAuthorizationCode:async({code:a,redirectURI:o})=>iO({code:a,redirectURI:e.redirectURI||o,options:r,tokenEndpoint:t,tokenEndpointAuth:i,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>iy({refreshToken:e,options:r,tokenEndpoint:t,tokenEndpointAuth:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(i)return null;let a=await e.mapProfileToUser?.(r),o=a?.email||iG({identifier:r.id,namespace:"reddit"});return{user:{name:r.name,image:r.icon_img?.split("?")[0],...a,email:o,emailVerified:a?.emailVerified??!1},data:r}},options:e}},roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"roblox",options:e,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"select_account consent",additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.nickname||r.preferred_username||"",image:r.picture,email:iG({identifier:r.sub,namespace:"roblox"}),emailVerified:!1,...a},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",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",a=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",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new p.p("codeVerifier is required for Salesforce");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),i&&s.push(...i),rz({id:"salesforce",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:e.redirectURI||o,additionalParams:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await ie(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return u.y.error("Failed to fetch user info from Salesforce"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...i},data:r}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["email","phone"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a,deviceId:o})=>iO({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,deviceId:o,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i,error:a}=await ie("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(a)return null;let o=await e.mapProfileToUser?.(i);return i.user.email||o?.email?{user:{first_name:i.user.first_name,last_name:i.user.last_name,email:i.user.email,image:i.user.avatar,emailVerified:!1,birthday:i.user.birthday,sex:i.user.sex,name:`${i.user.first_name} ${i.user.last_name}`,...o},data:i}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:i,additionalParams:a})=>rz({id:"zoom",options:t,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:e,redirectURI:r,codeVerifier:t.pkce?i:void 0,additionalParams:a}),validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:i})=>iO({code:e,redirectURI:t.redirectURI||r,codeVerifier:i,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>iy({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:i}=await ie("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(i)return null;let a=await t.mapProfileToUser?.(r);return{user:{name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...a},data:{...r}}},options:t}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=(e.disableDefaultScope,[]);return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:{...o??{},owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!r)return null;let a=r.bot?.owner?.user;if(!a)return null;let o=await e.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.person?.email||null,image:a.avatar_url,emailVerified:!1,...o},data:a}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r),o=r.kakao_account||{},n=o.profile||{};return{user:{name:n.nickname||o.name||"",email:o.email,image:n.profile_image_url||n.thumbnail_image_url,emailVerified:!!o.is_email_valid&&!!o.is_email_verified,...a},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r||"00"!==r.resultcode)return null;let a=await e.mapProfileToUser?.(r),o=r.response||{};return{user:{name:o.name||o.nickname||"",email:o.email,image:o.profile_image,emailVerified:!1,...a},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await rz({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,r)=>{let i=new URLSearchParams;i.set("id_token",t),i.set("client_id",e.clientId),r&&i.set("nonce",r);let{data:a,error:o}=await ii("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:i});return!o&&!!a&&a.aud===e.clientId&&(!a.nonce||a.nonce===r)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=iR(t.idToken)}catch{}if(!r){let{data:e}=await ie("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,i=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,loginHint:n,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new p.p("codeVerifier is required for Paybin");let l=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&l.push(...e.scope),i&&l.push(...i),await rz({id:"paybin",options:e,authorizationEndpoint:r,scopes:l,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,loginHint:n,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=iR(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...i},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",i=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",a=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",o={clientId:e.clientId,clientSecret:e.clientSecret},n={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");return await rz({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>{try{return await iO({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw u.y.error("PayPal token exchange failed:",e),new p.p("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await iy({refreshToken:e,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw u.y.error("PayPal token refresh failed:",e),new p.p("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return u.y.error("Access token is required to fetch PayPal user info"),null;try{let r=await ie(`${a}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return u.y.error("Failed to fetch user info from PayPal"),null;let i=r.data;if(t.idToken){let e;try{e=iR(t.idToken).sub}catch(e){return u.y.error("Failed to decode PayPal ID token:",e),null}let r=i.sub??i.user_id;if(!e||r!==e)return u.y.error("PayPal user info subject does not match ID token subject"),null}let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...o},data:i}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:iK,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:iK,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...a},data:r}},options:e}),vercel:e=>{let t=e.tokenEndpointAuth?.method;if(e.clientSecret&&("private_key_jwt"===t||"none"===t))throw new p.p(`Vercel ${t} token endpoint authentication cannot be combined with clientSecret`);if(!e.clientSecret&&("client_secret_basic"===t||"client_secret_post"===t))throw new p.p(`Vercel ${t} token endpoint authentication requires clientSecret`);return{id:"vercel",name:"Vercel",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n;if(!i)throw new p.p("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(n=[],e.scope&&n.push(...e.scope),r&&n.push(...r)),rz({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token",tokenEndpointAuth:e.tokenEndpointAuth}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},wechat:e=>({id:"wechat",name:"WeChat",accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://open.weixin.qq.com/connect/qrconnect");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("appid",e.clientId),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),n.searchParams.set("lang",e.lang||"cn"),a)for(let[e,t]of Object.entries(a))rC.has(e)||"appid"!==e&&n.searchParams.set(e,t);return n.hash="wechat_redirect",n},validateAuthorizationCode:async({code:t})=>{let{data:r,error:i}=await ii("https://api.weixin.qq.com/sns/oauth2/access_token",{method:"GET",query:{appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}});if(i||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||i?.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:i}=await ii("https://api.weixin.qq.com/sns/oauth2/refresh_token",{method:"GET",query:{appid:e.clientId,grant_type:"refresh_token",refresh_token:t}});if(i||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||i?.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 i=new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}),{data:a,error:o}=await ie("https://api.weixin.qq.com/sns/userinfo?"+i.toString(),{method:"GET"});if(o||!a||a.errcode)return null;let n=await e.mapProfileToUser?.(a),s=a.unionid||a.openid||r;return{user:{name:a.nickname,email:a.email||iG({identifier:s,namespace:"wechat"}),image:a.headimgurl,emailVerified:!1,...n},data:a}},options:e})},iQ=Object.keys(iJ),iY=P.enum(iQ).or(P.string());function iZ(e){return e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}let iX=(0,C.g)("/list-accounts",{method:"GET",use:[t9.Z],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,...i}=(0,ex.s)(e.context.options,t);return{...i,scopes:iZ(r)}}))}),i0=(0,C.g)("/link-social",{method:"POST",requireHeaders:!0,body:P.object({callbackURL:P.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:iY,idToken:P.object({token:P.string(),nonce:P.string().optional(),accessToken:P.string().optional(),refreshToken:P.string().optional()}).optional(),requestSignUp:P.boolean().optional(),scopes:P.array(P.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:P.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:P.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:P.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rj,additionalData:P.record(P.string(),P.any()).optional()}),use:[t9.i],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 e8(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}),p.E.from("NOT_FOUND",G.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rq(r))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),p.E.from("NOT_FOUND",G.f.ID_TOKEN_NOT_SUPPORTED);let{token:i,nonce:a}=e.body.idToken;if(!await rH(r,i,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.INVALID_TOKEN);let o={idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n=r.getUserInfoFromIdToken?await r.getUserInfoFromIdToken(i):await r.getUserInfo(o);if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);if(!n.user.email)throw e.context.logger.error(t4(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.USER_EMAIL_NOT_FOUND);let s=await t0(r,{idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n.data),l=await e.context.internalAdapter.findAccountByKey(s);if(l?.userId===t.user.id){let a=Object.fromEntries(Object.entries({providerId:r.id,accessToken:await rn(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await rn(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>void 0!==t));return await e.context.internalAdapter.updateAccount(l.id,a),await rw(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}if(l)throw p.E.from("CONFLICT",G.f.SOCIAL_ACCOUNT_ALREADY_LINKED);let c=e.context.trustedProviders.includes(r.id),d=rd(n.user.emailVerified)??!1;if(!c&&!d||e.context.options.account?.accountLinking?.enabled===!1)throw p.E.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(n.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw p.E.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,...s,accessToken:await rn(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await rn(e.body.idToken.refreshToken,e.context)})}catch{throw p.E.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await rw(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}let i=rU(r),a=await rN(e,{link:{userId:t.user.id,email:t.user.email,encryptedSessionToken:await tV({key:tZ(e.context.secretConfig,"oauth-link-session-token"),data:t.session.token})},additionalData:e.body.additionalData,idTokenNonce:i}),o=await r.createAuthorizationURL({state:a.state,codeVerifier:a.codeVerifier,idTokenNonce:i,redirectURI:`${e.context.baseURL}${rs(r)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),i1=(0,C.g)("/unlink-account",{method:"POST",body:P.object({accountId:P.string().meta({description:"The Better Auth account ID to unlink"})}),use:[t9.h],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{accountId:t}=e.body,r=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===r.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=r.find(e=>e.id===t);if(!i)throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})});async function i2(e,t){let r=await (0,t9.D)(e,{disableCookieCache:(0,t9.f)(e)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let i=r?.user?.id||t;if(!i)throw p.E.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return i}let i5=P.union([P.strictObject({accountId:P.string().meta({description:"The Better Auth account ID"}),userId:P.string().meta({description:"The user ID associated with the account"}).optional()}),P.strictObject({useAccountCookie:P.literal(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:P.string().meta({description:"The user ID associated with the account"}).optional()})]);function i6(e,t,{resolvedUserId:r,selection:i}){return(!(0,e3.d)(e.context.options)||t.userId===r)&&(!("accountId"in i)||t.id===i.accountId)}async function i8(e,{resolvedUserId:t,selection:r}){if("accountId"in r){let i=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===r.accountId);if(i)return{account:i,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let i=await (0,e9.q)(e);if(i&&i6(e,i,{resolvedUserId:t,selection:r}))return{account:i,accountCookie:i}}throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND)}async function i4(e,{resolvedUserId:t,selection:r,account:i}){let a=i??(await i8(e,{resolvedUserId:t,selection:r})).account;if(!i6(e,a,{resolvedUserId:t,selection:r}))throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND);let o=await e8(e.context.socialProviders,{value:a.providerId});if(!o)throw p.E.from("BAD_REQUEST",{message:`Provider ${a.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(a.refreshToken&&r&&o.refreshAccessToken){let r=await ro(a.refreshToken,e.context);t=await o.refreshAccessToken(r,e);let i={accessToken:await rn(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await rn(t.refreshToken,e.context):a.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??a.refreshTokenExpiresAt,idToken:t?.idToken||a.idToken},n=null;a.id&&(n=await e.context.internalAdapter.updateAccount(a.id,i)),e.context.options.account?.storeAccountCookie&&await (0,e9.L)(e,{...a,...n??i})}let i=t?.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:a.accessTokenExpiresAt?"string"==typeof a.accessTokenExpiresAt?new Date(a.accessTokenExpiresAt):a.accessTokenExpiresAt:void 0;return{accessToken:t?.accessToken??await ro(a.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:iZ(a.scope),idToken:t?.idToken??a.idToken??void 0}}catch(e){throw p.E.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let i3=(0,C.g)("/get-access-token",{method:"POST",body:i5,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{userId:t}=e.body,r=await i4(e,{resolvedUserId:await i2(e,t),selection:e.body});return e.json(r)}),i9=(0,C.g)("/refresh-token",{method:"POST",body:i5,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{userId:t}=e.body,{account:r,accountCookie:i}=await i8(e,{resolvedUserId:await i2(e,t),selection:e.body}),a=await e8(e.context.socialProviders,{value:r.providerId});if(!a)throw p.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!a.refreshAccessToken)throw p.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let o=r.refreshToken??void 0;if(!o)throw p.E.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let t=await ro(o,e.context),n=await a.refreshAccessToken(t,e),s=n.refreshToken?await rn(n.refreshToken,e.context):o,l=n.refreshTokenExpiresAt??r.refreshTokenExpiresAt,c={accessToken:await rn(n.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,idToken:n.idToken||r.idToken},d=null;if(r.id&&(d=await e.context.internalAdapter.updateAccount(r.id,c)),i?.id===r.id&&e.context.options.account?.storeAccountCookie){let t={...i,...d??c};await (0,e9.L)(e,t)}let u=d?.scope??r.scope;return e.json({accessToken:n.accessToken,refreshToken:n.refreshToken??t,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,scope:u,idToken:n.idToken||r.idToken,providerId:r.providerId,accountId:r.id})}catch(e){throw p.E.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),i7=(0,C.g)("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:i5},async e=>{let{userId:t}=e.query,r=await i2(e,t),{account:i}=await i8(e,{resolvedUserId:r,selection:e.query}),a=await e8(e.context.socialProviders,{value:i.providerId});if(!a)throw p.E.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let o=await i4(e,{resolvedUserId:r,selection:e.query,account:i});if(!o.accessToken)throw p.E.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let n=await a.getUserInfo({...o,accessToken:o.accessToken});if(!n)throw p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);return e.json({...n,account:{id:i.id,providerId:i.providerId,accountId:i.accountId}})});async function ae(e,t,r){let i;if(r.iss&&t.issuer&&r.iss!==t.issuer)return e.context.logger.error("OAuth issuer mismatch",{expected:t.issuer,received:r.iss}),{error:"issuer_mismatch"};if(t.requiresIdTokenNonce&&!r.idTokenNonce)return e.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:t.id}),{error:"nonce_binding_missing"};try{i=await t.validateAuthorizationCode({code:r.code,codeVerifier:r.codeVerifier,deviceId:r.deviceId,redirectURI:`${e.context.baseURL}${rs(t)}`})}catch(t){return e.context.logger.error("Failed to validate authorization code",t),{error:t1}}if(!i)return{error:t1};let a=await t.getUserInfo({...i,expectedIdTokenNonce:r.idTokenNonce,user:(0,e$.f)(r.user)??void 0});if(!a?.user)return e.context.logger.error("Unable to get user info"),{error:t2};let o=await tX(t,i,a.data).catch(r=>(e.context.logger.error("Unable to derive provider account identity",{providerId:t.id,error:r}),null));return o?{tokens:i,userInfo:a.user,providerProfile:a.data,accountKey:o}:{error:t2}}let at=P.object({code:P.string().optional(),error:P.string().optional(),device_id:P.string().optional(),error_description:P.string().optional(),state:P.string().optional(),user:P.string().optional(),iss:P.string().optional()}),ar=(0,C.g)("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:at.optional(),query:at.optional(),metadata:{...C.S,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?at.parse(e.body):{},r=e.query?at.parse(e.query):{},i=at.parse({...t,...r}),a=new URLSearchParams;for(let[e,t]of Object.entries(i))null!=t&&a.set(e,String(t));let o=`${e.context.baseURL}/callback/${e.params.id}?${a.toString()}`;throw e.redirect(o)}try{if("GET"===e.method)t=at.parse(e.query);else if("POST"===e.method)t=at.parse(e.body);else throw Error("Unsupported method")}catch(r){e.context.logger.error("INVALID_CALLBACK_REQUEST",r);let t=Y(a,new URLSearchParams({error:"invalid_callback_request"}));throw e.redirect(t)}let{code:o,error:n,state:s,error_description:l,device_id:c,user:d,iss:u}=t;if(void 0===s&&o){let t=await e8(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let r=rU(t),{state:i,codeVerifier:a}=await rN(e,{idTokenNonce:r}),o=await t.createAuthorizationURL({state:i,codeVerifier:a,idTokenNonce:r,redirectURI:`${e.context.baseURL}${rs(t)}`});throw e.redirect(o.toString())}}if(!s){e.context.logger.error("State not found",n);let t=Y(a,new URLSearchParams({error:"state_not_found"}));throw e.redirect(t)}let{codeVerifier:f,callbackURL:p,link:m,errorURL:h,newUserURL:g,requestSignUp:y,idTokenNonce:w}=await rD(e);function b(t,r){let i=h??a,o=new URLSearchParams({error:t});r&&o.set("error_description",r);let n=Y(i,o);throw e.redirect(n)}if(n&&b(n,l),!o)throw e.context.logger.warn("Code not found"),b("no_code");let E=await e8(e.context.socialProviders,{value:e.params.id});if(!E)throw e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),b("oauth_provider_not_found");let A=await ae(e,E,{code:o,codeVerifier:f,iss:u,deviceId:c,user:d,idTokenNonce:w});if(A.error)throw b(A.error);let{tokens:I,userInfo:T,providerProfile:_,accountKey:v}=A,{accountId:O}=v;if(!p)throw e.context.logger.error("No callback URL found"),b("no_callback_url");let k={...v,...I,scope:I.scopes?.join(",")};if(m){let t=await rh(e,{link:m,userInfo:T,account:k,profile:_,scopes:I.scopes});if(!t.linked)return b(t.error.code,t.error.message);throw e.redirect(p)}if(!T.email)return e.context.logger.error(t4(E.id)),b("email_not_found");try{r=await rg(e,{userInfo:{...T,id:O,email:T.email,name:T.name||""},account:k,callbackURL:p,disableSignUp:E.disableImplicitSignUp&&!y||E.options?.disableSignUp,overrideUserInfo:E.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:E.id,profile:_}}})}catch(e){throw(0,L.f)(e)&&e.body?.code&&b(e.body.code,e.body.message),e}if(r.error)return e.context.logger.error(r.error.split(" ").join("_")),b(r.error.split(" ").join("_"));let{session:R,user:x}=r.data;await (0,ev.V)(e,{session:R,user:x});try{i=(r.isRegister&&g||p).toString()}catch{i=r.isRegister&&g||p}throw e.redirect(i)});function ai(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn("Password is too short"),p.E.from("BAD_REQUEST",G.f.PASSWORD_TOO_SHORT)}function aa(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn("Password is too long"),p.E.from("BAD_REQUEST",G.f.PASSWORD_TOO_LONG)}async function ao(e,t,r,i){await (0,eC.n)(e.context.adapter,async()=>{(await i?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t))?await e.context.internalAdapter.updatePassword(t,r):await e.context.internalAdapter.createAccount({userId:t,providerId:"credential",accountId:t,password:r})})}async function an(e,t){aa(e,t.password);let r=await e.context.internalAdapter.findCredentialAccount(t.userId),i=r?.password;return!!r&&!!i&&await e.context.password.verify({hash:i,password:t.password})}async function as(e,t){let r=t.body.password;"string"==typeof r&&aa(t,r);let i=await t.context.internalAdapter.findCredentialAccount(e),a=i?.password;if(!i||!a||!r)throw r&&await t.context.password.hash(r),p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);if(!await t.context.password.verify({hash:a,password:r}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);return!0}let al=P.record(P.string().meta({description:"Field name must be a string"}),P.any()),ac=(0,C.g)("/change-password",{method:"POST",operationId:"changePassword",body:P.object({newPassword:P.string().meta({description:"The new password to set"}),currentPassword:P.string().meta({description:"The current password is required"}),revokeOtherSessions:P.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[t9.i],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:i}=e.body,a=e.context.session;ai(e,t),aa(e,t),aa(e,r);let o=await e.context.internalAdapter.findCredentialAccount(a.user.id);if(!o||!o.password)throw p.E.from("BAD_REQUEST",G.f.CREDENTIAL_ACCOUNT_NOT_FOUND);let n=await e.context.password.hash(t);if(!await e.context.password.verify({hash:o.password,password:r}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);let s=await (0,eC.n)(e.context.adapter,async()=>{if(i&&await e.context.internalAdapter.deleteUserSessions(a.user.id),await e.context.internalAdapter.updateAccount(o.id,{password:n}),!i)return null;let t=await e.context.internalAdapter.createSession(a.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw p.E.from("INTERNAL_SERVER_ERROR",G.f.FAILED_TO_GET_SESSION);return t}),l=null;return s&&(await (0,ev.V)(e,{session:s,user:a.user}),l=s.token),e.json({token:l,user:(0,ex.$)(e.context.options,a.user)})}),ad=C.g.serverOnly({method:"POST",body:P.object({newPassword:P.string().meta({description:"The new password to set is required"})}),use:[t9.i]},async e=>{let{newPassword:t}=e.body,r=e.context.session;ai(e,t),aa(e,t);let i=await e.context.internalAdapter.findCredentialAccount(r.user.id),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json({status:!0});if(!i.password)return await e.context.internalAdapter.updateAccount(i.id,{password:a}),e.json({status:!0});throw p.E.from("BAD_REQUEST",G.f.PASSWORD_ALREADY_SET)});async function au(e,t){let r=e.context.options.user?.deleteUser?.beforeDelete;r&&await r(t,e.request),await e.context.internalAdapter.deleteUser(t.id),await e.context.internalAdapter.deleteUserSessions(t.id),(0,ev.Q)(e);let i=e.context.options.user?.deleteUser?.afterDelete;i&&await i(t,e.request)}async function af(e,t,r){let i=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${r}`);if(!i||i.value!==t.id)throw p.E.from("NOT_FOUND",G.f.INVALID_TOKEN);await au(e,t)}let ap=(0,C.g)("/delete-user",{method:"POST",use:[t9.i],body:P.object({callbackURL:P.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:P.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:P.string().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"),p.E.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){aa(e,e.body.password);let r=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!r||!r.password)throw p.E.from("BAD_REQUEST",G.f.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD)}if(e.body.token)return await af(e,t.user,e.body.token),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=tn(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 i=`${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:i,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(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw p.E.from("BAD_REQUEST",G.f.SESSION_EXPIRED)}return await au(e,t.user),e.json({success:!0,message:"User deleted"})}),am=(0,C.g)("/delete-user/callback",{method:"GET",query:P.object({token:P.string().meta({description:"The token to verify the deletion request"}),callbackURL:P.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[er(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"),p.E.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await (0,t9.D)(e,{disableCookieCache:(0,t9.f)(e)});if(!t)throw p.E.from("NOT_FOUND",G.f.FAILED_TO_GET_USER_INFO);if(await af(e,t.user,e.query.token),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),ah=(0,C.g)("/change-email",{method:"POST",body:P.object({newEmail:P.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:P.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[t9.i],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."),p.E.from("BAD_REQUEST",G.f.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),p.E.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,i=e.context.options.emailVerification?.sendVerificationEmail,a=i&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!a&&!i)throw e.context.logger.error("Verification email isn't enabled."),p.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await (0,ev.V)(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),i){let r=await rt(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:a,token:r},e.request))}return e.json({status:!0})}if(a){let r=await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation",userId:e.context.session.user.id}),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(a({user:e.context.session.user,newEmail:t,url:i,token:r},e.request)),e.json({status:!0})}if(!i)throw e.context.logger.error("Verification email isn't enabled."),p.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:e.context.session.user.id}),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:n,token:o},e.request)),e.json({status:!0})});function ag(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 ay=(0,C.g)("/error",{method:"GET",metadata:{...C.S,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",i=t.searchParams.get("error_description")||null,a=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",o=i?ag(i):null,n=new URLSearchParams;n.set("error",a),i&&n.set("error_description",i);let s=e.context.options,l=s.onAPIError?.errorURL;return l?new Response(null,{status:302,headers:{Location:Y(l,n)}}):en.C&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${n.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let i=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
135
|
+
`})});if(i||!r?.data?.viewer)return null;let a=r.data.viewer,o=await e.mapProfileToUser?.(a);return{user:{name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...o},data:a}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await rz({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:n,state:t,loginHint:a,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>await iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...a},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:i,userinfoEndpoint:a}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:iB(`${t}/oauth/authorize`),tokenEndpoint:iB(`${t}/oauth/token`),userinfoEndpoint:iB(`${t}/api/v4/user`)}),o="gitlab";return{id:o,name:"Gitlab",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:t,scopes:i,codeVerifier:a,loginHint:n,redirectURI:s,additionalParams:l})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),i&&c.push(...i),await rz({id:o,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:a,loginHint:n,additionalParams:l})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:a})=>iO({code:t,redirectURI:r,options:e,codeVerifier:a,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie(a,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||"active"!==r.state||r.locked)return null;let o=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...o},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/",r={method:"custom",customizeRequest({body:t}){t.set("client_key",e.clientKey),t.set("client_secret",e.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user.info.profile"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://www.tiktok.com/v2/auth/authorize");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("client_key",e.clientKey),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),a)for(let[e,t]of Object.entries(a))rC.has(e)||"client_key"!==e&&n.searchParams.set(e,t);return n},validateAuthorizationCode:async({code:i,codeVerifier:a,redirectURI:o})=>iO({code:i,codeVerifier:a,redirectURI:e.redirectURI||o,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>iy({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{email:r.data.user.email||iG({identifier:r.data.user.open_id,namespace:"tiktok"}),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=>{let t="https://www.reddit.com/api/v1/access_token",r={clientId:e.clientId,clientSecret:e.clientSecret},i={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identity"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:i,duration:e.duration,additionalParams:a})},validateAuthorizationCode:async({code:a,redirectURI:o})=>iO({code:a,redirectURI:e.redirectURI||o,options:r,tokenEndpoint:t,tokenEndpointAuth:i,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>iy({refreshToken:e,options:r,tokenEndpoint:t,tokenEndpointAuth:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(i)return null;let a=await e.mapProfileToUser?.(r),o=a?.email||iG({identifier:r.id,namespace:"reddit"});return{user:{name:r.name,image:r.icon_img?.split("?")[0],...a,email:o,emailVerified:a?.emailVerified??!1},data:r}},options:e}},roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"roblox",options:e,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"select_account consent",additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.nickname||r.preferred_username||"",image:r.picture,email:iG({identifier:r.sub,namespace:"roblox"}),emailVerified:!1,...a},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",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",a=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",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new p.p("codeVerifier is required for Salesforce");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),i&&s.push(...i),rz({id:"salesforce",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:e.redirectURI||o,additionalParams:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await ie(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return u.y.error("Failed to fetch user info from Salesforce"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...i},data:r}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["email","phone"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a,deviceId:o})=>iO({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,deviceId:o,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i,error:a}=await ie("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(a)return null;let o=await e.mapProfileToUser?.(i);return i.user.email||o?.email?{user:{first_name:i.user.first_name,last_name:i.user.last_name,email:i.user.email,image:i.user.avatar,emailVerified:!1,birthday:i.user.birthday,sex:i.user.sex,name:`${i.user.first_name} ${i.user.last_name}`,...o},data:i}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:i,additionalParams:a})=>rz({id:"zoom",options:t,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:e,redirectURI:r,codeVerifier:t.pkce?i:void 0,additionalParams:a}),validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:i})=>iO({code:e,redirectURI:t.redirectURI||r,codeVerifier:i,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>iy({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:i}=await ie("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(i)return null;let a=await t.mapProfileToUser?.(r);return{user:{name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...a},data:{...r}}},options:t}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=(e.disableDefaultScope,[]);return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:{...o??{},owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!r)return null;let a=r.bot?.owner?.user;if(!a)return null;let o=await e.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.person?.email||null,image:a.avatar_url,emailVerified:!1,...o},data:a}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r),o=r.kakao_account||{},n=o.profile||{};return{user:{name:n.nickname||o.name||"",email:o.email,image:n.profile_image_url||n.thumbnail_image_url,emailVerified:!!o.is_email_valid&&!!o.is_email_verified,...a},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),rz({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>iO({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r||"00"!==r.resultcode)return null;let a=await e.mapProfileToUser?.(r),o=r.response||{};return{user:{name:o.name||o.nickname||"",email:o.email,image:o.profile_image,emailVerified:!1,...a},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await rz({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,r)=>{let i=new URLSearchParams;i.set("id_token",t),i.set("client_id",e.clientId),r&&i.set("nonce",r);let{data:a,error:o}=await ii("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:i});return!o&&!!a&&a.aud===e.clientId&&(!a.nonce||a.nonce===r)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=ik(t.idToken)}catch{}if(!r){let{data:e}=await ie("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,i=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,loginHint:n,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new p.p("codeVerifier is required for Paybin");let l=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&l.push(...e.scope),i&&l.push(...i),await rz({id:"paybin",options:e,authorizationEndpoint:r,scopes:l,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,loginHint:n,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>iO({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=ik(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...i},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",i=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",a=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",o={clientId:e.clientId,clientSecret:e.clientSecret},n={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw u.y.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new p.p("CLIENT_ID_AND_SECRET_REQUIRED");return await rz({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>{try{return await iO({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw u.y.error("PayPal token exchange failed:",e),new p.p("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await iy({refreshToken:e,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw u.y.error("PayPal token refresh failed:",e),new p.p("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return u.y.error("Access token is required to fetch PayPal user info"),null;try{let r=await ie(`${a}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return u.y.error("Failed to fetch user info from PayPal"),null;let i=r.data;if(t.idToken){let e;try{e=ik(t.idToken).sub}catch(e){return u.y.error("Failed to decode PayPal ID token:",e),null}let r=i.sub??i.user_id;if(!e||r!==e)return u.y.error("PayPal user info subject does not match ID token subject"),null}let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...o},data:i}}catch(e){return u.y.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",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>iO({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>iy({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:i}=await ie("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),rz({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:iK,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>iy({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:iK,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...a},data:r}},options:e}),vercel:e=>{let t=e.tokenEndpointAuth?.method;if(e.clientSecret&&("private_key_jwt"===t||"none"===t))throw new p.p(`Vercel ${t} token endpoint authentication cannot be combined with clientSecret`);if(!e.clientSecret&&("client_secret_basic"===t||"client_secret_post"===t))throw new p.p(`Vercel ${t} token endpoint authentication requires clientSecret`);return{id:"vercel",name:"Vercel",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n;if(!i)throw new p.p("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(n=[],e.scope&&n.push(...e.scope),r&&n.push(...r)),rz({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>iO({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token",tokenEndpointAuth:e.tokenEndpointAuth}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await ie("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},wechat:e=>({id:"wechat",name:"WeChat",accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://open.weixin.qq.com/connect/qrconnect");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("appid",e.clientId),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),n.searchParams.set("lang",e.lang||"cn"),a)for(let[e,t]of Object.entries(a))rC.has(e)||"appid"!==e&&n.searchParams.set(e,t);return n.hash="wechat_redirect",n},validateAuthorizationCode:async({code:t})=>{let{data:r,error:i}=await ii("https://api.weixin.qq.com/sns/oauth2/access_token",{method:"GET",query:{appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}});if(i||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||i?.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:i}=await ii("https://api.weixin.qq.com/sns/oauth2/refresh_token",{method:"GET",query:{appid:e.clientId,grant_type:"refresh_token",refresh_token:t}});if(i||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||i?.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 i=new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}),{data:a,error:o}=await ie("https://api.weixin.qq.com/sns/userinfo?"+i.toString(),{method:"GET"});if(o||!a||a.errcode)return null;let n=await e.mapProfileToUser?.(a),s=a.unionid||a.openid||r;return{user:{name:a.nickname,email:a.email||iG({identifier:s,namespace:"wechat"}),image:a.headimgurl,emailVerified:!1,...n},data:a}},options:e})},iQ=Object.keys(iJ),iY=P.enum(iQ).or(P.string());function iZ(e){return e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}let iX=(0,C.g)("/list-accounts",{method:"GET",use:[t9.Z],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,...i}=(0,ex.s)(e.context.options,t);return{...i,scopes:iZ(r)}}))}),i0=(0,C.g)("/link-social",{method:"POST",requireHeaders:!0,body:P.object({callbackURL:P.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:iY,idToken:P.object({token:P.string(),nonce:P.string().optional(),accessToken:P.string().optional(),refreshToken:P.string().optional()}).optional(),requestSignUp:P.boolean().optional(),scopes:P.array(P.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:P.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:P.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:P.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rj,additionalData:P.record(P.string(),P.any()).optional()}),use:[t9.i],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 e8(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}),p.E.from("NOT_FOUND",G.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rq(r))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),p.E.from("NOT_FOUND",G.f.ID_TOKEN_NOT_SUPPORTED);let{token:i,nonce:a}=e.body.idToken;if(!await rH(r,i,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.INVALID_TOKEN);let o={idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n=r.getUserInfoFromIdToken?await r.getUserInfoFromIdToken(i):await r.getUserInfo(o);if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);if(!n.user.email)throw e.context.logger.error(t4(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.USER_EMAIL_NOT_FOUND);let s=await t0(r,{idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n.data),l=await e.context.internalAdapter.findAccountByKey(s);if(l?.userId===t.user.id){let a=Object.fromEntries(Object.entries({providerId:r.id,accessToken:await rn(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await rn(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>void 0!==t));return await e.context.internalAdapter.updateAccount(l.id,a),await rw(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}if(l)throw p.E.from("CONFLICT",G.f.SOCIAL_ACCOUNT_ALREADY_LINKED);let c=e.context.trustedProviders.includes(r.id),d=rd(n.user.emailVerified)??!1;if(!c&&!d||e.context.options.account?.accountLinking?.enabled===!1)throw p.E.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(n.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw p.E.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,...s,accessToken:await rn(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await rn(e.body.idToken.refreshToken,e.context)})}catch{throw p.E.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await rw(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}let i=rU(r),a=await rN(e,{link:{userId:t.user.id,email:t.user.email,encryptedSessionToken:await tV({key:tZ(e.context.secretConfig,"oauth-link-session-token"),data:t.session.token})},additionalData:e.body.additionalData,idTokenNonce:i}),o=await r.createAuthorizationURL({state:a.state,codeVerifier:a.codeVerifier,idTokenNonce:i,redirectURI:`${e.context.baseURL}${rs(r)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),i1=(0,C.g)("/unlink-account",{method:"POST",body:P.object({accountId:P.string().meta({description:"The Better Auth account ID to unlink"})}),use:[t9.h],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{accountId:t}=e.body,r=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===r.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=r.find(e=>e.id===t);if(!i)throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})});async function i2(e,t){let r=await (0,t9.D)(e,{disableCookieCache:(0,t9.f)(e)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let i=r?.user?.id||t;if(!i)throw p.E.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return i}let i5=P.union([P.strictObject({accountId:P.string().meta({description:"The Better Auth account ID"}),userId:P.string().meta({description:"The user ID associated with the account"}).optional()}),P.strictObject({useAccountCookie:P.literal(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:P.string().meta({description:"The user ID associated with the account"}).optional()})]);function i6(e,t,{resolvedUserId:r,selection:i}){return(!(0,e3.d)(e.context.options)||t.userId===r)&&(!("accountId"in i)||t.id===i.accountId)}async function i8(e,{resolvedUserId:t,selection:r}){if("accountId"in r){let i=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===r.accountId);if(i)return{account:i,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let i=await (0,e9.q)(e);if(i&&i6(e,i,{resolvedUserId:t,selection:r}))return{account:i,accountCookie:i}}throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND)}async function i4(e,{resolvedUserId:t,selection:r,account:i}){let a=i??(await i8(e,{resolvedUserId:t,selection:r})).account;if(!i6(e,a,{resolvedUserId:t,selection:r}))throw p.E.from("BAD_REQUEST",G.f.ACCOUNT_NOT_FOUND);let o=await e8(e.context.socialProviders,{value:a.providerId});if(!o)throw p.E.from("BAD_REQUEST",{message:`Provider ${a.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(a.refreshToken&&r&&o.refreshAccessToken){let r=await ro(a.refreshToken,e.context);t=await o.refreshAccessToken(r,e);let i={accessToken:await rn(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await rn(t.refreshToken,e.context):a.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??a.refreshTokenExpiresAt,idToken:t?.idToken||a.idToken},n=null;a.id&&(n=await e.context.internalAdapter.updateAccount(a.id,i)),e.context.options.account?.storeAccountCookie&&await (0,e9.L)(e,{...a,...n??i})}let i=t?.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:a.accessTokenExpiresAt?"string"==typeof a.accessTokenExpiresAt?new Date(a.accessTokenExpiresAt):a.accessTokenExpiresAt:void 0;return{accessToken:t?.accessToken??await ro(a.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:iZ(a.scope),idToken:t?.idToken??a.idToken??void 0}}catch(e){throw p.E.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let i3=(0,C.g)("/get-access-token",{method:"POST",body:i5,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{userId:t}=e.body,r=await i4(e,{resolvedUserId:await i2(e,t),selection:e.body});return e.json(r)}),i9=(0,C.g)("/refresh-token",{method:"POST",body:i5,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{userId:t}=e.body,{account:r,accountCookie:i}=await i8(e,{resolvedUserId:await i2(e,t),selection:e.body}),a=await e8(e.context.socialProviders,{value:r.providerId});if(!a)throw p.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!a.refreshAccessToken)throw p.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let o=r.refreshToken??void 0;if(!o)throw p.E.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let t=await ro(o,e.context),n=await a.refreshAccessToken(t,e),s=n.refreshToken?await rn(n.refreshToken,e.context):o,l=n.refreshTokenExpiresAt??r.refreshTokenExpiresAt,c={accessToken:await rn(n.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,idToken:n.idToken||r.idToken},d=null;if(r.id&&(d=await e.context.internalAdapter.updateAccount(r.id,c)),i?.id===r.id&&e.context.options.account?.storeAccountCookie){let t={...i,...d??c};await (0,e9.L)(e,t)}let u=d?.scope??r.scope;return e.json({accessToken:n.accessToken,refreshToken:n.refreshToken??t,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,scope:u,idToken:n.idToken||r.idToken,providerId:r.providerId,accountId:r.id})}catch(e){throw p.E.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),i7=(0,C.g)("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:i5},async e=>{let{userId:t}=e.query,r=await i2(e,t),{account:i}=await i8(e,{resolvedUserId:r,selection:e.query}),a=await e8(e.context.socialProviders,{value:i.providerId});if(!a)throw p.E.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let o=await i4(e,{resolvedUserId:r,selection:e.query,account:i});if(!o.accessToken)throw p.E.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let n=await a.getUserInfo({...o,accessToken:o.accessToken});if(!n)throw p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);return e.json({...n,account:{id:i.id,providerId:i.providerId,accountId:i.accountId}})});async function ae(e,t,r){let i;if(r.iss&&t.issuer&&r.iss!==t.issuer)return e.context.logger.error("OAuth issuer mismatch",{expected:t.issuer,received:r.iss}),{error:"issuer_mismatch"};if(t.requiresIdTokenNonce&&!r.idTokenNonce)return e.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:t.id}),{error:"nonce_binding_missing"};try{i=await t.validateAuthorizationCode({code:r.code,codeVerifier:r.codeVerifier,deviceId:r.deviceId,redirectURI:`${e.context.baseURL}${rs(t)}`})}catch(t){return e.context.logger.error("Failed to validate authorization code",t),{error:t1}}if(!i)return{error:t1};let a=await t.getUserInfo({...i,expectedIdTokenNonce:r.idTokenNonce,user:(0,e$.f)(r.user)??void 0});if(!a?.user)return e.context.logger.error("Unable to get user info"),{error:t2};let o=await tX(t,i,a.data).catch(r=>(e.context.logger.error("Unable to derive provider account identity",{providerId:t.id,error:r}),null));return o?{tokens:i,userInfo:a.user,providerProfile:a.data,accountKey:o}:{error:t2}}let at=P.object({code:P.string().optional(),error:P.string().optional(),device_id:P.string().optional(),error_description:P.string().optional(),state:P.string().optional(),user:P.string().optional(),iss:P.string().optional()}),ar=(0,C.g)("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:at.optional(),query:at.optional(),metadata:{...C.S,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?at.parse(e.body):{},r=e.query?at.parse(e.query):{},i=at.parse({...t,...r}),a=new URLSearchParams;for(let[e,t]of Object.entries(i))null!=t&&a.set(e,String(t));let o=`${e.context.baseURL}/callback/${e.params.id}?${a.toString()}`;throw e.redirect(o)}try{if("GET"===e.method)t=at.parse(e.query);else if("POST"===e.method)t=at.parse(e.body);else throw Error("Unsupported method")}catch(r){e.context.logger.error("INVALID_CALLBACK_REQUEST",r);let t=Y(a,new URLSearchParams({error:"invalid_callback_request"}));throw e.redirect(t)}let{code:o,error:n,state:s,error_description:l,device_id:c,user:d,iss:u}=t;if(void 0===s&&o){let t=await e8(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let r=rU(t),{state:i,codeVerifier:a}=await rN(e,{idTokenNonce:r}),o=await t.createAuthorizationURL({state:i,codeVerifier:a,idTokenNonce:r,redirectURI:`${e.context.baseURL}${rs(t)}`});throw e.redirect(o.toString())}}if(!s){e.context.logger.error("State not found",n);let t=Y(a,new URLSearchParams({error:"state_not_found"}));throw e.redirect(t)}let{codeVerifier:f,callbackURL:p,link:m,errorURL:h,newUserURL:g,requestSignUp:y,idTokenNonce:w}=await rD(e);function b(t,r){let i=h??a,o=new URLSearchParams({error:t});r&&o.set("error_description",r);let n=Y(i,o);throw e.redirect(n)}if(n&&b(n,l),!o)throw e.context.logger.warn("Code not found"),b("no_code");let E=await e8(e.context.socialProviders,{value:e.params.id});if(!E)throw e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),b("oauth_provider_not_found");let A=await ae(e,E,{code:o,codeVerifier:f,iss:u,deviceId:c,user:d,idTokenNonce:w});if(A.error)throw b(A.error);let{tokens:I,userInfo:T,providerProfile:_,accountKey:v}=A,{accountId:O}=v;if(!p)throw e.context.logger.error("No callback URL found"),b("no_callback_url");let R={...v,...I,scope:I.scopes?.join(",")};if(m){let t=await rh(e,{link:m,userInfo:T,account:R,profile:_,scopes:I.scopes});if(!t.linked)return b(t.error.code,t.error.message);throw e.redirect(p)}if(!T.email)return e.context.logger.error(t4(E.id)),b("email_not_found");try{r=await rg(e,{userInfo:{...T,id:O,email:T.email,name:T.name||""},account:R,callbackURL:p,disableSignUp:E.disableImplicitSignUp&&!y||E.options?.disableSignUp,overrideUserInfo:E.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:E.id,profile:_}}})}catch(e){throw(0,L.f)(e)&&e.body?.code&&b(e.body.code,e.body.message),e}if(r.error)return e.context.logger.error(r.error.split(" ").join("_")),b(r.error.split(" ").join("_"));let{session:k,user:x}=r.data;await (0,ev.V)(e,{session:k,user:x});try{i=(r.isRegister&&g||p).toString()}catch{i=r.isRegister&&g||p}throw e.redirect(i)});function ai(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn("Password is too short"),p.E.from("BAD_REQUEST",G.f.PASSWORD_TOO_SHORT)}function aa(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn("Password is too long"),p.E.from("BAD_REQUEST",G.f.PASSWORD_TOO_LONG)}async function ao(e,t,r,i){await (0,eC.n)(e.context.adapter,async()=>{(await i?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t))?await e.context.internalAdapter.updatePassword(t,r):await e.context.internalAdapter.createAccount({userId:t,providerId:"credential",accountId:t,password:r})})}async function an(e,t){aa(e,t.password);let r=await e.context.internalAdapter.findCredentialAccount(t.userId),i=r?.password;return!!r&&!!i&&await e.context.password.verify({hash:i,password:t.password})}async function as(e,t){let r=t.body.password;"string"==typeof r&&aa(t,r);let i=await t.context.internalAdapter.findCredentialAccount(e),a=i?.password;if(!i||!a||!r)throw r&&await t.context.password.hash(r),p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);if(!await t.context.password.verify({hash:a,password:r}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);return!0}let al=P.record(P.string().meta({description:"Field name must be a string"}),P.any()),ac=(0,C.g)("/change-password",{method:"POST",operationId:"changePassword",body:P.object({newPassword:P.string().meta({description:"The new password to set"}),currentPassword:P.string().meta({description:"The current password is required"}),revokeOtherSessions:P.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[t9.i],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:i}=e.body,a=e.context.session;ai(e,t),aa(e,t),aa(e,r);let o=await e.context.internalAdapter.findCredentialAccount(a.user.id);if(!o||!o.password)throw p.E.from("BAD_REQUEST",G.f.CREDENTIAL_ACCOUNT_NOT_FOUND);let n=await e.context.password.hash(t);if(!await e.context.password.verify({hash:o.password,password:r}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);let s=await (0,eC.n)(e.context.adapter,async()=>{if(i&&await e.context.internalAdapter.deleteUserSessions(a.user.id),await e.context.internalAdapter.updateAccount(o.id,{password:n}),!i)return null;let t=await e.context.internalAdapter.createSession(a.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw p.E.from("INTERNAL_SERVER_ERROR",G.f.FAILED_TO_GET_SESSION);return t}),l=null;return s&&(await (0,ev.V)(e,{session:s,user:a.user}),l=s.token),e.json({token:l,user:(0,ex.$)(e.context.options,a.user)})}),ad=C.g.serverOnly({method:"POST",body:P.object({newPassword:P.string().meta({description:"The new password to set is required"})}),use:[t9.i]},async e=>{let{newPassword:t}=e.body,r=e.context.session;ai(e,t),aa(e,t);let i=await e.context.internalAdapter.findCredentialAccount(r.user.id),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json({status:!0});if(!i.password)return await e.context.internalAdapter.updateAccount(i.id,{password:a}),e.json({status:!0});throw p.E.from("BAD_REQUEST",G.f.PASSWORD_ALREADY_SET)});async function au(e,t){let r=e.context.options.user?.deleteUser?.beforeDelete;r&&await r(t,e.request),await e.context.internalAdapter.deleteUser(t.id),await e.context.internalAdapter.deleteUserSessions(t.id),(0,ev.Q)(e);let i=e.context.options.user?.deleteUser?.afterDelete;i&&await i(t,e.request)}async function af(e,t,r){let i=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${r}`);if(!i||i.value!==t.id)throw p.E.from("NOT_FOUND",G.f.INVALID_TOKEN);await au(e,t)}let ap=(0,C.g)("/delete-user",{method:"POST",use:[t9.i],body:P.object({callbackURL:P.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:P.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:P.string().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"),p.E.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){aa(e,e.body.password);let r=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!r||!r.password)throw p.E.from("BAD_REQUEST",G.f.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD)}if(e.body.token)return await af(e,t.user,e.body.token),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=tn(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 i=`${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:i,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(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw p.E.from("BAD_REQUEST",G.f.SESSION_EXPIRED)}return await au(e,t.user),e.json({success:!0,message:"User deleted"})}),am=(0,C.g)("/delete-user/callback",{method:"GET",query:P.object({token:P.string().meta({description:"The token to verify the deletion request"}),callbackURL:P.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[er(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"),p.E.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await (0,t9.D)(e,{disableCookieCache:(0,t9.f)(e)});if(!t)throw p.E.from("NOT_FOUND",G.f.FAILED_TO_GET_USER_INFO);if(await af(e,t.user,e.query.token),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),ah=(0,C.g)("/change-email",{method:"POST",body:P.object({newEmail:P.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:P.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[t9.i],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."),p.E.from("BAD_REQUEST",G.f.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),p.E.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,i=e.context.options.emailVerification?.sendVerificationEmail,a=i&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!a&&!i)throw e.context.logger.error("Verification email isn't enabled."),p.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await (0,ev.V)(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),i){let r=await rt(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:a,token:r},e.request))}return e.json({status:!0})}if(a){let r=await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation",userId:e.context.session.user.id}),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(a({user:e.context.session.user,newEmail:t,url:i,token:r},e.request)),e.json({status:!0})}if(!i)throw e.context.logger.error("Verification email isn't enabled."),p.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await rt(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:e.context.session.user.id}),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:n,token:o},e.request)),e.json({status:!0})});function ag(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 ay=(0,C.g)("/error",{method:"GET",metadata:{...C.S,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",i=t.searchParams.get("error_description")||null,a=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",o=i?ag(i):null,n=new URLSearchParams;n.set("error",a),i&&n.set("error_description",i);let s=e.context.options,l=s.onAPIError?.errorURL;return l?new Response(null,{status:302,headers:{Location:Y(l,n)}}):en.C&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${n.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let i=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
136
136
|
<html lang="en">
|
|
137
137
|
<head>
|
|
138
138
|
<meta charset="UTF-8" />
|
|
@@ -466,7 +466,7 @@ ${i?.disableBackgroundGrid?"":`
|
|
|
466
466
|
</div>
|
|
467
467
|
</div>
|
|
468
468
|
</body>
|
|
469
|
-
</html>`})(e.context.options,a,o),{headers:{"Content-Type":"text/html"}})}),aw=(0,C.g)("/ok",{method:"GET",metadata:{...C.S,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 ab(e,t,r){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href}let aE=(0,C.g)("/request-password-reset",{method:"POST",body:P.object({email:P.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:P.string().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:[er(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!"),p.E.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return(0,eM.f)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let a=(0,eO.f)(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),o=(0,eM.f)(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`reset-password:${o}`,expiresAt:a});let n=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${o}?callbackURL=${n}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:o},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),aA=(0,C.g)("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:P.object({callbackURL:P.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[er(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 i,{token:a}=e.params,{callbackURL:o}=e.query;if(!a||!o)throw e.redirect(ab(e.context,o,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${a}`);if(!n||n.expiresAt<new Date)throw e.redirect(ab(e.context,o,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:a},i=new URL(o,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href))}),aI=(0,C.g)("/reset-password",{method:"POST",operationId:"resetPassword",query:P.object({token:P.string().optional()}).optional(),body:P.object({newPassword:P.string().meta({description:"The new password to set"}),token:P.string().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 p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN);let{newPassword:r}=e.body;ai(e,r),aa(e,r);let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN);let o=a.value,n=await e.context.internalAdapter.findUserById(o);if(!n)throw p.E.from("BAD_REQUEST",G.f.USER_NOT_FOUND);let s=await e.context.password.hash(r);return await ao(e,o,s,async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(i))throw p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:n},e.request),e.json({status:!0})}),aT=(0,C.g)("/verify-password",{method:"POST",body:P.object({password:P.string().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:[t9.i]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await an(e,{password:t,userId:r.user.id}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);return e.json({status:!0})}),a_=P.object({callbackURL:P.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:P.string().optional(),errorCallbackURL:P.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:iY,disableRedirect:P.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:P.optional(P.object({token:P.string().meta({description:"ID token from the provider"}),nonce:P.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:P.string().meta({description:"Access token from the provider"}).optional(),refreshToken:P.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:P.number().meta({description:"Expiry date of the token"}).optional(),user:P.object({name:P.object({firstName:P.string().optional(),lastName:P.string().optional()}).optional(),email:P.string().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:P.array(P.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:P.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:P.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rj,additionalData:P.record(P.string(),P.any()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),av=P.object({callbackURL:P.string().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:P.boolean().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:P.string().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),aO=e=>({success:!0,url:e?.url,redirect:e?.redirect}),ak=(0,C.g)("/sign-out",{method:"POST",body:av,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"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),r=null;if(t)try{r=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error("Failed to read session from database",t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}(0,ev.Q)(e);let i=await (async()=>{try{if(!r)return null;let t=await e.context.internalAdapter.findAccounts(r.user.id),i=new Map(e.context.socialProviders.map(e=>[e.id,e])),a=t.filter(e=>!!i.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(0===a.length)return null;let o=new Set,n=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of a){if(o.has(t.providerId))continue;o.add(t.providerId);let r=i.get(t.providerId);try{let i=await r?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:n,state:e.body?.state});if(i)return i.toString()}catch(r){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,r)}}return null}catch(t){return e.context.logger.error("Failed to create provider logout URL",t),null}})();if(i){let t=!e.body?.disableRedirect;return t&&e.setHeader("Location",i),e.json(aO({url:i,redirect:t}))}return e.json(aO())}),aR=P.object({name:P.string(),email:P.email(),password:P.string().nonempty(),image:P.string().optional(),callbackURL:P.string().optional(),rememberMe:P.boolean().optional()}).and(P.record(P.string(),P.any())),ax=P.record(P.string().meta({description:"Field name must be a string"}),P.any());var aS=e.i(30273);let aU=eK((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),aN=new WeakMap;function aD(e,t){let r=e.options;return r?.operationId??r?.metadata?.openapi?.operationId??t??e.path??"/:virtual"}function aL(e,t,r){let i=t.toLowerCase();if("set-cookie"===i)return void e.append(t,r);if("access-control-expose-headers"===i){let i=(e.get(t)??"").split(",").map(e=>e.trim()).filter(Boolean);for(let e of r.split(",").map(e=>e.trim()))e&&!i.some(t=>t.toLowerCase()===e.toLowerCase())&&i.push(e);e.set(t,i.join(", "));return}e.set(t,r)}function aC(e,t){t&&t.forEach((t,r)=>{e.responseHeaders??=new Headers,aL(e.responseHeaders,r,t)})}function az(e){let t=e[iw.p],r=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!r)return null;let i=new Headers;return t?.forEach((e,t)=>{i.append(t,e)}),r?.forEach((e,t)=>{aL(i,t,e)}),i}async function aj(e,t,r,i){let a=(0,eP.f)(e.context.options),o={};for(let n of t){let t=!1;try{t=n.matcher(e)}catch(r){let t=aN.get(n.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${t} hook matcher execution:`,r),new p.E("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!t)continue;let s=aN.get(n.handler)??"unknown",l=r.path??"/:virtual",c=await a(`hook before ${l} ${s}`,{[ej.A]:"before",[ej.F]:l,[ej.s]:s,[ej.c]:i},()=>n.handler({...e,returnHeaders:!0})).catch(t=>{throw(0,L.f)(t)&&(0,u.m)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),t});aC(e.context,c?.headers);let d=c?.response;if(d&&"object"==typeof d){if("context"in d&&"object"==typeof d.context){let{headers:e,...t}=d.context;e instanceof Headers&&(o.headers?e.forEach((e,t)=>{o.headers?.set(t,e)}):o.headers=e),o=aU(t,o);continue}return d}}return{context:o}}async function aP(e,t,r,i){let a=(0,eP.f)(e.context.options);for(let o of t){if(!o.matcher(e))continue;let t=aN.get(o.handler)??"unknown",n=r.path??"/:virtual",s=await a(`hook after ${n} ${t}`,{[ej.A]:"after",[ej.F]:n,[ej.s]:t,[ej.c]:i},()=>o.handler(e)).catch(t=>{if((0,L.f)(t))return(0,u.m)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),{response:t,headers:az(t)};throw t});aC(e.context,s.headers),void 0!==s.response&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}async function aB(e,t){let r=(0,eP.f)(t.context.options),i=t.operationId??aD(e),a=e.path??"/:virtual",o=e.options?.method,n=Array.isArray(o)?o[0]:o,s=t.method??t.request?.method??n??"?",l=t.asResponse??(0,z.T)(t.request),c={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return r(`${s} ${a}`,{[ej.F]:a,[ej.c]:i},async()=>(0,ez.a)(c,async()=>{var o;let n,s,d,f,p,m,h,{beforeHooks:g,afterHooks:y}=(n=(o=c.context).options.plugins||[],s=[],d=[],(f=o.options.hooks?.before)&&(aN.set(f,"user"),s.push({matcher:()=>!0,handler:f})),(p=o.options.hooks?.after)&&(aN.set(p,"user"),d.push({matcher:()=>!0,handler:p})),m=n.flatMap(e=>(e.hooks?.before??[]).map(t=>(aN.set(t.handler,`plugin:${e.id}`),t))),h=n.flatMap(e=>(e.hooks?.after??[]).map(t=>(aN.set(t.handler,`plugin:${e.id}`),t))),m.length&&s.push(...m),h.length&&d.push(...h),{beforeHooks:s,afterHooks:d}),w=await aj(c,g,e,i);if("context"in w&&w.context&&"object"==typeof w.context){let{headers:e,...t}=w.context;if(e){c.headers||(c.headers=new Headers);let t=c.headers;e.forEach((e,r)=>{t.set(r,e)})}c=aU(t,c)}else if(w){let e=c.context.responseHeaders;return l?(0,aS.f)(w,{headers:e}):t.returnHeaders?{headers:e,response:w}:w}c.asResponse=!1,c.returnHeaders=!0,c.returnStatus=!0;let b=await (0,ez.a)(c,()=>r(`handler ${a}`,{[ej.F]:a,[ej.c]:i},()=>e(c))).catch(e=>{if((0,L.f)(e))return{response:e,status:e.statusCode,headers:az(e)};throw e});if(b instanceof Response)return b;c.context.returned=b.response,aC(c.context,b.headers);let E=await aP(c,y,e,i);if(void 0!==E.response&&(b.response=E.response),b.headers=E.headers??b.headers,(0,L.f)(b.response)&&(0,u.m)(c.context.logger.level,"debug")&&(b.response.stack=b.response.errorStack),(0,L.f)(b.response)&&!l)throw b.headers&&Object.defineProperty(b.response,iw.p,{enumerable:!1,configurable:!0,writable:!1,value:b.headers}),b.response;return l?(0,aS.f)(b.response,{headers:b.headers??void 0,status:b.status}):t.returnHeaders?t.returnStatus?{headers:b.headers,response:b.response,status:b.status}:{headers:b.headers,response:b.response}:t.returnStatus?{response:b.response,status:b.status}:b.response}))}async function aM(e,t){if(e.baseURL)return e;let r=function(e){if((0,z.T)(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),i=e.options.baseURL,a=(0,z._)(i)&&!!i.fallback;if(void 0===r&&!a)throw new p.E("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 e6(e,r,e5(e.options))}catch(e){if(e instanceof p.p)throw new p.E("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}let{get:a$}=(0,rb.z)(()=>new Set);e.i(80849);var aq=e.i(86097);function aH(e,t){let r=(0,eP.f)(t),i=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},a=t.plugins?.map(t=>t.middlewares?.map(i=>{let a=async a=>{let o=await e;return r(`middleware ${i.path} ${t.id}`,{[ej.A]:"middleware",[ej.F]:i.path,[ej.s]:`plugin:${t.id}`},()=>i.middleware({...a,context:{...o,...a.context}}))};return a.options=i.middleware.options,{path:i.path,middleware:a}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[i,a]of Object.entries(e))r[i]=async e=>{let r=aD(a,i),o=async()=>{let i=await t,o=i.checkSchema?.();o&&await o;let n=(0,z._)(i.options.baseURL)?await aM(i,e):i;return aB(a,{...e,context:n,operationId:r,asResponse:e?.asResponse??(0,z.T)(e?.request)})};return await (0,rb.B)()?o():(0,rb.O)(new WeakMap,o)},r[i].path=a.path,r[i].options=a.options;return r}({signInSocial:(0,C.g)("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:a_,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 e8(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}),p.E.from("NOT_FOUND",G.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rq(t))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),p.E.from("NOT_FOUND",G.f.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await rH(t,r,i,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.INVALID_TOKEN);let a={idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},o=t.getUserInfoFromIdToken?await t.getUserInfoFromIdToken(r):await t.getUserInfo(a);if(!o||!o?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);if(!o.user.email)throw e.context.logger.error(t4(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.USER_EMAIL_NOT_FOUND);let n=await t0(t,a,o.data),s=o.data,l=await rg(e,{userInfo:{...o.user,email:o.user.email,id:n.accountId,name:o.user.name||"",image:o.user.image,emailVerified:o.user.emailVerified||!1},account:{...n,accessToken:e.body.idToken.accessToken,idToken:r},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:"oauth",oauth:{providerId:t.id,profile:s}}});if(l.error){if(l.error===t6)throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED);throw p.E.from("UNAUTHORIZED",{message:l.error,code:"OAUTH_LINK_ERROR"})}return await (0,ev.V)(e,l.data),e.json({redirect:!1,token:l.data.session.token,url:void 0,user:(0,ex.$)(e.context.options,l.data.user)})}let r=rU(t),{codeVerifier:i,state:a}=await rN(e,{additionalData:e.body.additionalData,idTokenNonce:r}),o=await t.createAuthorizationURL({state:a,codeVerifier:i,idTokenNonce:r,redirectURI:`${e.context.baseURL}${rs(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:ar,getSession:(0,t9.v)(),signOut:ak,signUpEmail:(0,C.g)("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[ea],body:aR,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>(0,eC.n)(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw p.E.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:i,email:a,password:o,image:n,callbackURL:s,rememberMe:l,...c}=r;if(!P.email().safeParse(a).success)throw p.E.from("BAD_REQUEST",G.f.INVALID_EMAIL);if(!o||"string"!=typeof o)throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);ai(e,o),aa(e,o);let d=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,u=!1===e.context.options.emailAndPassword.autoSignIn||d,f=(0,ex.R)(e.context.options,c,"create"),m=a.toLowerCase(),h=()=>{let t,r=new Date,a=e.context.generateId({model:"user"})||(0,eM.f)(),o={name:i,email:m,emailVerified:!1,image:n??null,createdAt:r,updatedAt:r},s=e.context.options.emailAndPassword?.customSyntheticUser;if(s){let r=Object.keys(e.context.options.user?.additionalFields??{}),i={};for(let e of r)e in f&&(i[e]=f[e]);let n=s({coreFields:o,additionalFields:i,id:a});t=(0,ex.g)(e.context.options,n)}else t=(0,ex.g)(e.context.options,{...o,...f,id:a});return e.json({token:null,user:(0,ex.$)(e.context.options,t)})},g=await e.context.internalAdapter.findUserByEmail(m);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${a}`),d){await e.context.password.hash(o);let t=e.context.options.emailAndPassword?.onExistingUserSignUp;if(t){let r=t3(e.request);await (0,eC.A)(async()=>{await e.context.runInBackgroundOrAwait(t({user:g.user},r))},{onError:t=>e.context.logger.error("Failed to run onExistingUserSignUp after sign-up",t)})}return h()}throw p.E.from("UNPROCESSABLE_ENTITY",G.f.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let y=await e.context.password.hash(o);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:i,image:n,...f,emailVerified:!1},{method:"email-password"})))throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_CREATE_USER)}catch(t){if((0,L.f)(t)){if(403===t.statusCode&&d)return h();throw t}throw(0,en.o)()&&e.context.logger.error("Failed to create user",t),e.context.logger?.error("Failed to create user",t),p.E.from("UNPROCESSABLE_ENTITY",G.f.FAILED_TO_CREATE_USER)}if(!t)throw p.E.from("UNPROCESSABLE_ENTITY",G.f.FAILED_TO_CREATE_USER);await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:y});let w=e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification,b=e.context.options.emailVerification?.sendVerificationEmail;if(w&&b){let i=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),a=t3(e.request);await (0,eC.A)(async()=>{let r=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.runInBackgroundOrAwait(b({user:t,url:o,token:r},a))},{onError:t=>e.context.logger.error("Failed to send the sign-up verification email",t)})}if(u)return e.json({token:null,user:(0,ex.$)(e.context.options,t)});let E=await e.context.internalAdapter.createSession(t.id,!1===l,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!E)throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_CREATE_SESSION);return await (0,ev.V)(e,{session:E,user:t},!1===l),e.json({token:E.token,user:(0,ex.$)(e.context.options,t)})})),signInEmail:(0,C.g)("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[ea],cloneRequest:!0,body:P.object({email:P.string().meta({description:"Email of the user"}),password:P.string().meta({description:"Password of the user"}),callbackURL:P.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:P.boolean().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!"),p.E.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!P.email().safeParse(t).success)throw p.E.from("BAD_REQUEST",G.f.INVALID_EMAIL);aa(e,r);let i=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),a=i?.accounts.find(e=>"credential"===e.providerId&&e.accountId===i.user.id);if(!i||!a)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);let o=i.user,n=a.password;if(!n)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:n,password:r}))throw e.context.logger.warn("Invalid password"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await rt(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:o.id}),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:o,url:i,token:t},t3(e.request)))}throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(o.id,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_CREATE_SESSION);return await (0,ev.V)(e,{session:s,user:o},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:(0,ex.$)(e.context.options,o)})}),resetPassword:aI,verifyPassword:aT,verifyEmail:ra,sendVerificationEmail:ri,changeEmail:ah,changePassword:ac,setPassword:ad,updateSession:(0,C.g)("/update-session",{method:"POST",operationId:"updateSession",body:ax,use:[t9.Z],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=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw p.E.from("BAD_REQUEST",G.f.BODY_MUST_BE_AN_OBJECT);let r=e.context.session,i=(0,ex.z)(e.context.options,t,"update");if(0===Object.keys(i).length)throw p.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(r.session.token,{...i,updatedAt:new Date});if(!a&&(0,t9.f)(e))throw(0,ev.Q)(e),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_SESSION);let o=a??{...r.session,...i,updatedAt:new Date};return await (0,ev.V)(e,{session:o,user:r.user}),e.json({session:(0,ex.Q)(e.context.options,o)})}),updateUser:(0,C.g)("/update-user",{method:"POST",operationId:"updateUser",body:al,use:[t9.Z],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 p.E.from("BAD_REQUEST",G.f.BODY_MUST_BE_AN_OBJECT);if(t.email)throw p.E.from("BAD_REQUEST",G.f.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:i,...a}=t,o=e.context.session,n=(0,ex.R)(e.context.options,a,"update");if(void 0===i&&void 0===r&&0===Object.keys(n).length)throw p.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(o.user.id,{name:r,image:i,...n})??{...o.user,...void 0!==r&&{name:r},...void 0!==i&&{image:i},...n};return await (0,ev.V)(e,{session:o.session,user:s}),e.json({status:!0})}),deleteUser:ap,requestPasswordReset:aE,requestPasswordResetCallback:aA,listSessions:(0,t9.T)(),revokeSession:t9.G,revokeSessions:t9.$,revokeOtherSessions:t9.Y,linkSocialAccount:i0,listUserAccounts:iX,deleteUserCallback:am,unlinkAccount:i1,refreshToken:i9,getAccessToken:i3,accountInfo:i7,...i,ok:aw,error:ay},e),middlewares:a}}var aF=e.i(14268),aV=e.i(2157),aW=e.i(12714),aK=e.i(60526),aG=e.i(50227);async function aJ(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 i="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!i.mapProfileToUser,disableDefaultScope:!!i.disableDefaultScope,disableIdTokenSignIn:!!i.disableIdTokenSignIn,disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,getUserInfo:!!i.getUserInfo,overrideUserInfoOnSignIn:!!i.overrideUserInfoOnSignIn,prompt:i.prompt,verifyIdToken:!!i.verifyIdToken,scope:i.scope,refreshAccessToken:!!i.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 aQ(e){let t=await (0,eU.f)("SHA-256").digest(e);return eS.t.encode(t)}async function aY(){if(r)return r;try{let e=process.cwd();if(!e)return;let t=await aW.default.readFile(aG.default.join(e,"package.json"),"utf-8");return r=JSON.parse(t)}catch{}}async function aZ(e){if(r)return r.dependencies?.[e]||r.devDependencies?.[e]||r.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=aG.default.join(t,"node_modules",e,"package.json"),i=await aW.default.readFile(r,"utf-8");return JSON.parse(i).version||await aX(e)||void 0}catch{}return aX(e)}async function aX(e){let t=await aY();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function a0(){return(await aY())?.name}async function a1(){try{let e,t,r=aK.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||(0,eB.p)()?"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:aK.default.platform(),systemRelease:aK.default.release(),systemArchitecture:aK.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:aK.default.totalmem(),isWSL:await a8(),isDocker:await a6(),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 a2(){try{return aV.default.statSync("/.dockerenv"),!0}catch{return!1}}async function a5(){try{return aV.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function a6(){return void 0===i&&(i=await a2()||await a5()),i}async function a8(){try{return!1}catch{return!1}}let a4=null;async function a3(e){if(a4)return a4;let t=await a0();return a4=t?await aQ(e?e+t:t):e?await aQ(e):(0,to.f)("a-z","A-Z","0-9")(32)}async function a9(){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 aZ(e);if(r)return{name:t,version:r}}}async function a7(){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 aZ(e);if(r)return{name:t,version:r}}}let oe=async function(){};async function ot(e,t){let r,i,a=e.telemetry?.debug||(0,en.O)("BETTER_AUTH_TELEMETRY_DEBUG",!1),o=en.w.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!o&&!t?.customTrack)return{publish:oe};let n=async e=>{t?.customTrack?await t.customTrack(e).catch(u.y.error):o&&(a?u.y.info("telemetry event",JSON.stringify(e,null,2)):await ie(o,{method:"POST",body:e}).catch(u.y.error))},s=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,en.O)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,en.s)())},l=await s();return l&&(r=await a3("string"==typeof e.baseURL?e.baseURL:void 0).catch(()=>void 0)),r&&n({type:"init",payload:{config:await aJ(e,t),runtime:"deno"===(i=(0,eB.a)())?{name:i,version:Deno?.version?.deno??null}:"bun"===i?{name:i,version:Bun?.version??null}:"node"===i?{name:i,version:process.versions.node??null}:{name:i??"edge",version:null},database:await a9(),framework:await a7(),environment:"production"===(0,en.B)("NODE_ENV")?"production":"false"!==en.$.CI&&("BUILD_ID"in en.$||"BUILD_NUMBER"in en.$||"CI"in en.$||"CI_APP_ID"in en.$||"CI_BUILD_ID"in en.$||"CI_BUILD_NUMBER"in en.$||"CI_NAME"in en.$||"CONTINUOUS_INTEGRATION"in en.$||"RUN_ID"in en.$)?"ci":(0,en.s)()?"test":"development",systemInfo:await a1(),packageManager:function(){let e=en.$.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),i=t.substring(0,r);return{name:"npminstall"===i?"cnpm":i,version:t.substring(r+1)}}()},anonymousId:r}),{publish:async t=>{l&&(r||(r=await a3("string"==typeof e.baseURL?e.baseURL:void 0)),await n({type:t.type,payload:t.payload,anonymousId:r}))}}}async function or(e,t,r){let i,a,o,n,s=(0,e3.z)(t);s||(t=eG(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=eG(t,{account:{storeAccountCookie:!0}}));let l=t.plugins||[],c=(w=t,w.advanced?.crossSubDomainCookies?.enabled,[]),f=(0,u.J)(t.logger),m=(0,z._)(t.baseURL);if((0,z._)(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new p.p('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let h=m?void 0:(0,z.X)("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);h||m||f.warn("[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&f.error(`[better-auth] Misconfiguration detected.
|
|
469
|
+
</html>`})(e.context.options,a,o),{headers:{"Content-Type":"text/html"}})}),aw=(0,C.g)("/ok",{method:"GET",metadata:{...C.S,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 ab(e,t,r){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href}let aE=(0,C.g)("/request-password-reset",{method:"POST",body:P.object({email:P.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:P.string().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:[er(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!"),p.E.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return(0,eM.f)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let a=(0,eO.f)(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),o=(0,eM.f)(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`reset-password:${o}`,expiresAt:a});let n=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${o}?callbackURL=${n}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:o},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),aA=(0,C.g)("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:P.object({callbackURL:P.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[er(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 i,{token:a}=e.params,{callbackURL:o}=e.query;if(!a||!o)throw e.redirect(ab(e.context,o,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${a}`);if(!n||n.expiresAt<new Date)throw e.redirect(ab(e.context,o,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:a},i=new URL(o,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href))}),aI=(0,C.g)("/reset-password",{method:"POST",operationId:"resetPassword",query:P.object({token:P.string().optional()}).optional(),body:P.object({newPassword:P.string().meta({description:"The new password to set"}),token:P.string().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 p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN);let{newPassword:r}=e.body;ai(e,r),aa(e,r);let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN);let o=a.value,n=await e.context.internalAdapter.findUserById(o);if(!n)throw p.E.from("BAD_REQUEST",G.f.USER_NOT_FOUND);let s=await e.context.password.hash(r);return await ao(e,o,s,async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(i))throw p.E.from("BAD_REQUEST",G.f.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:n},e.request),e.json({status:!0})}),aT=(0,C.g)("/verify-password",{method:"POST",body:P.object({password:P.string().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:[t9.i]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await an(e,{password:t,userId:r.user.id}))throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);return e.json({status:!0})}),a_=P.object({callbackURL:P.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:P.string().optional(),errorCallbackURL:P.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:iY,disableRedirect:P.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:P.optional(P.object({token:P.string().meta({description:"ID token from the provider"}),nonce:P.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:P.string().meta({description:"Access token from the provider"}).optional(),refreshToken:P.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:P.number().meta({description:"Expiry date of the token"}).optional(),user:P.object({name:P.object({firstName:P.string().optional(),lastName:P.string().optional()}).optional(),email:P.string().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:P.array(P.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:P.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:P.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rj,additionalData:P.record(P.string(),P.any()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),av=P.object({callbackURL:P.string().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:P.boolean().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:P.string().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),aO=e=>({success:!0,url:e?.url,redirect:e?.redirect}),aR=(0,C.g)("/sign-out",{method:"POST",body:av,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"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),r=null;if(t)try{r=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error("Failed to read session from database",t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}(0,ev.Q)(e);let i=await (async()=>{try{if(!r)return null;let t=await e.context.internalAdapter.findAccounts(r.user.id),i=new Map(e.context.socialProviders.map(e=>[e.id,e])),a=t.filter(e=>!!i.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(0===a.length)return null;let o=new Set,n=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of a){if(o.has(t.providerId))continue;o.add(t.providerId);let r=i.get(t.providerId);try{let i=await r?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:n,state:e.body?.state});if(i)return i.toString()}catch(r){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,r)}}return null}catch(t){return e.context.logger.error("Failed to create provider logout URL",t),null}})();if(i){let t=!e.body?.disableRedirect;return t&&e.setHeader("Location",i),e.json(aO({url:i,redirect:t}))}return e.json(aO())}),ak=P.object({name:P.string(),email:P.email(),password:P.string().nonempty(),image:P.string().optional(),callbackURL:P.string().optional(),rememberMe:P.boolean().optional()}).and(P.record(P.string(),P.any())),ax=P.record(P.string().meta({description:"Field name must be a string"}),P.any());var aS=e.i(30273);let aU=eK((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),aN=new WeakMap;function aD(e,t){let r=e.options;return r?.operationId??r?.metadata?.openapi?.operationId??t??e.path??"/:virtual"}function aL(e,t,r){let i=t.toLowerCase();if("set-cookie"===i)return void e.append(t,r);if("access-control-expose-headers"===i){let i=(e.get(t)??"").split(",").map(e=>e.trim()).filter(Boolean);for(let e of r.split(",").map(e=>e.trim()))e&&!i.some(t=>t.toLowerCase()===e.toLowerCase())&&i.push(e);e.set(t,i.join(", "));return}e.set(t,r)}function aC(e,t){t&&t.forEach((t,r)=>{e.responseHeaders??=new Headers,aL(e.responseHeaders,r,t)})}function az(e){let t=e[iw.p],r=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!r)return null;let i=new Headers;return t?.forEach((e,t)=>{i.append(t,e)}),r?.forEach((e,t)=>{aL(i,t,e)}),i}async function aj(e,t,r,i){let a=(0,eP.f)(e.context.options),o={};for(let n of t){let t=!1;try{t=n.matcher(e)}catch(r){let t=aN.get(n.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${t} hook matcher execution:`,r),new p.E("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!t)continue;let s=aN.get(n.handler)??"unknown",l=r.path??"/:virtual",c=await a(`hook before ${l} ${s}`,{[ej.A]:"before",[ej.F]:l,[ej.s]:s,[ej.c]:i},()=>n.handler({...e,returnHeaders:!0})).catch(t=>{throw(0,L.f)(t)&&(0,u.m)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),t});aC(e.context,c?.headers);let d=c?.response;if(d&&"object"==typeof d){if("context"in d&&"object"==typeof d.context){let{headers:e,...t}=d.context;e instanceof Headers&&(o.headers?e.forEach((e,t)=>{o.headers?.set(t,e)}):o.headers=e),o=aU(t,o);continue}return d}}return{context:o}}async function aP(e,t,r,i){let a=(0,eP.f)(e.context.options);for(let o of t){if(!o.matcher(e))continue;let t=aN.get(o.handler)??"unknown",n=r.path??"/:virtual",s=await a(`hook after ${n} ${t}`,{[ej.A]:"after",[ej.F]:n,[ej.s]:t,[ej.c]:i},()=>o.handler(e)).catch(t=>{if((0,L.f)(t))return(0,u.m)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),{response:t,headers:az(t)};throw t});aC(e.context,s.headers),void 0!==s.response&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}async function aB(e,t){let r=(0,eP.f)(t.context.options),i=t.operationId??aD(e),a=e.path??"/:virtual",o=e.options?.method,n=Array.isArray(o)?o[0]:o,s=t.method??t.request?.method??n??"?",l=t.asResponse??(0,z.T)(t.request),c={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return r(`${s} ${a}`,{[ej.F]:a,[ej.c]:i},async()=>(0,ez.a)(c,async()=>{var o;let n,s,d,f,p,m,h,{beforeHooks:g,afterHooks:y}=(n=(o=c.context).options.plugins||[],s=[],d=[],(f=o.options.hooks?.before)&&(aN.set(f,"user"),s.push({matcher:()=>!0,handler:f})),(p=o.options.hooks?.after)&&(aN.set(p,"user"),d.push({matcher:()=>!0,handler:p})),m=n.flatMap(e=>(e.hooks?.before??[]).map(t=>(aN.set(t.handler,`plugin:${e.id}`),t))),h=n.flatMap(e=>(e.hooks?.after??[]).map(t=>(aN.set(t.handler,`plugin:${e.id}`),t))),m.length&&s.push(...m),h.length&&d.push(...h),{beforeHooks:s,afterHooks:d}),w=await aj(c,g,e,i);if("context"in w&&w.context&&"object"==typeof w.context){let{headers:e,...t}=w.context;if(e){c.headers||(c.headers=new Headers);let t=c.headers;e.forEach((e,r)=>{t.set(r,e)})}c=aU(t,c)}else if(w){let e=c.context.responseHeaders;return l?(0,aS.f)(w,{headers:e}):t.returnHeaders?{headers:e,response:w}:w}c.asResponse=!1,c.returnHeaders=!0,c.returnStatus=!0;let b=await (0,ez.a)(c,()=>r(`handler ${a}`,{[ej.F]:a,[ej.c]:i},()=>e(c))).catch(e=>{if((0,L.f)(e))return{response:e,status:e.statusCode,headers:az(e)};throw e});if(b instanceof Response)return b;c.context.returned=b.response,aC(c.context,b.headers);let E=await aP(c,y,e,i);if(void 0!==E.response&&(b.response=E.response),b.headers=E.headers??b.headers,(0,L.f)(b.response)&&(0,u.m)(c.context.logger.level,"debug")&&(b.response.stack=b.response.errorStack),(0,L.f)(b.response)&&!l)throw b.headers&&Object.defineProperty(b.response,iw.p,{enumerable:!1,configurable:!0,writable:!1,value:b.headers}),b.response;return l?(0,aS.f)(b.response,{headers:b.headers??void 0,status:b.status}):t.returnHeaders?t.returnStatus?{headers:b.headers,response:b.response,status:b.status}:{headers:b.headers,response:b.response}:t.returnStatus?{response:b.response,status:b.status}:b.response}))}async function aM(e,t){if(e.baseURL)return e;let r=function(e){if((0,z.T)(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),i=e.options.baseURL,a=(0,z._)(i)&&!!i.fallback;if(void 0===r&&!a)throw new p.E("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 e6(e,r,e5(e.options))}catch(e){if(e instanceof p.p)throw new p.E("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}let{get:a$}=(0,rb.z)(()=>new Set);e.i(80849);var aq=e.i(86097);function aH(e,t){let r=(0,eP.f)(t),i=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},a=t.plugins?.map(t=>t.middlewares?.map(i=>{let a=async a=>{let o=await e;return r(`middleware ${i.path} ${t.id}`,{[ej.A]:"middleware",[ej.F]:i.path,[ej.s]:`plugin:${t.id}`},()=>i.middleware({...a,context:{...o,...a.context}}))};return a.options=i.middleware.options,{path:i.path,middleware:a}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[i,a]of Object.entries(e))r[i]=async e=>{let r=aD(a,i),o=async()=>{let i=await t,o=i.checkSchema?.();o&&await o;let n=(0,z._)(i.options.baseURL)?await aM(i,e):i;return aB(a,{...e,context:n,operationId:r,asResponse:e?.asResponse??(0,z.T)(e?.request)})};return await (0,rb.B)()?o():(0,rb.O)(new WeakMap,o)},r[i].path=a.path,r[i].options=a.options;return r}({signInSocial:(0,C.g)("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:a_,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 e8(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}),p.E.from("NOT_FOUND",G.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rq(t))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),p.E.from("NOT_FOUND",G.f.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await rH(t,r,i,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.INVALID_TOKEN);let a={idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},o=t.getUserInfoFromIdToken?await t.getUserInfoFromIdToken(r):await t.getUserInfo(a);if(!o||!o?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_USER_INFO);if(!o.user.email)throw e.context.logger.error(t4(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),p.E.from("UNAUTHORIZED",G.f.USER_EMAIL_NOT_FOUND);let n=await t0(t,a,o.data),s=o.data,l=await rg(e,{userInfo:{...o.user,email:o.user.email,id:n.accountId,name:o.user.name||"",image:o.user.image,emailVerified:o.user.emailVerified||!1},account:{...n,accessToken:e.body.idToken.accessToken,idToken:r},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:"oauth",oauth:{providerId:t.id,profile:s}}});if(l.error){if(l.error===t6)throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED);throw p.E.from("UNAUTHORIZED",{message:l.error,code:"OAUTH_LINK_ERROR"})}return await (0,ev.V)(e,l.data),e.json({redirect:!1,token:l.data.session.token,url:void 0,user:(0,ex.$)(e.context.options,l.data.user)})}let r=rU(t),{codeVerifier:i,state:a}=await rN(e,{additionalData:e.body.additionalData,idTokenNonce:r}),o=await t.createAuthorizationURL({state:a,codeVerifier:i,idTokenNonce:r,redirectURI:`${e.context.baseURL}${rs(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:ar,getSession:(0,t9.v)(),signOut:aR,signUpEmail:(0,C.g)("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[ea],body:ak,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>(0,eC.n)(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw p.E.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:i,email:a,password:o,image:n,callbackURL:s,rememberMe:l,...c}=r;if(!P.email().safeParse(a).success)throw p.E.from("BAD_REQUEST",G.f.INVALID_EMAIL);if(!o||"string"!=typeof o)throw p.E.from("BAD_REQUEST",G.f.INVALID_PASSWORD);ai(e,o),aa(e,o);let d=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,u=!1===e.context.options.emailAndPassword.autoSignIn||d,f=(0,ex.R)(e.context.options,c,"create"),m=a.toLowerCase(),h=()=>{let t,r=new Date,a=e.context.generateId({model:"user"})||(0,eM.f)(),o={name:i,email:m,emailVerified:!1,image:n??null,createdAt:r,updatedAt:r},s=e.context.options.emailAndPassword?.customSyntheticUser;if(s){let r=Object.keys(e.context.options.user?.additionalFields??{}),i={};for(let e of r)e in f&&(i[e]=f[e]);let n=s({coreFields:o,additionalFields:i,id:a});t=(0,ex.g)(e.context.options,n)}else t=(0,ex.g)(e.context.options,{...o,...f,id:a});return e.json({token:null,user:(0,ex.$)(e.context.options,t)})},g=await e.context.internalAdapter.findUserByEmail(m);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${a}`),d){await e.context.password.hash(o);let t=e.context.options.emailAndPassword?.onExistingUserSignUp;if(t){let r=t3(e.request);await (0,eC.A)(async()=>{await e.context.runInBackgroundOrAwait(t({user:g.user},r))},{onError:t=>e.context.logger.error("Failed to run onExistingUserSignUp after sign-up",t)})}return h()}throw p.E.from("UNPROCESSABLE_ENTITY",G.f.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let y=await e.context.password.hash(o);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:i,image:n,...f,emailVerified:!1},{method:"email-password"})))throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_CREATE_USER)}catch(t){if((0,L.f)(t)){if(403===t.statusCode&&d)return h();throw t}throw(0,en.o)()&&e.context.logger.error("Failed to create user",t),e.context.logger?.error("Failed to create user",t),p.E.from("UNPROCESSABLE_ENTITY",G.f.FAILED_TO_CREATE_USER)}if(!t)throw p.E.from("UNPROCESSABLE_ENTITY",G.f.FAILED_TO_CREATE_USER);await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:y});let w=e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification,b=e.context.options.emailVerification?.sendVerificationEmail;if(w&&b){let i=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),a=t3(e.request);await (0,eC.A)(async()=>{let r=await rt(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.runInBackgroundOrAwait(b({user:t,url:o,token:r},a))},{onError:t=>e.context.logger.error("Failed to send the sign-up verification email",t)})}if(u)return e.json({token:null,user:(0,ex.$)(e.context.options,t)});let E=await e.context.internalAdapter.createSession(t.id,!1===l,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!E)throw p.E.from("BAD_REQUEST",G.f.FAILED_TO_CREATE_SESSION);return await (0,ev.V)(e,{session:E,user:t},!1===l),e.json({token:E.token,user:(0,ex.$)(e.context.options,t)})})),signInEmail:(0,C.g)("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[ea],cloneRequest:!0,body:P.object({email:P.string().meta({description:"Email of the user"}),password:P.string().meta({description:"Password of the user"}),callbackURL:P.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:P.boolean().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!"),p.E.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!P.email().safeParse(t).success)throw p.E.from("BAD_REQUEST",G.f.INVALID_EMAIL);aa(e,r);let i=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),a=i?.accounts.find(e=>"credential"===e.providerId&&e.accountId===i.user.id);if(!i||!a)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);let o=i.user,n=a.password;if(!n)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:n,password:r}))throw e.context.logger.warn("Invalid password"),p.E.from("UNAUTHORIZED",G.f.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await rt(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:o.id}),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:o,url:i,token:t},t3(e.request)))}throw p.E.from("FORBIDDEN",G.f.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(o.id,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_CREATE_SESSION);return await (0,ev.V)(e,{session:s,user:o},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:(0,ex.$)(e.context.options,o)})}),resetPassword:aI,verifyPassword:aT,verifyEmail:ra,sendVerificationEmail:ri,changeEmail:ah,changePassword:ac,setPassword:ad,updateSession:(0,C.g)("/update-session",{method:"POST",operationId:"updateSession",body:ax,use:[t9.Z],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=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw p.E.from("BAD_REQUEST",G.f.BODY_MUST_BE_AN_OBJECT);let r=e.context.session,i=(0,ex.z)(e.context.options,t,"update");if(0===Object.keys(i).length)throw p.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(r.session.token,{...i,updatedAt:new Date});if(!a&&(0,t9.f)(e))throw(0,ev.Q)(e),p.E.from("UNAUTHORIZED",G.f.FAILED_TO_GET_SESSION);let o=a??{...r.session,...i,updatedAt:new Date};return await (0,ev.V)(e,{session:o,user:r.user}),e.json({session:(0,ex.Q)(e.context.options,o)})}),updateUser:(0,C.g)("/update-user",{method:"POST",operationId:"updateUser",body:al,use:[t9.Z],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 p.E.from("BAD_REQUEST",G.f.BODY_MUST_BE_AN_OBJECT);if(t.email)throw p.E.from("BAD_REQUEST",G.f.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:i,...a}=t,o=e.context.session,n=(0,ex.R)(e.context.options,a,"update");if(void 0===i&&void 0===r&&0===Object.keys(n).length)throw p.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(o.user.id,{name:r,image:i,...n})??{...o.user,...void 0!==r&&{name:r},...void 0!==i&&{image:i},...n};return await (0,ev.V)(e,{session:o.session,user:s}),e.json({status:!0})}),deleteUser:ap,requestPasswordReset:aE,requestPasswordResetCallback:aA,listSessions:(0,t9.T)(),revokeSession:t9.G,revokeSessions:t9.$,revokeOtherSessions:t9.Y,linkSocialAccount:i0,listUserAccounts:iX,deleteUserCallback:am,unlinkAccount:i1,refreshToken:i9,getAccessToken:i3,accountInfo:i7,...i,ok:aw,error:ay},e),middlewares:a}}var aF=e.i(14268),aV=e.i(2157),aW=e.i(12714),aK=e.i(60526),aG=e.i(50227);async function aJ(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 i="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!i.mapProfileToUser,disableDefaultScope:!!i.disableDefaultScope,disableIdTokenSignIn:!!i.disableIdTokenSignIn,disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,getUserInfo:!!i.getUserInfo,overrideUserInfoOnSignIn:!!i.overrideUserInfoOnSignIn,prompt:i.prompt,verifyIdToken:!!i.verifyIdToken,scope:i.scope,refreshAccessToken:!!i.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 aQ(e){let t=await (0,eU.f)("SHA-256").digest(e);return eS.t.encode(t)}async function aY(){if(r)return r;try{let e=process.cwd();if(!e)return;let t=await aW.default.readFile(aG.default.join(e,"package.json"),"utf-8");return r=JSON.parse(t)}catch{}}async function aZ(e){if(r)return r.dependencies?.[e]||r.devDependencies?.[e]||r.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=aG.default.join(t,"node_modules",e,"package.json"),i=await aW.default.readFile(r,"utf-8");return JSON.parse(i).version||await aX(e)||void 0}catch{}return aX(e)}async function aX(e){let t=await aY();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function a0(){return(await aY())?.name}async function a1(){try{let e,t,r=aK.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||(0,eB.p)()?"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:aK.default.platform(),systemRelease:aK.default.release(),systemArchitecture:aK.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:aK.default.totalmem(),isWSL:await a8(),isDocker:await a6(),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 a2(){try{return aV.default.statSync("/.dockerenv"),!0}catch{return!1}}async function a5(){try{return aV.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function a6(){return void 0===i&&(i=await a2()||await a5()),i}async function a8(){try{return!1}catch{return!1}}let a4=null;async function a3(e){if(a4)return a4;let t=await a0();return a4=t?await aQ(e?e+t:t):e?await aQ(e):(0,to.f)("a-z","A-Z","0-9")(32)}async function a9(){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 aZ(e);if(r)return{name:t,version:r}}}async function a7(){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 aZ(e);if(r)return{name:t,version:r}}}let oe=async function(){};async function ot(e,t){let r,i,a=e.telemetry?.debug||(0,en.O)("BETTER_AUTH_TELEMETRY_DEBUG",!1),o=en.w.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!o&&!t?.customTrack)return{publish:oe};let n=async e=>{t?.customTrack?await t.customTrack(e).catch(u.y.error):o&&(a?u.y.info("telemetry event",JSON.stringify(e,null,2)):await ie(o,{method:"POST",body:e}).catch(u.y.error))},s=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,en.O)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,en.s)())},l=await s();return l&&(r=await a3("string"==typeof e.baseURL?e.baseURL:void 0).catch(()=>void 0)),r&&n({type:"init",payload:{config:await aJ(e,t),runtime:"deno"===(i=(0,eB.a)())?{name:i,version:Deno?.version?.deno??null}:"bun"===i?{name:i,version:Bun?.version??null}:"node"===i?{name:i,version:process.versions.node??null}:{name:i??"edge",version:null},database:await a9(),framework:await a7(),environment:"production"===(0,en.B)("NODE_ENV")?"production":"false"!==en.$.CI&&("BUILD_ID"in en.$||"BUILD_NUMBER"in en.$||"CI"in en.$||"CI_APP_ID"in en.$||"CI_BUILD_ID"in en.$||"CI_BUILD_NUMBER"in en.$||"CI_NAME"in en.$||"CONTINUOUS_INTEGRATION"in en.$||"RUN_ID"in en.$)?"ci":(0,en.s)()?"test":"development",systemInfo:await a1(),packageManager:function(){let e=en.$.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),i=t.substring(0,r);return{name:"npminstall"===i?"cnpm":i,version:t.substring(r+1)}}()},anonymousId:r}),{publish:async t=>{l&&(r||(r=await a3("string"==typeof e.baseURL?e.baseURL:void 0)),await n({type:t.type,payload:t.payload,anonymousId:r}))}}}async function or(e,t,r){let i,a,o,n,s=(0,e3.z)(t);s||(t=eG(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=eG(t,{account:{storeAccountCookie:!0}}));let l=t.plugins||[],c=(w=t,w.advanced?.crossSubDomainCookies?.enabled,[]),f=(0,u.J)(t.logger),m=(0,z._)(t.baseURL);if((0,z._)(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new p.p('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let h=m?void 0:(0,z.X)("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);h||m||f.warn("[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&f.error(`[better-auth] Misconfiguration detected.
|
|
470
470
|
You are using the memory DB with generateId: false.
|
|
471
471
|
This will cause no id to be generated for any model.
|
|
472
472
|
Most of the features of Better Auth will not work correctly.`);let g=t.secrets??((b=en.$.BETTER_AUTH_SECRETS)?b.split(",").map((e,t)=>{let r=(e=e.trim()).indexOf(":");if(-1===r)throw new p.p(`Invalid BETTER_AUTH_SECRETS entry at position ${t+1}. Expected format: "<version>:<secret>"`);let i=parseInt(e.slice(0,r),10);if(!Number.isInteger(i)||i<0)throw new p.p(`Invalid version in BETTER_AUTH_SECRETS entry at position ${t+1}. Version must be a non-negative integer.`);let a=e.slice(r+1).trim();if(!a)throw new p.p(`Empty secret value for version ${i} in BETTER_AUTH_SECRETS.`);return{version:i,value:a}}):null),y=t.secret||en.$.BETTER_AUTH_SECRET||en.$.AUTH_SECRET||"";if(g)!function(e,t){var r;let i;if(0===e.length)throw new p.p("`secrets` array must contain at least one entry.");let a=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 p.p(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new p.p(`Empty secret value for version ${e} in \`secrets\`.`);if(a.has(e))throw new p.p(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);a.add(e)}let o=e[0];o.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${o.version}) should be at least 32 characters long for adequate security.`),120>(0===(i=new Set(r=o.value).size)?0:Math.log2(Math.pow(i,r.length)))&&t.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(g,f),i=g[0].value,a=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}}(g,y);else{var w,b,E=i=y||"better-auth-secret-12345678901234567890";let e="better-auth-secret-12345678901234567890"===E;if(!(0,en.s)()){let t;if(e&&en.C)throw new p.p("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!E)throw new p.p("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");E.length<32&&f.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(E).size)?0:Math.log2(Math.pow(t,E.length)))&&f.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}a=i}!function(e,t){let r=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,i]of Object.entries(e.endpoints))if(i&&"path"in i&&"string"==typeof i.path){let a=i.path,o=[];i.options&&"method"in i.options&&(Array.isArray(i.options.method)?o=i.options.method:"string"==typeof i.options.method&&(o=[i.options.method])),0===o.length&&(o=["*"]),r.has(a)||r.set(a,[]),r.get(a).push({pluginId:e.id,endpointKey:t,methods:o})}}});let i=[];for(let[e,t]of r.entries())if(t.length>1){let r=new Map,a=!1;for(let e of t)for(let i of e.methods)r.has(i)||r.set(i,[]),r.get(i).push(e.pluginId),r.get(i).length>1&&(a=!0),"*"===i&&t.length>1?a=!0:"*"!==i&&r.has("*")&&(a=!0);if(a){let a=[...new Set(t.map(e=>e.pluginId))],o=[];for(let[e,i]of r.entries())(i.length>1||"*"===e&&t.length>1||"*"!==e&&r.has("*"))&&o.push(e);i.push({path:e,plugins:a,conflictingMethods:o})}}if(i.length>0){let e=i.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:
|
|
@@ -476,9 +476,9 @@ To resolve this, you can:
|
|
|
476
476
|
1. Use only one of the conflicting plugins
|
|
477
477
|
2. Configure the plugins to use different paths (if supported)
|
|
478
478
|
3. Ensure plugins use different HTTP methods for the same path
|
|
479
|
-
`)}}(t={...t,secret:i,baseURL:m?t.baseURL:h?new URL(h).origin:"",basePath:t.basePath||"/api/auth",plugins:l.concat(c)},f);let I=t.advanced?.ipAddress?.trustedProxies;if(I&&I.length>0){let e=I.filter(e=>null===eg(e));e.length>0&&f.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let T=(0,ev.e)(t),_=(0,d.R)(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||f.warn(`Social provider ${e} is missing clientId or clientSecret`);let i=iJ[e](r);return i.disableImplicitSignUp=r.disableImplicitSignUp,i}))).filter(e=>null!==e),O=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let i=t?.advanced?.database?.generateId;return"function"==typeof i?i({model:e,size:r}):"uuid"===i?crypto.randomUUID():"serial"!==i&&!1!==i&&(0,eM.f)(r)},{publish:k}=await ot(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),R=new Set(t.plugins.map(e=>e.id)),x=await e2(t),S=await e4(t),U={appName:t.appName||"Better Auth",baseURL:h||"",version:(0,aF.I)(),socialProviders:v,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:_,trustedOrigins:x,trustedProviders:S,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>K(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:(o=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300,s&&o?(f.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!==o&&void 0!==o&&(!0===o?{enabled:!0,updateAge:Math.floor(.2*n)}:{enabled:!0,updateAge:void 0!==o.updateAge?o.updateAge:Math.floor(.2*n)}))},secret:i,secretConfig:a,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??en.C,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:T,logger:f,generateId:O,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||tr,verify:t.emailAndPassword?.password?.verify||ta,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:as},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:eF(e,{options:t,logger:f,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:O}),createAuthCookie:(0,ev.g)(t),async runMigrations(){throw new p.p("runMigrations will be set by the specific init implementation")},publishTelemetry:k,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,en.s)(),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=>{f.error("Failed to run background task:",e)})):await e}catch(e){f.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>R.has(e)},N=e1(U);return(0,eV.f)(N)&&await N,U.checkSchema=(0,A.f)(U.adapter),U.explicitSchemaCheck=(0,A.j)(U.adapter),U}let oi=async e=>{let t=await m(e),r=await or(t,e,e=>(0,g.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new p.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await D(e);await t()},r};e.s(["f",0,e=>((e,t)=>{let r=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;return e.checkSchema||!1===t||e.logger[!0===t?"warn":"debug"](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`),e}),{api:i}=aH(r,e),a=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),o=async t=>{let i,a=await r,o=a.options.basePath||"/api/auth";if((0,z._)(e.baseURL))i=await e6(a,t,e5(a.options));else{i=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));let e=a.options;if(!a.options.baseURL){let r=(0,z.X)(void 0,o,t,void 0,a.options.advanced?.trustedProxyHeaders);if(!r)throw new p.p("Could not get base URL from request. Please provide a valid base URL.");i.baseURL=r,i.options={...a.options,baseURL:(0,z.H)(r)||void 0},e=i.options}i.trustedOrigins=await e2(e,t),i.trustedProviders=await e4(e,t)}let{handler:n}=((e,t)=>{let r=(0,eP.f)(t),{api:i,middlewares:a}=aH(e,t),o=new URL(e.baseURL).pathname;return(0,aq.f)(i,{routerContext:e,openapi:{disabled:!0},basePath:o,routerMiddleware:[{path:"/**",middleware:et},...a],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let i=e.options.disabledPaths||[],a=J(t.url,o);if(i.includes(a))return new Response("Not Found",{status:404});let n=e.checkSchema?.();n&&await n;let s=t,l=await eT(s,e);if(l)return l;for(let t of e.options.plugins||[])if(t.onRequest){let i=await r(`onRequest ${t.id}`,{[ej.A]:"onRequest",[ej.s]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(i&&"response"in i)return i.response;i&&"request"in i&&(s=i.request)}return s},async onResponse(t,i){for(let i of e.options.plugins||[])if(i.onResponse){let a=await r(`onResponse ${i.id}`,{[ej.A]:"onResponse",[ej.s]:`plugin:${i.id}`,[ej.h]:t.status},()=>i.onResponse(t,e));if(a)return a.response}return t},async onError(r){if((0,L.f)(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError){try{await t.onAPIError.onError(r,e)}catch(t){e.logger.error("onAPIError.onError threw",t)}return}let i=t.logger?.level,a="error"===i||"warn"===i||"debug"===i?u.y: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);(0,L.f)(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),a?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(i,e);return(0,eC.Q)(i.adapter,()=>n(t))};return{handler:o,fetch:o,api:i,options:e,$context:r,$ERROR_CODES:{...a,...G.f}}})(e,oi)],4721)},46754,e=>{"use strict";function t(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function r(e){if(!e)return[];let t=[],r=0,i=0;for(;i<e.length;){if(","===e[i]){let a=i+1;for(;a<e.length&&" "===e[a];)a++;for(;a<e.length&&"="!==e[a]&&";"!==e[a]&&","!==e[a];)a++;if(a<e.length&&"="===e[a]){let a=e.slice(r,i).trim();for(a&&t.push(a),r=i+1;r<e.length&&" "===e[r];)r++;i=r;continue}}i++}let a=e.slice(r).trim();return a&&t.push(a),t}function i(e){let i=new Map;return r(e).forEach(e=>{let[r,...a]=e.split(";").map(e=>e.trim()),[o,...s]=(r||"").split("="),l=n(s.join("="));if(!o)return;let c={value:t(l)};a.forEach(e=>{let[t,...r]=e.split("="),i=r.join("="),a=t.trim().toLowerCase();switch(a){case"max-age":c["max-age"]=i?parseInt(i.trim(),10):void 0;break;case"expires":c.expires=i?new Date(i.trim()):void 0;break;case"domain":c.domain=i?i.trim():void 0;break;case"path":c.path=i?i.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=i?i.trim().toLowerCase():void 0;break;case"partitioned":c.partitioned=!0;break;default:c[a]=!i||i.trim()}}),i.set(o,c)}),i}let a=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,o=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function n(e){return!(e.length<2)&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function s(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 l(e){let r=new Map;if(e.length<2)return r;for(let i of e.split(";")){let e=i.indexOf("=");if(-1===e)continue;let l=s(i.slice(0,e)),c=n(s(i.slice(e+1)));a.test(l)&&o.test(c)&&r.set(l,t(c))}return r}function c(e,t){let r=l(e.get("cookie")||"");for(let e of t)for(let[t,o]of i(e))a.test(t)&&r.set(t,o.value);e.set("cookie",Array.from(r,([e,t])=>`${e}=${encodeURIComponent(t)}`).join("; "))}e.s(["D",0,"__Host-","d",0,"__Secure-","B",0,c,"T",0,a,"X",0,l,"p",0,i,"H",0,function(e){return t=>{let r=t.response.headers.get("set-cookie");r&&c(e,[r])}},"K",0,function(e,t,r){let i=l(e.get("cookie")||"");a.test(t)&&i.set(t,r),e.set("cookie",Array.from(i,([e,t])=>`${e}=${encodeURIComponent(t)}`).join("; "))},"Z",0,r,"P",0,function(e){return e.startsWith("__Secure-")?e.slice(9):e.startsWith("__Host-")?e.slice(7):e},"n",0,function(e){return{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}}])},49599,e=>{"use strict";let t;var r=e.i(80849),i=e.i(46754),a=e.i(72003),o=e.i(90659);let n=()=>t??=e.A(6878).catch(e=>{throw t=void 0,e});e.s(["A",0,()=>{let e=!1;return{id:"next-cookies",version:a.f,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,o.a)(async t=>{let i;if(e||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let i=r.findIndex(e=>e.id===t);-1===i||r.slice(i+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.`)}(t.context,"next-cookies"),e=!0),"_flag"in t&&"router"===t._flag)return;try{let{headers:e}=await n();i=await e()}catch{return}let a="1"===i.get("RSC"),o=!!i.get("next-action");a&&!o&&await (0,r.w)(!0)})}],after:[{matcher:e=>!0,handler:(0,o.a)(async e=>{let t=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&t instanceof Headers){let e,r=t?.get("set-cookie");if(!r)return;let a=(0,i.p)(r);try{let{cookies:t}=await n();e=await t()}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((t,r)=>{if(r)try{e.set(r,t.value,(0,i.n)(t))}catch{}});return}})}]}}},"z",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}}],49599)},34975,e=>{"use strict";var t=e.i(12996),r=e.i(72003),i=e.i(71616);function a(e){return"OR"===e?"OR":"AND"}function o(e){return Array.isArray(e)}function n(e,t){return"string"==typeof t&&e.includes(t)}let s=e=>{var t;return{authorize(e,r="AND"){let s=!1;for(let[l,c]of Object.entries(e)){let e=t[l];if(!e){if("AND"===r)return{success:!1,error:`You are not allowed to access resource: ${l}`};continue}let d=function(e,{actions:t,connector:r}){return 0!==t.length&&("OR"===r?t.some(t=>n(e,t)):t.every(t=>n(e,t)))}(e,function(e){if(o(e))return{actions:e,connector:"AND"};if(!e||"object"!=typeof e)throw new i.p("Invalid access control request");let{actions:t,connector:r}=e;return o(t)?{actions:t,connector:a(r)}:{actions:[],connector:a(r)}}(c));if(d&&(s=!0),d&&"OR"===r)return{success:!0};if(!d&&"AND"===r)return{success:!1,error:`unauthorized to access resource "${l}"`}}return s?{success:!0}:{success:!1,error:"Not authorized"}},statements:t=e}},l={admin:s({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),owner:s({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),member:s({organization:[],member:[],invitation:[],team:[],ac:["read"]})};function c(e){return(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(Boolean)}function d(e){return c(e).join(",")}let u=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,f={true:!0,false:!1,null:null,undefined:void 0,nan:0/0,infinity:1/0,"-infinity":-1/0},p=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;var m=e.i(42158),h=e.i(73436),g=e.i(74285),y=e.i(30501),w=e.i(82318);async function b(e){let t=await (0,w.f)("SHA-256").digest(new TextEncoder().encode(JSON.stringify([e.teamId,e.userId])));return y.W.encode(new Uint8Array(t),{padding:!1})}async function E(e,t){let r=await e.findOne({model:"teamMember",where:[{field:"membershipKey",value:t.membershipKey}]});return r||e.findOne({model:"teamMember",where:[{field:"teamId",value:t.teamId},{field:"userId",value:t.userId}]})}async function A(e,t){let r=await e.count({model:"teamMember",where:[{field:"teamId",value:t}]});await e.incrementOne({model:"team",where:[{field:"id",value:t},{field:"memberCount",operator:"lt",value:r}],increment:{},set:{memberCount:r}})}async function I(e,t){return!!await e.incrementOne({model:"team",where:[{field:"id",value:t.teamId},{field:"memberCount",operator:"lt",value:t.maximumMembersPerTeam}],increment:{memberCount:1}})}async function T(e,t){await e.incrementOne({model:"team",where:[{field:"id",value:t}],increment:{memberCount:1}})}async function _(e,t,r){r<=0||await e.incrementOne({model:"team",where:[{field:"id",value:t},{field:"memberCount",operator:"gte",value:r}],increment:{memberCount:-r}})}async function v(e,t){try{return{status:"created",member:await e.create({model:"teamMember",data:{teamId:t.teamId,userId:t.userId,membershipKey:t.membershipKey,createdAt:new Date}})}}catch(i){let r=await E(e,t);if(r)return{status:"existing",member:r};throw i}}function O(e){let{membershipKey:t,...r}=e;return r}let k=(e,t)=>{let r=e.adapter,a=t?.schema?.organization?.additionalFields,o=t?.schema?.member?.additionalFields,n=t?.schema?.invitation?.additionalFields,s=t?.schema?.team?.additionalFields;return{findOrganizationBySlug:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"organization",where:[{field:"slug",value:e}]});return(0,g.f)(t,a)},createOrganization:async e=>{let t=await (await (0,h.g)(r)).create({model:"organization",data:{...e.organization,metadata:e.organization.metadata?JSON.stringify(e.organization.metadata):void 0},forceAllowId:!0}),i={...t,metadata:t.metadata&&"string"==typeof t.metadata?JSON.parse(t.metadata):void 0};return(0,g.f)(i,a)},findMemberByEmail:async e=>{let t=await (0,h.g)(r),i=await t.findOne({model:"user",where:[{field:"email",value:e.email.toLowerCase()}]});if(!i)return null;let a=await t.findOne({model:"member",where:[{field:"organizationId",value:e.organizationId},{field:"userId",value:i.id}]});return a?{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},listMembers:async e=>{let a=await (0,h.g)(r),o=await Promise.all([a.findMany({model:"member",where:[{field:"organizationId",value:e.organizationId},...e.filter?.field?[{field:e.filter?.field,value:e.filter?.value,...e.filter.operator?{operator:e.filter.operator}:{}}]:[]],limit:e.limit||("number"==typeof t?.membershipLimit?t.membershipLimit:100)||100,offset:e.offset||0,sortBy:e.sortBy?{field:e.sortBy,direction:e.sortOrder||"asc"}:void 0}),a.count({model:"member",where:[{field:"organizationId",value:e.organizationId},...e.filter?.field?[{field:e.filter?.field,value:e.filter?.value,...e.filter.operator?{operator:e.filter.operator}:{}}]:[]]})]);if(0===o[0].length)return{members:[],total:o[1]};let n=await a.findMany({model:"user",where:[{field:"id",value:o[0].map(e=>e.userId),operator:"in"}],limit:o[0].length});return{members:o[0].map(e=>{let t=n.find(t=>t.id===e.userId);if(!t)throw new i.p("Unexpected error: User not found for member");return{...e,user:{id:t.id,name:t.name,email:t.email,image:t.image}}}),total:o[1]}},findMemberByOrgId:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"userId",value:e.userId},{field:"organizationId",value:e.organizationId}],join:{user:!0}});if(!t||!t.user)return null;let{user:i,...a}=t;return{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"id",value:e}],join:{user:!0}});if(!t)return null;let{user:i,...a}=t;return{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},createMember:async e=>await (await (0,h.g)(r)).create({model:"member",data:{...e,createdAt:new Date}}),updateMember:async(e,t)=>await (await (0,h.g)(r)).update({model:"member",where:[{field:"id",value:e}],update:{role:t}}),deleteMember:async({memberId:e,organizationId:a,userId:o})=>(0,h.n)(r,async()=>{let n,s=await (0,h.g)(r);if(o)n=o;else{let t=await s.findOne({model:"member",where:[{field:"id",value:e}]});if(!t)throw new i.p("Member not found");n=t.userId}let l=await s.delete({model:"member",where:[{field:"id",value:e}]});if(t?.teams?.enabled)for(let e of(await s.findMany({model:"team",where:[{field:"organizationId",value:a}]}))){let t=await s.deleteMany({model:"teamMember",where:[{field:"userId",value:n},{field:"teamId",value:e.id}]});await _(s,e.id,t)}return l}),updateOrganization:async(e,t)=>{let i=await (await (0,h.g)(r)).update({model:"organization",where:[{field:"id",value:e}],update:{...t,metadata:"object"==typeof t.metadata?JSON.stringify(t.metadata):t.metadata}});if(!i)return null;let o={...i,metadata:i.metadata?function(e,t={strict:!0}){return function(e,t={}){let{strict:r=!1,warnings:i=!1,reviver:a,parseDates:o=!0}=t;if("string"!=typeof e)return e;let n=e.trim(),s=n.toLowerCase();if(s.length<=9&&s in f)return f[s];if(!u.test(n)){if(r)throw SyntaxError("[better-json] Invalid JSON");return e}try{return JSON.parse(n,(e,t)=>{if("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t){if(r)throw Error("[better-json] Potential prototype pollution attempt detected");i&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(o&&"string"==typeof t){let e=function(e){let t=p.exec(e);if(!t)return null;let[,r,i,a,o,n,s,l,c,d,u]=t,f=new Date(Date.UTC(parseInt(r,10),parseInt(i,10)-1,parseInt(a,10),parseInt(o,10),parseInt(n,10),parseInt(s,10),l?parseInt(l.padEnd(3,"0"),10):0));if(c){let e=(60*parseInt(d,10)+parseInt(u,10))*("+"===c?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return f instanceof Date&&!isNaN(f.getTime())?f:null}(t);if(e)return e}return a?a(e,t):t})}catch(t){if(r)throw t;return e}}(e,t)}(i.metadata):void 0};return(0,g.f)(o,a)},deleteOrganization:async e=>(0,h.n)(r,async()=>{let t=await (0,h.g)(r);return await t.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await t.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),await t.delete({model:"organization",where:[{field:"id",value:e}]}),e}),setActiveOrganization:async(t,r,i)=>await e.internalAdapter.updateSession(t,{activeOrganizationId:r}),findOrganizationById:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"organization",where:[{field:"id",value:e}]});return(0,g.f)(t,a)},checkMembership:async({userId:e,organizationId:t})=>await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"userId",value:e},{field:"organizationId",value:t}]}),findFullOrganization:async({organizationId:e,isSlug:l,includeTeams:c,membersLimit:d})=>{let u=await (0,h.g)(r),f=await u.findOne({model:"organization",where:[{field:l?"slug":"id",value:e}],join:{invitation:!0,member:!d||{limit:d},...c?{team:!0}:{}}});if(!f)return null;let{invitation:p,member:m,team:y,...w}=f,b=m.map(e=>e.userId),E=new Map((b.length>0?await u.findMany({model:"user",where:[{field:"id",value:b,operator:"in"}],limit:("number"==typeof t?.membershipLimit?t.membershipLimit:100)||100}):[]).map(e=>[e.id,e])),A=m.map(e=>{let t=E.get(e.userId);if(!t)throw new i.p("Unexpected error: User not found for member");return{...(0,g.f)(e,o),user:{id:t.id,name:t.name,email:t.email,image:t.image}}}),I=(0,g.f)(w,a),T=p.map(e=>(0,g.f)(e,n)),_=y?.map(e=>(0,g.f)(e,s));return{...I,invitations:T,members:A,teams:_}},listOrganizations:async e=>{let t=await (await (0,h.g)(r)).findMany({model:"member",where:[{field:"userId",value:e}],join:{organization:!0}});return t&&0!==t.length?t.map(e=>(0,g.f)(e.organization,a)):[]},createTeam:async e=>{let{memberCount:t,...i}=await (await (0,h.g)(r)).create({model:"team",data:{...e,memberCount:0},forceAllowId:!0});return(0,g.f)(i,s)},findTeamById:async({teamId:e,organizationId:t,includeTeamMembers:i})=>{let a=await (await (0,h.g)(r)).findOne({model:"team",where:[{field:"id",value:e},...t?[{field:"organizationId",value:t}]:[]],join:{...i?{teamMember:!0}:{}}});if(!a)return null;let{teamMember:o,memberCount:n,...l}=a;return{...(0,g.f)(l,s),...i?{members:(o??[]).map(O)}:{}}},updateTeam:async(e,t)=>{let i=await (0,h.g)(r);"id"in t&&(t.id=void 0);let a=await i.update({model:"team",where:[{field:"id",value:e}],update:{...t}});if(!a)return a;let{memberCount:o,...n}=a;return(0,g.f)(n,s)},deleteTeam:async e=>{let t=await (0,h.g)(r);return await t.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await t.delete({model:"team",where:[{field:"id",value:e}]})},listTeams:async e=>(await (await (0,h.g)(r)).findMany({model:"team",where:[{field:"organizationId",value:e}]})).map(e=>{let{memberCount:t,...r}=e;return(0,g.f)(r,s)}),createTeamInvitation:async({email:e,role:t,teamId:i,organizationId:a,inviterId:o,expiresIn:n=1728e5})=>{let s=await (0,h.g)(r),l=(0,m.f)(n);return await s.create({model:"invitation",data:{email:e,role:t,organizationId:a,teamId:i,inviterId:o,status:"pending",expiresAt:l}})},setActiveTeam:async(t,r,i)=>await e.internalAdapter.updateSession(t,{activeTeamId:r}),listTeamMembers:async e=>(await (await (0,h.g)(r)).findMany({model:"teamMember",where:[{field:"teamId",value:e.teamId}]})).map(O),countTeamMembers:async e=>await (await (0,h.g)(r)).count({model:"teamMember",where:[{field:"teamId",value:e.teamId}]}),countMembers:async e=>await (await (0,h.g)(r)).count({model:"member",where:[{field:"organizationId",value:e.organizationId}]}),listTeamsByUser:async e=>(await (await (0,h.g)(r)).findMany({model:"teamMember",where:[{field:"userId",value:e.userId}],join:{team:!0}})).map(e=>{let{memberCount:t,...r}=e.team;return(0,g.f)(r,s)}),findTeamMember:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"teamMember",where:[{field:"teamId",value:e.teamId},{field:"userId",value:e.userId}]});return t?O(t):null},findOrCreateTeamMember:async e=>(0,h.n)(r,async()=>{let t=await (0,h.g)(r),i=await b(e),a=await E(t,{...e,membershipKey:i});if(a)return O(a);await A(t,e.teamId);let o=await v(t,{...e,membershipKey:i});return"created"===o.status&&await T(t,e.teamId),O(o.member)}),addTeamMemberWithLimit:async e=>(0,h.n)(r,async()=>{let t,i=await (0,h.g)(r),a=await b(e),o=await E(i,{teamId:e.teamId,userId:e.userId,membershipKey:a});if(o)return{status:"added",member:O(o)};if(await A(i,e.teamId),!await I(i,{teamId:e.teamId,maximumMembersPerTeam:e.maximumMembersPerTeam}))return{status:"limitReached"};try{t=await v(i,{teamId:e.teamId,userId:e.userId,membershipKey:a})}catch(t){throw await _(i,e.teamId,1),t}return"existing"===t.status&&await _(i,e.teamId,1),{status:"added",member:O(t.member)}}),removeTeamMember:async e=>{let t=await (0,h.g)(r),i=await t.deleteMany({model:"teamMember",where:[{field:"teamId",value:e.teamId},{field:"userId",value:e.userId}]});await _(t,e.teamId,i)},findInvitationsByTeamId:async e=>await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"teamId",value:e}]}),listUserInvitations:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"email",value:e.toLowerCase()}],join:{organization:!0}})).filter(Boolean).map(({organization:e,...t})=>({...t,organizationName:e?.name})),createInvitation:async({invitation:i,user:a})=>{let o=await (0,h.g)(r),n=(0,m.f)(t?.invitationExpiresIn||172800,"sec");return await o.create({model:"invitation",data:{...e.options.advanced?.database?.generateId===void 0&&{id:e.generateId({model:"invitation"})},status:"pending",expiresAt:n,createdAt:new Date,inviterId:a.id,...i,teamId:i.teamIds.length>0?i.teamIds.join(","):null},forceAllowId:!0})},findInvitationById:async e=>await (await (0,h.g)(r)).findOne({model:"invitation",where:[{field:"id",value:e}]}),findPendingInvitation:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"email",value:e.email.toLowerCase()},{field:"organizationId",value:e.organizationId},{field:"status",value:"pending"}]})).filter(e=>new Date(e.expiresAt)>new Date),findPendingInvitations:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"organizationId",value:e.organizationId},{field:"status",value:"pending"}]})).filter(e=>new Date(e.expiresAt)>new Date),listInvitations:async e=>await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"organizationId",value:e.organizationId}]}),updateInvitation:async e=>{let t=await (0,h.g)(r),i=[{field:"id",value:e.invitationId}];return e.fromStatus&&i.push({field:"status",value:e.fromStatus}),await t.incrementOne({model:"invitation",where:i,increment:{},set:{status:e.status}})}}};var R=e.i(90659);let x=(0,R.a)(async()=>({})),S=(0,R.a)({use:[t.Z]},async e=>({session:e.context.session})),U=(0,e.i(72823).f)({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION:"Email verification required to view or list invitations for the session email",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",YOU_ARE_NOT_ALLOWED_TO_LIST_INVITATIONS:"You are not allowed to list invitations for this organization",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role",ROLE_IS_ASSIGNED_TO_MEMBERS:"Cannot delete a role that is assigned to members. Please reassign the members to a different role first",INVALID_TEAM_ID:"Team id contains a reserved character"}),N=(e,t)=>{if(!e.permissions)return!1;let r=c(e.role),i=e.options.creatorRole||"owner",a=r.includes(i),o=e.allowCreatorAllPermissions||!1;if(a&&o)return!0;for(let i of r)if(t[i]?.authorize(e.permissions)?.success)return!0;return!1};var D=e.i(24374),L=e.i(7855);let C=L.record(L.string(),L.array(L.string())),z=(0,D.z)(()=>new WeakMap);async function j(e,t){if(!await (0,D.B)())return;let r=await z.get(),i=r.get(e.context.adapter)??new WeakMap;r.set(e.context.adapter,i);let a=i.get(t)??new Map;return i.set(t,a),a}let P=async(e,t)=>{let r={...e.options.roles||l},a=e.options.ac;if(!t||!e.organizationId||!e.options.dynamicAccessControl?.enabled||!a)return N(e,r);let o=await j(t,e.options),n=e.useMemoryCache?o?.get(e.organizationId):void 0;if(n)return N(e,n);for(let{role:o,permission:n}of(await t.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:e.organizationId}]}))){let e=JSON.parse(n),s=C.safeParse(e);if(!s.success)throw t.context.logger.error("[hasPermission] Invalid permissions for role "+o,{permissions:e}),new i.E("INTERNAL_SERVER_ERROR",{message:"Invalid permissions for role "+o});let l={...r[o]?.statements};for(let[e,t]of Object.entries(s.data))l[e]=[...new Set([...l[e]??[],...t])];r[o]=a.newRole(l)}return o?.set(e.organizationId,r),N(e,r)},B=(e,t)=>P({...e,permissions:{invitation:["create"]}},t),M=(e,t)=>{let r=t.options.creatorRole||"owner";return c(t.role).includes(r)?e:e.filter(e=>!c(e.role).includes(r))},$={string:L.string,number:L.number,boolean:L.boolean,date:L.date};function q({fields:e,isClientSide:t}){let r=Object.keys(e).reduce((r,i)=>{let a,o=e[i];return!o||t&&!1===o.input?r:(a="json"===o.type?L.json():"string[]"===o.type||"number[]"===o.type?L.array("string[]"===o.type?L.string():L.number()):Array.isArray(o.type)?L.any():$[o.type](),o?.required===!1&&(a=a.nullish()),t||o?.returned!==!1)?{...r,[i]:a}:r},{});return L.object(r)}let H=(e,t=!1)=>{let r=e?.schema?.organizationRole?.additionalFields||{};if(t)for(let e in r)r[e].required=!1;return{additionalFieldsSchema:q({fields:r,isClientSide:!0}),$AdditionalFields:{},$ReturnAdditionalFields:{}}},F=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to create the role in. If not provided, the user's active organization will be used."}),role:L.string().meta({description:"The name of the role to create"}),permission:L.record(L.string(),L.array(L.string())).meta({description:"The permission to assign to the role"})}),V=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to create the role in. If not provided, the user's active organization will be used."})}).and(L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to delete"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to delete"})})])),W=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to list roles for. If not provided, the user's active organization will be used."})}).optional(),K=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to read a role for. If not provided, the user's active organization will be used."})}).and(L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to read"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to read"})})])).optional(),G=L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to update"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to update"})})]);async function J({ac:e,ctx:t,permission:r}){let a=Object.keys(e.statements),o=Object.keys(r);if(o.some(e=>!a.includes(e)))throw t.context.logger.error("[Dynamic Access Control] The provided permission includes an invalid resource.",{providedResources:o,validResources:a}),i.E.from("BAD_REQUEST",U.INVALID_RESOURCE)}async function Q({ctx:e,permissionRequired:t,options:r,organizationId:a,member:o,user:n,action:s}){let l=[];for await(let[i,n]of Object.entries(t))for await(let t of n)l.push({resource:{[i]:[t]},hasPermission:await P({options:r,organizationId:a,permissions:{[i]:[t]},useMemoryCache:!0,role:o.role},e)});let c=l.filter(e=>!1===e.hasPermission).map(e=>{let t=Object.keys(e.resource)[0];return`${t}:${e.resource[t][0]}`});if(c.length>0){let t;throw e.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${s} a role with those set of permissions.
|
|
480
|
-
`,{userId:n.id,organizationId:a,role:o.role,missingPermissions:c}),t="create"===s?U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"update"===s?U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"delete"===s?U.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"read"===s?U.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"list"===s?U.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:U.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE,i.E.fromStatus("FORBIDDEN",{message:t.message,code:t.code,missingPermissions:c})}}async function Y({options:e,organizationId:t,role:r,ctx:a}){let o=e.roles?Object.keys(e.roles):["owner","admin","member"];if(o.includes(r))throw a.context.logger.error(`[Dynamic Access Control] The role name "${r}" is already taken by a pre-defined role.`,{role:r,organizationId:t,defaultRoles:o}),i.E.from("BAD_REQUEST",U.ROLE_NAME_IS_ALREADY_TAKEN)}async function Z({organizationId:e,role:t,ctx:r}){if(await r.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:e,operator:"eq",connector:"AND"},{field:"role",value:t,operator:"eq",connector:"AND"}]}))throw r.context.logger.error(`[Dynamic Access Control] The role name "${t}" is already taken by a role in the database.`,{role:t,organizationId:e}),i.E.from("BAD_REQUEST",U.ROLE_NAME_IS_ALREADY_TAKEN)}var X=e.i(70728),ee=e.i(10228);let et=L.object({email:L.string().meta({description:"The email address of the user to invite"}),role:L.union([L.string().meta({description:"The role to assign to the user"}),L.array(L.string().meta({description:"The roles to assign to the user"}))]).meta({description:'The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: "member"'}),organizationId:L.string().meta({description:"The organization ID to invite the user to"}).optional(),resend:L.boolean().meta({description:"Resend the invitation email, if the user is already invited. Eg: true"}).optional(),teamId:L.union([L.string().meta({description:"The team ID to invite the user to"}).optional(),L.array(L.string()).meta({description:"The team IDs to invite the user to"}).optional()])}),er=e=>{if("object"!=typeof e||null===e)return;let t=e.generateId;if("function"==typeof t)return t},ei=({organizationOptions:e,advancedGenerateId:t,databaseGenerateId:r})=>void 0!==e.requireEmailVerificationOnInvitation?e.requireEmailVerificationOnInvitation:!(({advancedGenerateId:e,databaseGenerateId:t})=>void 0===e&&(void 0===t||"uuid"===t))({advancedGenerateId:t,databaseGenerateId:r}),ea=L.object({invitationId:L.string().meta({description:"The ID of the invitation to accept"})}),eo=L.object({invitationId:L.string().meta({description:"The ID of the invitation to reject"})}),en=L.object({invitationId:L.string().meta({description:"The ID of the invitation to cancel"})}),es=L.object({id:L.string().meta({description:"The ID of the invitation to get"})}),el=L.object({organizationId:L.string().meta({description:"The ID of the organization to list invitations for"}).optional()}).optional();e.i(67200),e.i(24891),e.i(82868),e.i(26388),e.i(46378),e.i(31139),e.i(4383),e.i(71928);let ec=["eq","ne","lt","lte","gt","gte","in","not_in","contains","starts_with","ends_with"];var ed=e.i(54257);let eu=L.object({userId:ed.f.string().meta({description:'The ID of the user to add as a member. Eg: "user-id"'}),role:L.union([L.string(),L.array(L.string())]).meta({description:'The role(s) to assign to the new member. Eg: ["admin", "sale"]'}),organizationId:L.string().meta({description:'An optional organization ID to pass. If not provided, will default to the user\'s active organization. Eg: "org-id"'}).optional(),teamId:L.string().meta({description:'An optional team ID to add the member to. Eg: "team-id"'}).optional()}),ef=L.object({memberIdOrEmail:L.string().meta({description:"The ID or email of the member to remove"}),organizationId:L.string().meta({description:'The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: "org-id"'}).optional()}),ep=L.object({role:L.union([L.string(),L.array(L.string())]).meta({description:'The new role to be applied. This can be a string or array of strings representing the roles. Eg: ["admin", "sale"]'}),memberId:L.string().meta({description:'The member id to apply the role update to. Eg: "member-id"'}),organizationId:L.string().meta({description:'An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: "organization-id"'}).optional()}),em=L.object({organizationId:L.string().meta({description:'The organization Id for the member to leave. Eg: "organization-id"'})}),eh=L.object({userId:L.string().meta({description:"The user ID to get the role for. If not provided, will default to the current user's"}).optional(),organizationId:L.string().meta({description:'The organization ID to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-id"'}).optional(),organizationSlug:L.string().meta({description:'The organization slug to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-slug"'}).optional()}).optional(),eg=L.object({name:L.string().min(1).meta({description:"The name of the organization"}),slug:L.string().min(1).meta({description:"The slug of the organization"}),userId:ed.f.string().meta({description:'The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: "user-id"'}).optional(),logo:L.string().meta({description:"The logo of the organization"}).nullish(),metadata:L.record(L.string(),L.any()).meta({description:"The metadata of the organization"}).optional(),keepCurrentActiveOrganization:L.boolean().meta({description:"Whether to keep the current active organization active after creating a new one. Eg: true"}).optional()}),ey=L.object({slug:L.string().meta({description:'The organization slug to check. Eg: "my-org"'})}),ew=L.object({name:L.string().min(1).meta({description:"The name of the organization"}).optional(),slug:L.string().min(1).meta({description:"The slug of the organization"}).optional(),logo:L.string().meta({description:"The logo of the organization"}).nullish(),metadata:L.record(L.string(),L.any()).meta({description:"The metadata of the organization"}).optional()}),eb=L.object({organizationId:L.string().meta({description:"The organization id to delete"})}),eE=L.optional(L.object({organizationId:L.string().meta({description:"The organization id to get"}).optional(),organizationSlug:L.string().meta({description:"The organization slug to get"}).optional()})),eA=L.optional(L.object({organizationId:L.string().meta({description:"The organization id to get"}).optional(),organizationSlug:L.string().meta({description:"The organization slug to get"}).optional(),membersLimit:L.number().or(L.string().transform(e=>parseInt(e))).meta({description:"The limit of members to get. By default, it uses the membershipLimit option."}).optional()})),eI=L.object({organizationId:L.string().meta({description:'The organization id to set as active. It can be null to unset the active organization. Eg: "org-id"'}).nullable().optional(),organizationSlug:L.string().meta({description:'The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: "org-slug"'}).optional()});var eT=e.i(18195);let e_=L.string(),ev=L.enum(["pending","accepted","rejected","canceled"]).default("pending");L.object({id:L.string().default(eT.f),name:L.string(),slug:L.string(),logo:L.string().nullish().optional(),metadata:L.record(L.string(),L.unknown()).or(L.string().transform(e=>JSON.parse(e))).optional(),createdAt:L.date()}),L.object({id:L.string().default(eT.f),organizationId:L.string(),userId:ed.f.string(),role:e_,createdAt:L.date().default(()=>new Date)}),L.object({id:L.string().default(eT.f),organizationId:L.string(),email:L.string(),role:e_,status:ev,teamId:L.string().nullish(),inviterId:L.string(),expiresAt:L.date(),createdAt:L.date().default(()=>new Date)});let eO=L.object({id:L.string().default(eT.f),name:L.string().min(1),organizationId:L.string(),createdAt:L.date(),updatedAt:L.date().optional()});L.object({id:L.string().default(eT.f),teamId:L.string(),userId:L.string(),createdAt:L.date().default(()=>new Date)}),L.object({id:L.string().default(eT.f),organizationId:L.string(),role:L.string(),permission:L.record(L.string(),L.array(L.string())),createdAt:L.date().default(()=>new Date),updatedAt:L.date().optional()});let ek=["admin","member","owner"];L.union([L.enum(ek),L.array(L.enum(ek))]);let eR=L.object({name:L.string().meta({description:'The name of the team. Eg: "my-team"'}),organizationId:L.string().meta({description:'The organization ID which the team will be created in. Defaults to the active organization. Eg: "organization-id"'}).optional()}),ex=L.object({teamId:L.string().meta({description:'The team ID of the team to remove. Eg: "team-id"'}),organizationId:L.string().meta({description:'The organization ID which the team falls under. If not provided, it will default to the user\'s active organization. Eg: "organization-id"'}).optional()}),eS=L.optional(L.object({organizationId:L.string().meta({description:'The organization ID which the teams are under to list. Defaults to the users active organization. Eg: "organization-id"'}).optional()})),eU=L.object({teamId:L.string().meta({description:"The team id to set as active. It can be null to unset the active team"}).nullable().optional()}),eN=L.optional(L.object({teamId:L.string().optional().meta({description:"The team whose members we should return. If this is not provided the members of the current active team get returned."})})),eD=L.object({teamId:L.string().meta({description:"The team the user should be a member of."}),userId:ed.f.string().meta({description:"The user Id which represents the user to be added as a member."}),organizationId:L.string().meta({description:"The organization ID which the team falls under. If not provided, it will default to the user's active organization."}).optional()}),eL=L.object({teamId:L.string().meta({description:"The team the user should be removed from."}),userId:ed.f.string().meta({description:"The user which should be removed from the team."}),organizationId:L.string().meta({description:"The organization ID which the team falls under. If not provided, it will default to the user's active organization."}).optional()}),eC=L.object({organizationId:L.string().optional()}).and(L.xor([L.object({permission:L.record(L.string(),L.array(L.string()))}),L.object({permissions:L.record(L.string(),L.array(L.string()))})]));e.s(["f",0,function(e){let a,o,n,s,u,f,p=e||{},g={createOrganization:(a=q({fields:p?.schema?.organization?.additionalFields||{},isClientSide:!0}),(0,R.g)("/organization/create",{method:"POST",body:L.object({...eg.shape,...a.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r,a=await (0,t.D)(e);if(!a&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");let o=a?.user||null;if(!o){if(!e.body.userId)throw i.E.fromStatus("UNAUTHORIZED");o=await e.context.internalAdapter.findUserById(e.body.userId)}if(!o)throw i.E.fromStatus("UNAUTHORIZED");let n=e.context.orgOptions,s="function"==typeof n?.allowUserToCreateOrganization?await n.allowUserToCreateOrganization(o):n?.allowUserToCreateOrganization===void 0||n.allowUserToCreateOrganization,l=!a&&e.body.userId;if(!s&&!l)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION);let c=k(e.context,n),d=await c.listOrganizations(o.id);if("number"==typeof n.organizationLimit?d.length>=n.organizationLimit:"function"==typeof n.organizationLimit&&await n.organizationLimit(o))throw i.E.from("FORBIDDEN",U.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS);if(await c.findOrganizationBySlug(e.body.slug))throw i.E.from("BAD_REQUEST",U.ORGANIZATION_ALREADY_EXISTS);let{keepCurrentActiveOrganization:u,userId:f,...p}=e.body;if(n?.organizationHooks?.beforeCreateOrganization){let t=await n?.organizationHooks.beforeCreateOrganization({organization:p,user:o});t&&"object"==typeof t&&"data"in t&&(p={...e.body,...t.data})}let m=await c.createOrganization({organization:{...p,createdAt:new Date}}),h=null,g={userId:o.id,organizationId:m.id,role:e.context.orgOptions.creatorRole||"owner"};if(n?.organizationHooks?.beforeAddMember){let t=await n?.organizationHooks.beforeAddMember({member:{userId:o.id,organizationId:m.id,role:e.context.orgOptions.creatorRole||"owner"},user:o,organization:m});t&&"object"==typeof t&&"data"in t&&(g={...g,...t.data})}if(r=await c.createMember(g),n?.organizationHooks?.afterAddMember&&await n?.organizationHooks.afterAddMember({member:r,user:o,organization:m}),n?.teams?.enabled&&n.teams.defaultTeam?.enabled!==!1){let t={organizationId:m.id,name:`${m.name}`,createdAt:new Date};if(n?.organizationHooks?.beforeCreateTeam){let e=await n?.organizationHooks.beforeCreateTeam({team:{organizationId:m.id,name:`${m.name}`},user:o,organization:m});e&&"object"==typeof e&&"data"in e&&(t={...t,...e.data})}let r=await n.teams.defaultTeam?.customCreateDefaultTeam?.(m,e)||await c.createTeam(t);h=await c.findOrCreateTeamMember({teamId:r.id,userId:o.id}),n?.organizationHooks?.afterCreateTeam&&await n?.organizationHooks.afterCreateTeam({team:r,user:o,organization:m})}return n?.organizationHooks?.afterCreateOrganization&&await n?.organizationHooks.afterCreateOrganization({organization:m,user:o,member:r}),e.context.session&&!e.body.keepCurrentActiveOrganization&&await c.setActiveOrganization(e.context.session.session.token,m.id,e),h&&e.context.session&&!e.body.keepCurrentActiveOrganization&&await c.setActiveTeam(e.context.session.session.token,h.teamId,e),e.json({...m,metadata:m.metadata&&"string"==typeof m.metadata?JSON.parse(m.metadata):m.metadata,members:[r]})})),updateOrganization:(o=q({fields:p?.schema?.organization?.additionalFields||{},isClientSide:!0}),(0,R.g)("/organization/update",{method:"POST",body:L.object({data:L.object({...o.shape,...ew.shape}).partial(),organizationId:L.string().meta({description:'The organization ID. Eg: "org-id"'}).optional()}),requireHeaders:!0,use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw i.E.fromStatus("UNAUTHORIZED",{message:"User not found"});let r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=k(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({permissions:{organization:["update"]},role:o.role,options:e.context.orgOptions,organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION);if("string"==typeof e.body.data.slug){let t=await a.findOrganizationBySlug(e.body.data.slug);if(t&&t.id!==r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_SLUG_ALREADY_TAKEN)}if(p?.organizationHooks?.beforeUpdateOrganization){let r=await p.organizationHooks.beforeUpdateOrganization({organization:e.body.data,user:t.user,member:o});r&&"object"==typeof r&&"data"in r&&(e.body.data={...e.body.data,...r.data})}let n=await a.updateOrganization(r,e.body.data);return p?.organizationHooks?.afterUpdateOrganization&&await p.organizationHooks.afterUpdateOrganization({organization:n,user:t.user,member:o}),e.json(n)})),deleteOrganization:(0,R.g)("/organization/delete",{method:"POST",body:eb,requireHeaders:!0,use:[x],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{if(e.context.orgOptions.disableOrganizationDeletion)throw i.E.from("NOT_FOUND",{message:"Organization deletion is disabled",code:"ORGANIZATION_DELETION_DISABLED"});let t=await e.context.getSession(e);if(!t)throw i.E.fromStatus("UNAUTHORIZED");let r=e.body.organizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=k(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:o.role,permissions:{organization:["delete"]},organizationId:r,options:e.context.orgOptions},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION);let n=await a.findOrganizationById(r);if(!n)throw i.E.fromStatus("BAD_REQUEST");return p?.organizationHooks?.beforeDeleteOrganization&&await p.organizationHooks.beforeDeleteOrganization({organization:n,user:t.user},e),await a.deleteOrganization(r),r===t.session.activeOrganizationId&&await a.setActiveOrganization(t.session.token,null,e),p?.organizationHooks?.afterDeleteOrganization&&await p.organizationHooks.afterDeleteOrganization({organization:n,user:t.user},e),e.json(n)}),setActiveOrganization:(0,R.g)("/organization/set-active",{method:"POST",body:eI,use:[S,x],requireHeaders:!0,metadata:{openapi:{operationId:"setActiveOrganization",description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=k(e.context,p),r=e.context.session,a=e.body.organizationId,o=e.body.organizationSlug;if(null===a){if(!r.session.activeOrganizationId)return e.json(null);let i=await t.setActiveOrganization(r.session.token,null,e);return await (0,X.V)(e,{session:i,user:r.user}),e.json(null)}if(!a&&!o){let t=r.session.activeOrganizationId;if(!t)return e.json(null);a=t}if(o&&!a){let e=await t.findOrganizationBySlug(o);if(!e)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);a=e.id}if(!a)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(!await t.checkMembership({userId:r.user.id,organizationId:a}))throw await t.setActiveOrganization(r.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let n=await t.findOrganizationById(a);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let s=await t.setActiveOrganization(r.session.token,n.id,e);return await (0,X.V)(e,{session:s,user:r.user}),e.json(n)}),getOrganization:(0,R.g)("/organization/get-organization",{method:"GET",query:eE,requireHeaders:!0,use:[x,S],metadata:{openapi:{operationId:"getOrganization",description:"Get the organization metadata",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,r=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let a=k(e.context,p),o=e.query?.organizationSlug?await a.findOrganizationBySlug(r):await a.findOrganizationById(r);if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(!await a.checkMembership({userId:t.user.id,organizationId:o.id}))throw await a.setActiveOrganization(t.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);return e.json(o)}),getFullOrganization:(0,R.g)("/organization/get-full-organization",{method:"GET",query:eA,requireHeaders:!0,use:[x,S],metadata:{openapi:{operationId:"getFullOrganization",description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,r=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let a=k(e.context,p),o=await a.findFullOrganization({organizationId:r,isSlug:!!e.query?.organizationSlug,includeTeams:e.context.orgOptions.teams?.enabled,membersLimit:e.query?.membersLimit});if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let n=await a.checkMembership({userId:t.user.id,organizationId:o.id});if(!n)throw await a.setActiveOrganization(t.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);return o.invitations=o.invitations.length>0&&await B({role:n.role,options:e.context.orgOptions,organizationId:o.id},e)?M(o.invitations,{role:n.role,options:e.context.orgOptions}):[],e.json(o)}),listOrganizations:(0,R.g)("/organization/list",{method:"GET",use:[x,S],requireHeaders:!0,metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await k(e.context,p).listOrganizations(e.context.session.user.id);return e.json(t)}),createInvitation:(n=q({fields:p?.schema?.invitation?.additionalFields||{},isClientSide:!0}),(0,R.g)("/organization/invite-member",{method:"POST",requireHeaders:!0,use:[x,S],body:L.object({...et.shape,...n.shape}),metadata:{$Infer:{body:{}},openapi:{operationId:"createOrganizationInvitation",description:"Create an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},createdAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","createdAt"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=e.body.email.toLowerCase();if(!L.email().safeParse(a).success)throw i.E.from("BAD_REQUEST",ee.f.INVALID_EMAIL);let o=k(e.context,p),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{invitation:["create"]},organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);let s=e.context.orgOptions.creatorRole||"owner",u=c(e.body.role);if(0===u.length)throw i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let f=d(u),h=new Set([...Object.keys(l),...Object.keys(e.context.orgOptions.roles||{})]),g=u.filter(e=>!h.has(e));if(g.length>0)if(e.context.orgOptions.dynamicAccessControl?.enabled){let t=(await e.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:r},{field:"role",value:g,operator:"in"}]})).map(e=>e.role),a=g.filter(e=>!t.includes(e));if(a.length>0)throw new i.E("BAD_REQUEST",{message:`${U.ROLE_NOT_FOUND}: ${a.join(", ")}`})}else throw new i.E("BAD_REQUEST",{message:`${U.ROLE_NOT_FOUND}: ${g.join(", ")}`});if(!c(n.role).includes(s)&&u.includes(s))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);if(await o.findMemberByEmail({email:a,organizationId:r}))throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);let y=await o.findPendingInvitation({email:a,organizationId:r});if(y.length&&!e.body.resend&&!e.context.orgOptions.cancelPendingInvitationsOnReInvite)throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION);let w=await o.findOrganizationById(r);if(!w)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let b=y[0];if(b&&e.body.resend){if(!c(n.role).includes(s)&&c(b.role).includes(s))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);let r=(0,m.f)(e.context.orgOptions.invitationExpiresIn||172800,"sec");await e.context.adapter.update({model:"invitation",where:[{field:"id",value:b.id}],update:{expiresAt:r}});let a={...b,expiresAt:r};return e.context.orgOptions.sendInvitationEmail&&await e.context.runInBackgroundOrAwait(e.context.orgOptions.sendInvitationEmail({id:a.id,role:a.role,email:a.email.toLowerCase(),organization:w,inviter:{...n,user:t.user},invitation:a},e.request)),e.json(a)}y.length&&e.context.orgOptions.cancelPendingInvitationsOnReInvite&&await o.updateInvitation({invitationId:y[0].id,status:"canceled"});let E="function"==typeof e.context.orgOptions.invitationLimit?await e.context.orgOptions.invitationLimit({user:t.user,organization:w,member:n},e.context):e.context.orgOptions.invitationLimit??100;if((await o.findPendingInvitations({organizationId:r})).length>=E)throw i.E.from("FORBIDDEN",U.INVITATION_LIMIT_REACHED);if(e.context.orgOptions.teams?.enabled&&"teamId"in e.body&&e.body.teamId){let t="string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId;if(t.some(e=>e.includes(",")))throw i.E.from("BAD_REQUEST",U.INVALID_TEAM_ID);for(let e of t)if(!await o.findTeamById({teamId:e,organizationId:r}))throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND)}if(e.context.orgOptions.teams&&e.context.orgOptions.teams.enabled&&void 0!==e.context.orgOptions.teams.maximumMembersPerTeam&&"teamId"in e.body&&e.body.teamId)for(let a of"string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId){let n=await o.findTeamById({teamId:a,organizationId:r,includeTeamMembers:!0});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let s="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:a,session:t,organizationId:r}):e.context.orgOptions.teams.maximumMembersPerTeam;if(n.members.length>=s)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}let A="teamId"in e.body?"string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId??[]:[],{email:I,role:T,organizationId:_,resend:v,...O}=e.body,R={role:f,email:a,organizationId:r,teamIds:A,...O||{}};if(p?.organizationHooks?.beforeCreateInvitation){let e=await p?.organizationHooks.beforeCreateInvitation({invitation:{...R,inviterId:t.user.id,teamId:A.length>0?A[0]:void 0},inviter:t.user,organization:w});e&&"object"==typeof e&&"data"in e&&(R={...R,...e.data})}let x=await o.createInvitation({invitation:R,user:t.user});return e.context.orgOptions.sendInvitationEmail&&await e.context.runInBackgroundOrAwait(e.context.orgOptions.sendInvitationEmail({id:x.id,role:x.role,email:x.email.toLowerCase(),organization:w,inviter:{...n,user:t.user},invitation:x},e.request)),p?.organizationHooks?.afterCreateInvitation&&await p?.organizationHooks.afterCreateInvitation({invitation:x,inviter:t.user,organization:w}),e.json(x)})),cancelInvitation:(0,R.g)("/organization/cancel-invitation",{method:"POST",body:en,requireHeaders:!0,use:[x,S],openapi:{operationId:"cancelOrganizationInvitation",description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,r=k(e.context,p),a=await r.findInvitationById(e.body.invitationId);if(!a)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:a.organizationId});if(!o)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{invitation:["cancel"]},organizationId:a.organizationId},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION);let n=await r.findOrganizationById(a.organizationId);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);p?.organizationHooks?.beforeCancelInvitation&&await p?.organizationHooks.beforeCancelInvitation({invitation:a,cancelledBy:t.user,organization:n});let s=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return p?.organizationHooks?.afterCancelInvitation&&await p?.organizationHooks.afterCancelInvitation({invitation:s||a,cancelledBy:t.user,organization:n}),e.json(s)}),acceptInvitation:(0,R.g)("/organization/accept-invitation",{method:"POST",body:ea,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,r=k(e.context,p),a=await r.findInvitationById(e.body.invitationId);if(!a||a.expiresAt<new Date||"pending"!==a.status)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);if(a.email.toLowerCase()!==t.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!t.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);let o=e.context.orgOptions?.membershipLimit||100,n=await r.countMembers({organizationId:a.organizationId}),s=await r.findOrganizationById(a.organizationId);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(n>=("number"==typeof o?o:await o(t.user,s)))throw i.E.from("FORBIDDEN",U.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);p?.organizationHooks?.beforeAcceptInvitation&&await p?.organizationHooks.beforeAcceptInvitation({invitation:a,user:t.user,organization:s});let l=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted",fromStatus:"pending"});if(!l)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);let c=await (0,h.n)(e.context.adapter,async()=>{if(e.context.orgOptions.teams&&e.context.orgOptions.teams.enabled&&"teamId"in l&&l.teamId){let a=l.teamId.split(","),o=1===a.length;for(let o of a){if(!await r.findTeamById({teamId:o,organizationId:l.organizationId}))throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(void 0!==e.context.orgOptions.teams.maximumMembersPerTeam){let a="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:o,session:t,organizationId:l.organizationId}):e.context.orgOptions.teams.maximumMembersPerTeam;if("limitReached"===(await r.addTeamMemberWithLimit({teamId:o,userId:t.user.id,maximumMembersPerTeam:a})).status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}else await r.findOrCreateTeamMember({teamId:o,userId:t.user.id})}if(o){let i=a[0],o=await r.setActiveTeam(t.session.token,i,e);await (0,X.V)(e,{session:o,user:t.user})}}let a=await r.createMember({organizationId:l.organizationId,userId:t.user.id,role:d(l.role),createdAt:new Date});return await r.setActiveOrganization(t.session.token,l.organizationId,e),a}).catch(async t=>{throw await r.updateInvitation({invitationId:e.body.invitationId,status:"pending",fromStatus:"accepted"}),t});return p?.organizationHooks?.afterAcceptInvitation&&await p?.organizationHooks.afterAcceptInvitation({invitation:l,member:c,user:t.user,organization:s}),e.json({invitation:l,member:c})}),getInvitation:(0,R.g)("/organization/get-invitation",{method:"GET",use:[x],requireHeaders:!0,query:es,metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let r=await (0,t.D)(e);if(!r)throw i.E.fromStatus("UNAUTHORIZED",{message:"Not authenticated"});let a=k(e.context,p),o=await a.findInvitationById(e.query.id);if(!o||"pending"!==o.status||o.expiresAt<new Date)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);if(o.email.toLowerCase()!==r.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!r.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION);let n=await a.findOrganizationById(o.organizationId);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let s=await a.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!s)throw i.E.from("BAD_REQUEST",U.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION);return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:s.user.email})}),rejectInvitation:(0,R.g)("/organization/reject-invitation",{method:"POST",body:eo,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object",nullable:!0}}}}}}}}}},async e=>{let t=e.context.session,r=k(e.context,e.context.orgOptions),a=await r.findInvitationById(e.body.invitationId);if(!a||"pending"!==a.status)throw i.E.from("BAD_REQUEST",{message:"Invitation not found!",code:"INVITATION_NOT_FOUND"});if(a.email.toLowerCase()!==t.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!t.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);let o=await r.findOrganizationById(a.organizationId);if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);p?.organizationHooks?.beforeRejectInvitation&&await p?.organizationHooks.beforeRejectInvitation({invitation:a,user:t.user,organization:o});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return p?.organizationHooks?.afterRejectInvitation&&await p?.organizationHooks.afterRejectInvitation({invitation:n||a,user:t.user,organization:o}),e.json({invitation:n,member:null})}),listInvitations:(0,R.g)("/organization/list-invitations",{method:"GET",requireHeaders:!0,use:[x,S],query:el},async e=>{let r=await (0,t.D)(e);if(!r)throw i.E.fromStatus("UNAUTHORIZED",{message:"Not authenticated"});let a=e.query?.organizationId||r.session.activeOrganizationId;if(!a)throw i.E.fromStatus("BAD_REQUEST",{message:"Organization ID is required"});let o=k(e.context,p),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!n)throw i.E.fromStatus("FORBIDDEN",{message:"You are not a member of this organization"});if(!await B({role:n.role,options:e.context.orgOptions,organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_LIST_INVITATIONS);let s=await o.listInvitations({organizationId:a});return e.json(M(s,{role:n.role,options:e.context.orgOptions}))}),getActiveMember:(0,R.g)("/organization/get-active-member",{method:"GET",use:[x,S],requireHeaders:!0,metadata:{openapi:{description:"Get the member details of the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,r=t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=await k(e.context,p).findMemberByOrgId({userId:t.user.id,organizationId:r});if(!a)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return e.json(a)}),checkOrganizationSlug:(0,R.g)("/organization/check-slug",{method:"POST",body:ey,use:[t.b,x]},async e=>{if(!await k(e.context,p).findOrganizationBySlug(e.body.slug))return e.json({status:!0});throw i.E.from("BAD_REQUEST",U.ORGANIZATION_SLUG_ALREADY_TAKEN)}),addMember:(s=q({fields:p?.schema?.member?.additionalFields||{},isClientSide:!0}),(0,R.g)({method:"POST",body:L.object({...eu.shape,...s.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{operationId:"addOrganizationMember",description:"Add a member to an organization"}}},async e=>{let r=e.body.userId?await (0,t.D)(e).catch(e=>null):null,a=e.body.organizationId||r?.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o="teamId"in e.body?e.body.teamId:void 0;if(o&&!e.context.orgOptions.teams?.enabled)throw e.context.logger.error("Teams are not enabled"),i.E.fromStatus("BAD_REQUEST",{message:"Teams are not enabled"});let n=k(e.context,p),s=await e.context.internalAdapter.findUserById(e.body.userId);if(!s)throw i.E.from("BAD_REQUEST",ee.f.USER_NOT_FOUND);if(await n.findMemberByEmail({email:s.email,organizationId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);if(o){let e=await n.findTeamById({teamId:o,organizationId:a});if(!e||e.organizationId!==a)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND)}let l=e.context.orgOptions?.membershipLimit||100,c=await n.countMembers({organizationId:a}),u=await n.findOrganizationById(a);if(!u)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(c>=("number"==typeof l?l:await l(s,u)))throw i.E.from("FORBIDDEN",U.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);let{role:f,userId:m,organizationId:h,...g}=e.body,y={organizationId:a,userId:s.id,role:d(e.body.role),createdAt:new Date,...g||{}};if(p?.organizationHooks?.beforeAddMember){let t=await p?.organizationHooks.beforeAddMember({member:{userId:s.id,organizationId:a,role:d(e.body.role),...g},user:s,organization:u});t&&"object"==typeof t&&"data"in t&&(y={...y,...t.data})}let w=await n.createMember(y);if(o)try{if(void 0!==e.context.orgOptions.teams?.maximumMembersPerTeam){let t,l=e.context.orgOptions.teams.maximumMembersPerTeam;if("function"==typeof l){if(!r)throw i.E.fromStatus("UNAUTHORIZED");t=await l({teamId:o,session:{user:r.user,session:r.session},organizationId:a})}else t=l;if("limitReached"===(await n.addTeamMemberWithLimit({userId:s.id,teamId:o,maximumMembersPerTeam:t})).status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}else await n.findOrCreateTeamMember({userId:s.id,teamId:o})}catch(e){throw await n.deleteMember({memberId:w.id,organizationId:a,userId:s.id}),e}return p?.organizationHooks?.afterAddMember&&await p?.organizationHooks.afterAddMember({member:w,user:s,organization:u}),e.json(w)})),removeMember:(0,R.g)("/organization/remove-member",{method:"POST",body:ef,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=k(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let n=null;if(e.body.memberIdOrEmail.includes("@"))n=await a.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r});else{let t=await a.findMemberById(e.body.memberIdOrEmail);if(t){let{user:e,...r}=t;n=r}else n=null}if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let s=c(n.role),l=e.context.orgOptions?.creatorRole||"owner";if(s.includes(l)){if(!c(o.role).includes(l))throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);let{members:e}=await a.listMembers({organizationId:r});if(e.filter(e=>c(e.role).includes(l)).length<=1)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER)}if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["delete"]},organizationId:r},e))throw i.E.from("UNAUTHORIZED",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER);if(n?.organizationId!==r)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let d=await a.findOrganizationById(r);if(!d)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let u=await e.context.internalAdapter.findUserById(n.userId);if(!u)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});return p?.organizationHooks?.beforeRemoveMember&&await p?.organizationHooks.beforeRemoveMember({member:n,user:u,organization:d}),await a.deleteMember({memberId:n.id,organizationId:r,userId:n.userId}),t.user.id===n.userId&&t.session.activeOrganizationId===n.organizationId&&await a.setActiveOrganization(t.session.token,null,e),p?.organizationHooks?.afterRemoveMember&&await p?.organizationHooks.afterRemoveMember({member:n,user:u,organization:d}),e.json({member:n})}),updateMemberRole:(0,R.g)("/organization/update-member-role",{method:"POST",body:ep,use:[x,S],requireHeaders:!0,metadata:{$Infer:{body:{}},openapi:{operationId:"updateOrganizationMemberRole",description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session;if(!e.body.role)throw i.E.fromStatus("BAD_REQUEST");let r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=k(e.context,e.context.orgOptions),o=c(e.body.role);if(0===o.length)throw i.E.fromStatus("BAD_REQUEST");let n=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let s=n.id!==e.body.memberId?await a.findMemberById(e.body.memberId):n;if(!s)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(s.organizationId!==r)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);let u=e.context.orgOptions?.creatorRole||"owner",f=c(n.role),m=c(s.role).includes(u),h=f.includes(u),g=o.includes(u),y=n.id===s.id;if(m&&!h||g&&!h)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);if(h&&y&&(await e.context.adapter.findMany({model:"member",where:[{field:"organizationId",value:r}]})).filter(e=>c(e.role).includes(u)).length<=1&&!g)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{member:["update"]},allowCreatorAllPermissions:!0,organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);let w=new Set([...Object.keys(l),...Object.keys(e.context.orgOptions.roles||{})]),b=o.filter(e=>!w.has(e));if(b.length>0)if(e.context.orgOptions.dynamicAccessControl?.enabled){let t=(await e.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:r},{field:"role",value:b,operator:"in"}]})).map(e=>e.role),a=b.filter(e=>!t.includes(e));if(a.length>0)throw new i.E("BAD_REQUEST",{code:U.ROLE_NOT_FOUND.code,message:`${U.ROLE_NOT_FOUND.code}: ${a.join(", ")}`})}else throw new i.E("BAD_REQUEST",{code:U.ROLE_NOT_FOUND.code,message:`${U.ROLE_NOT_FOUND.code}: ${b.join(", ")}`});let E=await a.findOrganizationById(r);if(!E)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let A=await e.context.internalAdapter.findUserById(s.userId);if(!A)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});let I=s.role,T=d(o);if(p?.organizationHooks?.beforeUpdateMemberRole){let t=await p?.organizationHooks.beforeUpdateMemberRole({member:s,newRole:T,user:A,organization:E});if(t&&"object"==typeof t&&"data"in t){let r=await a.updateMember(e.body.memberId,t.data.role||T);if(!r)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return p?.organizationHooks?.afterUpdateMemberRole&&await p?.organizationHooks.afterUpdateMemberRole({member:r,previousRole:I,user:A,organization:E}),e.json(r)}}let _=await a.updateMember(e.body.memberId,T);if(!_)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return p?.organizationHooks?.afterUpdateMemberRole&&await p?.organizationHooks.afterUpdateMemberRole({member:_,previousRole:I,user:A,organization:E}),e.json(_)}),leaveOrganization:(0,R.g)("/organization/leave",{method:"POST",body:em,requireHeaders:!0,use:[t.Z,x]},async e=>{let t=e.context.session,r=k(e.context,p),a=await r.findMemberByOrgId({userId:t.user.id,organizationId:e.body.organizationId});if(!a)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let o=e.context.orgOptions?.creatorRole||"owner";if(c(a.role).includes(o)&&(await e.context.adapter.findMany({model:"member",where:[{field:"organizationId",value:e.body.organizationId}]})).filter(e=>c(e.role).includes(o)).length<=1)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);return await r.deleteMember({memberId:a.id,organizationId:e.body.organizationId,userId:t.user.id}),t.session.activeOrganizationId===e.body.organizationId&&await r.setActiveOrganization(t.session.token,null,e),e.json(a)}),listUserInvitations:(0,R.g)("/organization/list-user-invitations",{method:"GET",use:[x],query:L.object({email:L.string().meta({description:"The email of the user to list invitations for. This only works for server side API calls."}).optional()}).optional(),metadata:{openapi:{description:"List all invitations a user has received",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},organizationName:{type:"string"},inviterId:{type:"string",description:"The ID of the user who created the invitation"},teamId:{type:"string",description:"The ID of the team associated with the invitation",nullable:!0},status:{type:"string"},expiresAt:{type:"string"},createdAt:{type:"string"}},required:["id","email","role","organizationId","organizationName","inviterId","status","expiresAt","createdAt"]}}}}}}}}},async e=>{let r=await (0,t.D)(e);if(e.request&&e.query?.email)throw i.E.fromStatus("BAD_REQUEST",{message:"User email cannot be passed for client side API calls."});if(r&&!r.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION);let a=r?.user.email||e.query?.email;if(!a)throw i.E.fromStatus("BAD_REQUEST",{message:"Missing session headers, or email query parameter."});let o=(await k(e.context,p).listUserInvitations(a)).filter(e=>"pending"===e.status);return e.json(o)}),listMembers:(0,R.g)("/organization/list-members",{method:"GET",query:L.object({limit:L.string().meta({description:"The number of users to return"}).or(L.number()).optional(),offset:L.string().meta({description:"The offset to start from"}).or(L.number()).optional(),sortBy:L.string().meta({description:"The field to sort by"}).optional(),sortDirection:L.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:L.string().meta({description:"The field to filter by"}).optional(),filterValue:L.string().meta({description:"The value to filter by"}).or(L.number()).or(L.boolean()).or(L.array(L.string())).or(L.array(L.number())).optional(),filterOperator:L.enum(ec).meta({description:"The operator to use for the filter"}).optional(),organizationId:L.string().meta({description:'The organization ID to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-id"'}).optional(),organizationSlug:L.string().meta({description:'The organization slug to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-slug"'}).optional()}).optional(),requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t.session.activeOrganizationId,a=k(e.context,p);if(e.query?.organizationSlug){let t=await a.findOrganizationBySlug(e.query?.organizationSlug);if(!t)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);r=t.id}if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);if(!await a.findMemberByOrgId({userId:t.user.id,organizationId:r}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);let{members:o,total:n}=await a.listMembers({organizationId:r,limit:e.query?.limit?Number(e.query.limit):void 0,offset:e.query?.offset?Number(e.query.offset):void 0,sortBy:e.query?.sortBy,sortOrder:e.query?.sortDirection,filter:e.query?.filterField?{field:e.query?.filterField,operator:e.query.filterOperator,value:e.query.filterValue}:void 0});return e.json({members:o,total:n})}),getActiveMemberRole:(0,R.g)("/organization/get-active-member-role",{method:"GET",query:eh,requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t.session.activeOrganizationId,a=k(e.context,p);if(e.query?.organizationSlug){let t=await a.findOrganizationBySlug(e.query?.organizationSlug);if(!t)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);r=t.id}if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!e.query?.userId)return e.json({role:o.role});let n=e.query?.userId,s=await a.findMemberByOrgId({userId:n,organizationId:r});if(!s)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);return e.json({role:s.role})})},y=p.teams?.enabled,w={createTeam:(u=q({fields:p?.schema?.team?.additionalFields??{},isClientSide:!0}),(0,R.g)("/organization/create-team",{method:"POST",body:L.object({...eR.shape,...u.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Create a new team within an organization",responses:{200:{description:"Team created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the created team"},name:{type:"string",description:"Name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]}}}}}}}},async e=>{let r=await (0,t.D)(e),a=e.body.organizationId||r?.session.activeOrganizationId;if(!r&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=k(e.context,p);if(r){let t=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!t)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);if(!await P({role:t.role,options:e.context.orgOptions,permissions:{team:["create"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION)}let n=await o.listTeams(a),s="function"==typeof e.context.orgOptions.teams?.maximumTeams?await e.context.orgOptions.teams?.maximumTeams({organizationId:a,session:r},e):e.context.orgOptions.teams?.maximumTeams;if(s&&n.length>=s)throw i.E.from("BAD_REQUEST",U.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS);let{name:l,organizationId:c,...d}=e.body,u=await o.findOrganizationById(a);if(!u)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let f={name:l,organizationId:a,createdAt:new Date,updatedAt:new Date,...d};if(p?.organizationHooks?.beforeCreateTeam){let e=await p?.organizationHooks.beforeCreateTeam({team:{name:l,organizationId:a,...d},user:r?.user,organization:u});e&&"object"==typeof e&&"data"in e&&(f={...f,...e.data})}let m=await o.createTeam(f);return p?.organizationHooks?.afterCreateTeam&&await p?.organizationHooks.afterCreateTeam({team:m,user:r?.user,organization:u}),e.json(m)})),listOrganizationTeams:(0,R.g)("/organization/list-teams",{method:"GET",query:eS,metadata:{openapi:{description:"List all teams in an organization",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the team"},name:{type:"string",description:"Name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]},description:"Array of team objects within the organization"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t?.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=k(e.context,p);if(!await a.findMemberByOrgId({userId:t.user.id,organizationId:r||""}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION);let o=await a.listTeams(r);return e.json(o)}),removeTeam:(0,R.g)("/organization/remove-team",{method:"POST",body:ex,use:[x],metadata:{openapi:{description:"Remove a team from an organization",responses:{200:{description:"Team removed successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Confirmation message indicating successful removal",enum:["Team removed successfully."]}},required:["message"]}}}}}}}},async e=>{let r=await (0,t.D)(e),a=e.body.organizationId||r?.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);if(!r&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");let o=k(e.context,p);if(r){let t=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!t||r.session?.activeTeamId===e.body.teamId)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM);if(!await P({role:t.role,options:e.context.orgOptions,permissions:{team:["delete"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION)}let n=await o.findTeamById({teamId:e.body.teamId,organizationId:a});if(!n||n.organizationId!==a)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!e.context.orgOptions.teams?.allowRemovingAllTeams&&(await o.listTeams(a)).length<=1)throw i.E.from("BAD_REQUEST",U.UNABLE_TO_REMOVE_LAST_TEAM);let s=await o.findOrganizationById(a);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);return p?.organizationHooks?.beforeDeleteTeam&&await p?.organizationHooks.beforeDeleteTeam({team:n,user:r?.user,organization:s}),await (0,h.n)(e.context.adapter,async()=>{await o.deleteTeam(n.id);let t=await o.findPendingInvitations({organizationId:a}),r=await (0,h.g)(e.context.adapter);for(let e of t){if(!("teamId"in e)||!e.teamId)continue;let t=e.teamId.split(",");if(!t.includes(n.id))continue;let i=t.filter(e=>e!==n.id);await r.update({model:"invitation",where:[{field:"id",value:e.id}],update:{teamId:i.length>0?i.join(","):null}})}}),p?.organizationHooks?.afterDeleteTeam&&await p?.organizationHooks.afterDeleteTeam({team:n,user:r?.user,organization:s}),e.json({message:"Team removed successfully."})}),updateTeam:(f=q({fields:p?.schema?.team?.additionalFields??{},isClientSide:!0}),(0,R.g)("/organization/update-team",{method:"POST",body:L.object({teamId:L.string().meta({description:'The ID of the team to be updated. Eg: "team-id"'}),data:L.object({...eO.omit({id:!0,createdAt:!0,updatedAt:!0}).shape,...f.shape}).partial()}),requireHeaders:!0,use:[x,S],metadata:{$Infer:{body:{}},openapi:{description:"Update an existing team in an organization",responses:{200:{description:"Team updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the updated team"},name:{type:"string",description:"Updated name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.data.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=k(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o||!await P({role:o.role,options:e.context.orgOptions,permissions:{team:["update"]},organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);let n=await a.findTeamById({teamId:e.body.teamId,organizationId:r});if(!n||n.organizationId!==r)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let{name:s,organizationId:l,...c}=e.body.data,d=await a.findOrganizationById(r);if(!d)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let u={name:s,...c};if(p?.organizationHooks?.beforeUpdateTeam){let r=await p?.organizationHooks.beforeUpdateTeam({team:n,updates:u,user:t.user,organization:d});if(r&&"object"==typeof r&&"data"in r){let i=r.data,o=await a.updateTeam(n.id,i);return p?.organizationHooks?.afterUpdateTeam&&await p?.organizationHooks.afterUpdateTeam({team:o,user:t.user,organization:d}),e.json(o)}}let f=await a.updateTeam(n.id,u);return p?.organizationHooks?.afterUpdateTeam&&await p?.organizationHooks.afterUpdateTeam({team:f,user:t.user,organization:d}),e.json(f)})),setActiveTeam:(0,R.g)("/organization/set-active-team",{method:"POST",body:eU,requireHeaders:!0,use:[S,x],metadata:{openapi:{description:"Set the active team for the current active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The team",$ref:"#/components/schemas/Team"}}}}}}}},async e=>{let t,r=k(e.context,e.context.orgOptions),a=e.context.session;if(null===e.body.teamId){if(!a.session.activeTeamId)return e.json(null);let t=await r.setActiveTeam(a.session.token,null,e);return await (0,X.V)(e,{session:t,user:a.user}),e.json(null)}if(e.body.teamId)t=e.body.teamId;else{let r=a.session.activeTeamId;if(!r)return e.json(null);t=r}let o=a.session.activeOrganizationId;if(!o)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await r.findTeamById({teamId:t,organizationId:o});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!await r.findTeamMember({teamId:t,userId:a.user.id}))throw i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);let s=await r.setActiveTeam(a.session.token,n.id,e);return await (0,X.V)(e,{session:s,user:a.user}),e.json(n)}),listUserTeams:(0,R.g)("/organization/list-user-teams",{method:"GET",query:L.object({userId:L.string().optional().meta({description:"The user ID to list teams for. Defaults to the current session user."}),organizationId:L.string().optional().meta({description:"The organization ID to scope the team list to. When omitted on a self-query, teams are returned across every organization the user belongs to. When querying another user, falls back to the session's active organization and is required if there is no active organization."})}).optional(),metadata:{openapi:{description:"List teams for a user. Without parameters, returns teams for the current user across every organization they belong to. Pass `organizationId` to scope the result to a specific organization. Pass `userId` to list teams for another member; this requires `member:update` permission in the target organization (the explicit `organizationId` if provided, otherwise the session's active organization).",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",description:"The team",$ref:"#/components/schemas/Team"},description:"Array of team objects within the organization"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=k(e.context,e.context.orgOptions),a=e.query?.userId||t.user.id,o=a===t.user.id,n=e.query?.organizationId||t.session.activeOrganizationId,s=!!e.query?.organizationId;if(!o){if(!n)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:n});if(!o)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["update"]},organizationId:n},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);if(!await r.findMemberByOrgId({userId:a,organizationId:n}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let s=await r.listTeamsByUser({userId:a});return e.json(s.filter(e=>e.organizationId===n))}if(s&&n){if(!await r.findMemberByOrgId({userId:t.user.id,organizationId:n}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);let a=await r.listTeamsByUser({userId:t.user.id});return e.json(a.filter(e=>e.organizationId===n))}let l=await r.listTeamsByUser({userId:t.user.id}),c=[...new Set(l.map(e=>e.organizationId))],d=await Promise.all(c.map(e=>r.checkMembership({userId:t.user.id,organizationId:e}))),u=new Set(c.filter((e,t)=>d[t]));return e.json(l.filter(e=>u.has(e.organizationId)))}),listTeamMembers:(0,R.g)("/organization/list-team-members",{method:"GET",query:eN,metadata:{openapi:{description:"List the members of the given team.",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",description:"The team member",properties:{id:{type:"string",description:"Unique identifier of the team member"},userId:{type:"string",description:"The user ID of the team member"},teamId:{type:"string",description:"The team ID of the team the team member is in"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team member was created"}},required:["id","userId","teamId","createdAt"]},description:"Array of team member objects within the team"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=k(e.context,e.context.orgOptions),a=e.query?.teamId||t?.session.activeTeamId;if(!a)throw i.E.from("BAD_REQUEST",U.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM);let o=await r.findTeamById({teamId:a});if(!o)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!await r.checkMembership({userId:t.user.id,organizationId:o.organizationId})||!await r.findTeamMember({userId:t.user.id,teamId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);let n=await r.listTeamMembers({teamId:a});return e.json(n)}),addTeamMember:(0,R.g)("/organization/add-team-member",{method:"POST",body:eD,metadata:{openapi:{description:"The newly created member",responses:{200:{description:"Team member created successfully",content:{"application/json":{schema:{type:"object",description:"The team member",properties:{id:{type:"string",description:"Unique identifier of the team member"},userId:{type:"string",description:"The user ID of the team member"},teamId:{type:"string",description:"The team ID of the team the team member is in"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team member was created"}},required:["id","userId","teamId","createdAt"]}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t,r=e.context.session,a=k(e.context,e.context.orgOptions),o=e.body.organizationId||r.session.activeOrganizationId;if(!o)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await a.findMemberByOrgId({userId:r.user.id,organizationId:o});if(!n)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{member:["update"]},organizationId:o},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER);if(!await a.findMemberByOrgId({userId:e.body.userId,organizationId:o}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let s=await a.findTeamById({teamId:e.body.teamId,organizationId:o});if(!s)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let l=await a.findOrganizationById(o);if(!l)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let c=await e.context.internalAdapter.findUserById(e.body.userId);if(!c)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});if(p?.organizationHooks?.beforeAddTeamMember&&await p?.organizationHooks.beforeAddTeamMember({teamMember:{teamId:e.body.teamId,userId:e.body.userId},team:s,user:c,organization:l}),void 0!==e.context.orgOptions.teams?.maximumMembersPerTeam){let n="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:e.body.teamId,session:r,organizationId:o}):e.context.orgOptions.teams.maximumMembersPerTeam,s=await a.addTeamMemberWithLimit({teamId:e.body.teamId,userId:e.body.userId,maximumMembersPerTeam:n});if("limitReached"===s.status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED);t=s.member}else t=await a.findOrCreateTeamMember({teamId:e.body.teamId,userId:e.body.userId});return p?.organizationHooks?.afterAddTeamMember&&await p?.organizationHooks.afterAddTeamMember({teamMember:t,team:s,user:c,organization:l}),e.json(t)}),removeTeamMember:(0,R.g)("/organization/remove-team-member",{method:"POST",body:eL,metadata:{openapi:{description:"Remove a member from a team",responses:{200:{description:"Team member removed successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Confirmation message indicating successful removal",enum:["Team member removed successfully."]}},required:["message"]}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=k(e.context,e.context.orgOptions),a=e.body.organizationId||t.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:a});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["delete"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER);if(!await r.findMemberByOrgId({userId:e.body.userId,organizationId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let n=await r.findTeamById({teamId:e.body.teamId,organizationId:a});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let s=await r.findOrganizationById(a);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let l=await e.context.internalAdapter.findUserById(e.body.userId);if(!l)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});let c=await r.findTeamMember({teamId:e.body.teamId,userId:e.body.userId});if(!c)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);return p?.organizationHooks?.beforeRemoveTeamMember&&await p?.organizationHooks.beforeRemoveTeamMember({teamMember:c,team:n,user:l,organization:s}),await r.removeTeamMember({teamId:e.body.teamId,userId:e.body.userId}),p?.organizationHooks?.afterRemoveTeamMember&&await p?.organizationHooks.afterRemoveTeamMember({teamMember:c,team:n,user:l,organization:s}),e.json({message:"Team member removed successfully."})})};y&&(g={...g,...w});let b={createOrgRole:(e=>{let{additionalFieldsSchema:t,$AdditionalFields:r,$ReturnAdditionalFields:a}=H(e,!1);return(0,R.g)("/organization/create-role",{method:"POST",body:F.safeExtend({additionalFields:L.object({...t.shape}).optional()}),metadata:{$Infer:{body:{}}},requireHeaders:!0,use:[S]},async t=>{let{session:r,user:a}=t.context.session,o=t.body.role,n=t.body.permission,s=t.body.additionalFields,l=e.ac;if(!l)throw t.context.logger.error("[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.",`
|
|
481
|
-
Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`),i.E.from("NOT_IMPLEMENTED",U.MISSING_AC_INSTANCE);let c=t.body.organizationId??r.activeOrganizationId;if(!c)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body."),i.E.from("BAD_REQUEST",U.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE);o=o.toLowerCase(),await Y({role:o,organizationId:c,options:e,ctx:t});let d=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:c,operator:"eq",connector:"AND"},{field:"userId",value:a.id,operator:"eq",connector:"AND"}]});if(!d)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to create a role.",{userId:a.id,organizationId:c}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:c,permissions:{ac:["create"]},role:d.role},t))throw t.context.logger.error('[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "create" permission.',{userId:a.id,organizationId:c,role:d.role}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE);let u="function"==typeof e.dynamicAccessControl?.maximumRolesPerOrganization?await e.dynamicAccessControl.maximumRolesPerOrganization(c):e.dynamicAccessControl?.maximumRolesPerOrganization??1/0,f=await t.context.adapter.count({model:"organizationRole",where:[{field:"organizationId",value:c,operator:"eq",connector:"AND"}]});if(f>=u)throw t.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${u}.`,{organizationId:c,maximumRolesPerOrganization:u,rolesInDB:f}),i.E.from("BAD_REQUEST",U.TOO_MANY_ROLES);await J({ac:l,ctx:t,permission:n}),await Q({ctx:t,member:d,options:e,organizationId:c,permissionRequired:n,user:a,action:"create"}),await Z({ctx:t,organizationId:c,role:o});let p=l.newRole(n),m={...await t.context.adapter.create({model:"organizationRole",data:{createdAt:new Date,organizationId:c,permission:JSON.stringify(n),role:o,...s}}),permission:n};return t.json({success:!0,roleData:m,statements:p.statements})})})(p),deleteOrgRole:(0,
|
|
482
|
-
Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`),i.E.from("NOT_IMPLEMENTED",U.MISSING_AC_INSTANCE);let s=t.body.organizationId??a.activeOrganizationId;if(!s)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body."),i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let l=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},{field:"userId",value:o.id,operator:"eq",connector:"AND"}]});if(!l)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to update a role.",{userId:o.id,organizationId:s}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:s,role:l.role,permissions:{ac:["update"]}},t))throw t.context.logger.error("[Dynamic Access Control] The user is not permitted to update a role."),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE);if(t.body.roleName)r={field:"role",value:t.body.roleName,operator:"eq",connector:"AND"};else if(t.body.roleId)r={field:"id",value:t.body.roleId,operator:"eq",connector:"AND"};else throw t.context.logger.error("[Dynamic Access Control] The role name/id is not provided in the request body."),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let c=await t.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},r]});if(!c)throw t.context.logger.error("[Dynamic Access Control] The role name/id does not exist in the database.",{..."roleName"in t.body?{roleName:t.body.roleName}:{roleId:t.body.roleId},organizationId:s}),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);c.permission=c.permission?JSON.parse(c.permission):void 0;let{permission:d,roleName:u,...f}=t.body.data,p={...f};if(t.body.data.permission){let r=t.body.data.permission;await J({ac:n,ctx:t,permission:r}),await Q({ctx:t,member:l,options:e,organizationId:s,permissionRequired:r,user:o,action:"update"}),p.permission=r}if(t.body.data.roleName){let r=t.body.data.roleName;r=r.toLowerCase(),await Y({role:r,organizationId:s,options:e,ctx:t}),await Z({role:r,organizationId:s,ctx:t}),p.role=r}let m={...p,...p.permission?{permission:JSON.stringify(p.permission)}:{}};return await t.context.adapter.updateMany({model:"organizationRole",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},r],update:m}),t.json({success:!0,roleData:{...c,...m,permission:p.permission||c.permission||null}})})})(p)};p.dynamicAccessControl?.enabled&&(g={...g,...b});let E={...l,...p.roles},A=y?{team:{modelName:p.schema?.team?.modelName,fields:{name:{type:"string",required:!0,fieldName:p.schema?.team?.fields?.name},memberCount:{type:"number",required:!0,defaultValue:0,input:!1,returned:!1,fieldName:p.schema?.team?.fields?.memberCount},organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.team?.fields?.organizationId,index:!0},createdAt:{type:"date",required:!0,fieldName:p.schema?.team?.fields?.createdAt},updatedAt:{type:"date",required:!1,fieldName:p.schema?.team?.fields?.updatedAt,onUpdate:()=>new Date},...p.schema?.team?.additionalFields||{}}},teamMember:{modelName:p.schema?.teamMember?.modelName,fields:{teamId:{type:"string",required:!0,references:{model:"team",field:"id"},fieldName:p.schema?.teamMember?.fields?.teamId,index:!0},userId:{type:"string",required:!0,references:{model:"user",field:"id"},fieldName:p.schema?.teamMember?.fields?.userId,index:!0},membershipKey:{type:"string",required:!1,unique:!0,input:!1,returned:!1,fieldName:p.schema?.teamMember?.fields?.membershipKey},createdAt:{type:"date",required:!1,fieldName:p.schema?.teamMember?.fields?.createdAt}}}}:{},I=p.dynamicAccessControl?.enabled?{organizationRole:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.organizationRole?.fields?.organizationId,index:!0},role:{type:"string",required:!0,fieldName:p.schema?.organizationRole?.fields?.role,index:!0},permission:{type:"string",required:!0,fieldName:p.schema?.organizationRole?.fields?.permission},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:p.schema?.organizationRole?.fields?.createdAt},updatedAt:{type:"date",required:!1,fieldName:p.schema?.organizationRole?.fields?.updatedAt,onUpdate:()=>new Date},...p.schema?.organizationRole?.additionalFields||{}},modelName:p.schema?.organizationRole?.modelName}}:{},T={organization:{modelName:p.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,sortable:!0,fieldName:p.schema?.organization?.fields?.name},slug:{type:"string",required:!0,unique:!0,sortable:!0,fieldName:p.schema?.organization?.fields?.slug,index:!0},logo:{type:"string",required:!1,fieldName:p.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:p.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:p.schema?.organization?.fields?.metadata},...p.schema?.organization?.additionalFields||{}}},...I,...A,member:{modelName:p.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.member?.fields?.organizationId,index:!0},userId:{type:"string",required:!0,fieldName:p.schema?.member?.fields?.userId,references:{model:"user",field:"id"},index:!0},role:{type:"string",required:!0,sortable:!0,defaultValue:"member",fieldName:p.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:p.schema?.member?.fields?.createdAt},...p.schema?.member?.additionalFields||{}}},invitation:{modelName:p.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.invitation?.fields?.organizationId,index:!0},email:{type:"string",required:!0,sortable:!0,fieldName:p.schema?.invitation?.fields?.email,index:!0},role:{type:"string",required:!1,sortable:!0,fieldName:p.schema?.invitation?.fields?.role},...y?{teamId:{type:"string",required:!1,sortable:!0,fieldName:p.schema?.invitation?.fields?.teamId}}:{},status:{type:"string",required:!0,sortable:!0,defaultValue:"pending",fieldName:p.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:p.schema?.invitation?.fields?.expiresAt},createdAt:{type:"date",required:!0,fieldName:p.schema?.invitation?.fields?.createdAt,defaultValue:()=>new Date},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:p.schema?.invitation?.fields?.inviterId,required:!0},...p.schema?.invitation?.additionalFields||{}}}},_=((e,t)=>{let r={};for(let[i,a]of Object.entries(e))r[i]=e=>a({...e,context:{...t,...e.context}}),r[i].path=a.path,r[i].method=a.method,r[i].options=a.options,r[i].headers=a.headers;return r})(g,{orgOptions:p,roles:E,getSession:async e=>await (0,t.D)(e)});return{id:"organization",version:r.f,endpoints:{..._,hasPermission:(0,R.g)("/organization/has-permission",{method:"POST",requireHeaders:!0,body:eC,use:[S],metadata:{$Infer:{body:{}},openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check",deprecated:!0},permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async e=>{let t=e.body.organizationId||e.context.session.session.activeOrganizationId;if(!t)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let r=await k(e.context,p).findMemberByOrgId({userId:e.context.session.user.id,organizationId:t});if(!r)throw i.E.from("UNAUTHORIZED",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let a=await P({role:r.role,options:p,permissions:e.body.permissions,organizationId:t},e);return e.json({error:null,success:a})})},schema:{...T,session:{fields:{activeOrganizationId:{type:"string",required:!1,input:!1,fieldName:p.schema?.session?.fields?.activeOrganizationId},...y?{activeTeamId:{type:"string",required:!1,input:!1,fieldName:p.schema?.session?.fields?.activeTeamId}}:{}}}},$Infer:{Organization:{},Invitation:{},Member:{},Team:{},TeamMember:{},ActiveOrganization:{}},$ERROR_CODES:U,options:p}}],34975)},96481,76411,67850,69381,1083,32802,63370,65466,83817,92449,24472,16760,27957,1889,12319,41242,9939,75742,74285,56023,42158,76660,54257,97554,96161,70728,82318,73436,12996,e=>{"use strict";let t,r,i;function a(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function o(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function n(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 i="",o="",n=".";!0===r?(i="/",o="[/\\\\]",n="[^/\\\\]"):r&&((o=function(e){let t="";for(let r=0;r<e.length;r++)t+=a(e[r]);return t}(i=r)).length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let s=r?`${o}+?`:"",l=r?`${o}*?`:"",c=r?t.split(i):[t],d="";for(let e=0;e<c.length;e++){let t=c[e],i=c[e+1],o="";if(t||!(e>0)){if(r&&(o=e===c.length-1?l:"**"!==i?s:""),r&&"**"===t){o&&(d+=0===e?"":o,d+=`(?:${n}*?${o})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(d+=a(t[e+1]),e++):"?"===r?d+=n:"*"===r?d+=`${n}*?`:d+=a(r)}d+=o}}return d}(e,t.separator),i=RegExp(`^${r}$`,t.flags),n=o.bind(null,i);return n.options=t,n.pattern=e,n.regexp=i,n}e.s(["f",0,n],76411);var s=e.i(47391),l=e.i(71616);function c(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)}function d(e,t="/api/auth"){try{let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new l.p(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof l.p)throw t;throw new l.p(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}if(function(e){try{return"/"!==(c(new URL(e).pathname)||"/")}catch{throw new l.p(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e))return e;let r=c(e);return t&&"/"!==t?(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`):r}function u(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 f(e,t,r,i,a){if(e)return d(e,t);if(!1!==i){let e=s.$.BETTER_AUTH_URL||s.$.NEXT_PUBLIC_BETTER_AUTH_URL||s.$.PUBLIC_BETTER_AUTH_URL||s.$.NUXT_PUBLIC_BETTER_AUTH_URL||s.$.NUXT_PUBLIC_AUTH_URL||("/"!==s.$.BASE_URL?s.$.BASE_URL:void 0);if(e)return d(e,t)}let o=r?.headers.get("x-forwarded-host"),n=r?.headers.get("x-forwarded-proto");if(o&&n&&a&&u(n,"proto")&&u(o,"host"))try{return d(`${n}://${o}`,t)}catch(e){}if(r){let e=p(r.url);if(!e)throw new l.p("Could not get origin from request. Please provide a valid base URL.");return d(e,t)}}function p(e){try{let t=new URL(e);return"null"===t.origin?null:t.origin}catch{return null}}function m(e){return"object"==typeof e&&null!==e&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function h(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 g(e,t){let r=h(e)?e.headers:e;if(t){let e=r.get("x-forwarded-host");if(e&&u(e,"host"))return e}let i=r.get("host");if(i&&u(i,"host"))return i;if(h(e))try{return new URL(e.url).host}catch{}return null}function y(e){return!!e.database||!!e.secondaryStorage}function w(e){return!!e.database}e.s(["X",0,f,"$",0,function(e){try{return new URL(e).host}catch{return null}},"H",0,p,"Y",0,function(e){try{return new URL(e).protocol}catch{return null}},"_",0,m,"T",0,h,"A",0,function(e,t,r,i,a){if(m(e)){if(r){let i=g(r,a);if(!i){if(e.fallback)return d(e.fallback,t);throw new l.p("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(),i=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return i.includes("*")||i.includes("?")?n(i)(r):r.toLowerCase()===i.toLowerCase()})(i,e)))return d(`${function(e,t,r){let i;if("http"===t||"https"===t)return t;let a=h(e)?e.headers:e;if(r){let e=a.get("x-forwarded-proto");if(e&&u(e,"proto"))return e}if(h(e))try{let t=new URL(e.url);if("http:"===t.protocol||"https:"===t.protocol)return t.protocol.slice(0,-1)}catch{}let o=g(e,r);return o&&("localhost"===(i=o.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||i.endsWith(".localhost")||"::1"===i||i.startsWith("127."))?"http":"https"}(r,e.protocol,a)}://${i}`,t);if(e.fallback)return d(e.fallback,t);throw new l.p(`Host "${i}" 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?d(e.fallback,t):f(void 0,t,void 0,i,a)}let o=h(r)?r:void 0;return"string"==typeof e?f(e,t,o,i,a):f(void 0,t,o,i,a)}],96481),e.s(["z",0,y,"d",0,w],67850);var b=e.i(97858);class E{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if((0,b.v)(e),(0,b.B)(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),(0,b.f)(i)}update(e){return(0,b.s)(this),this.iHash.update(e),this}digestInto(e){(0,b.s)(this),(0,b.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:i,destroyed:a,blockLen:o,outputLen:n,canXOF:s}=this;return e.finished=i,e.destroyed=a,e.blockLen=o,e.outputLen=n,e.canXOF=s,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 A=((i=(e,t,r)=>new E(e,t).update(r).digest()).create=(e,t)=>new E(e,t),i),I=Uint8Array.of(0),T=Uint8Array.of(),_=(e,t,r,i,a)=>{(0,b.v)(e),void 0===r&&(r=new Uint8Array(e.outputLen));let o=A.create(e,r).update(t);return function(e,t,r,i=32,a){(0,b.v)(e),(0,b.N)(i,"length"),(0,b.B)(t,void 0,"prk");let o=e.outputLen;if(t.length<o)throw Error('"prk" must be at least HashLen octets');if(i>255*o)throw Error("Length must be <= 255*HashLen");let n=Math.ceil(i/o);if(void 0===r?r=T:(0,b.B)(r,void 0,"info"),!n)return a&&(0,b.f)(t),new Uint8Array;let s=a&&1===n?t:new Uint8Array(n*o),{iHash:l,oHash:c}=A.create(e,t),d=a?t:new Uint8Array(o),u=n>1?a?.iHash||e.create():void 0;for(let e=0;e<n-1;e++){I[0]=e+1;let t=l._cloneInto(u);e&&t.update(d),t.update(r).update(I).digestInto(d),c._cloneInto(u).update(d).digestInto(d),s.set(d,o*e)}if(I[0]=n,n>1&&l.update(d),l.update(r).update(I).digestInto(d),c.update(d).digestInto(d),s.set(d,o*(n-1)),l.destroy(),c.destroy(),u?.destroy(),d!==s&&(0,b.f)(d),(0,b.f)(I),i===s.length)return s;let f=s.slice(0,i);return(0,b.f)(s),f}(e,o.digest(),i,a,o)};e.s(["f",0,_],69381);let v=BigInt(0xffffffff),O=BigInt(32);class k{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=(0,b.y)(this.buffer)}update(e){(0,b.s)(this),(0,b.B)(e);let{view:t,buffer:r,blockLen:i}=this,a=e.length,o=!1;for(let n=0;n<a;){let s=Math.min(i-this.pos,a-n);if(s===i){let t=(0,b.y)(e);for(;i<=a-n;n+=i)this.process(t,n);o=!0;continue}r.set(0===n&&s===a?e:e.subarray(n,n+s),this.pos),this.pos+=s,n+=s,this.pos===i&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){var t,r,i,a;let o,n;(0,b.s)(this),(0,b.W)(e,this),this.finished=!0;let{buffer:s,view:l,blockLen:c,isLE:d}=this,{pos:u}=this;s[u++]=128,s.fill(0,u),this.padOffset>c-u&&(this.process(l,0),s.fill(0)),t=l,r=c-8,i=8*this.length,a=d,o=i/0x100000000|0,n=i>>>0,t.setUint32(r,a?n:o,a),t.setUint32(r+4,a?o:n,a),this.process(l,0),this.roundClean();let f=e===s?l:(0,b.y)(e),p=this.outputLen,m=p/4,h=this.get();if(p%4||m>h.length)throw Error("invalid outputLen");for(let e=0;e<m;e++)f.setUint32(4*e,h[e],d)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}}let R=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),x=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),S=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),U=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),N=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]),D=new Uint32Array(64);class L extends k{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=0|t[0],this.B=0|t[1],this.C=0|t[2],this.D=0|t[3],this.E=0|t[4],this.F=0|t[5],this.G=0|t[6],this.H=0|t[7]}get(){let{A:e,B:t,C:r,D:i,E:a,F:o,G:n,H:s}=this;return[e,t,r,i,a,o,n,s]}set(e,t,r,i,a,o,n,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|i,this.E=0|a,this.F=0|o,this.G=0|n,this.H=0|s}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let r=0;r<16;r++,t+=4)D[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=D[e-15],r=D[e-2],i=(0,b.M)(t,7)^(0,b.M)(t,18)^t>>>3,a=(0,b.M)(r,17)^(0,b.M)(r,19)^r>>>10;D[e]=a+D[e-7]+i+D[e-16]|0}let{A:r,B:i,C:a,D:o,E:n,F:s,G:l,H:c}=this;for(let e=0;e<64;e++){var d,u,f,p;let t=c+((0,b.M)(n,6)^(0,b.M)(n,11)^(0,b.M)(n,25))+((d=n)&s^~d&l)+N[e]+D[e]|0,m=((0,b.M)(r,2)^(0,b.M)(r,13)^(0,b.M)(r,22))+((u=r)&(f=i)^u&(p=a)^f&p)|0;c=l,l=s,s=n,n=o+t|0,o=a,a=i,i=r,r=t+m|0}r=r+this.A|0,i=i+this.B|0,a=a+this.C|0,o=o+this.D|0,n=n+this.E|0,s=s+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,i,a,o,n,s,l,c)}roundClean(){(0,b.f)(D)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),(0,b.f)(this.buffer)}}class C extends L{constructor(){super(32,R)}}let z=function(e,t=!1){let r=e.length,i=new Uint32Array(r),a=new Uint32Array(r);for(let o=0;o<r;o++){let{h:r,l:n}=function(e,t=!1){return t?{h:Number(e&v),l:Number(e>>O&v)}:{h:0|Number(e>>O&v),l:0|Number(e&v)}}(e[o],t);[i[o],a[o]]=[r,n]}return[i,a]}(["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))),j=z[0],P=z[1],B=new Uint32Array(80),M=new Uint32Array(80),$=(0,b.O)(()=>new C,(0,b.Y)(1));e.s(["f",0,$],1083);let q=new TextEncoder,H=new TextDecoder,F=new TextDecoder("utf-8",{fatal:!0});function V(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let i of e)t.set(i,r),r+=i.length;return t}function W(e,t,r){if(t<0||t>=0x100000000)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function K(e){let t=Math.floor(e/0x100000000),r=new Uint8Array(8);return W(r,t,0),W(r,e%0x100000000,4),r}function G(e){let t=new Uint8Array(4);return W(t,e),t}let J=/[^\x00-\x7f]/;function Q(e){if("string"==typeof e&&e.length>=128){if(J.test(e))throw TypeError("non-ASCII string encountered in encode()");return q.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=i}return t}function Y(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=[];for(let t=0;t<e.length;t+=32768)r.push(String.fromCharCode.apply(null,e.subarray(t,t+32768)));let i=btoa(r.join(""));return t?i.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):i}function Z(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}async function X(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}function ee(e){try{return Z("string"==typeof e?e:H.decode(e),!0)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function et(e){return Y("string"==typeof e?q.encode(e):e,!0)}e.s(["w",0,V,"F",0,Z,"P",0,H,"X",0,X,"q",0,Q,"Y",0,Y,"h",0,q,"L",0,F,"T",0,G,"U",0,K],32802),e.s(["decode",0,ee,"encode",0,et],63370);class er 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 ei extends er{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.claim=r,this.reason=i,this.payload=t}}class ea extends er{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.claim=r,this.reason=i,this.payload=t}}class eo extends er{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class en extends er{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class es extends er{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class el extends er{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class ec extends er{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class ed extends er{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class eu extends er{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class ef extends er{[Symbol.asyncIterator]=async function*(){};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 ep extends er{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function em(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function eh(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function eg(...e){let t=new Set;for(let r of e)if(r)for(let e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}function ey(e,t){if(void 0!==e)throw TypeError(`${t} can only be called once`)}function ew(e,t,r){try{return ee(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}function eb(e,t,r){try{return Q(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}function eE(e,t,r){let i;try{i=JSON.parse(F.decode(ee(e)))}catch(e){throw new t(r,{cause:e})}if(!eh(i))throw new t(r);return i}e.s(["JOSEAlgNotAllowed",0,eo,"JOSEError",0,er,"JOSENotSupported",0,en,"JWEDecryptionFailed",0,es,"JWEInvalid",0,el,"JWKInvalid",0,eu,"JWKSInvalid",0,class extends er{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},"JWKSMultipleMatchingKeys",0,ef,"JWKSNoMatchingKey",0,class extends er{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)}},"JWKSTimeout",0,class extends er{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},"JWSInvalid",0,ec,"JWSSignatureVerificationFailed",0,ep,"JWTClaimValidationFailed",0,ei,"JWTExpired",0,ea,"JWTInvalid",0,ed],65466);let eA={__proto__:null,b64:!0},eI={__proto__:null};function eT(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`);return void 0===t?void 0:new Set(t)}function e_(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function ev(e,t,r,i,a){if(void 0!==a.crit&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return[];if(!Array.isArray(i.crit)||0===i.crit.length||i.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');let o=void 0===r?t:{__proto__:null,...r,...t};for(let t of i.crit){if(!(t in o))throw new en(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(a,t)||void 0===a[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o[t]&&(!Object.hasOwn(i,t)||void 0===i[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return i.crit}function eO(e,t){if(t.includes("b64")){let t=e.b64;if("boolean"!=typeof t)throw new ec('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}function ek(e,t){let r,i;try{r=JSON.stringify(t),i=JSON.parse(r)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!eh(i))throw new e("JOSE Header is not a JSON object");return[i,r]}async function eR(e,r,i){let a,o,{alg:n,secret:s}=e,l="decrypt"===i||"sign"===i;if(s&&r instanceof Uint8Array)return r;if(eh(r)){if("string"!=typeof(a=eq(r)).kty)throw ez(n,r,s);if(!(s?"oct"===a.kty&&"string"==typeof a.k:"oct"!==a.kty&&(l?"AKP"===a.kty&&"string"==typeof a.priv||"string"==typeof a.d:void 0===a.d&&void 0===a.priv)))throw TypeError(s?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${l?"private":"public"} JWK`);if(((e,t,r)=>{let{alg:i}=e;if(void 0!==t.use){let e="sign"===r||"verify"===r?"sig":"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!==i)throw TypeError(`Invalid key for this operation, its "alg" must be "${i}" when present`);if(Array.isArray(t.key_ops)){let i="encrypt"===r||"decrypt"===r?e.ops?.[+("encrypt"!==r)]:r;if(i&&!t.key_ops.includes(i))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}})(e,a,i),"oct"===a.kty)return ee(a.k);if(!Object.isFrozen(r)){let{key_ops:e}=r;Array.isArray(e)&&Object.freeze(e),Object.freeze(r)}}else{if(!eD(r))throw ez(n,r,s);let e=s?"secret":l?"private":"public";if(r.type!==e&&(s||["secret","public","private"].includes(r.type)))throw TypeError(`${r[Symbol.toStringTag]} instances must be of type "${e}" for the ${n} algorithm`);if(eU(r))return r;if("secret"===(o=r).type)return o.export()}let c=(t||=new WeakMap).get(r);if(c?.[n])return c[n];if(c||t.set(r,c={}),o&&"function"==typeof o.toCryptoKey){let t="public"===o.type,r=ex[o.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:r,asymmetricKeyType:o.asymmetricKeyType})??e.subtle;return c[n]=o.toCryptoKey(i,t,e.usages[+!t])}return(a??=o.export({format:"jwk"})).alg=n,c[n]=await eF(e,a)}e.s(["F",0,eI,"U",0,eA,"x",0,ey,"_",0,em,"n",0,ew,"E",0,eb,"J",0,eg,"q",0,function(e){return eh(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(eh)},"C",0,eh,"H",0,eE,"M",0,ek,"L",0,eT,"e",0,eO,"l",0,ev,"h",0,e_],83817);let ex={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function eS(e){if(!eU(e))throw Error("CryptoKey instance expected")}let eU=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},eN=e=>e?.[Symbol.toStringTag]==="KeyObject",eD=e=>eU(e)||eN(e);function eL(e,t,...r){if(r.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 eC=(e,...t)=>eL("Key must be ",e,...t);function ez(e,t,r){let i=["CryptoKey","KeyObject","JSON Web Key"];return r&&i.push("Uint8Array"),TypeError(eL(`Key for the ${e} algorithm must be `,t,...i))}let ej=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function eP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function eB(e,t){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function eM(e,t,r){let i=e.algorithm;if(i.name!==t.name)throw ej(t.name);if(t.hash&&i.hash?.name!==t.hash)throw ej(t.hash,"algorithm.hash");if(t.namedCurve&&i.namedCurve!==t.namedCurve)throw ej(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&i.length!==t.length)throw ej(t.length,"algorithm.length");eP(e,r)}function e$(e){return{__proto__:null,...e}}function eq(e){let t=e$(e);if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){let e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}function eH(e){if(void 0!==e&&"boolean"!=typeof e)throw TypeError('"extractable" option must be a boolean');return e}async function eF(e,t,r){if(!e.kty.includes(t.kty))throw new en('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let i=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,a=!!(t.d||t.priv),o={...t,ext:r??t.ext};return"AKP"!==o.kty&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,i,o.ext??!a,t.key_ops??e.usages[+!!a])}async function eV(e,t,r,i=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,i,[r])),eM(e,t,r),e}e.s(["w",0,eS,"U",0,eM,"y",0,eB,"V",0,eP,"W",0,eC,"L",0,eU,"e",0,eD,"o",0,eN,"f",0,eF,"P",0,eq,"X",0,eR,"c",0,eV,"C",0,e$,"T",0,eH],92449);let eW=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function eK(e,t){let r=e.byteLength<<3;if(r!==t)throw new el(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function eG(e,t){if(t.length<<3!==e.ivBits)throw new el("Invalid Initialization Vector length")}async function eJ(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(eC(t,"Uint8Array"));let i=e.cekBits>>1;return[await crypto.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,[r]),await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),i]}async function eQ(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function eY(e,t,r,i,a){let[o,n,s]=await eJ(e,r,"encrypt"),l=new Uint8Array(await crypto.subtle.encrypt({iv:i,name:"AES-CBC"},o,t)),c=K(8*a.length),d=V(a,i,l,c);return{ciphertext:l,tag:await eQ(n,d,s),iv:i}}async function eZ(e,t){let r={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.generateKey(r,!1,["sign","verify"]),a=await crypto.subtle.sign(r,i,e);return crypto.subtle.verify(r,i,a,t)}async function eX(e,t,r,i,a,o){let[n,s,l]=await eJ(e,t,"decrypt"),c=K(8*o.length),d=V(o,i,r,c),u=await eQ(s,d,l);try{if(await eZ(a,u))return new Uint8Array(await crypto.subtle.decrypt({iv:i,name:"AES-CBC"},n,r))}catch{}throw new es}async function e0(e,t,r,i,a){if(!eU(r)&&!(r instanceof Uint8Array))throw TypeError(eC(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(i?eG(e,i):i=crypto.getRandomValues(new Uint8Array(e.ivBits>>3)),r instanceof Uint8Array&&eK(r,e.cekBits),e.cbc)return eY(e,t,r,i,a);let o=await eV(r,e.subtle,"encrypt"),n=new Uint8Array(await crypto.subtle.encrypt({additionalData:a,iv:i,name:"AES-GCM",tagLength:128},o,t));return{ciphertext:n.subarray(0,-16),tag:n.subarray(-16),iv:i}}async function e1(e,t,r,i,a,o){if(!eU(t)&&!(t instanceof Uint8Array))throw TypeError(eC(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!i)throw new el("JWE Initialization Vector missing");if(!a)throw new el("JWE Authentication Tag missing");if(!e.cbc&&16!==a.length)throw new el("Invalid Authentication Tag length");if(eG(e,i),t instanceof Uint8Array&&eK(t,e.cekBits),e.cbc)return eX(e,t,r,i,a,o);let n=await eV(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:i,name:"AES-GCM",tagLength:128},n,V(r,a)))}catch{throw new es}}function e2(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}let e5=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],e6=[[],["deriveBits"]],e8=[[],[]];function e4(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:e5,ops:["wrapKey","unwrapKey"]}}function e3(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new en('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:e6,ops:[void 0,"deriveBits"]}}function e9(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:e8,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function e7(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:e8,ops:["deriveBits","deriveBits"]}}let te=e2({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:e8,ops:["encrypt","decrypt"]},"RSA-OAEP":e4(1),"RSA-OAEP-256":e4(256),"RSA-OAEP-384":e4(384),"RSA-OAEP-512":e4(512),"ECDH-ES":e3("direct-key-agreement"),"ECDH-ES+A128KW":e3("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":e3("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":e3("key-agreement-with-key-wrapping"),A128KW:e9(128),A192KW:e9(192),A256KW:e9(256),A128GCMKW:e9(128,!0),A192GCMKW:e9(192,!0),A256GCMKW:e9(256,!0),"PBES2-HS256+A128KW":e7(),"PBES2-HS384+A192KW":e7(),"PBES2-HS512+A256KW":e7()}),tt=["encrypt","decrypt"];function tr(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:e8,ops:tt,cekBits:e,ivBits:t?128:96,cbc:t}}let ti=e2({A128GCM:tr(128),A192GCM:tr(192),A256GCM:tr(256),"A128CBC-HS256":tr(256,!0),"A192CBC-HS384":tr(384,!0),"A256CBC-HS512":tr(512,!0)});function ta(e,t){throw new en(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function to(e){return("string"==typeof e?te[e]:void 0)??ta("alg","Algorithm")}function tn(e){return"key-wrapping"===e.mode||"key-encryption"===e.mode||"key-agreement-with-key-wrapping"===e.mode}function ts(e){return("string"==typeof e?ti[e]:void 0)??ta("enc","Encryption Algorithm")}function tl(e,t){if("ECDH"!==e.algorithm.name&&"X25519"!==e.algorithm.name)throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");eP(e,t)}async function tc(e,t,r){let i=await eV(t,to(e).subtle,"wrapKey",!0),a=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",a,i,"AES-KW"))}async function td(e,t,r){let i=await eV(t,to(e).subtle,"unwrapKey",!0),a=await crypto.subtle.unwrapKey("raw",r,i,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",a))}function tu(e,t,r){eM(t,to(e).subtle,r),eB(e,t)}async function tf(e,t,r,i){if(!(e instanceof Uint8Array)||e.length<8)throw new el("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||1!==Math.sign(r))throw new el("PBES2 Count Input must be a positive integer");let a=V(Q(t),Uint8Array.of(0),e),o=parseInt(t.slice(13,16),10),n={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:a},s=await eV(i,to(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(n,s,o))}function tp(e){return V(G(e.length),e)}async function tm(e,t,r){let i=t>>3,a=Math.ceil(i/32),o=new Uint8Array(32*a);for(let t=1;t<=a;t++){let i=await X("sha256",V(G(t),e,r));o.set(i,(t-1)*32)}return o.slice(0,i)}async function th(e,t,r,i,a=new Uint8Array,o=new Uint8Array){tl(e),tl(t,"deriveBits");let n=V(tp(Q(r)),tp(a),tp(o),G(i));return tm(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,"X25519"===e.algorithm.name?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),i,n)}function tg(e){eS(e);let t=e.algorithm.namedCurve;if("P-256"!==t&&"P-384"!==t&&"P-521"!==t&&"X25519"!==e.algorithm.name)throw new en("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ty(e,t){let r=e[t];if(void 0!==r){if("string"!=typeof r)throw new el(`JOSE Header "${t}" (Agreement Party${"apu"===t?"U":"V"}Info) invalid`);return ew(r,t,el)}}function tw(e,t){if(void 0!==e&&void 0!==t&&e.byteLength===t.byteLength){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new el('JOSE Header "apu" and "apv" values must be distinct')}}function tb(e){if(void 0!==e)throw new el("Encountered unexpected JWE Encrypted Key")}async function tE(e,t,r,i,a,o){let{alg:n}=e,s=e.mode;if("direct-encryption"===s)return tb(i),r;let l="direct-key-agreement"===s;switch(l?tb(i):function(e){if(void 0===e)throw new el("JWE Encrypted Key missing")}(i),e.subtle.name){case"ECDH":{let{epk:i}=a;if(!eh(i)||["d","k","p","q","dp","dq","qi","oth","priv"].some(e=>Object.hasOwn(i,e)))throw new el('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');tg(r);let o=await eF(e,i),s=ty(a,"apu"),c=ty(a,"apv");tw(s,c);let d=await th(o,r,l?t.alg:n,l?t.cekBits:parseInt(n.slice(-5,-2),10),s,c);if(l)return d;r=d;break}case"RSA-OAEP":return eS(r),tu(n,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,i));case"PBKDF2":{if("number"!=typeof a.p2c)throw new el('JOSE Header "p2c" (PBES2 Count) missing or invalid');if(a.p2c>(o??1e4))throw new el('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof a.p2s)throw new el('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let e=ew(a.p2s,"p2s",el);r=await tf(e,n,a.p2c,r);break}case"AES-GCM":{if("string"!=typeof a.iv)throw new el('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof a.tag)throw new el('JOSE Header "tag" (Authentication Tag) missing or invalid');let e=ew(a.iv,"iv",el),t=ew(a.tag,"tag",el);if(12!==e.byteLength)throw new el("Invalid Initialization Vector length");if(16!==t.byteLength)throw new el("Invalid Authentication Tag length");return e1(ts(n.slice(0,-2)),r,i,e,t,new Uint8Array)}}return td(n.slice(-6),r,i)}async function tA(e,t,r,i,a,o={}){let n,s,{alg:l,mode:c}=e,d=tn(e);if(void 0!==a&&!d)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);let u=await eR("direct-encryption"===c?t:e,r,"encrypt");if("direct-encryption"===c)return[u,void 0,void 0];let f=d?a??eW(t):void 0;switch(f&&eK(f,t.cekBits),e.subtle.name){case"ECDH":{let r;tg(u);let{apu:a,apv:n}=o;void 0!==a&&em(a,'"apu"'),void 0!==n&&em(n,'"apv"');let d=a??ty(i,"apu"),f=n??ty(i,"apv");tw(d,f),r=void 0!==o.epk?await eR(e,o.epk,"decrypt"):(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let p=crypto.subtle,m=r;if(!m.extractable){if("function"!=typeof p.getPublicKey)throw TypeError('CryptoKey for "epk" must be extractable');m=await p.getPublicKey(r,[])}let{x:h,y:g,crv:y,kty:w}=await p.exportKey("jwk",m),b="direct-key-agreement"===c,E=await th(u,r,b?t.alg:l,b?t.cekBits:parseInt(l.slice(-5,-2),10),d,f),A={x:h,crv:y,kty:w};if("EC"===w&&(A.y=g),s={epk:A},void 0!==a&&(s.apu=et(a)),void 0!==n&&(s.apv=et(n)),b)return[E,void 0,s];u=E;break}case"RSA-OAEP":eS(u),tu(l,u,"encrypt"),n=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,f));break;case"PBKDF2":{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=o;u=await tf(t,l,e,u),s={p2c:e,p2s:et(t)};break}case"AES-GCM":{let e=void 0===o.iv?crypto.getRandomValues(new Uint8Array(12)):o.iv;if(!(e instanceof Uint8Array))throw TypeError('"iv" must be an instance of Uint8Array');let t=await e0(ts(l.slice(0,-2)),f,u,e,new Uint8Array);n=t.ciphertext,s={iv:et(t.iv),tag:et(t.tag)}}}if(!((n??=await tc(l.slice(-6),u,f))instanceof Uint8Array)||!n.byteLength)throw TypeError("JWE key management algorithm did not produce an Encrypted Key");return[f,n,s]}function tI(e,t){if(void 0!==e.zip&&"DEF"!==e.zip)throw new en('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==e.zip&&!t?.zip)throw new el('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function tT(e){if(typeof globalThis[e]>"u")throw new en(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function t_(e,t,r=1/0){let i=e.writable.getWriter();i.write(t).catch(()=>{}),i.close().catch(()=>{});let a=[],o=0,n=e.readable.getReader();for(;;){let{value:e,done:t}=await n.read();if(t)break;if(a.push(e),o+=e.byteLength,1/0!==r&&o>r)throw await n.cancel().catch(()=>{}),new el("Decompressed plaintext exceeded the configured limit")}return V(...a)}async function tv(e){return tT("CompressionStream"),t_(new CompressionStream("deflate-raw"),e)}async function tO(e,t){return tT("DecompressionStream"),t_(new DecompressionStream("deflate-raw"),e,t)}function tk(e,t,r){if(!eg(e,t,r))throw new el("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}async function tR(e,t,r){let i,a,o,n,s,l,[c,d,u]=t,[f,p,m,h,g,y,w,b,,E]=e,A=p,I=m,T=u??to(c.alg);"integrated-encryption"===T.mode?o=await eR(T,r,"encrypt"):[o,i,a]=await tA(T,d,r,c,y,b),a&&(E?I=I?{...I,...a}:a:A=A?{...A,...a}:a,tk(A,I,h));let _=A?et(JSON.stringify(A)):"",v=g?.byteLength?et(g):void 0,O=Q(v?`${_}.${v}`:_),k=f;"DEF"===c.zip&&(k=await tv(k).catch(e=>{throw new el("Failed to compress plaintext",{cause:e})})),"integrated-encryption"===T.mode?[i,n]=await T.encrypt(o,k,O,A,c,b):{ciphertext:n,tag:s,iv:l}=await e0(d,k,o,w,O);let R={ciphertext:et(n)};return l&&(R.iv=et(l)),s&&(R.tag=et(s)),i?.byteLength&&(R.encrypted_key=et(i)),v&&(R.aad=v),A&&(R.protected=_),h&&(R.unprotected=h),I&&(R.header=I),R}async function tx(e,t,r){return tR(e,function(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new el("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");void 0!==t&&(e[8]=t?.crit);let[,i,a,o,n,s,l,c,d]=e;if(void 0!==n&&em(n,"JWE Additional Authenticated Data"),void 0!==s&&em(s,"JWE Content Encryption Key"),void 0!==l&&em(l,"JWE Initialization Vector"),r||void 0===i||(i=ek(el,i)[0],e[1]=i),void 0!==a&&(a=ek(el,a)[0],e[2]=a),r||void 0===o||(o=ek(el,o)[0],e[3]=o),void 0!==c&&!eh(c))throw TypeError("JWE Key Management Parameters must be an object");tk(i,a,o);let u={...i,...a,...o};e_(el,i),ev(el,eI,d,i,u),tI(u,i);let{alg:f,enc:p}=u;if("string"!=typeof f||!f)throw new el('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=te[f];if(m?.mode==="integrated-encryption"){if(void 0!==p)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(void 0!==s)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(void 0!==l)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[u,void 0,m]}if("string"!=typeof p||!p)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[u,ts(p),m]}(e,r),t)}let tS=e=>Math.floor(e.getTime()/1e3),tU={s:1,m:60,h:3600,d:86400,w:604800,y:0x1e187e0},tN=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,tD="check_failed";function tL(){throw TypeError("Invalid time period format")}function tC(e){"string"!=typeof e&&tL();let t=tN.exec(e);(!t||t[4]&&t[1])&&tL();let r=Math.round(parseFloat(t[2])*tU[t[3][0].toLowerCase()]);return Number.isFinite(r)||tL(),"-"===t[1]||"ago"===t[4]?-r:r}function tz(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function tj(e,t){if("string"!=typeof t)throw TypeError(`"${e}" claim must be a string`)}function tP(e,t){return"number"==typeof e?tz(t,e):e instanceof Date?tz(t,tS(e)):tS(new Date)+tC(e)}let tB=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function tM(e,t,r=!1){let i=e[t];if(!(void 0===i&&!r)){if("number"!=typeof i)throw new ei(`"${t}" claim must be a number`,e,t,"invalid");return i}}function t$(e,t){throw new ei(`unexpected "${t}" claim value`,e,t,tD)}function tq(e,t,r={}){let i,a,o;try{i=JSON.parse(F.decode(t))}catch(e){throw new ed("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!eh(i))throw new ed("JWT Claims Set must be a top-level JSON object");let{typ:n}=r;if(void 0!==n&&("string"!=typeof e.typ||tB(e.typ)!==tB(n)))throw new ei('unexpected "typ" JWT header value',i,"typ",tD);let{requiredClaims:s=[],issuer:l,subject:c,audience:d,maxTokenAge:u}=r,f=[...s];for(let e of(void 0!==u&&f.push("iat"),void 0!==d&&f.push("aud"),void 0!==c&&f.push("sub"),void 0!==l&&f.push("iss"),new Set(f.reverse())))if(!Object.hasOwn(i,e))throw new ei(`missing required "${e}" claim`,i,e,"missing");void 0===l||(Array.isArray(l)?l:[l]).includes(i.iss)||t$(i,"iss"),void 0!==c&&i.sub!==c&&t$(i,"sub"),void 0===d||(a=i.aud,o="string"==typeof d?[d]:d,"string"==typeof a?o.includes(a):!!Array.isArray(a)&&o.some(e=>a.includes(e)))||t$(i,"aud");let{clockTolerance:p}=r,m=0;if("string"==typeof p)m=tC(p);else if(void 0!==p){if("number"!=typeof p)throw TypeError("Invalid clockTolerance option type");m=p}if(tz("clockTolerance option",m),m<0)throw TypeError("Invalid clockTolerance option input");let{currentDate:h}=r,g=tz("currentDate option",tS(void 0===h?new Date:h)),y=tM(i,"iat",void 0!==u),w=tM(i,"nbf");if(void 0!==w&&w>g+m)throw new ei('"nbf" claim timestamp check failed',i,"nbf",tD);let b=tM(i,"exp");if(void 0!==b&&b<=g-m)throw new ea('"exp" claim timestamp check failed',i,"exp",tD);if(void 0!==u){let e=g-y,t=tz("maxTokenAge option","number"==typeof u?u:tC(u));if(t<0)throw TypeError("Invalid maxTokenAge option input");if(e-m>t)throw new ea('"iat" claim timestamp check failed (too far in the past)',i,"iat",tD);if(e<-m)throw new ei('"iat" claim timestamp check failed (it should be in the past)',i,"iat",tD)}return i}function tH(e){return r.get(e)}function tF(e){let t=tH(e);for(let e of["iat","nbf","exp"]){let r=t[e];if("number"==typeof r&&!Number.isFinite(r))throw TypeError(`"${e}" claim must be a finite number`)}return q.encode(JSON.stringify(t))}function tV(e,t){return tH(e)[t]}class tW{constructor(e={}){if(!eh(e))throw TypeError("JWT Claims Set MUST be an object");(r||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return tj("iss",e),tH(this).iss=e,this}setSubject(e){return tj("sub",e),tH(this).sub=e,this}setAudience(e){return function(e){if("string"!=typeof e&&(!Array.isArray(e)||Array.from(e).some(e=>"string"!=typeof e)))throw TypeError('"aud" claim must be a string or an array of strings')}(e),tH(this).aud=e,this}setJti(e){return tj("jti",e),tH(this).jti=e,this}setNotBefore(e){return tH(this).nbf=tP(e,"setNotBefore"),this}setExpirationTime(e){return tH(this).exp=tP(e,"setExpirationTime"),this}setIssuedAt(e){let t=tH(this);return void 0===e?t.iat=tS(new Date):"string"==typeof e?t.iat=tz("setIssuedAt",tS(new Date)+tC(e)):t.iat=tP(e,"setIssuedAt"),this}}e.s(["C",0,tW,"o",0,tV,"w",0,tF,"L",0,tq],24472);let tK=tW;class tG extends tK{#e=[void 0];#t;#r;#i;setProtectedHeader(e){return ey(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return ey(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}setContentEncryptionKey(e){return ey(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return ey(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#r=!0,this}replicateAudienceAsHeader(){return this.#i=!0,this}async encrypt(e,t){var r;let i=tF(this);this.#e[1]&&(this.#t||this.#r||this.#i)&&(this.#e[1]={...this.#e[1],iss:this.#t?tV(this,"iss"):void 0,sub:this.#r?tV(this,"sub"):void 0,aud:this.#i?tV(this,"aud"):void 0});let a=[...this.#e];return a[0]=i,[(r=await tx(a,e,t)).protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}let tJ=[["verify"],["sign"]];function tQ(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:tJ}}function tY(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:tJ,minRsaBits:2048}}function tZ(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:tJ}}function tX(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:tJ}}function t0(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:tJ}}let t1=e2({HS256:tQ(256),HS384:tQ(384),HS512:tQ(512),RS256:tY(256),RS384:tY(384),RS512:tY(512),PS256:tY(256,32),PS384:tY(384,48),PS512:tY(512,64),ES256:tZ("P-256",256),ES384:tZ("P-384",384),ES512:tZ("P-521",512),EdDSA:tX(),Ed25519:tX(),"ML-DSA-44":t0(44),"ML-DSA-65":t0(65),"ML-DSA-87":t0(87)});function t2(e){let t="string"==typeof e?t1[e]:void 0;if(!t)throw new en(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}async function t5(e,t,r){let[i,a,o,n]=e,s="";if(void 0!==a){let e=ek(ec,a);a=e[0],s=et(e[1])}if(void 0!==o&&(o=ek(ec,o)[0]),!a&&!o)throw new ec("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eg(a,o))throw new ec("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...a,...o};e_(ec,a);let c=eO(a,ev(ec,eA,n,a,l));c||r?.();let{alg:d}=l;if("string"!=typeof d||!d)throw new ec('JWS "alg" (Algorithm) Header Parameter missing or invalid');let u=t2(d),f="",p=i,m;if(c){let t=e[4];t?(f=t[0]??=et(i),p=t[1]??=Q(f)):(f=et(i),m=q.encode(`${s}.${f}`))}m??=V(Q(s),Q("."),p);let h=await eV(await eR(u,t,"sign"),u.subtle,"sign");u.minRsaBits&&eB(u.alg,h);let g={signature:et(new Uint8Array(await crypto.subtle.sign(u.signing,h,m))),payload:f};return a&&(g.protected=s),o&&(g.header=o),[g,c]}async function t6(e,t,r,i,a){let[o]=await t5([e,t,void 0,r],i,a);return`${o.protected}.${o.payload}.${o.signature}`}e.s(["K",0,t1,"l",0,t2],16760);let t8=tW;class t4 extends t8{#a;setProtectedHeader(e){return ey(this.#a,"setProtectedHeader"),this.#a=e,this}async sign(e,t){return t6(tF(this),this.#a,t?.crit,e,()=>{throw new ed("JWTs MUST NOT use unencoded payload")})}}e.s(["f",0,t4],27957);var t3=e.i(63370);e.s(["f",0,t3],1889);var t3=t3;let t9='"alg" (Algorithm)';function t7(e='JWK "alg" (Algorithm) Parameter'){throw new en(`Invalid or unsupported ${e} value`)}function re(e,t){return("string"==typeof e?t1[e]??te[e]:void 0)??t7(t)}let rt=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},rr=e=>{let t=e.data[e.pos++];if(void 0===t)throw Error("Unexpected end of ASN.1 input");return t},ri=e=>{let t=rr(e);if(128&t){let r=127&t,i=0;for(let t=0;t<r;t++)i=i<<8|rr(e);return i}return t},ra=(e,t,r)=>{if(rr(e)!==t)throw Error(r)},ro=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},rn=async(e,t,r,i)=>{let a,o=eH(i?.extractable),n=re(r,t9);n.secret&&t7(t9);let s="spki"===e;if(n.resolve)try{let r={data:t,pos:0};(function(e,t){if(ra(e,48,`Invalid ${"spki"===t?"SPKI":"PKCS#8"} structure`),ri(e),"pkcs8"===t){ra(e,2,"Expected version field");let t=ri(e);e.pos+=t}ra(e,48,"Expected algorithm identifier"),ri(e)})(r,e),a=n.resolve({crv:(e=>{let t,r=(ra(e,6,"Expected algorithm OID"),t=ri(e),ro(e,t));if(rt(r,[43,101,110]))return"X25519";if(!rt(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");ra(e,6,"Expected curve OID");let i=ri(e),a=ro(e,i);if(rt(a,[42,134,72,206,61,3,1,7]))return"P-256";if(rt(a,[43,129,4,0,34]))return"P-384";if(rt(a,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")})(r)})}catch(e){throw new en("Invalid or unsupported key format",{cause:e})}else a=n.subtle;return crypto.subtle.importKey(e,t,a,o??s,n.usages[+!s])};async function rs(e){if(eN(e))if("secret"!==e.type)return e.export({format:"jwk"});else e=e.export();if(e instanceof Uint8Array)return{kty:"oct",k:et(e)};if(!eU(e))throw TypeError(eC(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);for(let e of(delete t.ext,delete t.key_ops,delete t.use,"AKP"!==t.kty&&delete t.alg,Object.keys(t)))void 0===t[e]&&delete t[e];return t}let rl=(e,t)=>{if("string"!=typeof e||!e)throw new eu(`${t} missing or invalid`)};async function rc(e,t){let r,i;if(eh(e)){if("string"!=typeof(r=e$(e)).kty)throw TypeError(eC(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(eD(e))r=e$(await rs(e));else throw TypeError(eC(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":rl(r.alg,'"alg" (Algorithm) Parameter'),rl(r.pub,'"pub" (Public key) Parameter'),i={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":rl(r.crv,'"crv" (Curve) Parameter'),rl(r.x,'"x" (X Coordinate) Parameter'),rl(r.y,'"y" (Y Coordinate) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":rl(r.crv,'"crv" (Subtype of Key Pair) Parameter'),rl(r.x,'"x" (Public Key) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":rl(r.e,'"e" (Exponent) Parameter'),rl(r.n,'"n" (Modulus) Parameter'),i={e:r.e,kty:r.kty,n:r.n};break;case"oct":if("string"!=typeof r.k)throw new eu('"k" (Key Value) Parameter missing or invalid');i={k:r.k,kty:r.kty};break;default:throw new en('"kty" (Key Type) Parameter missing or unsupported')}let a=Q(JSON.stringify(i));return et(await X(t,a))}function rd(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");let r="Invalid Token or Protected Header formatting";if("string"!=typeof t||!t)throw TypeError(r);return eE(t,TypeError,r)}async function ru(e,t,r,i=function(e){let t,{protected:r,ciphertext:i,iv:a,tag:o,aad:n}=e;return void 0!==r&&(t=eE(r,el,"JWE Protected Header is invalid")),[t,ew(i,"ciphertext",el),void 0!==a?ew(a,"iv",el):void 0,void 0!==o?ew(o,"tag",el):void 0,eb((r??"")+(void 0!==n?`.${n}`:""),"aad",el)]}(e)){let a,o,n,s,[l,c,d,u,f]=i,{header:p,unprotected:m,aad:h}=e;if(void 0!==p||void 0!==m){if(!eg(l,p,m))throw new el("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");a={...l,...p,...m}}else a=l??{};let[g,y,w,b,E]=t,{encrypted_key:A}=e;ev(el,eI,w,l,a),tI(a,l);let{alg:I,enc:T}=a;if("string"!=typeof I||!I)throw new el("missing JWE Algorithm (alg) in JWE Header");let _=te[I];if(""===A&&(!_||!tn(_)))throw new el("JWE Encrypted Key incorrect type");let v=_?.mode==="integrated-encryption";if(!v&&("string"!=typeof T||!T))throw new el("missing JWE Encryption Algorithm (enc) in JWE Header");if(g&&!g.has(I)||!g&&I.startsWith("PBES2"))throw new eo('"alg" (Algorithm) Header Parameter value not allowed');if(v){if(void 0!==T)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(d?.byteLength)throw new el("JWE Initialization Vector must be empty for integrated encryption");if(u?.byteLength)throw new el("JWE Authentication Tag must be empty for integrated encryption")}else{if(y&&!y.has(T))throw new eo('"enc" (Encryption Algorithm) Header Parameter value not allowed');o=ts(T)}if(void 0!==A)try{n=ew(A,"encrypted_key",el)}catch(e){if(!_||!tn(_))throw e;n=new Uint8Array}let O=!1;"function"==typeof r&&(r=await r(l,e),O=!0);let k=_??to(I);tn(k)&&void 0===n&&(n=new Uint8Array);let R=await eR("direct-encryption"===k.mode?o:k,r,"decrypt");if("integrated-encryption"===k.mode)s=await k.decrypt(R,n,c,f,l,a);else{let e,t=o;try{e=await tE(k,t,R,n,a,b),tn(k)&&e instanceof Uint8Array&&e.byteLength<<3!==t.cekBits&&(e=eW(t))}catch(r){if(r instanceof TypeError||r instanceof el||r instanceof en)throw r;e=eW(t)}s=await e1(t,e,c,d,u,f)}if("DEF"===a.zip){let e=E??25e4;if(0===e)throw new en('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');s=await tO(s,e).catch(e=>{throw e instanceof el?e:new el("Failed to decompress plaintext",{cause:e})})}return{plaintext:s,...l&&{protectedHeader:l},...void 0!==h&&{additionalAuthenticatedData:ew(h,"aad",el)},...m&&{sharedUnprotectedHeader:m},...p&&{unprotectedHeader:p},...O&&{key:R}}}async function rf(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),"string"!=typeof e)throw new el("Compact JWE must be a string or Uint8Array");let{0:i,1:a,2:o,3:n,4:s,length:l}=e.split(".");if(5!==l)throw new el("Invalid Compact JWE");return ru({ciphertext:n,iv:o||void 0,protected:i,tag:s||void 0,encrypted_key:a||void 0},t,r)}async function rp(e,t,r){let{plaintext:i,...a}=await rf(e,function(e){let t=e&&eT("keyManagementAlgorithms",e.keyManagementAlgorithms),r=e&&eT("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),{crit:i,maxPBES2Count:a,maxDecompressedLength:o}=e??{};if(void 0!==a&&1/0!==a&&(!Number.isSafeInteger(a)||a<1))throw TypeError("maxPBES2Count must be a positive safe integer or Infinity");let n=o??25e4;if(0!==n&&1/0!==n&&(!Number.isSafeInteger(n)||n<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");return[t,r,i,a,o]}(r),t),{protectedHeader:o}=a,n=tq(o,i,r);for(let e of["iss","sub","aud"])if(void 0!==o[e]&&("aud"===e?JSON.stringify(o.aud)!==JSON.stringify(n.aud):o[e]!==n[e]))throw new ei(`replicated "${e}" claim header parameter mismatch`,n,e,"mismatch");return{payload:n,...a}}function rm(e){try{return Q(e)}catch(e){throw new ec("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}async function rh(e,t,r,i,a){let{protected:o,header:n,payload:s}=e,l=a??(void 0===o?{}:eE(o,ec,"JWS Protected Header is invalid"));if(!eg(l,n))throw new ec("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...l,...n},d=eO(l,ev(ec,eA,t[1],l,c)),{alg:u}=c;if("string"!=typeof u||!u)throw new ec('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(u))throw new eo('"alg" (Algorithm) Header Parameter value not allowed');if(d){if("string"!=typeof s)throw new ec("JWS Payload must be a string")}else if("string"!=typeof s&&!(s instanceof Uint8Array))throw new ec("JWS Payload must be a string or an Uint8Array instance");let f=d||"string"!=typeof s?s:i(s),p=!1;"function"==typeof r&&(r=await r(l,e),p=!0);let m=t2(u),h=V(void 0!==o?Q(o):new Uint8Array,Q("."),"string"==typeof f?t[2]??=eb(f,"payload",ec):f),g=ew(e.signature,"signature",ec),y=await eR(m,r,"verify"),w=await eV(y,m.subtle,"verify");m.minRsaBits&&eB(m.alg,w);let b=!1;try{b=await crypto.subtle.verify(m.signing,w,g,h)}catch(e){throw new ep(void 0,{cause:e})}if(!b)throw new ep;let E={payload:"string"==typeof f?ew(f,"payload",ec):f};return void 0!==o&&(E.protectedHeader=l),void 0!==n&&(E.unprotectedHeader=n),p?[{...E,key:y},d]:[E,d]}async function rg(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),"string"!=typeof e)throw new ec("Compact JWS must be a string or Uint8Array");let{0:i,1:a,2:o,length:n}=e.split(".");if(3!==n)throw new ec("Invalid Compact JWS");return rh({payload:a,protected:i,signature:o},t,r,rm)}async function ry(e,t,r){let[i,a]=await rg(e,[r&&eT("algorithms",r.algorithms),r?.crit],t);if(!a)throw new ed("JWTs MUST NOT use unencoded payload");let o=tq(i.protectedHeader,i.payload,r);return{...i,payload:o}}async function rw(e,t,r=3600){return await new t4(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function rb(e,t){try{return(await ry(e,new TextEncoder().encode(t))).payload}catch{return null}}e.s(["f",0,rc],12319),e.s(["f",0,rd],41242),e.s(["f",0,ry],9939);let rE=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]),rA="A256CBC-HS512";function rI(e,t){return _($,new TextEncoder().encode(e),new TextEncoder().encode(t),rE,64)}function rT(e){if("string"==typeof e)return[{version:0,value:e}];let t=[];for(let[r,i]of e.keys)t.push({version:r,value:i});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function r_(e,t,r,i=3600){let a=rI(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),o=await rc({kty:"oct",k:t3.encode(a)},"sha256");return await new tG(e).setProtectedHeader({alg:"dir",enc:rA,kid:o}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+i).setJti(crypto.randomUUID()).encrypt(a)}let rv={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[rA,"A256GCM"]};async function rO(e,t,r){if(!e)return null;let i=!1;try{i=void 0!==rd(e).kid}catch{return null}try{let i=rT(t),{payload:a}=await rp(e,async e=>{let t=e.kid;if(void 0!==t){for(let e of i){let i=rI(e.value,r);if(t===await rc({kty:"oct",k:t3.encode(i)},"sha256"))return i}throw Error("no matching decryption secret")}return i.length,rI(i[0].value,r)},rv);return a}catch{if(i)return null;let a=rT(t);if(a.length<=1)return null;for(let t=1;t<a.length;t++)try{let i=a[t],o=rI(i.value,r),{payload:n}=await rp(e,o,rv);return n}catch{continue}return null}}e.s(["X",0,rw,"y",0,rO,"h",0,r_,"u",0,rb],75742);var rk=e.i(69774),rR=e.i(10228);function rx(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}),{})}e.s(["f",0,rx],74285);let rS=new WeakMap;function rU(e,t,r){let i=`${t}:${r}`;rS.has(e)||rS.set(e,new Map);let a=rS.get(e);if(a.has(i))return a.get(i);let o="output"===r?(0,rk.R)(e)[t]?.fields??{}:{},n="user"===t||"session"===t||"account"===t?e[t]?.additionalFields:void 0,s={...o,...n??{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(s={...s,...r.schema[t].fields});return a.set(i,s),s}function rN(e,t){return rx(t,rU(e,"user","output"))}function rD(e,t){return rx(t,rU(e,"session","output"))}function rL(e,t){let r=t.action||"create",i=t.fields,a=Object.create(null);for(let t in i){if(t in e){if(!1===i[t].input){if(void 0!==i[t].defaultValue&&"update"!==r){a[t]=i[t].defaultValue;continue}if(e[t])throw l.E.from("BAD_REQUEST",{...rR.f.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(i[t].validator?.input&&void 0!==e[t]){let r=i[t].validator.input["~standard"].validate(e[t]);if(r instanceof Promise)throw l.E.from("INTERNAL_SERVER_ERROR",rR.f.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in r&&r.issues)throw l.E.from("BAD_REQUEST",{...rR.f.VALIDATION_ERROR,message:r.issues[0]?.message||"Validation Error"});a[t]=r.value;continue}if(i[t].transform?.input&&void 0!==e[t]){a[t]=i[t].transform?.input(e[t]);continue}a[t]=e[t];continue}if(void 0!==i[t].defaultValue&&"create"===r){if("function"==typeof i[t].defaultValue){a[t]=i[t].defaultValue();continue}a[t]=i[t].defaultValue;continue}if(i[t].required&&"create"===r)throw l.E.from("BAD_REQUEST",{...rR.f.MISSING_FIELD,message:`${t} is required`})}return a}e.s(["g",0,function(e,t){let r=rU(e,"user","output"),i={};for(let e in r){let a=r[e];!1!==a.returned&&(e in t&&void 0!==t[e]?i[e]=t[e]:void 0!==a.defaultValue?i[e]="function"==typeof a.defaultValue?a.defaultValue():a.defaultValue:a.required||(i[e]=null))}return"id"in t&&(i.id=t.id),i},"P",0,function(e){let t=rU(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},"s",0,function(e,t){let{accessToken:r,refreshToken:i,idToken:a,accessTokenExpiresAt:o,refreshTokenExpiresAt:n,password:s,...l}=rx(t,rU(e,"account","output"));return l},"W",0,function(e,t={},r){let i=rU(e,"user","input"),a=Object.create(null);for(let e of Object.keys(t))i[e]?.input!==!1&&(a[e]=t[e]);return rL(a,{fields:i,action:r})},"z",0,function(e,t,r){return rL(t,{fields:rU(e,"session","input"),action:r})},"Q",0,rD,"R",0,function(e,t={},r){return rL(t,{fields:rU(e,"user","input"),action:r})},"$",0,rN],56023);let rC=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e));function rz(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.s(["f",0,rC],42158),e.s(["f",0,rz],76660);let rj=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;var rP=e.i(7855);let rB=rP.object({id:rP.string(),createdAt:rP.date().default(()=>new Date),updatedAt:rP.date().default(()=>new Date)});var rM=e.i(62061);e.s(["bigint",0,function(e){return rM.Br(rP.ZodBigInt,e)},"boolean",0,function(e){return rM.HN(rP.ZodBoolean,e)},"date",0,function(e){return rM.fj(rP.ZodDate,e)},"number",0,function(e){return rM.NE(rP.ZodNumber,e)},"string",0,function(e){return rM.jK(rP.ZodString,e)}],34512);var r$=e.i(34512);e.s(["f",0,r$],54257);var r$=r$;let rq=rB.extend({userId:r$.string(),expiresAt:rP.date(),token:rP.string(),ipAddress:rP.string().nullish(),userAgent:rP.string().nullish()}),rH=rB.extend({email:rP.string().transform(e=>e.toLowerCase()),emailVerified:rP.boolean().default(!1),name:rP.string(),image:rP.string().nullish()});var rF=e.i(90126),rV=e.i(30283);let rW=rP.looseObject({session:rq.loose(),user:rH.loose(),updatedAt:rP.number(),version:rP.string().optional()}),rK=rP.object({session:rP.record(rP.string(),rP.unknown()),expiresAt:rP.number(),signature:rP.string()});function rG(e){let t=(0,rV.f)(e);if(null===t)return null;let r=rW.safeParse(t);return r.success?r.data:(rF.y.warn("Cookie cache payload failed schema validation",{issues:r.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}var rJ=e.i(46754);async function rQ(e,t,r){let i;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return rn("pkcs8",(i=/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,Z(e.replace(i,""))),t,r)}async function rY(e,t,r){if(!eh(e))throw TypeError("JWK must be an object");let i=eq(e),a=eH(r?.extractable),{alg:o}=i;if(t??=o,"oct"!==i.kty&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(i.kty){case"oct":if("string"!=typeof i.k)throw TypeError('missing "k" (Key Value) Parameter value');return ee(i.k);case"AKP":if("string"!=typeof o||!o)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==o)throw TypeError("JWK alg and alg option value mismatch");return eF(re(t),i,a);case"RSA":case"EC":case"OKP":return eF(re(t),i,a);default:throw new en('Unsupported "kty" (Key Type) Parameter value')}}e.s(["g",0,rY,"r",0,rQ],97554),e.i(18069);var rZ=e.i(44336),r$=r$;function rX(e,t){let r=`${e}.`;if(!t.startsWith(r))return null;let i=t.slice(r.length),a=Number(i);return!Number.isSafeInteger(a)||a<0||String(a)!==i?null:a}let r0=e=>(t,r,i)=>{let a=function(e,t){let r={};for(let[i,a]of(0,rJ.X)(t.headers?.get("cookie")||""))(i===e||null!==rX(e,i))&&(r[i]=a);return r}(t,i),o=i.context.logger,n=()=>{let e=function(e,t){let r={};for(let i in e)r[i]={name:i,value:"",attributes:{...t,maxAge:0}};return r}(a,r);for(let e in a)delete a[e];return e};return{chunk(i,s){let l=n();for(let n of function(e,t,r,i){var a,o;let n=(a=`${t.name}.99`,o=t.attributes,4050-(0,rZ.j)(a,"",{...o}).length),s=n>0?Math.ceil(t.value.length/n):1/0;if(s<=1)return r[t.name]=t.value,[t];if(s>100)return i.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let l=[];for(let e=0;e<s;e++){let i=`${t.name}.${e}`,a=e*n,o=t.value.substring(a,a+n);l.push({...t,name:i,value:o}),r[i]=o}return i.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the 4050 byte limit and was split into ${s} chunks.`,valueSize:t.value.length,chunkCount:s,chunkSizes:l.map(e=>e.value.length)}),l}(e,{name:t,value:i,attributes:{...r,...s}},a,o))l[n.name]=n;return Object.values(l)},clean:()=>Object.values(n()),setCookies(e){for(let t of e)i.setCookie(t.name,t.value,t.attributes)}}},r1=r0("Session"),r2=r0("Account");function r5(e,t){let r=e.getCookie(t);if(r)return r;let i=[],a=e.headers?.get("cookie");if(!a)return null;for(let[e,r]of(0,rJ.X)(a)){let a=rX(t,e);null!==a&&i.push({index:a,value:r})}return i.length>0?(i.sort((e,t)=>e.index-t.index),i.map(e=>e.value).join("")):null}async function r6(e,t){let r=e.context.authCookies.accountData,i={maxAge:300,...r.attributes},a=await r_(t,e.context.secretConfig,"better-auth-account",i.maxAge),o=r2(r.name,i,e);o.setCookies(o.chunk(a,i))}async function r8(e){let t=r5(e,e.context.authCookies.accountData.name);if(t){let r=(0,rV.f)(await rO(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}let r4=rP.optional(rP.object({disableCookieCache:r$.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:r$.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));e.s(["v",0,r2,"X",0,r1,"q",0,r8,"K",0,r5,"H",0,r4,"L",0,r6],96161);var r3=e.i(30501);let r9=new Map;new TextEncoder;var r7=e.i(96101),ie=e.i(16029),it=e.i(72381);let ir=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>(0,r7.f)().importKey("raw",(0,ie.Y)(t),{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,i)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let a=await (0,r7.f)().sign("HMAC",e,(0,ie.Y)(i));return"hex"===t?it.f.encode(a):"base64"===t?r3.t.encode(a):"base64url"===t||"base64urlnopad"===t?r3.W.encode(a,{padding:"base64urlnopad"!==t}):a},verify:async(e,i,a)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(a="string"==typeof a?it.f.toBytes(a):a),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(a=await r3.t.decode(a)),(0,r7.f)().verify("HMAC",e,(0,ie.Y)(a),(0,ie.Y)(i)))};return r};function ii(e){let t="string"==typeof e.baseURL?e.baseURL:void 0,r="object"==typeof e.baseURL&&null!==e.baseURL?e.baseURL.protocol:void 0,i=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:"https"===r||"http"!==r&&(t?t.startsWith("https://"):s.C))?rJ.d:"",a=!!e.advanced?.crossSubDomainCookies?.enabled,o=a?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(a&&!o&&!m(e.baseURL))throw new l.p("baseURL is required when crossSubdomainCookies are enabled.");return function(t,r={}){let n=e.advanced?.cookiePrefix||"better-auth",s=e.advanced?.cookies?.[t]?.name||`${n}.${t}`,l=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${i}${s}`,attributes:{secure:!!i,sameSite:"lax",path:"/",httpOnly:!0,...a?{domain:o}:{},...e.advanced?.defaultCookieAttributes,...r,...l}}}}async function ia(e,t,r){let i;if(!e.context.options.session?.cookieCache?.enabled)return;let a=rx(t.session,e.context.options.session?.additionalFields),o=rN(e.context.options,t.user),n=e.context.options.session?.cookieCache?.version,s="1";if(n){if("string"==typeof n)s=n;else if("function"==typeof n){let e=n(t.session,t.user);s=rz(e)?await e:e}}let l={session:a,user:o,updatedAt:Date.now(),version:s},c={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},d=rC(c.maxAge||60,"sec").getTime(),u=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===u)i=await r_(l,e.context.secretConfig,"better-auth-session",c.maxAge||300);else if("jwt"===u){let t=e.context.sessionConfig.cookieCacheSigner;i=t?await t.sign(e,l,c.maxAge||300):await rw(l,e.context.secret,c.maxAge||300)}else i=r3.W.encode(JSON.stringify({session:l,expiresAt:d,signature:await ir("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...l,expiresAt:d}))}),{padding:!1});let f=r1(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(i,c)),e.context.options.account?.storeAccountCookie&&!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if(("function"==typeof e.getSetCookie?e.getSetCookie():(0,rJ.Z)(e.get("set-cookie")||"")).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}(e,e.context.authCookies.accountData.name)){let r=await r8(e);if(r)if(w(e.context.options)&&r.userId!==t.user.id){il(e,e.context.authCookies.accountData);let t=r2(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}else await r6(e,r)}}async function io(e,t){var r;let i,a=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===a){let r=await rO(t,e.context.secretConfig,"better-auth-session"),i=rG(r);return i?{session:i,expiresAt:r?.exp?1e3*r.exp:Date.now()}:null}if("jwt"===a){let r=e.context.sessionConfig.cookieCacheSigner;if(r){let i=await r.verify(e,t);return i?{session:i.payload,expiresAt:i.expiresAt}:null}let i=await rb(t,e.context.secret),a=rG(i);return a?{session:a,expiresAt:i?.exp?1e3*i.exp:Date.now()}:null}let o=(r=(0,rV.f)(((e,t="utf-8")=>(r9.has(t)||r9.set(t,new TextDecoder(t)),r9.get(t).decode(e)))(r3.W.decode(t))),(i=rK.safeParse(r)).success?i.data:null);if(!o||!await ir("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature))return null;let n=rG(o.session);return n?{session:n,expiresAt:o.expiresAt}:null}async function is(e,t,r,i){let a=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!a;let o=e.context.authCookies.sessionToken.attributes,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...o,maxAge:n,...i}),r?await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes):a&&il(e,e.context.authCookies.dontRememberToken),await ia(e,t,r),e.context.setNewSession(t)}function il(e,t){!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t="function"==typeof e.getSetCookie?e.getSetCookie():(0,rJ.Z)(e.get("set-cookie")||"");if(!t.length)continue;let r=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));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 ic(e,t){if(il(e,e.context.authCookies.sessionToken),il(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){il(e,e.context.authCookies.accountData);let t=r2(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),r=t.clean();t.setCookies(r)}"cookie"===e.context.oauthConfig.storeStateStrategy&&il(e,e.context.createAuthCookie("oauth_state"));let r=r1(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),i=r.clean();r.setCookies(i),t||il(e,e.context.authCookies.dontRememberToken)}e.s(["g",0,ii,"J",0,io,"Q",0,ic,"c",0,il,"e",0,function(e){let t=ii(e),r=t("session_token",{maxAge:e.session?.expiresIn||Math.round(function(){let e,t=rj.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]),i=t[3].toLowerCase();switch(i){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: "${i}"`)}return"-"===t[1]||"ago"===t[4]?-e:e}()/1e3)}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),a=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),o=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:i.name,attributes:i.attributes},dontRememberToken:{name:o.name,attributes:o.attributes},accountData:{name:a.name,attributes:a.attributes}}},"b",0,ia,"V",0,is],70728),e.s(["f",0,function(e,t){return{digest:async r=>{let i=(0,ie.Y)(r),a=await (0,r7.f)().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")?r3.W.encode(a,{padding:"base64urlnopad"!==t}):r3.t.encode(a):a}}}],82318);var id=e.i(73278),iu=e.i(14268),ip=e.i(95934);let im=async()=>{let e=(0,iu.l)(),t=e.context.adapterAsyncStorage;if(t)return t;let r=await (0,ip.f)();return e.context.adapterAsyncStorage??=new r,e.context.adapterAsyncStorage},ih=async e=>im().then(t=>t.getStore()?.adapter||e).catch(()=>e),ig=async(e,t)=>{let r=!1;return im().then(async i=>{let a,o;r=!0;let n=[],s=!1;try{a=await i.run({adapter:e,pendingHooks:n,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of n)await e();if(s)throw o;return a}).catch(e=>{if(!r)return t();throw e})},iy=async(e,t,r)=>{let i=!1;return im().then(async a=>{let o,n;if(i=!0,a.getStore()?.isTransactionActive)return t();let s=(0,id.f)(e)?.();s&&await s;let l=[],c=!1;try{o=await e.transaction(async e=>(l=[],a.run({adapter:e,pendingHooks:l,isTransactionActive:!0},t)))}catch(e){c=!0,n=e}let d=async e=>{for(let t of l)try{await t()}catch(t){if(!r?.onAfterCommitHookError){if("throw"===e)throw t;try{rF.y.error("Failed to run an after-commit hook for work that could not roll back",t)}catch{}continue}try{await r.onAfterCommitHookError(t)}catch{}}};if(c)throw e.options?.adapterConfig.transaction===!1&&await d("log"),n;return await d("throw"),o}).catch(e=>{if(!i)return t();throw e})},iw=async(e,t)=>{let r,i=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}};try{r=await im()}catch{return i()}let a=r.getStore();if(!a?.isTransactionActive)return i();a.pendingHooks.push(i)};e.s(["g",0,ih,"A",0,iw,"Q",0,ig,"n",0,iy],73436);var ib=e.i(86198),iE=e.i(80849),iA=e.i(90659);let iI=()=>(0,iA.g)("/get-session",{method:["GET","POST"],operationId:"getSession",query:r4,requireHeaders:!0,disableBody:!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=>{e.setHeader("cache-control","no-store"),e.setHeader("pragma","no-cache"),e.context.session=null;let t=e.context.options.session?.deferSessionRefresh,r="POST"===e.method;if(r&&!t)throw l.E.from("METHOD_NOT_ALLOWED",rR.f.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let i=e.context.options.session?.cookieCache?.enabled===!0,a=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!a&&i)return null;let o=r5(e,e.context.authCookies.sessionData.name);if(o&&!i){let t=r1(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!a)return null;let n=i&&!e.query?.disableCookieCache,s=n&&o?await io(e,o):null;n&&o&&!s&&il(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,r=t.session.token!==a;if(!r){let i=e.context.options.session?.cookieCache?.version,a="1";if(i){if("string"==typeof i)a=i;else if("function"==typeof i){let e=i(t.session,t.user);a=e instanceof Promise?await e:e}}r=(t.version||"1")!==a}if(!r){let e=Date.now(),i=new Date(t.session.expiresAt).getTime();r=s.expiresAt<e||!Number.isFinite(i)||i<e}if(r)il(e,e.context.authCookies.sessionData);else{let r=e.context.sessionConfig.cookieRefreshCache;if(!1===r){e.context.session=t;let r=rD(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),i=rN(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:r,user:i})}let i=s.expiresAt-Date.now(),a=1e3*r.updateAge,o=await (0,iE.T)();if(i<a&&!o){let r={session:{...t.session},user:t.user,updatedAt:Date.now()};await ia(e,r,!1);let i=e.context.authCookies.sessionToken.attributes,a=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:a});let o=rD(e.context.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),n=rN(e.context.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)});return e.context.session={session:o,user:n},e.json({session:o,user:n})}let n=rD(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=rN(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:n,user:l},e.json({session:n,user:l})}}let d=await e.context.internalAdapter.findSession(a);if(!d||d.session.expiresAt<new Date)return ic(e),d&&(!t||r)&&await e.context.internalAdapter.deleteSession(d.session.token),e.json(null);if(e.context.session=d,c||e.query?.disableRefresh){let t=rD(e.context.options,d.session),r=rN(e.context.options,d.user);return e.json({session:t,user:r})}let u=e.context.sessionConfig.expiresIn,f=e.context.sessionConfig.updateAge,p=d.session.expiresAt.valueOf()-1e3*u+1e3*f<=Date.now(),m=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,h=await (0,iE.T)(),g=p&&!m&&!h;if(t&&!r){await ia(e,d,!!c);let t=rD(e.context.options,d.session),r=rN(e.context.options,d.user);return e.json({session:t,user:r,needsRefresh:g})}if(g){let t=await e.context.internalAdapter.updateSession(d.session.token,{expiresAt:rC(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)throw ic(e),l.E.from("UNAUTHORIZED",rR.f.FAILED_TO_GET_SESSION);let r=e.context.sessionConfig.expiresIn;await is(e,{session:t,user:d.user},!1,{maxAge:r});let i=rD(e.context.options,t),a=rN(e.context.options,d.user);return e.json({session:i,user:a})}await ia(e,d,!!c);let y=rD(e.context.options,d.session),w=rN(e.context.options,d.user);return e.json({session:y,user:w})}catch(t){if(e.context.session=null,(0,ib.f)(t))throw t;throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),l.E.from("INTERNAL_SERVER_ERROR",rR.f.FAILED_TO_GET_SESSION,{cause:t})}}),iT=e=>y(e.context.options),i_=async(e,t)=>{if(e.context.session)return e.context.session;let r=await iI()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return r?(r.headers&&r.headers.forEach((t,r)=>{let i=r.toLowerCase();"cache-control"!==i&&"pragma"!==i&&("set-cookie"===i?e.responseHeaders.append(r,t):e.responseHeaders.set(r,t))}),e.context.session=r.response,r.response):(e.context.session=null,null)},iv=async e=>iT(e)?(e.context.session=null,i_(e,{disableCookieCache:!0})):i_(e),iO=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),ik=(0,iA.a)(async e=>{let t=await iv(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),iR=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session&&(e.request||e.headers))throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),ix=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw l.E.from("FORBIDDEN",rR.f.SESSION_NOT_FRESH)}return{session:t}}),iS=(0,iA.g)("/revoke-session",{method:"POST",body:rP.object({token:rP.string().meta({description:"The token to revoke"})}),use:[ik],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),l.E.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t===e.context.session.session.token&&ic(e),e.json({status:!0})}),iU=(0,iA.g)("/revoke-sessions",{method:"POST",use:[ik],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),l.E.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return ic(e),e.json({status:!0})}),iN=(0,iA.g)("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[ik],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 l.E.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})});e.s(["h",0,ix,"M",0,iv,"v",0,iI,"D",0,i_,"f",0,iT,"T",0,()=>(0,iA.g)("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[ix],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=>rD(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),"b",0,iR,"Y",0,iN,"G",0,iS,"$",0,iU,"i",0,ik,"Z",0,iO],12996)},72003,e=>{"use strict";e.s(["f",0,"1.7.25"],72003)},18516,e=>e.a(async(t,r)=>{try{var i=e.i(60338),a=e.i(75225),o=e.i(24924),n=e.i(92335),s=e.i(45967),l=t([o]);async function c(e){return o.r.transaction(async t=>1!==((await t.select({n:(0,i.H)()}).from(s.organization))[0]?.n??0)?0:(await t.update(n.c).set({organizationId:e}).where((0,a.M)(n.c.organizationId)).returning({id:n.c.id})).length)}[o]=l.then?(await l)():l,e.s(["f",0,c]),r()}catch(e){r(e)}},!1),18188,e=>e.a(async(t,r)=>{try{var i=e.i(71616),a=e.i(75225),o=e.i(60338),n=e.i(24924),s=e.i(92335),l=e.i(45967),c=e.i(120),d=e.i(81822),u=e.i(82283),f=t([n,c,d]);[n,c,d]=f.then?(await f)():f;let g=["queued","running","waiting_approval"];async function p(e){let t=await n.r.select({id:l.organization.id,name:l.organization.name,role:l.member.role}).from(l.member).innerJoin(l.organization,(0,a.u)(l.organization.id,l.member.organizationId)).where((0,a.u)(l.member.userId,e)),r={deleted:[],left:[],blocked:[]};for(let i of t){if(((await n.r.select({n:(0,o.H)()}).from(l.member).where((0,a.b)((0,a.u)(l.member.organizationId,i.id),(0,a.c)(l.member.userId,e))))[0]?.n??0)>0){"owner"===i.role?r.blocked.push(u.f.auth.deleteBlockedOwner(i.name)):r.left.push({id:i.id,name:i.name});continue}let t=(await n.r.select({id:s.c.id}).from(s.c).where((0,a.u)(s.c.organizationId,i.id))).map(e=>e.id),c=t.length?await n.r.select({status:s.B.status}).from(s.B).where((0,a.y)(s.B.projectId,t)):[];c.some(e=>g.includes(e.status))&&r.blocked.push(u.f.auth.deleteBlockedLive(i.name)),r.deleted.push({id:i.id,name:i.name,projects:t.length,tasks:c.length})}return r}async function m(e){for(let t of(await n.r.select({id:s.c.id,repoPath:s.c.repoPath}).from(s.c).where((0,a.u)(s.c.organizationId,e)))){for(let e of(await n.r.select({id:s.B.id}).from(s.B).where((0,a.u)(s.B.projectId,t.id))))await (0,d.O)(e.id);(0,c.F)(t.id,t.repoPath)}await n.r.delete(l.organization).where((0,a.u)(l.organization.id,e))}async function h(e){let t=await p(e);if(t.blocked.length)throw new i.E("BAD_REQUEST",{message:t.blocked.join(" ")});for(let e of t.deleted)await m(e.id)}e.s(["C",0,h,"j",0,p]),r()}catch(e){r(e)}},!1),3087,e=>e.a(async(t,r)=>{try{var i=e.i(66680),a=e.i(2157),o=e.i(50227),n=e.i(4721),s=e.i(36254),l=e.i(49599),c=e.i(89171),d=e.i(34975),u=e.i(49129),f=e.i(75225),p=e.i(24924);e.i(92335);var m=e.i(45967),h=e.i(18516),g=e.i(62626),y=e.i(44030),w=e.i(18188),b=e.i(91138),E=t([p,h,g,w]);[p,h,g,w]=E.then?(await E)():E;let A=process.env.BETTER_AUTH_URL??"http://127.0.0.1:4100",I=process.env.GITHUB_CLIENT_ID&&process.env.GITHUB_CLIENT_SECRET?{clientId:process.env.GITHUB_CLIENT_ID,clientSecret:process.env.GITHUB_CLIENT_SECRET}:null,T=(0,n.f)({baseURL:A,secret:function(){if(process.env.BETTER_AUTH_SECRET)return process.env.BETTER_AUTH_SECRET;if(process.env.VITEST)return"test-secret-test-secret-test-secret-00";if(process.env.FACTORY_HOSTED)throw Error("BETTER_AUTH_SECRET is not set.");let e=(0,o.join)(b.f,"auth-secret");if((0,a.existsSync)(e)){let t=(0,a.readFileSync)(e,"utf8").trim();if(t.length>=32)return t}let t=(0,i.randomBytes)(32).toString("hex");return(0,a.mkdirSync)((0,o.dirname)(e),{recursive:!0}),(0,a.writeFileSync)(e,t,{mode:384}),t}(),trustedOrigins:[A,A.replace("127.0.0.1","localhost")],database:(0,s.f)(p.r,{provider:"pg",schema:{user:m.user,session:m.session,account:m.account,verification:m.verification,organization:m.organization,member:m.member,invitation:m.invitation}}),emailAndPassword:{enabled:!0,minPasswordLength:8},user:{deleteUser:{enabled:!0,beforeDelete:async e=>void await (0,w.C)(e.id)}},socialProviders:I?{github:I}:{},databaseHooks:{session:{create:{before:async e=>{let t=(await p.r.select({id:m.member.organizationId}).from(m.member).where((0,f.u)(m.member.userId,e.userId)).orderBy((0,u.M)(m.member.createdAt)).limit(1))[0];return{data:{...e,activeOrganizationId:t?.id??null}}}}}},plugins:[(0,d.f)({invitationExpiresIn:604800,cancelPendingInvitationsOnReInvite:!0,organizationHooks:{afterCreateOrganization:async({organization:e})=>{await (0,h.f)(e.id),(0,y.M)()&&(0,c.after)(()=>(0,g.f)(e.id).then(()=>void 0,e=>console.warn("Organization database not made yet:",e instanceof Error?e.message:e)))}}}),(0,l.A)()]});e.s(["f",0,T]),r()}catch(e){r(e)}},!1),81822,e=>e.a(async(t,r)=>{try{var i=e.i(74533),a=e.i(2157),o=e.i(50227),n=e.i(75225),s=e.i(24924),l=e.i(92335),c=e.i(82461),d=e.i(20195),u=e.i(69608),f=e.i(92835),p=e.i(18536),m=e.i(82283),h=e.i(64950),g=e.i(65272),y=t([s,c,d,u,f,h]);[s,c,d,u,f,h]=y.then?(await y)():y;class E extends Error{status;constructor(e,t){super(e),this.status=t,this.name="RunDeleteError"}}let A=new Set(["queued","running","waiting_approval"]);function w(e,t){let r=(0,o.relative)((0,o.resolve)(e),(0,o.resolve)(t));return""!==r&&!r.startsWith("..")&&!r.startsWith(o.sep)&&!r.includes(`..${o.sep}`)}async function b(e,t={}){let r=(await s.r.select().from(l.B).where((0,n.u)(l.B.id,e)))[0];if(!r)throw new E(m.f.errors.runNotFound,404);if(A.has(r.status))throw new E(m.f.history.stillLive,409);let y=(await (0,h.I)(r.projectId))?.repoPath??null,I=await s.r.select({id:l.K.id,path:l.K.path}).from(l.K).where((0,n.u)(l.K.runId,e)),T=I.map(e=>e.path);(0,d.D)(e),await (0,f.i)(e,t.snapshotDir??u.P).catch(()=>void 0),await s.r.delete(l.B).where((0,n.u)(l.B.id,e));let _=t.worktreeRoot??p.U,v=r.worktreePath;if(v&&w(_,v)&&(0,a.existsSync)(v)){try{y&&(0,i.execFileSync)("git",["worktree","remove","--force",v],{cwd:y,stdio:"ignore"})}catch{}if((0,a.rmSync)(v,{recursive:!0,force:!0}),y)try{(0,i.execFileSync)("git",["worktree","prune"],{cwd:y,stdio:"ignore"})}catch{}}let O=t.attachmentDir??c.o;for(let e of T)w(O,e)&&(0,a.rmSync)(e,{force:!0});/^[0-9A-Z]{26}$/i.test(e)&&(0,a.rmSync)((0,o.join)(t.snapshotDir??u.P,e),{recursive:!0,force:!0});let k=(0,g.h)();if(k&&/^[0-9A-Z]{26}$/i.test(e))for(let t of(await k.deletePrefix(`snapshots/${e}/`),I))await k.deletePrefix((0,g._)(t.id,(0,o.extname)(t.path).slice(1)||"png"))}e.s(["N",0,E,"O",0,b]),r()}catch(e){r(e)}},!1)];
|
|
479
|
+
`)}}(t={...t,secret:i,baseURL:m?t.baseURL:h?new URL(h).origin:"",basePath:t.basePath||"/api/auth",plugins:l.concat(c)},f);let I=t.advanced?.ipAddress?.trustedProxies;if(I&&I.length>0){let e=I.filter(e=>null===eg(e));e.length>0&&f.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let T=(0,ev.e)(t),_=(0,d.R)(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||f.warn(`Social provider ${e} is missing clientId or clientSecret`);let i=iJ[e](r);return i.disableImplicitSignUp=r.disableImplicitSignUp,i}))).filter(e=>null!==e),O=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let i=t?.advanced?.database?.generateId;return"function"==typeof i?i({model:e,size:r}):"uuid"===i?crypto.randomUUID():"serial"!==i&&!1!==i&&(0,eM.f)(r)},{publish:R}=await ot(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),k=new Set(t.plugins.map(e=>e.id)),x=await e2(t),S=await e4(t),U={appName:t.appName||"Better Auth",baseURL:h||"",version:(0,aF.I)(),socialProviders:v,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:_,trustedOrigins:x,trustedProviders:S,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>K(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:(o=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300,s&&o?(f.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!==o&&void 0!==o&&(!0===o?{enabled:!0,updateAge:Math.floor(.2*n)}:{enabled:!0,updateAge:void 0!==o.updateAge?o.updateAge:Math.floor(.2*n)}))},secret:i,secretConfig:a,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??en.C,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:T,logger:f,generateId:O,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||tr,verify:t.emailAndPassword?.password?.verify||ta,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:as},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:eF(e,{options:t,logger:f,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:O}),createAuthCookie:(0,ev.g)(t),async runMigrations(){throw new p.p("runMigrations will be set by the specific init implementation")},publishTelemetry:R,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,en.s)(),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=>{f.error("Failed to run background task:",e)})):await e}catch(e){f.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>k.has(e)},N=e1(U);return(0,eV.f)(N)&&await N,U.checkSchema=(0,A.f)(U.adapter),U.explicitSchemaCheck=(0,A.j)(U.adapter),U}let oi=async e=>{let t=await m(e),r=await or(t,e,e=>(0,g.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new p.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await D(e);await t()},r};e.s(["f",0,e=>((e,t)=>{let r=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;return e.checkSchema||!1===t||e.logger[!0===t?"warn":"debug"](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`),e}),{api:i}=aH(r,e),a=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),o=async t=>{let i,a=await r,o=a.options.basePath||"/api/auth";if((0,z._)(e.baseURL))i=await e6(a,t,e5(a.options));else{i=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));let e=a.options;if(!a.options.baseURL){let r=(0,z.X)(void 0,o,t,void 0,a.options.advanced?.trustedProxyHeaders);if(!r)throw new p.p("Could not get base URL from request. Please provide a valid base URL.");i.baseURL=r,i.options={...a.options,baseURL:(0,z.H)(r)||void 0},e=i.options}i.trustedOrigins=await e2(e,t),i.trustedProviders=await e4(e,t)}let{handler:n}=((e,t)=>{let r=(0,eP.f)(t),{api:i,middlewares:a}=aH(e,t),o=new URL(e.baseURL).pathname;return(0,aq.f)(i,{routerContext:e,openapi:{disabled:!0},basePath:o,routerMiddleware:[{path:"/**",middleware:et},...a],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let i=e.options.disabledPaths||[],a=J(t.url,o);if(i.includes(a))return new Response("Not Found",{status:404});let n=e.checkSchema?.();n&&await n;let s=t,l=await eT(s,e);if(l)return l;for(let t of e.options.plugins||[])if(t.onRequest){let i=await r(`onRequest ${t.id}`,{[ej.A]:"onRequest",[ej.s]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(i&&"response"in i)return i.response;i&&"request"in i&&(s=i.request)}return s},async onResponse(t,i){for(let i of e.options.plugins||[])if(i.onResponse){let a=await r(`onResponse ${i.id}`,{[ej.A]:"onResponse",[ej.s]:`plugin:${i.id}`,[ej.h]:t.status},()=>i.onResponse(t,e));if(a)return a.response}return t},async onError(r){if((0,L.f)(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError){try{await t.onAPIError.onError(r,e)}catch(t){e.logger.error("onAPIError.onError threw",t)}return}let i=t.logger?.level,a="error"===i||"warn"===i||"debug"===i?u.y: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);(0,L.f)(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),a?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(i,e);return(0,eC.Q)(i.adapter,()=>n(t))};return{handler:o,fetch:o,api:i,options:e,$context:r,$ERROR_CODES:{...a,...G.f}}})(e,oi)],4721)},46754,e=>{"use strict";function t(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function r(e){if(!e)return[];let t=[],r=0,i=0;for(;i<e.length;){if(","===e[i]){let a=i+1;for(;a<e.length&&" "===e[a];)a++;for(;a<e.length&&"="!==e[a]&&";"!==e[a]&&","!==e[a];)a++;if(a<e.length&&"="===e[a]){let a=e.slice(r,i).trim();for(a&&t.push(a),r=i+1;r<e.length&&" "===e[r];)r++;i=r;continue}}i++}let a=e.slice(r).trim();return a&&t.push(a),t}function i(e){let i=new Map;return r(e).forEach(e=>{let[r,...a]=e.split(";").map(e=>e.trim()),[o,...s]=(r||"").split("="),l=n(s.join("="));if(!o)return;let c={value:t(l)};a.forEach(e=>{let[t,...r]=e.split("="),i=r.join("="),a=t.trim().toLowerCase();switch(a){case"max-age":c["max-age"]=i?parseInt(i.trim(),10):void 0;break;case"expires":c.expires=i?new Date(i.trim()):void 0;break;case"domain":c.domain=i?i.trim():void 0;break;case"path":c.path=i?i.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=i?i.trim().toLowerCase():void 0;break;case"partitioned":c.partitioned=!0;break;default:c[a]=!i||i.trim()}}),i.set(o,c)}),i}let a=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,o=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function n(e){return!(e.length<2)&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function s(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 l(e){let r=new Map;if(e.length<2)return r;for(let i of e.split(";")){let e=i.indexOf("=");if(-1===e)continue;let l=s(i.slice(0,e)),c=n(s(i.slice(e+1)));a.test(l)&&o.test(c)&&r.set(l,t(c))}return r}function c(e,t){let r=l(e.get("cookie")||"");for(let e of t)for(let[t,o]of i(e))a.test(t)&&r.set(t,o.value);e.set("cookie",Array.from(r,([e,t])=>`${e}=${encodeURIComponent(t)}`).join("; "))}e.s(["D",0,"__Host-","d",0,"__Secure-","B",0,c,"T",0,a,"X",0,l,"p",0,i,"H",0,function(e){return t=>{let r=t.response.headers.get("set-cookie");r&&c(e,[r])}},"K",0,function(e,t,r){let i=l(e.get("cookie")||"");a.test(t)&&i.set(t,r),e.set("cookie",Array.from(i,([e,t])=>`${e}=${encodeURIComponent(t)}`).join("; "))},"Z",0,r,"P",0,function(e){return e.startsWith("__Secure-")?e.slice(9):e.startsWith("__Host-")?e.slice(7):e},"n",0,function(e){return{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}}])},49599,e=>{"use strict";let t;var r=e.i(80849),i=e.i(46754),a=e.i(72003),o=e.i(90659);let n=()=>t??=e.A(6878).catch(e=>{throw t=void 0,e});e.s(["A",0,()=>{let e=!1;return{id:"next-cookies",version:a.f,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,o.a)(async t=>{let i;if(e||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let i=r.findIndex(e=>e.id===t);-1===i||r.slice(i+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.`)}(t.context,"next-cookies"),e=!0),"_flag"in t&&"router"===t._flag)return;try{let{headers:e}=await n();i=await e()}catch{return}let a="1"===i.get("RSC"),o=!!i.get("next-action");a&&!o&&await (0,r.w)(!0)})}],after:[{matcher:e=>!0,handler:(0,o.a)(async e=>{let t=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&t instanceof Headers){let e,r=t?.get("set-cookie");if(!r)return;let a=(0,i.p)(r);try{let{cookies:t}=await n();e=await t()}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((t,r)=>{if(r)try{e.set(r,t.value,(0,i.n)(t))}catch{}});return}})}]}}},"z",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}}],49599)},34975,e=>{"use strict";var t=e.i(12996),r=e.i(72003),i=e.i(71616);function a(e){return"OR"===e?"OR":"AND"}function o(e){return Array.isArray(e)}function n(e,t){return"string"==typeof t&&e.includes(t)}let s=e=>{var t;return{authorize(e,r="AND"){let s=!1;for(let[l,c]of Object.entries(e)){let e=t[l];if(!e){if("AND"===r)return{success:!1,error:`You are not allowed to access resource: ${l}`};continue}let d=function(e,{actions:t,connector:r}){return 0!==t.length&&("OR"===r?t.some(t=>n(e,t)):t.every(t=>n(e,t)))}(e,function(e){if(o(e))return{actions:e,connector:"AND"};if(!e||"object"!=typeof e)throw new i.p("Invalid access control request");let{actions:t,connector:r}=e;return o(t)?{actions:t,connector:a(r)}:{actions:[],connector:a(r)}}(c));if(d&&(s=!0),d&&"OR"===r)return{success:!0};if(!d&&"AND"===r)return{success:!1,error:`unauthorized to access resource "${l}"`}}return s?{success:!0}:{success:!1,error:"Not authorized"}},statements:t=e}},l={admin:s({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),owner:s({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),member:s({organization:[],member:[],invitation:[],team:[],ac:["read"]})};function c(e){return(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(Boolean)}function d(e){return c(e).join(",")}let u=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,f={true:!0,false:!1,null:null,undefined:void 0,nan:0/0,infinity:1/0,"-infinity":-1/0},p=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;var m=e.i(42158),h=e.i(73436),g=e.i(74285),y=e.i(30501),w=e.i(82318);async function b(e){let t=await (0,w.f)("SHA-256").digest(new TextEncoder().encode(JSON.stringify([e.teamId,e.userId])));return y.W.encode(new Uint8Array(t),{padding:!1})}async function E(e,t){let r=await e.findOne({model:"teamMember",where:[{field:"membershipKey",value:t.membershipKey}]});return r||e.findOne({model:"teamMember",where:[{field:"teamId",value:t.teamId},{field:"userId",value:t.userId}]})}async function A(e,t){let r=await e.count({model:"teamMember",where:[{field:"teamId",value:t}]});await e.incrementOne({model:"team",where:[{field:"id",value:t},{field:"memberCount",operator:"lt",value:r}],increment:{},set:{memberCount:r}})}async function I(e,t){return!!await e.incrementOne({model:"team",where:[{field:"id",value:t.teamId},{field:"memberCount",operator:"lt",value:t.maximumMembersPerTeam}],increment:{memberCount:1}})}async function T(e,t){await e.incrementOne({model:"team",where:[{field:"id",value:t}],increment:{memberCount:1}})}async function _(e,t,r){r<=0||await e.incrementOne({model:"team",where:[{field:"id",value:t},{field:"memberCount",operator:"gte",value:r}],increment:{memberCount:-r}})}async function v(e,t){try{return{status:"created",member:await e.create({model:"teamMember",data:{teamId:t.teamId,userId:t.userId,membershipKey:t.membershipKey,createdAt:new Date}})}}catch(i){let r=await E(e,t);if(r)return{status:"existing",member:r};throw i}}function O(e){let{membershipKey:t,...r}=e;return r}let R=(e,t)=>{let r=e.adapter,a=t?.schema?.organization?.additionalFields,o=t?.schema?.member?.additionalFields,n=t?.schema?.invitation?.additionalFields,s=t?.schema?.team?.additionalFields;return{findOrganizationBySlug:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"organization",where:[{field:"slug",value:e}]});return(0,g.f)(t,a)},createOrganization:async e=>{let t=await (await (0,h.g)(r)).create({model:"organization",data:{...e.organization,metadata:e.organization.metadata?JSON.stringify(e.organization.metadata):void 0},forceAllowId:!0}),i={...t,metadata:t.metadata&&"string"==typeof t.metadata?JSON.parse(t.metadata):void 0};return(0,g.f)(i,a)},findMemberByEmail:async e=>{let t=await (0,h.g)(r),i=await t.findOne({model:"user",where:[{field:"email",value:e.email.toLowerCase()}]});if(!i)return null;let a=await t.findOne({model:"member",where:[{field:"organizationId",value:e.organizationId},{field:"userId",value:i.id}]});return a?{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},listMembers:async e=>{let a=await (0,h.g)(r),o=await Promise.all([a.findMany({model:"member",where:[{field:"organizationId",value:e.organizationId},...e.filter?.field?[{field:e.filter?.field,value:e.filter?.value,...e.filter.operator?{operator:e.filter.operator}:{}}]:[]],limit:e.limit||("number"==typeof t?.membershipLimit?t.membershipLimit:100)||100,offset:e.offset||0,sortBy:e.sortBy?{field:e.sortBy,direction:e.sortOrder||"asc"}:void 0}),a.count({model:"member",where:[{field:"organizationId",value:e.organizationId},...e.filter?.field?[{field:e.filter?.field,value:e.filter?.value,...e.filter.operator?{operator:e.filter.operator}:{}}]:[]]})]);if(0===o[0].length)return{members:[],total:o[1]};let n=await a.findMany({model:"user",where:[{field:"id",value:o[0].map(e=>e.userId),operator:"in"}],limit:o[0].length});return{members:o[0].map(e=>{let t=n.find(t=>t.id===e.userId);if(!t)throw new i.p("Unexpected error: User not found for member");return{...e,user:{id:t.id,name:t.name,email:t.email,image:t.image}}}),total:o[1]}},findMemberByOrgId:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"userId",value:e.userId},{field:"organizationId",value:e.organizationId}],join:{user:!0}});if(!t||!t.user)return null;let{user:i,...a}=t;return{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"id",value:e}],join:{user:!0}});if(!t)return null;let{user:i,...a}=t;return{...a,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},createMember:async e=>await (await (0,h.g)(r)).create({model:"member",data:{...e,createdAt:new Date}}),updateMember:async(e,t)=>await (await (0,h.g)(r)).update({model:"member",where:[{field:"id",value:e}],update:{role:t}}),deleteMember:async({memberId:e,organizationId:a,userId:o})=>(0,h.n)(r,async()=>{let n,s=await (0,h.g)(r);if(o)n=o;else{let t=await s.findOne({model:"member",where:[{field:"id",value:e}]});if(!t)throw new i.p("Member not found");n=t.userId}let l=await s.delete({model:"member",where:[{field:"id",value:e}]});if(t?.teams?.enabled)for(let e of(await s.findMany({model:"team",where:[{field:"organizationId",value:a}]}))){let t=await s.deleteMany({model:"teamMember",where:[{field:"userId",value:n},{field:"teamId",value:e.id}]});await _(s,e.id,t)}return l}),updateOrganization:async(e,t)=>{let i=await (await (0,h.g)(r)).update({model:"organization",where:[{field:"id",value:e}],update:{...t,metadata:"object"==typeof t.metadata?JSON.stringify(t.metadata):t.metadata}});if(!i)return null;let o={...i,metadata:i.metadata?function(e,t={strict:!0}){return function(e,t={}){let{strict:r=!1,warnings:i=!1,reviver:a,parseDates:o=!0}=t;if("string"!=typeof e)return e;let n=e.trim(),s=n.toLowerCase();if(s.length<=9&&s in f)return f[s];if(!u.test(n)){if(r)throw SyntaxError("[better-json] Invalid JSON");return e}try{return JSON.parse(n,(e,t)=>{if("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t){if(r)throw Error("[better-json] Potential prototype pollution attempt detected");i&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(o&&"string"==typeof t){let e=function(e){let t=p.exec(e);if(!t)return null;let[,r,i,a,o,n,s,l,c,d,u]=t,f=new Date(Date.UTC(parseInt(r,10),parseInt(i,10)-1,parseInt(a,10),parseInt(o,10),parseInt(n,10),parseInt(s,10),l?parseInt(l.padEnd(3,"0"),10):0));if(c){let e=(60*parseInt(d,10)+parseInt(u,10))*("+"===c?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return f instanceof Date&&!isNaN(f.getTime())?f:null}(t);if(e)return e}return a?a(e,t):t})}catch(t){if(r)throw t;return e}}(e,t)}(i.metadata):void 0};return(0,g.f)(o,a)},deleteOrganization:async e=>(0,h.n)(r,async()=>{let t=await (0,h.g)(r);return await t.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await t.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),await t.delete({model:"organization",where:[{field:"id",value:e}]}),e}),setActiveOrganization:async(t,r,i)=>await e.internalAdapter.updateSession(t,{activeOrganizationId:r}),findOrganizationById:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"organization",where:[{field:"id",value:e}]});return(0,g.f)(t,a)},checkMembership:async({userId:e,organizationId:t})=>await (await (0,h.g)(r)).findOne({model:"member",where:[{field:"userId",value:e},{field:"organizationId",value:t}]}),findFullOrganization:async({organizationId:e,isSlug:l,includeTeams:c,membersLimit:d})=>{let u=await (0,h.g)(r),f=await u.findOne({model:"organization",where:[{field:l?"slug":"id",value:e}],join:{invitation:!0,member:!d||{limit:d},...c?{team:!0}:{}}});if(!f)return null;let{invitation:p,member:m,team:y,...w}=f,b=m.map(e=>e.userId),E=new Map((b.length>0?await u.findMany({model:"user",where:[{field:"id",value:b,operator:"in"}],limit:("number"==typeof t?.membershipLimit?t.membershipLimit:100)||100}):[]).map(e=>[e.id,e])),A=m.map(e=>{let t=E.get(e.userId);if(!t)throw new i.p("Unexpected error: User not found for member");return{...(0,g.f)(e,o),user:{id:t.id,name:t.name,email:t.email,image:t.image}}}),I=(0,g.f)(w,a),T=p.map(e=>(0,g.f)(e,n)),_=y?.map(e=>(0,g.f)(e,s));return{...I,invitations:T,members:A,teams:_}},listOrganizations:async e=>{let t=await (await (0,h.g)(r)).findMany({model:"member",where:[{field:"userId",value:e}],join:{organization:!0}});return t&&0!==t.length?t.map(e=>(0,g.f)(e.organization,a)):[]},createTeam:async e=>{let{memberCount:t,...i}=await (await (0,h.g)(r)).create({model:"team",data:{...e,memberCount:0},forceAllowId:!0});return(0,g.f)(i,s)},findTeamById:async({teamId:e,organizationId:t,includeTeamMembers:i})=>{let a=await (await (0,h.g)(r)).findOne({model:"team",where:[{field:"id",value:e},...t?[{field:"organizationId",value:t}]:[]],join:{...i?{teamMember:!0}:{}}});if(!a)return null;let{teamMember:o,memberCount:n,...l}=a;return{...(0,g.f)(l,s),...i?{members:(o??[]).map(O)}:{}}},updateTeam:async(e,t)=>{let i=await (0,h.g)(r);"id"in t&&(t.id=void 0);let a=await i.update({model:"team",where:[{field:"id",value:e}],update:{...t}});if(!a)return a;let{memberCount:o,...n}=a;return(0,g.f)(n,s)},deleteTeam:async e=>{let t=await (0,h.g)(r);return await t.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await t.delete({model:"team",where:[{field:"id",value:e}]})},listTeams:async e=>(await (await (0,h.g)(r)).findMany({model:"team",where:[{field:"organizationId",value:e}]})).map(e=>{let{memberCount:t,...r}=e;return(0,g.f)(r,s)}),createTeamInvitation:async({email:e,role:t,teamId:i,organizationId:a,inviterId:o,expiresIn:n=1728e5})=>{let s=await (0,h.g)(r),l=(0,m.f)(n);return await s.create({model:"invitation",data:{email:e,role:t,organizationId:a,teamId:i,inviterId:o,status:"pending",expiresAt:l}})},setActiveTeam:async(t,r,i)=>await e.internalAdapter.updateSession(t,{activeTeamId:r}),listTeamMembers:async e=>(await (await (0,h.g)(r)).findMany({model:"teamMember",where:[{field:"teamId",value:e.teamId}]})).map(O),countTeamMembers:async e=>await (await (0,h.g)(r)).count({model:"teamMember",where:[{field:"teamId",value:e.teamId}]}),countMembers:async e=>await (await (0,h.g)(r)).count({model:"member",where:[{field:"organizationId",value:e.organizationId}]}),listTeamsByUser:async e=>(await (await (0,h.g)(r)).findMany({model:"teamMember",where:[{field:"userId",value:e.userId}],join:{team:!0}})).map(e=>{let{memberCount:t,...r}=e.team;return(0,g.f)(r,s)}),findTeamMember:async e=>{let t=await (await (0,h.g)(r)).findOne({model:"teamMember",where:[{field:"teamId",value:e.teamId},{field:"userId",value:e.userId}]});return t?O(t):null},findOrCreateTeamMember:async e=>(0,h.n)(r,async()=>{let t=await (0,h.g)(r),i=await b(e),a=await E(t,{...e,membershipKey:i});if(a)return O(a);await A(t,e.teamId);let o=await v(t,{...e,membershipKey:i});return"created"===o.status&&await T(t,e.teamId),O(o.member)}),addTeamMemberWithLimit:async e=>(0,h.n)(r,async()=>{let t,i=await (0,h.g)(r),a=await b(e),o=await E(i,{teamId:e.teamId,userId:e.userId,membershipKey:a});if(o)return{status:"added",member:O(o)};if(await A(i,e.teamId),!await I(i,{teamId:e.teamId,maximumMembersPerTeam:e.maximumMembersPerTeam}))return{status:"limitReached"};try{t=await v(i,{teamId:e.teamId,userId:e.userId,membershipKey:a})}catch(t){throw await _(i,e.teamId,1),t}return"existing"===t.status&&await _(i,e.teamId,1),{status:"added",member:O(t.member)}}),removeTeamMember:async e=>{let t=await (0,h.g)(r),i=await t.deleteMany({model:"teamMember",where:[{field:"teamId",value:e.teamId},{field:"userId",value:e.userId}]});await _(t,e.teamId,i)},findInvitationsByTeamId:async e=>await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"teamId",value:e}]}),listUserInvitations:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"email",value:e.toLowerCase()}],join:{organization:!0}})).filter(Boolean).map(({organization:e,...t})=>({...t,organizationName:e?.name})),createInvitation:async({invitation:i,user:a})=>{let o=await (0,h.g)(r),n=(0,m.f)(t?.invitationExpiresIn||172800,"sec");return await o.create({model:"invitation",data:{...e.options.advanced?.database?.generateId===void 0&&{id:e.generateId({model:"invitation"})},status:"pending",expiresAt:n,createdAt:new Date,inviterId:a.id,...i,teamId:i.teamIds.length>0?i.teamIds.join(","):null},forceAllowId:!0})},findInvitationById:async e=>await (await (0,h.g)(r)).findOne({model:"invitation",where:[{field:"id",value:e}]}),findPendingInvitation:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"email",value:e.email.toLowerCase()},{field:"organizationId",value:e.organizationId},{field:"status",value:"pending"}]})).filter(e=>new Date(e.expiresAt)>new Date),findPendingInvitations:async e=>(await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"organizationId",value:e.organizationId},{field:"status",value:"pending"}]})).filter(e=>new Date(e.expiresAt)>new Date),listInvitations:async e=>await (await (0,h.g)(r)).findMany({model:"invitation",where:[{field:"organizationId",value:e.organizationId}]}),updateInvitation:async e=>{let t=await (0,h.g)(r),i=[{field:"id",value:e.invitationId}];return e.fromStatus&&i.push({field:"status",value:e.fromStatus}),await t.incrementOne({model:"invitation",where:i,increment:{},set:{status:e.status}})}}};var k=e.i(90659);let x=(0,k.a)(async()=>({})),S=(0,k.a)({use:[t.Z]},async e=>({session:e.context.session})),U=(0,e.i(72823).f)({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION:"Email verification required to view or list invitations for the session email",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",YOU_ARE_NOT_ALLOWED_TO_LIST_INVITATIONS:"You are not allowed to list invitations for this organization",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role",ROLE_IS_ASSIGNED_TO_MEMBERS:"Cannot delete a role that is assigned to members. Please reassign the members to a different role first",INVALID_TEAM_ID:"Team id contains a reserved character"}),N=(e,t)=>{if(!e.permissions)return!1;let r=c(e.role),i=e.options.creatorRole||"owner",a=r.includes(i),o=e.allowCreatorAllPermissions||!1;if(a&&o)return!0;for(let i of r)if(t[i]?.authorize(e.permissions)?.success)return!0;return!1};var D=e.i(24374),L=e.i(7855);let C=L.record(L.string(),L.array(L.string())),z=(0,D.z)(()=>new WeakMap);async function j(e,t){if(!await (0,D.B)())return;let r=await z.get(),i=r.get(e.context.adapter)??new WeakMap;r.set(e.context.adapter,i);let a=i.get(t)??new Map;return i.set(t,a),a}let P=async(e,t)=>{let r={...e.options.roles||l},a=e.options.ac;if(!t||!e.organizationId||!e.options.dynamicAccessControl?.enabled||!a)return N(e,r);let o=await j(t,e.options),n=e.useMemoryCache?o?.get(e.organizationId):void 0;if(n)return N(e,n);for(let{role:o,permission:n}of(await t.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:e.organizationId}]}))){let e=JSON.parse(n),s=C.safeParse(e);if(!s.success)throw t.context.logger.error("[hasPermission] Invalid permissions for role "+o,{permissions:e}),new i.E("INTERNAL_SERVER_ERROR",{message:"Invalid permissions for role "+o});let l={...r[o]?.statements};for(let[e,t]of Object.entries(s.data))l[e]=[...new Set([...l[e]??[],...t])];r[o]=a.newRole(l)}return o?.set(e.organizationId,r),N(e,r)},B=(e,t)=>P({...e,permissions:{invitation:["create"]}},t),M=(e,t)=>{let r=t.options.creatorRole||"owner";return c(t.role).includes(r)?e:e.filter(e=>!c(e.role).includes(r))},$={string:L.string,number:L.number,boolean:L.boolean,date:L.date};function q({fields:e,isClientSide:t}){let r=Object.keys(e).reduce((r,i)=>{let a,o=e[i];return!o||t&&!1===o.input?r:(a="json"===o.type?L.json():"string[]"===o.type||"number[]"===o.type?L.array("string[]"===o.type?L.string():L.number()):Array.isArray(o.type)?L.any():$[o.type](),o?.required===!1&&(a=a.nullish()),t||o?.returned!==!1)?{...r,[i]:a}:r},{});return L.object(r)}let H=(e,t=!1)=>{let r=e?.schema?.organizationRole?.additionalFields||{};if(t)for(let e in r)r[e].required=!1;return{additionalFieldsSchema:q({fields:r,isClientSide:!0}),$AdditionalFields:{},$ReturnAdditionalFields:{}}},F=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to create the role in. If not provided, the user's active organization will be used."}),role:L.string().meta({description:"The name of the role to create"}),permission:L.record(L.string(),L.array(L.string())).meta({description:"The permission to assign to the role"})}),V=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to create the role in. If not provided, the user's active organization will be used."})}).and(L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to delete"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to delete"})})])),W=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to list roles for. If not provided, the user's active organization will be used."})}).optional(),K=L.object({organizationId:L.string().optional().meta({description:"The id of the organization to read a role for. If not provided, the user's active organization will be used."})}).and(L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to read"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to read"})})])).optional(),G=L.union([L.object({roleName:L.string().nonempty().meta({description:"The name of the role to update"})}),L.object({roleId:L.string().nonempty().meta({description:"The id of the role to update"})})]);async function J({ac:e,ctx:t,permission:r}){let a=Object.keys(e.statements),o=Object.keys(r);if(o.some(e=>!a.includes(e)))throw t.context.logger.error("[Dynamic Access Control] The provided permission includes an invalid resource.",{providedResources:o,validResources:a}),i.E.from("BAD_REQUEST",U.INVALID_RESOURCE)}async function Q({ctx:e,permissionRequired:t,options:r,organizationId:a,member:o,user:n,action:s}){let l=[];for await(let[i,n]of Object.entries(t))for await(let t of n)l.push({resource:{[i]:[t]},hasPermission:await P({options:r,organizationId:a,permissions:{[i]:[t]},useMemoryCache:!0,role:o.role},e)});let c=l.filter(e=>!1===e.hasPermission).map(e=>{let t=Object.keys(e.resource)[0];return`${t}:${e.resource[t][0]}`});if(c.length>0){let t;throw e.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${s} a role with those set of permissions.
|
|
480
|
+
`,{userId:n.id,organizationId:a,role:o.role,missingPermissions:c}),t="create"===s?U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"update"===s?U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"delete"===s?U.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"read"===s?U.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"list"===s?U.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:U.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE,i.E.fromStatus("FORBIDDEN",{message:t.message,code:t.code,missingPermissions:c})}}async function Y({options:e,organizationId:t,role:r,ctx:a}){let o=e.roles?Object.keys(e.roles):["owner","admin","member"];if(o.includes(r))throw a.context.logger.error(`[Dynamic Access Control] The role name "${r}" is already taken by a pre-defined role.`,{role:r,organizationId:t,defaultRoles:o}),i.E.from("BAD_REQUEST",U.ROLE_NAME_IS_ALREADY_TAKEN)}async function Z({organizationId:e,role:t,ctx:r}){if(await r.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:e,operator:"eq",connector:"AND"},{field:"role",value:t,operator:"eq",connector:"AND"}]}))throw r.context.logger.error(`[Dynamic Access Control] The role name "${t}" is already taken by a role in the database.`,{role:t,organizationId:e}),i.E.from("BAD_REQUEST",U.ROLE_NAME_IS_ALREADY_TAKEN)}var X=e.i(70728),ee=e.i(10228);let et=L.object({email:L.string().meta({description:"The email address of the user to invite"}),role:L.union([L.string().meta({description:"The role to assign to the user"}),L.array(L.string().meta({description:"The roles to assign to the user"}))]).meta({description:'The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: "member"'}),organizationId:L.string().meta({description:"The organization ID to invite the user to"}).optional(),resend:L.boolean().meta({description:"Resend the invitation email, if the user is already invited. Eg: true"}).optional(),teamId:L.union([L.string().meta({description:"The team ID to invite the user to"}).optional(),L.array(L.string()).meta({description:"The team IDs to invite the user to"}).optional()])}),er=e=>{if("object"!=typeof e||null===e)return;let t=e.generateId;if("function"==typeof t)return t},ei=({organizationOptions:e,advancedGenerateId:t,databaseGenerateId:r})=>void 0!==e.requireEmailVerificationOnInvitation?e.requireEmailVerificationOnInvitation:!(({advancedGenerateId:e,databaseGenerateId:t})=>void 0===e&&(void 0===t||"uuid"===t))({advancedGenerateId:t,databaseGenerateId:r}),ea=L.object({invitationId:L.string().meta({description:"The ID of the invitation to accept"})}),eo=L.object({invitationId:L.string().meta({description:"The ID of the invitation to reject"})}),en=L.object({invitationId:L.string().meta({description:"The ID of the invitation to cancel"})}),es=L.object({id:L.string().meta({description:"The ID of the invitation to get"})}),el=L.object({organizationId:L.string().meta({description:"The ID of the organization to list invitations for"}).optional()}).optional();e.i(67200),e.i(24891),e.i(82868),e.i(26388),e.i(46378),e.i(31139),e.i(4383),e.i(71928);let ec=["eq","ne","lt","lte","gt","gte","in","not_in","contains","starts_with","ends_with"];var ed=e.i(54257);let eu=L.object({userId:ed.f.string().meta({description:'The ID of the user to add as a member. Eg: "user-id"'}),role:L.union([L.string(),L.array(L.string())]).meta({description:'The role(s) to assign to the new member. Eg: ["admin", "sale"]'}),organizationId:L.string().meta({description:'An optional organization ID to pass. If not provided, will default to the user\'s active organization. Eg: "org-id"'}).optional(),teamId:L.string().meta({description:'An optional team ID to add the member to. Eg: "team-id"'}).optional()}),ef=L.object({memberIdOrEmail:L.string().meta({description:"The ID or email of the member to remove"}),organizationId:L.string().meta({description:'The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: "org-id"'}).optional()}),ep=L.object({role:L.union([L.string(),L.array(L.string())]).meta({description:'The new role to be applied. This can be a string or array of strings representing the roles. Eg: ["admin", "sale"]'}),memberId:L.string().meta({description:'The member id to apply the role update to. Eg: "member-id"'}),organizationId:L.string().meta({description:'An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: "organization-id"'}).optional()}),em=L.object({organizationId:L.string().meta({description:'The organization Id for the member to leave. Eg: "organization-id"'})}),eh=L.object({userId:L.string().meta({description:"The user ID to get the role for. If not provided, will default to the current user's"}).optional(),organizationId:L.string().meta({description:'The organization ID to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-id"'}).optional(),organizationSlug:L.string().meta({description:'The organization slug to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-slug"'}).optional()}).optional(),eg=L.object({name:L.string().min(1).meta({description:"The name of the organization"}),slug:L.string().min(1).meta({description:"The slug of the organization"}),userId:ed.f.string().meta({description:'The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: "user-id"'}).optional(),logo:L.string().meta({description:"The logo of the organization"}).nullish(),metadata:L.record(L.string(),L.any()).meta({description:"The metadata of the organization"}).optional(),keepCurrentActiveOrganization:L.boolean().meta({description:"Whether to keep the current active organization active after creating a new one. Eg: true"}).optional()}),ey=L.object({slug:L.string().meta({description:'The organization slug to check. Eg: "my-org"'})}),ew=L.object({name:L.string().min(1).meta({description:"The name of the organization"}).optional(),slug:L.string().min(1).meta({description:"The slug of the organization"}).optional(),logo:L.string().meta({description:"The logo of the organization"}).nullish(),metadata:L.record(L.string(),L.any()).meta({description:"The metadata of the organization"}).optional()}),eb=L.object({organizationId:L.string().meta({description:"The organization id to delete"})}),eE=L.optional(L.object({organizationId:L.string().meta({description:"The organization id to get"}).optional(),organizationSlug:L.string().meta({description:"The organization slug to get"}).optional()})),eA=L.optional(L.object({organizationId:L.string().meta({description:"The organization id to get"}).optional(),organizationSlug:L.string().meta({description:"The organization slug to get"}).optional(),membersLimit:L.number().or(L.string().transform(e=>parseInt(e))).meta({description:"The limit of members to get. By default, it uses the membershipLimit option."}).optional()})),eI=L.object({organizationId:L.string().meta({description:'The organization id to set as active. It can be null to unset the active organization. Eg: "org-id"'}).nullable().optional(),organizationSlug:L.string().meta({description:'The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: "org-slug"'}).optional()});var eT=e.i(18195);let e_=L.string(),ev=L.enum(["pending","accepted","rejected","canceled"]).default("pending");L.object({id:L.string().default(eT.f),name:L.string(),slug:L.string(),logo:L.string().nullish().optional(),metadata:L.record(L.string(),L.unknown()).or(L.string().transform(e=>JSON.parse(e))).optional(),createdAt:L.date()}),L.object({id:L.string().default(eT.f),organizationId:L.string(),userId:ed.f.string(),role:e_,createdAt:L.date().default(()=>new Date)}),L.object({id:L.string().default(eT.f),organizationId:L.string(),email:L.string(),role:e_,status:ev,teamId:L.string().nullish(),inviterId:L.string(),expiresAt:L.date(),createdAt:L.date().default(()=>new Date)});let eO=L.object({id:L.string().default(eT.f),name:L.string().min(1),organizationId:L.string(),createdAt:L.date(),updatedAt:L.date().optional()});L.object({id:L.string().default(eT.f),teamId:L.string(),userId:L.string(),createdAt:L.date().default(()=>new Date)}),L.object({id:L.string().default(eT.f),organizationId:L.string(),role:L.string(),permission:L.record(L.string(),L.array(L.string())),createdAt:L.date().default(()=>new Date),updatedAt:L.date().optional()});let eR=["admin","member","owner"];L.union([L.enum(eR),L.array(L.enum(eR))]);let ek=L.object({name:L.string().meta({description:'The name of the team. Eg: "my-team"'}),organizationId:L.string().meta({description:'The organization ID which the team will be created in. Defaults to the active organization. Eg: "organization-id"'}).optional()}),ex=L.object({teamId:L.string().meta({description:'The team ID of the team to remove. Eg: "team-id"'}),organizationId:L.string().meta({description:'The organization ID which the team falls under. If not provided, it will default to the user\'s active organization. Eg: "organization-id"'}).optional()}),eS=L.optional(L.object({organizationId:L.string().meta({description:'The organization ID which the teams are under to list. Defaults to the users active organization. Eg: "organization-id"'}).optional()})),eU=L.object({teamId:L.string().meta({description:"The team id to set as active. It can be null to unset the active team"}).nullable().optional()}),eN=L.optional(L.object({teamId:L.string().optional().meta({description:"The team whose members we should return. If this is not provided the members of the current active team get returned."})})),eD=L.object({teamId:L.string().meta({description:"The team the user should be a member of."}),userId:ed.f.string().meta({description:"The user Id which represents the user to be added as a member."}),organizationId:L.string().meta({description:"The organization ID which the team falls under. If not provided, it will default to the user's active organization."}).optional()}),eL=L.object({teamId:L.string().meta({description:"The team the user should be removed from."}),userId:ed.f.string().meta({description:"The user which should be removed from the team."}),organizationId:L.string().meta({description:"The organization ID which the team falls under. If not provided, it will default to the user's active organization."}).optional()}),eC=L.object({organizationId:L.string().optional()}).and(L.xor([L.object({permission:L.record(L.string(),L.array(L.string()))}),L.object({permissions:L.record(L.string(),L.array(L.string()))})]));e.s(["f",0,function(e){let a,o,n,s,u,f,p=e||{},g={createOrganization:(a=q({fields:p?.schema?.organization?.additionalFields||{},isClientSide:!0}),(0,k.g)("/organization/create",{method:"POST",body:L.object({...eg.shape,...a.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r,a=await (0,t.D)(e);if(!a&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");let o=a?.user||null;if(!o){if(!e.body.userId)throw i.E.fromStatus("UNAUTHORIZED");o=await e.context.internalAdapter.findUserById(e.body.userId)}if(!o)throw i.E.fromStatus("UNAUTHORIZED");let n=e.context.orgOptions,s="function"==typeof n?.allowUserToCreateOrganization?await n.allowUserToCreateOrganization(o):n?.allowUserToCreateOrganization===void 0||n.allowUserToCreateOrganization,l=!a&&e.body.userId;if(!s&&!l)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION);let c=R(e.context,n),d=await c.listOrganizations(o.id);if("number"==typeof n.organizationLimit?d.length>=n.organizationLimit:"function"==typeof n.organizationLimit&&await n.organizationLimit(o))throw i.E.from("FORBIDDEN",U.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS);if(await c.findOrganizationBySlug(e.body.slug))throw i.E.from("BAD_REQUEST",U.ORGANIZATION_ALREADY_EXISTS);let{keepCurrentActiveOrganization:u,userId:f,...p}=e.body;if(n?.organizationHooks?.beforeCreateOrganization){let t=await n?.organizationHooks.beforeCreateOrganization({organization:p,user:o});t&&"object"==typeof t&&"data"in t&&(p={...e.body,...t.data})}let m=await c.createOrganization({organization:{...p,createdAt:new Date}}),h=null,g={userId:o.id,organizationId:m.id,role:e.context.orgOptions.creatorRole||"owner"};if(n?.organizationHooks?.beforeAddMember){let t=await n?.organizationHooks.beforeAddMember({member:{userId:o.id,organizationId:m.id,role:e.context.orgOptions.creatorRole||"owner"},user:o,organization:m});t&&"object"==typeof t&&"data"in t&&(g={...g,...t.data})}if(r=await c.createMember(g),n?.organizationHooks?.afterAddMember&&await n?.organizationHooks.afterAddMember({member:r,user:o,organization:m}),n?.teams?.enabled&&n.teams.defaultTeam?.enabled!==!1){let t={organizationId:m.id,name:`${m.name}`,createdAt:new Date};if(n?.organizationHooks?.beforeCreateTeam){let e=await n?.organizationHooks.beforeCreateTeam({team:{organizationId:m.id,name:`${m.name}`},user:o,organization:m});e&&"object"==typeof e&&"data"in e&&(t={...t,...e.data})}let r=await n.teams.defaultTeam?.customCreateDefaultTeam?.(m,e)||await c.createTeam(t);h=await c.findOrCreateTeamMember({teamId:r.id,userId:o.id}),n?.organizationHooks?.afterCreateTeam&&await n?.organizationHooks.afterCreateTeam({team:r,user:o,organization:m})}return n?.organizationHooks?.afterCreateOrganization&&await n?.organizationHooks.afterCreateOrganization({organization:m,user:o,member:r}),e.context.session&&!e.body.keepCurrentActiveOrganization&&await c.setActiveOrganization(e.context.session.session.token,m.id,e),h&&e.context.session&&!e.body.keepCurrentActiveOrganization&&await c.setActiveTeam(e.context.session.session.token,h.teamId,e),e.json({...m,metadata:m.metadata&&"string"==typeof m.metadata?JSON.parse(m.metadata):m.metadata,members:[r]})})),updateOrganization:(o=q({fields:p?.schema?.organization?.additionalFields||{},isClientSide:!0}),(0,k.g)("/organization/update",{method:"POST",body:L.object({data:L.object({...o.shape,...ew.shape}).partial(),organizationId:L.string().meta({description:'The organization ID. Eg: "org-id"'}).optional()}),requireHeaders:!0,use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw i.E.fromStatus("UNAUTHORIZED",{message:"User not found"});let r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=R(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({permissions:{organization:["update"]},role:o.role,options:e.context.orgOptions,organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION);if("string"==typeof e.body.data.slug){let t=await a.findOrganizationBySlug(e.body.data.slug);if(t&&t.id!==r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_SLUG_ALREADY_TAKEN)}if(p?.organizationHooks?.beforeUpdateOrganization){let r=await p.organizationHooks.beforeUpdateOrganization({organization:e.body.data,user:t.user,member:o});r&&"object"==typeof r&&"data"in r&&(e.body.data={...e.body.data,...r.data})}let n=await a.updateOrganization(r,e.body.data);return p?.organizationHooks?.afterUpdateOrganization&&await p.organizationHooks.afterUpdateOrganization({organization:n,user:t.user,member:o}),e.json(n)})),deleteOrganization:(0,k.g)("/organization/delete",{method:"POST",body:eb,requireHeaders:!0,use:[x],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{if(e.context.orgOptions.disableOrganizationDeletion)throw i.E.from("NOT_FOUND",{message:"Organization deletion is disabled",code:"ORGANIZATION_DELETION_DISABLED"});let t=await e.context.getSession(e);if(!t)throw i.E.fromStatus("UNAUTHORIZED");let r=e.body.organizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=R(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:o.role,permissions:{organization:["delete"]},organizationId:r,options:e.context.orgOptions},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION);let n=await a.findOrganizationById(r);if(!n)throw i.E.fromStatus("BAD_REQUEST");return p?.organizationHooks?.beforeDeleteOrganization&&await p.organizationHooks.beforeDeleteOrganization({organization:n,user:t.user},e),await a.deleteOrganization(r),r===t.session.activeOrganizationId&&await a.setActiveOrganization(t.session.token,null,e),p?.organizationHooks?.afterDeleteOrganization&&await p.organizationHooks.afterDeleteOrganization({organization:n,user:t.user},e),e.json(n)}),setActiveOrganization:(0,k.g)("/organization/set-active",{method:"POST",body:eI,use:[S,x],requireHeaders:!0,metadata:{openapi:{operationId:"setActiveOrganization",description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=R(e.context,p),r=e.context.session,a=e.body.organizationId,o=e.body.organizationSlug;if(null===a){if(!r.session.activeOrganizationId)return e.json(null);let i=await t.setActiveOrganization(r.session.token,null,e);return await (0,X.V)(e,{session:i,user:r.user}),e.json(null)}if(!a&&!o){let t=r.session.activeOrganizationId;if(!t)return e.json(null);a=t}if(o&&!a){let e=await t.findOrganizationBySlug(o);if(!e)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);a=e.id}if(!a)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(!await t.checkMembership({userId:r.user.id,organizationId:a}))throw await t.setActiveOrganization(r.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let n=await t.findOrganizationById(a);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let s=await t.setActiveOrganization(r.session.token,n.id,e);return await (0,X.V)(e,{session:s,user:r.user}),e.json(n)}),getOrganization:(0,k.g)("/organization/get-organization",{method:"GET",query:eE,requireHeaders:!0,use:[x,S],metadata:{openapi:{operationId:"getOrganization",description:"Get the organization metadata",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,r=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let a=R(e.context,p),o=e.query?.organizationSlug?await a.findOrganizationBySlug(r):await a.findOrganizationById(r);if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(!await a.checkMembership({userId:t.user.id,organizationId:o.id}))throw await a.setActiveOrganization(t.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);return e.json(o)}),getFullOrganization:(0,k.g)("/organization/get-full-organization",{method:"GET",query:eA,requireHeaders:!0,use:[x,S],metadata:{openapi:{operationId:"getFullOrganization",description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,r=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let a=R(e.context,p),o=await a.findFullOrganization({organizationId:r,isSlug:!!e.query?.organizationSlug,includeTeams:e.context.orgOptions.teams?.enabled,membersLimit:e.query?.membersLimit});if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let n=await a.checkMembership({userId:t.user.id,organizationId:o.id});if(!n)throw await a.setActiveOrganization(t.session.token,null,e),i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);return o.invitations=o.invitations.length>0&&await B({role:n.role,options:e.context.orgOptions,organizationId:o.id},e)?M(o.invitations,{role:n.role,options:e.context.orgOptions}):[],e.json(o)}),listOrganizations:(0,k.g)("/organization/list",{method:"GET",use:[x,S],requireHeaders:!0,metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await R(e.context,p).listOrganizations(e.context.session.user.id);return e.json(t)}),createInvitation:(n=q({fields:p?.schema?.invitation?.additionalFields||{},isClientSide:!0}),(0,k.g)("/organization/invite-member",{method:"POST",requireHeaders:!0,use:[x,S],body:L.object({...et.shape,...n.shape}),metadata:{$Infer:{body:{}},openapi:{operationId:"createOrganizationInvitation",description:"Create an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},createdAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","createdAt"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let a=e.body.email.toLowerCase();if(!L.email().safeParse(a).success)throw i.E.from("BAD_REQUEST",ee.f.INVALID_EMAIL);let o=R(e.context,p),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{invitation:["create"]},organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);let s=e.context.orgOptions.creatorRole||"owner",u=c(e.body.role);if(0===u.length)throw i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let f=d(u),h=new Set([...Object.keys(l),...Object.keys(e.context.orgOptions.roles||{})]),g=u.filter(e=>!h.has(e));if(g.length>0)if(e.context.orgOptions.dynamicAccessControl?.enabled){let t=(await e.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:r},{field:"role",value:g,operator:"in"}]})).map(e=>e.role),a=g.filter(e=>!t.includes(e));if(a.length>0)throw new i.E("BAD_REQUEST",{message:`${U.ROLE_NOT_FOUND}: ${a.join(", ")}`})}else throw new i.E("BAD_REQUEST",{message:`${U.ROLE_NOT_FOUND}: ${g.join(", ")}`});if(!c(n.role).includes(s)&&u.includes(s))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);if(await o.findMemberByEmail({email:a,organizationId:r}))throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);let y=await o.findPendingInvitation({email:a,organizationId:r});if(y.length&&!e.body.resend&&!e.context.orgOptions.cancelPendingInvitationsOnReInvite)throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION);let w=await o.findOrganizationById(r);if(!w)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let b=y[0];if(b&&e.body.resend){if(!c(n.role).includes(s)&&c(b.role).includes(s))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);let r=(0,m.f)(e.context.orgOptions.invitationExpiresIn||172800,"sec");await e.context.adapter.update({model:"invitation",where:[{field:"id",value:b.id}],update:{expiresAt:r}});let a={...b,expiresAt:r};return e.context.orgOptions.sendInvitationEmail&&await e.context.runInBackgroundOrAwait(e.context.orgOptions.sendInvitationEmail({id:a.id,role:a.role,email:a.email.toLowerCase(),organization:w,inviter:{...n,user:t.user},invitation:a},e.request)),e.json(a)}y.length&&e.context.orgOptions.cancelPendingInvitationsOnReInvite&&await o.updateInvitation({invitationId:y[0].id,status:"canceled"});let E="function"==typeof e.context.orgOptions.invitationLimit?await e.context.orgOptions.invitationLimit({user:t.user,organization:w,member:n},e.context):e.context.orgOptions.invitationLimit??100;if((await o.findPendingInvitations({organizationId:r})).length>=E)throw i.E.from("FORBIDDEN",U.INVITATION_LIMIT_REACHED);if(e.context.orgOptions.teams?.enabled&&"teamId"in e.body&&e.body.teamId){let t="string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId;if(t.some(e=>e.includes(",")))throw i.E.from("BAD_REQUEST",U.INVALID_TEAM_ID);for(let e of t)if(!await o.findTeamById({teamId:e,organizationId:r}))throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND)}if(e.context.orgOptions.teams&&e.context.orgOptions.teams.enabled&&void 0!==e.context.orgOptions.teams.maximumMembersPerTeam&&"teamId"in e.body&&e.body.teamId)for(let a of"string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId){let n=await o.findTeamById({teamId:a,organizationId:r,includeTeamMembers:!0});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let s="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:a,session:t,organizationId:r}):e.context.orgOptions.teams.maximumMembersPerTeam;if(n.members.length>=s)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}let A="teamId"in e.body?"string"==typeof e.body.teamId?[e.body.teamId]:e.body.teamId??[]:[],{email:I,role:T,organizationId:_,resend:v,...O}=e.body,k={role:f,email:a,organizationId:r,teamIds:A,...O||{}};if(p?.organizationHooks?.beforeCreateInvitation){let e=await p?.organizationHooks.beforeCreateInvitation({invitation:{...k,inviterId:t.user.id,teamId:A.length>0?A[0]:void 0},inviter:t.user,organization:w});e&&"object"==typeof e&&"data"in e&&(k={...k,...e.data})}let x=await o.createInvitation({invitation:k,user:t.user});return e.context.orgOptions.sendInvitationEmail&&await e.context.runInBackgroundOrAwait(e.context.orgOptions.sendInvitationEmail({id:x.id,role:x.role,email:x.email.toLowerCase(),organization:w,inviter:{...n,user:t.user},invitation:x},e.request)),p?.organizationHooks?.afterCreateInvitation&&await p?.organizationHooks.afterCreateInvitation({invitation:x,inviter:t.user,organization:w}),e.json(x)})),cancelInvitation:(0,k.g)("/organization/cancel-invitation",{method:"POST",body:en,requireHeaders:!0,use:[x,S],openapi:{operationId:"cancelOrganizationInvitation",description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,r=R(e.context,p),a=await r.findInvitationById(e.body.invitationId);if(!a)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:a.organizationId});if(!o)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{invitation:["cancel"]},organizationId:a.organizationId},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION);let n=await r.findOrganizationById(a.organizationId);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);p?.organizationHooks?.beforeCancelInvitation&&await p?.organizationHooks.beforeCancelInvitation({invitation:a,cancelledBy:t.user,organization:n});let s=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return p?.organizationHooks?.afterCancelInvitation&&await p?.organizationHooks.afterCancelInvitation({invitation:s||a,cancelledBy:t.user,organization:n}),e.json(s)}),acceptInvitation:(0,k.g)("/organization/accept-invitation",{method:"POST",body:ea,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,r=R(e.context,p),a=await r.findInvitationById(e.body.invitationId);if(!a||a.expiresAt<new Date||"pending"!==a.status)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);if(a.email.toLowerCase()!==t.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!t.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);let o=e.context.orgOptions?.membershipLimit||100,n=await r.countMembers({organizationId:a.organizationId}),s=await r.findOrganizationById(a.organizationId);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(n>=("number"==typeof o?o:await o(t.user,s)))throw i.E.from("FORBIDDEN",U.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);p?.organizationHooks?.beforeAcceptInvitation&&await p?.organizationHooks.beforeAcceptInvitation({invitation:a,user:t.user,organization:s});let l=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted",fromStatus:"pending"});if(!l)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);let c=await (0,h.n)(e.context.adapter,async()=>{if(e.context.orgOptions.teams&&e.context.orgOptions.teams.enabled&&"teamId"in l&&l.teamId){let a=l.teamId.split(","),o=1===a.length;for(let o of a){if(!await r.findTeamById({teamId:o,organizationId:l.organizationId}))throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(void 0!==e.context.orgOptions.teams.maximumMembersPerTeam){let a="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:o,session:t,organizationId:l.organizationId}):e.context.orgOptions.teams.maximumMembersPerTeam;if("limitReached"===(await r.addTeamMemberWithLimit({teamId:o,userId:t.user.id,maximumMembersPerTeam:a})).status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}else await r.findOrCreateTeamMember({teamId:o,userId:t.user.id})}if(o){let i=a[0],o=await r.setActiveTeam(t.session.token,i,e);await (0,X.V)(e,{session:o,user:t.user})}}let a=await r.createMember({organizationId:l.organizationId,userId:t.user.id,role:d(l.role),createdAt:new Date});return await r.setActiveOrganization(t.session.token,l.organizationId,e),a}).catch(async t=>{throw await r.updateInvitation({invitationId:e.body.invitationId,status:"pending",fromStatus:"accepted"}),t});return p?.organizationHooks?.afterAcceptInvitation&&await p?.organizationHooks.afterAcceptInvitation({invitation:l,member:c,user:t.user,organization:s}),e.json({invitation:l,member:c})}),getInvitation:(0,k.g)("/organization/get-invitation",{method:"GET",use:[x],requireHeaders:!0,query:es,metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let r=await (0,t.D)(e);if(!r)throw i.E.fromStatus("UNAUTHORIZED",{message:"Not authenticated"});let a=R(e.context,p),o=await a.findInvitationById(e.query.id);if(!o||"pending"!==o.status||o.expiresAt<new Date)throw i.E.from("BAD_REQUEST",U.INVITATION_NOT_FOUND);if(o.email.toLowerCase()!==r.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!r.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION);let n=await a.findOrganizationById(o.organizationId);if(!n)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let s=await a.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!s)throw i.E.from("BAD_REQUEST",U.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION);return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:s.user.email})}),rejectInvitation:(0,k.g)("/organization/reject-invitation",{method:"POST",body:eo,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object",nullable:!0}}}}}}}}}},async e=>{let t=e.context.session,r=R(e.context,e.context.orgOptions),a=await r.findInvitationById(e.body.invitationId);if(!a||"pending"!==a.status)throw i.E.from("BAD_REQUEST",{message:"Invitation not found!",code:"INVITATION_NOT_FOUND"});if(a.email.toLowerCase()!==t.user.email.toLowerCase())throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);if(ei({organizationOptions:e.context.orgOptions,advancedGenerateId:er(e.context.options.advanced),databaseGenerateId:e.context.options.advanced?.database?.generateId})&&!t.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);let o=await r.findOrganizationById(a.organizationId);if(!o)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);p?.organizationHooks?.beforeRejectInvitation&&await p?.organizationHooks.beforeRejectInvitation({invitation:a,user:t.user,organization:o});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return p?.organizationHooks?.afterRejectInvitation&&await p?.organizationHooks.afterRejectInvitation({invitation:n||a,user:t.user,organization:o}),e.json({invitation:n,member:null})}),listInvitations:(0,k.g)("/organization/list-invitations",{method:"GET",requireHeaders:!0,use:[x,S],query:el},async e=>{let r=await (0,t.D)(e);if(!r)throw i.E.fromStatus("UNAUTHORIZED",{message:"Not authenticated"});let a=e.query?.organizationId||r.session.activeOrganizationId;if(!a)throw i.E.fromStatus("BAD_REQUEST",{message:"Organization ID is required"});let o=R(e.context,p),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!n)throw i.E.fromStatus("FORBIDDEN",{message:"You are not a member of this organization"});if(!await B({role:n.role,options:e.context.orgOptions,organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_LIST_INVITATIONS);let s=await o.listInvitations({organizationId:a});return e.json(M(s,{role:n.role,options:e.context.orgOptions}))}),getActiveMember:(0,k.g)("/organization/get-active-member",{method:"GET",use:[x,S],requireHeaders:!0,metadata:{openapi:{description:"Get the member details of the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,r=t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=await R(e.context,p).findMemberByOrgId({userId:t.user.id,organizationId:r});if(!a)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return e.json(a)}),checkOrganizationSlug:(0,k.g)("/organization/check-slug",{method:"POST",body:ey,use:[t.b,x]},async e=>{if(!await R(e.context,p).findOrganizationBySlug(e.body.slug))return e.json({status:!0});throw i.E.from("BAD_REQUEST",U.ORGANIZATION_SLUG_ALREADY_TAKEN)}),addMember:(s=q({fields:p?.schema?.member?.additionalFields||{},isClientSide:!0}),(0,k.g)({method:"POST",body:L.object({...eu.shape,...s.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{operationId:"addOrganizationMember",description:"Add a member to an organization"}}},async e=>{let r=e.body.userId?await (0,t.D)(e).catch(e=>null):null,a=e.body.organizationId||r?.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o="teamId"in e.body?e.body.teamId:void 0;if(o&&!e.context.orgOptions.teams?.enabled)throw e.context.logger.error("Teams are not enabled"),i.E.fromStatus("BAD_REQUEST",{message:"Teams are not enabled"});let n=R(e.context,p),s=await e.context.internalAdapter.findUserById(e.body.userId);if(!s)throw i.E.from("BAD_REQUEST",ee.f.USER_NOT_FOUND);if(await n.findMemberByEmail({email:s.email,organizationId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);if(o){let e=await n.findTeamById({teamId:o,organizationId:a});if(!e||e.organizationId!==a)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND)}let l=e.context.orgOptions?.membershipLimit||100,c=await n.countMembers({organizationId:a}),u=await n.findOrganizationById(a);if(!u)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);if(c>=("number"==typeof l?l:await l(s,u)))throw i.E.from("FORBIDDEN",U.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);let{role:f,userId:m,organizationId:h,...g}=e.body,y={organizationId:a,userId:s.id,role:d(e.body.role),createdAt:new Date,...g||{}};if(p?.organizationHooks?.beforeAddMember){let t=await p?.organizationHooks.beforeAddMember({member:{userId:s.id,organizationId:a,role:d(e.body.role),...g},user:s,organization:u});t&&"object"==typeof t&&"data"in t&&(y={...y,...t.data})}let w=await n.createMember(y);if(o)try{if(void 0!==e.context.orgOptions.teams?.maximumMembersPerTeam){let t,l=e.context.orgOptions.teams.maximumMembersPerTeam;if("function"==typeof l){if(!r)throw i.E.fromStatus("UNAUTHORIZED");t=await l({teamId:o,session:{user:r.user,session:r.session},organizationId:a})}else t=l;if("limitReached"===(await n.addTeamMemberWithLimit({userId:s.id,teamId:o,maximumMembersPerTeam:t})).status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED)}else await n.findOrCreateTeamMember({userId:s.id,teamId:o})}catch(e){throw await n.deleteMember({memberId:w.id,organizationId:a,userId:s.id}),e}return p?.organizationHooks?.afterAddMember&&await p?.organizationHooks.afterAddMember({member:w,user:s,organization:u}),e.json(w)})),removeMember:(0,k.g)("/organization/remove-member",{method:"POST",body:ef,requireHeaders:!0,use:[x,S],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=R(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let n=null;if(e.body.memberIdOrEmail.includes("@"))n=await a.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r});else{let t=await a.findMemberById(e.body.memberIdOrEmail);if(t){let{user:e,...r}=t;n=r}else n=null}if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let s=c(n.role),l=e.context.orgOptions?.creatorRole||"owner";if(s.includes(l)){if(!c(o.role).includes(l))throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);let{members:e}=await a.listMembers({organizationId:r});if(e.filter(e=>c(e.role).includes(l)).length<=1)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER)}if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["delete"]},organizationId:r},e))throw i.E.from("UNAUTHORIZED",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER);if(n?.organizationId!==r)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let d=await a.findOrganizationById(r);if(!d)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let u=await e.context.internalAdapter.findUserById(n.userId);if(!u)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});return p?.organizationHooks?.beforeRemoveMember&&await p?.organizationHooks.beforeRemoveMember({member:n,user:u,organization:d}),await a.deleteMember({memberId:n.id,organizationId:r,userId:n.userId}),t.user.id===n.userId&&t.session.activeOrganizationId===n.organizationId&&await a.setActiveOrganization(t.session.token,null,e),p?.organizationHooks?.afterRemoveMember&&await p?.organizationHooks.afterRemoveMember({member:n,user:u,organization:d}),e.json({member:n})}),updateMemberRole:(0,k.g)("/organization/update-member-role",{method:"POST",body:ep,use:[x,S],requireHeaders:!0,metadata:{$Infer:{body:{}},openapi:{operationId:"updateOrganizationMemberRole",description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session;if(!e.body.role)throw i.E.fromStatus("BAD_REQUEST");let r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=R(e.context,e.context.orgOptions),o=c(e.body.role);if(0===o.length)throw i.E.fromStatus("BAD_REQUEST");let n=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let s=n.id!==e.body.memberId?await a.findMemberById(e.body.memberId):n;if(!s)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);if(s.organizationId!==r)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);let u=e.context.orgOptions?.creatorRole||"owner",f=c(n.role),m=c(s.role).includes(u),h=f.includes(u),g=o.includes(u),y=n.id===s.id;if(m&&!h||g&&!h)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);if(h&&y&&(await e.context.adapter.findMany({model:"member",where:[{field:"organizationId",value:r}]})).filter(e=>c(e.role).includes(u)).length<=1&&!g)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{member:["update"]},allowCreatorAllPermissions:!0,organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);let w=new Set([...Object.keys(l),...Object.keys(e.context.orgOptions.roles||{})]),b=o.filter(e=>!w.has(e));if(b.length>0)if(e.context.orgOptions.dynamicAccessControl?.enabled){let t=(await e.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:r},{field:"role",value:b,operator:"in"}]})).map(e=>e.role),a=b.filter(e=>!t.includes(e));if(a.length>0)throw new i.E("BAD_REQUEST",{code:U.ROLE_NOT_FOUND.code,message:`${U.ROLE_NOT_FOUND.code}: ${a.join(", ")}`})}else throw new i.E("BAD_REQUEST",{code:U.ROLE_NOT_FOUND.code,message:`${U.ROLE_NOT_FOUND.code}: ${b.join(", ")}`});let E=await a.findOrganizationById(r);if(!E)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let A=await e.context.internalAdapter.findUserById(s.userId);if(!A)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});let I=s.role,T=d(o);if(p?.organizationHooks?.beforeUpdateMemberRole){let t=await p?.organizationHooks.beforeUpdateMemberRole({member:s,newRole:T,user:A,organization:E});if(t&&"object"==typeof t&&"data"in t){let r=await a.updateMember(e.body.memberId,t.data.role||T);if(!r)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return p?.organizationHooks?.afterUpdateMemberRole&&await p?.organizationHooks.afterUpdateMemberRole({member:r,previousRole:I,user:A,organization:E}),e.json(r)}}let _=await a.updateMember(e.body.memberId,T);if(!_)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);return p?.organizationHooks?.afterUpdateMemberRole&&await p?.organizationHooks.afterUpdateMemberRole({member:_,previousRole:I,user:A,organization:E}),e.json(_)}),leaveOrganization:(0,k.g)("/organization/leave",{method:"POST",body:em,requireHeaders:!0,use:[t.Z,x]},async e=>{let t=e.context.session,r=R(e.context,p),a=await r.findMemberByOrgId({userId:t.user.id,organizationId:e.body.organizationId});if(!a)throw i.E.from("BAD_REQUEST",U.MEMBER_NOT_FOUND);let o=e.context.orgOptions?.creatorRole||"owner";if(c(a.role).includes(o)&&(await e.context.adapter.findMany({model:"member",where:[{field:"organizationId",value:e.body.organizationId}]})).filter(e=>c(e.role).includes(o)).length<=1)throw i.E.from("BAD_REQUEST",U.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);return await r.deleteMember({memberId:a.id,organizationId:e.body.organizationId,userId:t.user.id}),t.session.activeOrganizationId===e.body.organizationId&&await r.setActiveOrganization(t.session.token,null,e),e.json(a)}),listUserInvitations:(0,k.g)("/organization/list-user-invitations",{method:"GET",use:[x],query:L.object({email:L.string().meta({description:"The email of the user to list invitations for. This only works for server side API calls."}).optional()}).optional(),metadata:{openapi:{description:"List all invitations a user has received",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},organizationName:{type:"string"},inviterId:{type:"string",description:"The ID of the user who created the invitation"},teamId:{type:"string",description:"The ID of the team associated with the invitation",nullable:!0},status:{type:"string"},expiresAt:{type:"string"},createdAt:{type:"string"}},required:["id","email","role","organizationId","organizationName","inviterId","status","expiresAt","createdAt"]}}}}}}}}},async e=>{let r=await (0,t.D)(e);if(e.request&&e.query?.email)throw i.E.fromStatus("BAD_REQUEST",{message:"User email cannot be passed for client side API calls."});if(r&&!r.user.emailVerified)throw i.E.from("FORBIDDEN",U.EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION);let a=r?.user.email||e.query?.email;if(!a)throw i.E.fromStatus("BAD_REQUEST",{message:"Missing session headers, or email query parameter."});let o=(await R(e.context,p).listUserInvitations(a)).filter(e=>"pending"===e.status);return e.json(o)}),listMembers:(0,k.g)("/organization/list-members",{method:"GET",query:L.object({limit:L.string().meta({description:"The number of users to return"}).or(L.number()).optional(),offset:L.string().meta({description:"The offset to start from"}).or(L.number()).optional(),sortBy:L.string().meta({description:"The field to sort by"}).optional(),sortDirection:L.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:L.string().meta({description:"The field to filter by"}).optional(),filterValue:L.string().meta({description:"The value to filter by"}).or(L.number()).or(L.boolean()).or(L.array(L.string())).or(L.array(L.number())).optional(),filterOperator:L.enum(ec).meta({description:"The operator to use for the filter"}).optional(),organizationId:L.string().meta({description:'The organization ID to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-id"'}).optional(),organizationSlug:L.string().meta({description:'The organization slug to list members for. If not provided, will default to the user\'s active organization. Eg: "organization-slug"'}).optional()}).optional(),requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t.session.activeOrganizationId,a=R(e.context,p);if(e.query?.organizationSlug){let t=await a.findOrganizationBySlug(e.query?.organizationSlug);if(!t)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);r=t.id}if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);if(!await a.findMemberByOrgId({userId:t.user.id,organizationId:r}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);let{members:o,total:n}=await a.listMembers({organizationId:r,limit:e.query?.limit?Number(e.query.limit):void 0,offset:e.query?.offset?Number(e.query.offset):void 0,sortBy:e.query?.sortBy,sortOrder:e.query?.sortDirection,filter:e.query?.filterField?{field:e.query?.filterField,operator:e.query.filterOperator,value:e.query.filterValue}:void 0});return e.json({members:o,total:n})}),getActiveMemberRole:(0,k.g)("/organization/get-active-member-role",{method:"GET",query:eh,requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t.session.activeOrganizationId,a=R(e.context,p);if(e.query?.organizationSlug){let t=await a.findOrganizationBySlug(e.query?.organizationSlug);if(!t)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);r=t.id}if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!e.query?.userId)return e.json({role:o.role});let n=e.query?.userId,s=await a.findMemberByOrgId({userId:n,organizationId:r});if(!s)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);return e.json({role:s.role})})},y=p.teams?.enabled,w={createTeam:(u=q({fields:p?.schema?.team?.additionalFields??{},isClientSide:!0}),(0,k.g)("/organization/create-team",{method:"POST",body:L.object({...ek.shape,...u.shape}),use:[x],metadata:{$Infer:{body:{}},openapi:{description:"Create a new team within an organization",responses:{200:{description:"Team created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the created team"},name:{type:"string",description:"Name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]}}}}}}}},async e=>{let r=await (0,t.D)(e),a=e.body.organizationId||r?.session.activeOrganizationId;if(!r&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=R(e.context,p);if(r){let t=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!t)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);if(!await P({role:t.role,options:e.context.orgOptions,permissions:{team:["create"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION)}let n=await o.listTeams(a),s="function"==typeof e.context.orgOptions.teams?.maximumTeams?await e.context.orgOptions.teams?.maximumTeams({organizationId:a,session:r},e):e.context.orgOptions.teams?.maximumTeams;if(s&&n.length>=s)throw i.E.from("BAD_REQUEST",U.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS);let{name:l,organizationId:c,...d}=e.body,u=await o.findOrganizationById(a);if(!u)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let f={name:l,organizationId:a,createdAt:new Date,updatedAt:new Date,...d};if(p?.organizationHooks?.beforeCreateTeam){let e=await p?.organizationHooks.beforeCreateTeam({team:{name:l,organizationId:a,...d},user:r?.user,organization:u});e&&"object"==typeof e&&"data"in e&&(f={...f,...e.data})}let m=await o.createTeam(f);return p?.organizationHooks?.afterCreateTeam&&await p?.organizationHooks.afterCreateTeam({team:m,user:r?.user,organization:u}),e.json(m)})),listOrganizationTeams:(0,k.g)("/organization/list-teams",{method:"GET",query:eS,metadata:{openapi:{description:"List all teams in an organization",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the team"},name:{type:"string",description:"Name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]},description:"Array of team objects within the organization"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=e.query?.organizationId||t?.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=R(e.context,p);if(!await a.findMemberByOrgId({userId:t.user.id,organizationId:r||""}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION);let o=await a.listTeams(r);return e.json(o)}),removeTeam:(0,k.g)("/organization/remove-team",{method:"POST",body:ex,use:[x],metadata:{openapi:{description:"Remove a team from an organization",responses:{200:{description:"Team removed successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Confirmation message indicating successful removal",enum:["Team removed successfully."]}},required:["message"]}}}}}}}},async e=>{let r=await (0,t.D)(e),a=e.body.organizationId||r?.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);if(!r&&(e.request||e.headers))throw i.E.fromStatus("UNAUTHORIZED");let o=R(e.context,p);if(r){let t=await o.findMemberByOrgId({userId:r.user.id,organizationId:a});if(!t||r.session?.activeTeamId===e.body.teamId)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM);if(!await P({role:t.role,options:e.context.orgOptions,permissions:{team:["delete"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION)}let n=await o.findTeamById({teamId:e.body.teamId,organizationId:a});if(!n||n.organizationId!==a)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!e.context.orgOptions.teams?.allowRemovingAllTeams&&(await o.listTeams(a)).length<=1)throw i.E.from("BAD_REQUEST",U.UNABLE_TO_REMOVE_LAST_TEAM);let s=await o.findOrganizationById(a);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);return p?.organizationHooks?.beforeDeleteTeam&&await p?.organizationHooks.beforeDeleteTeam({team:n,user:r?.user,organization:s}),await (0,h.n)(e.context.adapter,async()=>{await o.deleteTeam(n.id);let t=await o.findPendingInvitations({organizationId:a}),r=await (0,h.g)(e.context.adapter);for(let e of t){if(!("teamId"in e)||!e.teamId)continue;let t=e.teamId.split(",");if(!t.includes(n.id))continue;let i=t.filter(e=>e!==n.id);await r.update({model:"invitation",where:[{field:"id",value:e.id}],update:{teamId:i.length>0?i.join(","):null}})}}),p?.organizationHooks?.afterDeleteTeam&&await p?.organizationHooks.afterDeleteTeam({team:n,user:r?.user,organization:s}),e.json({message:"Team removed successfully."})}),updateTeam:(f=q({fields:p?.schema?.team?.additionalFields??{},isClientSide:!0}),(0,k.g)("/organization/update-team",{method:"POST",body:L.object({teamId:L.string().meta({description:'The ID of the team to be updated. Eg: "team-id"'}),data:L.object({...eO.omit({id:!0,createdAt:!0,updatedAt:!0}).shape,...f.shape}).partial()}),requireHeaders:!0,use:[x,S],metadata:{$Infer:{body:{}},openapi:{description:"Update an existing team in an organization",responses:{200:{description:"Team updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the updated team"},name:{type:"string",description:"Updated name of the team"},organizationId:{type:"string",description:"ID of the organization the team belongs to"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team was created"},updatedAt:{type:"string",format:"date-time",description:"Timestamp when the team was last updated"}},required:["id","name","organizationId","createdAt","updatedAt"]}}}}}}}},async e=>{let t=e.context.session,r=e.body.data.organizationId||t.session.activeOrganizationId;if(!r)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let a=R(e.context,p),o=await a.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!o||!await P({role:o.role,options:e.context.orgOptions,permissions:{team:["update"]},organizationId:r},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);let n=await a.findTeamById({teamId:e.body.teamId,organizationId:r});if(!n||n.organizationId!==r)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let{name:s,organizationId:l,...c}=e.body.data,d=await a.findOrganizationById(r);if(!d)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let u={name:s,...c};if(p?.organizationHooks?.beforeUpdateTeam){let r=await p?.organizationHooks.beforeUpdateTeam({team:n,updates:u,user:t.user,organization:d});if(r&&"object"==typeof r&&"data"in r){let i=r.data,o=await a.updateTeam(n.id,i);return p?.organizationHooks?.afterUpdateTeam&&await p?.organizationHooks.afterUpdateTeam({team:o,user:t.user,organization:d}),e.json(o)}}let f=await a.updateTeam(n.id,u);return p?.organizationHooks?.afterUpdateTeam&&await p?.organizationHooks.afterUpdateTeam({team:f,user:t.user,organization:d}),e.json(f)})),setActiveTeam:(0,k.g)("/organization/set-active-team",{method:"POST",body:eU,requireHeaders:!0,use:[S,x],metadata:{openapi:{description:"Set the active team for the current active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The team",$ref:"#/components/schemas/Team"}}}}}}}},async e=>{let t,r=R(e.context,e.context.orgOptions),a=e.context.session;if(null===e.body.teamId){if(!a.session.activeTeamId)return e.json(null);let t=await r.setActiveTeam(a.session.token,null,e);return await (0,X.V)(e,{session:t,user:a.user}),e.json(null)}if(e.body.teamId)t=e.body.teamId;else{let r=a.session.activeTeamId;if(!r)return e.json(null);t=r}let o=a.session.activeOrganizationId;if(!o)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await r.findTeamById({teamId:t,organizationId:o});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!await r.findTeamMember({teamId:t,userId:a.user.id}))throw i.E.from("FORBIDDEN",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);let s=await r.setActiveTeam(a.session.token,n.id,e);return await (0,X.V)(e,{session:s,user:a.user}),e.json(n)}),listUserTeams:(0,k.g)("/organization/list-user-teams",{method:"GET",query:L.object({userId:L.string().optional().meta({description:"The user ID to list teams for. Defaults to the current session user."}),organizationId:L.string().optional().meta({description:"The organization ID to scope the team list to. When omitted on a self-query, teams are returned across every organization the user belongs to. When querying another user, falls back to the session's active organization and is required if there is no active organization."})}).optional(),metadata:{openapi:{description:"List teams for a user. Without parameters, returns teams for the current user across every organization they belong to. Pass `organizationId` to scope the result to a specific organization. Pass `userId` to list teams for another member; this requires `member:update` permission in the target organization (the explicit `organizationId` if provided, otherwise the session's active organization).",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",description:"The team",$ref:"#/components/schemas/Team"},description:"Array of team objects within the organization"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=R(e.context,e.context.orgOptions),a=e.query?.userId||t.user.id,o=a===t.user.id,n=e.query?.organizationId||t.session.activeOrganizationId,s=!!e.query?.organizationId;if(!o){if(!n)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:n});if(!o)throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["update"]},organizationId:n},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);if(!await r.findMemberByOrgId({userId:a,organizationId:n}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let s=await r.listTeamsByUser({userId:a});return e.json(s.filter(e=>e.organizationId===n))}if(s&&n){if(!await r.findMemberByOrgId({userId:t.user.id,organizationId:n}))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);let a=await r.listTeamsByUser({userId:t.user.id});return e.json(a.filter(e=>e.organizationId===n))}let l=await r.listTeamsByUser({userId:t.user.id}),c=[...new Set(l.map(e=>e.organizationId))],d=await Promise.all(c.map(e=>r.checkMembership({userId:t.user.id,organizationId:e}))),u=new Set(c.filter((e,t)=>d[t]));return e.json(l.filter(e=>u.has(e.organizationId)))}),listTeamMembers:(0,k.g)("/organization/list-team-members",{method:"GET",query:eN,metadata:{openapi:{description:"List the members of the given team.",responses:{200:{description:"Teams retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",description:"The team member",properties:{id:{type:"string",description:"Unique identifier of the team member"},userId:{type:"string",description:"The user ID of the team member"},teamId:{type:"string",description:"The team ID of the team the team member is in"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team member was created"}},required:["id","userId","teamId","createdAt"]},description:"Array of team member objects within the team"}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=R(e.context,e.context.orgOptions),a=e.query?.teamId||t?.session.activeTeamId;if(!a)throw i.E.from("BAD_REQUEST",U.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM);let o=await r.findTeamById({teamId:a});if(!o)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);if(!await r.checkMembership({userId:t.user.id,organizationId:o.organizationId})||!await r.findTeamMember({userId:t.user.id,teamId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);let n=await r.listTeamMembers({teamId:a});return e.json(n)}),addTeamMember:(0,k.g)("/organization/add-team-member",{method:"POST",body:eD,metadata:{openapi:{description:"The newly created member",responses:{200:{description:"Team member created successfully",content:{"application/json":{schema:{type:"object",description:"The team member",properties:{id:{type:"string",description:"Unique identifier of the team member"},userId:{type:"string",description:"The user ID of the team member"},teamId:{type:"string",description:"The team ID of the team the team member is in"},createdAt:{type:"string",format:"date-time",description:"Timestamp when the team member was created"}},required:["id","userId","teamId","createdAt"]}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t,r=e.context.session,a=R(e.context,e.context.orgOptions),o=e.body.organizationId||r.session.activeOrganizationId;if(!o)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await a.findMemberByOrgId({userId:r.user.id,organizationId:o});if(!n)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:n.role,options:e.context.orgOptions,permissions:{member:["update"]},organizationId:o},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER);if(!await a.findMemberByOrgId({userId:e.body.userId,organizationId:o}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let s=await a.findTeamById({teamId:e.body.teamId,organizationId:o});if(!s)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let l=await a.findOrganizationById(o);if(!l)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let c=await e.context.internalAdapter.findUserById(e.body.userId);if(!c)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});if(p?.organizationHooks?.beforeAddTeamMember&&await p?.organizationHooks.beforeAddTeamMember({teamMember:{teamId:e.body.teamId,userId:e.body.userId},team:s,user:c,organization:l}),void 0!==e.context.orgOptions.teams?.maximumMembersPerTeam){let n="function"==typeof e.context.orgOptions.teams.maximumMembersPerTeam?await e.context.orgOptions.teams.maximumMembersPerTeam({teamId:e.body.teamId,session:r,organizationId:o}):e.context.orgOptions.teams.maximumMembersPerTeam,s=await a.addTeamMemberWithLimit({teamId:e.body.teamId,userId:e.body.userId,maximumMembersPerTeam:n});if("limitReached"===s.status)throw i.E.from("FORBIDDEN",U.TEAM_MEMBER_LIMIT_REACHED);t=s.member}else t=await a.findOrCreateTeamMember({teamId:e.body.teamId,userId:e.body.userId});return p?.organizationHooks?.afterAddTeamMember&&await p?.organizationHooks.afterAddTeamMember({teamMember:t,team:s,user:c,organization:l}),e.json(t)}),removeTeamMember:(0,k.g)("/organization/remove-team-member",{method:"POST",body:eL,metadata:{openapi:{description:"Remove a member from a team",responses:{200:{description:"Team member removed successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Confirmation message indicating successful removal",enum:["Team member removed successfully."]}},required:["message"]}}}}}}},requireHeaders:!0,use:[x,S]},async e=>{let t=e.context.session,r=R(e.context,e.context.orgOptions),a=e.body.organizationId||t.session.activeOrganizationId;if(!a)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let o=await r.findMemberByOrgId({userId:t.user.id,organizationId:a});if(!o)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);if(!await P({role:o.role,options:e.context.orgOptions,permissions:{member:["delete"]},organizationId:a},e))throw i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER);if(!await r.findMemberByOrgId({userId:e.body.userId,organizationId:a}))throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let n=await r.findTeamById({teamId:e.body.teamId,organizationId:a});if(!n)throw i.E.from("BAD_REQUEST",U.TEAM_NOT_FOUND);let s=await r.findOrganizationById(a);if(!s)throw i.E.from("BAD_REQUEST",U.ORGANIZATION_NOT_FOUND);let l=await e.context.internalAdapter.findUserById(e.body.userId);if(!l)throw i.E.fromStatus("BAD_REQUEST",{message:"User not found"});let c=await r.findTeamMember({teamId:e.body.teamId,userId:e.body.userId});if(!c)throw i.E.from("BAD_REQUEST",U.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);return p?.organizationHooks?.beforeRemoveTeamMember&&await p?.organizationHooks.beforeRemoveTeamMember({teamMember:c,team:n,user:l,organization:s}),await r.removeTeamMember({teamId:e.body.teamId,userId:e.body.userId}),p?.organizationHooks?.afterRemoveTeamMember&&await p?.organizationHooks.afterRemoveTeamMember({teamMember:c,team:n,user:l,organization:s}),e.json({message:"Team member removed successfully."})})};y&&(g={...g,...w});let b={createOrgRole:(e=>{let{additionalFieldsSchema:t,$AdditionalFields:r,$ReturnAdditionalFields:a}=H(e,!1);return(0,k.g)("/organization/create-role",{method:"POST",body:F.safeExtend({additionalFields:L.object({...t.shape}).optional()}),metadata:{$Infer:{body:{}}},requireHeaders:!0,use:[S]},async t=>{let{session:r,user:a}=t.context.session,o=t.body.role,n=t.body.permission,s=t.body.additionalFields,l=e.ac;if(!l)throw t.context.logger.error("[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.",`
|
|
481
|
+
Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`),i.E.from("NOT_IMPLEMENTED",U.MISSING_AC_INSTANCE);let c=t.body.organizationId??r.activeOrganizationId;if(!c)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body."),i.E.from("BAD_REQUEST",U.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE);o=o.toLowerCase(),await Y({role:o,organizationId:c,options:e,ctx:t});let d=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:c,operator:"eq",connector:"AND"},{field:"userId",value:a.id,operator:"eq",connector:"AND"}]});if(!d)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to create a role.",{userId:a.id,organizationId:c}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:c,permissions:{ac:["create"]},role:d.role},t))throw t.context.logger.error('[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "create" permission.',{userId:a.id,organizationId:c,role:d.role}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE);let u="function"==typeof e.dynamicAccessControl?.maximumRolesPerOrganization?await e.dynamicAccessControl.maximumRolesPerOrganization(c):e.dynamicAccessControl?.maximumRolesPerOrganization??1/0,f=await t.context.adapter.count({model:"organizationRole",where:[{field:"organizationId",value:c,operator:"eq",connector:"AND"}]});if(f>=u)throw t.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${u}.`,{organizationId:c,maximumRolesPerOrganization:u,rolesInDB:f}),i.E.from("BAD_REQUEST",U.TOO_MANY_ROLES);await J({ac:l,ctx:t,permission:n}),await Q({ctx:t,member:d,options:e,organizationId:c,permissionRequired:n,user:a,action:"create"}),await Z({ctx:t,organizationId:c,role:o});let p=l.newRole(n),m={...await t.context.adapter.create({model:"organizationRole",data:{createdAt:new Date,organizationId:c,permission:JSON.stringify(n),role:o,...s}}),permission:n};return t.json({success:!0,roleData:m,statements:p.statements})})})(p),deleteOrgRole:(0,k.g)("/organization/delete-role",{method:"POST",body:V,requireHeaders:!0,use:[S],metadata:{$Infer:{body:{}}}},async e=>{let t,{session:r,user:a}=e.context.session,o=e.body.organizationId??r.activeOrganizationId;if(!o)throw e.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to delete a role. Either set an active org id, or pass an organizationId in the request body."),i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await e.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"},{field:"userId",value:a.id,operator:"eq",connector:"AND"}]});if(!n)throw e.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to delete a role.",{userId:a.id,organizationId:o}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:p,organizationId:o,permissions:{ac:["delete"]},role:n.role},e))throw e.context.logger.error('[Dynamic Access Control] The user is not permitted to delete a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "delete" permission.',{userId:a.id,organizationId:o,role:n.role}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE);if(e.body.roleName){let t=e.body.roleName,r=p.roles?Object.keys(p.roles):["owner","admin","member"];if(r.includes(t))throw e.context.logger.error("[Dynamic Access Control] Cannot delete a pre-defined role.",{roleName:t,organizationId:o,defaultRoles:r}),i.E.from("BAD_REQUEST",U.CANNOT_DELETE_A_PRE_DEFINED_ROLE)}if(e.body.roleName)t={field:"role",value:e.body.roleName,operator:"eq",connector:"AND"};else if(e.body.roleId)t={field:"id",value:e.body.roleId,operator:"eq",connector:"AND"};else throw e.context.logger.error("[Dynamic Access Control] The role name/id is not provided in the request body."),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let s=await e.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"},t]});if(!s)throw e.context.logger.error("[Dynamic Access Control] The role name/id does not exist in the database.",{..."roleName"in e.body?{roleName:e.body.roleName}:{roleId:e.body.roleId},organizationId:o}),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);s.permission=JSON.parse(s.permission);let l=s.role;if((await e.context.adapter.findMany({model:"member",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"},{field:"role",value:l,operator:"contains"}]})).find(e=>c(e.role).includes(l)))throw e.context.logger.error("[Dynamic Access Control] Cannot delete a role that is assigned to members.",{role:s.role,organizationId:o}),i.E.from("BAD_REQUEST",U.ROLE_IS_ASSIGNED_TO_MEMBERS);return await e.context.adapter.delete({model:"organizationRole",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"},t]}),e.json({success:!0})}),listOrgRoles:(e=>{let{$ReturnAdditionalFields:t}=H(e,!1);return(0,k.g)("/organization/list-roles",{method:"GET",requireHeaders:!0,use:[S],query:W},async t=>{let{session:r,user:a}=t.context.session,o=t.query?.organizationId??r.activeOrganizationId;if(!o)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to list roles. Either set an active org id, or pass an organizationId in the request query."),i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let n=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"},{field:"userId",value:a.id,operator:"eq",connector:"AND"}]});if(!n)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to list roles.",{userId:a.id,organizationId:o}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:o,permissions:{ac:["read"]},role:n.role},t))throw t.context.logger.error("[Dynamic Access Control] The user is not permitted to list roles.",{userId:a.id,organizationId:o,role:n.role}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE);let s=await t.context.adapter.findMany({model:"organizationRole",where:[{field:"organizationId",value:o,operator:"eq",connector:"AND"}]});return s=s.map(e=>({...e,permission:JSON.parse(e.permission)})),t.json(s)})})(p),getOrgRole:(e=>{let{$ReturnAdditionalFields:t}=H(e,!1);return(0,k.g)("/organization/get-role",{method:"GET",requireHeaders:!0,use:[S],query:K,metadata:{$Infer:{query:{}}}},async t=>{let r,{session:a,user:o}=t.context.session,n=t.query?.organizationId??a.activeOrganizationId;if(!n)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to read a role. Either set an active org id, or pass an organizationId in the request query."),i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let s=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:n,operator:"eq",connector:"AND"},{field:"userId",value:o.id,operator:"eq",connector:"AND"}]});if(!s)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to read a role.",{userId:o.id,organizationId:n}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:n,permissions:{ac:["read"]},role:s.role},t))throw t.context.logger.error("[Dynamic Access Control] The user is not permitted to read a role.",{userId:o.id,organizationId:n,role:s.role}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE);if(t.query.roleName)r={field:"role",value:t.query.roleName,operator:"eq",connector:"AND"};else if(t.query.roleId)r={field:"id",value:t.query.roleId,operator:"eq",connector:"AND"};else throw t.context.logger.error("[Dynamic Access Control] The role name/id is not provided in the request query."),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let l=await t.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:n,operator:"eq",connector:"AND"},r]});if(!l)throw t.context.logger.error("[Dynamic Access Control] The role name/id does not exist in the database.",{..."roleName"in t.query?{roleName:t.query.roleName}:{roleId:t.query.roleId},organizationId:n}),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);return l.permission=JSON.parse(l.permission),t.json(l)})})(p),updateOrgRole:(e=>{let{additionalFieldsSchema:t,$AdditionalFields:r,$ReturnAdditionalFields:a}=H(e,!0);return(0,k.g)("/organization/update-role",{method:"POST",body:L.object({organizationId:L.string().optional().meta({description:"The id of the organization to update the role in. If not provided, the user's active organization will be used."}),data:L.object({permission:L.record(L.string(),L.array(L.string())).optional().meta({description:"The permission to update the role with"}),roleName:L.string().optional().meta({description:"The name of the role to update"}),...t.shape})}).and(G),metadata:{$Infer:{body:{}}},requireHeaders:!0,use:[S]},async t=>{let r,{session:a,user:o}=t.context.session,n=e.ac;if(!n)throw t.context.logger.error("[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.",`
|
|
482
|
+
Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`),i.E.from("NOT_IMPLEMENTED",U.MISSING_AC_INSTANCE);let s=t.body.organizationId??a.activeOrganizationId;if(!s)throw t.context.logger.error("[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body."),i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let l=await t.context.adapter.findOne({model:"member",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},{field:"userId",value:o.id,operator:"eq",connector:"AND"}]});if(!l)throw t.context.logger.error("[Dynamic Access Control] The user is not a member of the organization to update a role.",{userId:o.id,organizationId:s}),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);if(!await P({options:e,organizationId:s,role:l.role,permissions:{ac:["update"]}},t))throw t.context.logger.error("[Dynamic Access Control] The user is not permitted to update a role."),i.E.from("FORBIDDEN",U.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE);if(t.body.roleName)r={field:"role",value:t.body.roleName,operator:"eq",connector:"AND"};else if(t.body.roleId)r={field:"id",value:t.body.roleId,operator:"eq",connector:"AND"};else throw t.context.logger.error("[Dynamic Access Control] The role name/id is not provided in the request body."),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);let c=await t.context.adapter.findOne({model:"organizationRole",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},r]});if(!c)throw t.context.logger.error("[Dynamic Access Control] The role name/id does not exist in the database.",{..."roleName"in t.body?{roleName:t.body.roleName}:{roleId:t.body.roleId},organizationId:s}),i.E.from("BAD_REQUEST",U.ROLE_NOT_FOUND);c.permission=c.permission?JSON.parse(c.permission):void 0;let{permission:d,roleName:u,...f}=t.body.data,p={...f};if(t.body.data.permission){let r=t.body.data.permission;await J({ac:n,ctx:t,permission:r}),await Q({ctx:t,member:l,options:e,organizationId:s,permissionRequired:r,user:o,action:"update"}),p.permission=r}if(t.body.data.roleName){let r=t.body.data.roleName;r=r.toLowerCase(),await Y({role:r,organizationId:s,options:e,ctx:t}),await Z({role:r,organizationId:s,ctx:t}),p.role=r}let m={...p,...p.permission?{permission:JSON.stringify(p.permission)}:{}};return await t.context.adapter.updateMany({model:"organizationRole",where:[{field:"organizationId",value:s,operator:"eq",connector:"AND"},r],update:m}),t.json({success:!0,roleData:{...c,...m,permission:p.permission||c.permission||null}})})})(p)};p.dynamicAccessControl?.enabled&&(g={...g,...b});let E={...l,...p.roles},A=y?{team:{modelName:p.schema?.team?.modelName,fields:{name:{type:"string",required:!0,fieldName:p.schema?.team?.fields?.name},memberCount:{type:"number",required:!0,defaultValue:0,input:!1,returned:!1,fieldName:p.schema?.team?.fields?.memberCount},organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.team?.fields?.organizationId,index:!0},createdAt:{type:"date",required:!0,fieldName:p.schema?.team?.fields?.createdAt},updatedAt:{type:"date",required:!1,fieldName:p.schema?.team?.fields?.updatedAt,onUpdate:()=>new Date},...p.schema?.team?.additionalFields||{}}},teamMember:{modelName:p.schema?.teamMember?.modelName,fields:{teamId:{type:"string",required:!0,references:{model:"team",field:"id"},fieldName:p.schema?.teamMember?.fields?.teamId,index:!0},userId:{type:"string",required:!0,references:{model:"user",field:"id"},fieldName:p.schema?.teamMember?.fields?.userId,index:!0},membershipKey:{type:"string",required:!1,unique:!0,input:!1,returned:!1,fieldName:p.schema?.teamMember?.fields?.membershipKey},createdAt:{type:"date",required:!1,fieldName:p.schema?.teamMember?.fields?.createdAt}}}}:{},I=p.dynamicAccessControl?.enabled?{organizationRole:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.organizationRole?.fields?.organizationId,index:!0},role:{type:"string",required:!0,fieldName:p.schema?.organizationRole?.fields?.role,index:!0},permission:{type:"string",required:!0,fieldName:p.schema?.organizationRole?.fields?.permission},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:p.schema?.organizationRole?.fields?.createdAt},updatedAt:{type:"date",required:!1,fieldName:p.schema?.organizationRole?.fields?.updatedAt,onUpdate:()=>new Date},...p.schema?.organizationRole?.additionalFields||{}},modelName:p.schema?.organizationRole?.modelName}}:{},T={organization:{modelName:p.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,sortable:!0,fieldName:p.schema?.organization?.fields?.name},slug:{type:"string",required:!0,unique:!0,sortable:!0,fieldName:p.schema?.organization?.fields?.slug,index:!0},logo:{type:"string",required:!1,fieldName:p.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:p.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:p.schema?.organization?.fields?.metadata},...p.schema?.organization?.additionalFields||{}}},...I,...A,member:{modelName:p.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.member?.fields?.organizationId,index:!0},userId:{type:"string",required:!0,fieldName:p.schema?.member?.fields?.userId,references:{model:"user",field:"id"},index:!0},role:{type:"string",required:!0,sortable:!0,defaultValue:"member",fieldName:p.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:p.schema?.member?.fields?.createdAt},...p.schema?.member?.additionalFields||{}}},invitation:{modelName:p.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:p.schema?.invitation?.fields?.organizationId,index:!0},email:{type:"string",required:!0,sortable:!0,fieldName:p.schema?.invitation?.fields?.email,index:!0},role:{type:"string",required:!1,sortable:!0,fieldName:p.schema?.invitation?.fields?.role},...y?{teamId:{type:"string",required:!1,sortable:!0,fieldName:p.schema?.invitation?.fields?.teamId}}:{},status:{type:"string",required:!0,sortable:!0,defaultValue:"pending",fieldName:p.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:p.schema?.invitation?.fields?.expiresAt},createdAt:{type:"date",required:!0,fieldName:p.schema?.invitation?.fields?.createdAt,defaultValue:()=>new Date},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:p.schema?.invitation?.fields?.inviterId,required:!0},...p.schema?.invitation?.additionalFields||{}}}},_=((e,t)=>{let r={};for(let[i,a]of Object.entries(e))r[i]=e=>a({...e,context:{...t,...e.context}}),r[i].path=a.path,r[i].method=a.method,r[i].options=a.options,r[i].headers=a.headers;return r})(g,{orgOptions:p,roles:E,getSession:async e=>await (0,t.D)(e)});return{id:"organization",version:r.f,endpoints:{..._,hasPermission:(0,k.g)("/organization/has-permission",{method:"POST",requireHeaders:!0,body:eC,use:[S],metadata:{$Infer:{body:{}},openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check",deprecated:!0},permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async e=>{let t=e.body.organizationId||e.context.session.session.activeOrganizationId;if(!t)throw i.E.from("BAD_REQUEST",U.NO_ACTIVE_ORGANIZATION);let r=await R(e.context,p).findMemberByOrgId({userId:e.context.session.user.id,organizationId:t});if(!r)throw i.E.from("UNAUTHORIZED",U.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);let a=await P({role:r.role,options:p,permissions:e.body.permissions,organizationId:t},e);return e.json({error:null,success:a})})},schema:{...T,session:{fields:{activeOrganizationId:{type:"string",required:!1,input:!1,fieldName:p.schema?.session?.fields?.activeOrganizationId},...y?{activeTeamId:{type:"string",required:!1,input:!1,fieldName:p.schema?.session?.fields?.activeTeamId}}:{}}}},$Infer:{Organization:{},Invitation:{},Member:{},Team:{},TeamMember:{},ActiveOrganization:{}},$ERROR_CODES:U,options:p}}],34975)},96481,76411,67850,69381,1083,32802,63370,65466,83817,92449,24472,16760,27957,1889,12319,41242,9939,75742,74285,56023,42158,76660,54257,97554,96161,70728,82318,73436,12996,e=>{"use strict";let t,r,i;function a(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function o(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function n(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 i="",o="",n=".";!0===r?(i="/",o="[/\\\\]",n="[^/\\\\]"):r&&((o=function(e){let t="";for(let r=0;r<e.length;r++)t+=a(e[r]);return t}(i=r)).length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let s=r?`${o}+?`:"",l=r?`${o}*?`:"",c=r?t.split(i):[t],d="";for(let e=0;e<c.length;e++){let t=c[e],i=c[e+1],o="";if(t||!(e>0)){if(r&&(o=e===c.length-1?l:"**"!==i?s:""),r&&"**"===t){o&&(d+=0===e?"":o,d+=`(?:${n}*?${o})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(d+=a(t[e+1]),e++):"?"===r?d+=n:"*"===r?d+=`${n}*?`:d+=a(r)}d+=o}}return d}(e,t.separator),i=RegExp(`^${r}$`,t.flags),n=o.bind(null,i);return n.options=t,n.pattern=e,n.regexp=i,n}e.s(["f",0,n],76411);var s=e.i(47391),l=e.i(71616);function c(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)}function d(e,t="/api/auth"){try{let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new l.p(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof l.p)throw t;throw new l.p(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}if(function(e){try{return"/"!==(c(new URL(e).pathname)||"/")}catch{throw new l.p(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e))return e;let r=c(e);return t&&"/"!==t?(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`):r}function u(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 f(e,t,r,i,a){if(e)return d(e,t);if(!1!==i){let e=s.$.BETTER_AUTH_URL||s.$.NEXT_PUBLIC_BETTER_AUTH_URL||s.$.PUBLIC_BETTER_AUTH_URL||s.$.NUXT_PUBLIC_BETTER_AUTH_URL||s.$.NUXT_PUBLIC_AUTH_URL||("/"!==s.$.BASE_URL?s.$.BASE_URL:void 0);if(e)return d(e,t)}let o=r?.headers.get("x-forwarded-host"),n=r?.headers.get("x-forwarded-proto");if(o&&n&&a&&u(n,"proto")&&u(o,"host"))try{return d(`${n}://${o}`,t)}catch(e){}if(r){let e=p(r.url);if(!e)throw new l.p("Could not get origin from request. Please provide a valid base URL.");return d(e,t)}}function p(e){try{let t=new URL(e);return"null"===t.origin?null:t.origin}catch{return null}}function m(e){return"object"==typeof e&&null!==e&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function h(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 g(e,t){let r=h(e)?e.headers:e;if(t){let e=r.get("x-forwarded-host");if(e&&u(e,"host"))return e}let i=r.get("host");if(i&&u(i,"host"))return i;if(h(e))try{return new URL(e.url).host}catch{}return null}function y(e){return!!e.database||!!e.secondaryStorage}function w(e){return!!e.database}e.s(["X",0,f,"$",0,function(e){try{return new URL(e).host}catch{return null}},"H",0,p,"Y",0,function(e){try{return new URL(e).protocol}catch{return null}},"_",0,m,"T",0,h,"A",0,function(e,t,r,i,a){if(m(e)){if(r){let i=g(r,a);if(!i){if(e.fallback)return d(e.fallback,t);throw new l.p("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(),i=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return i.includes("*")||i.includes("?")?n(i)(r):r.toLowerCase()===i.toLowerCase()})(i,e)))return d(`${function(e,t,r){let i;if("http"===t||"https"===t)return t;let a=h(e)?e.headers:e;if(r){let e=a.get("x-forwarded-proto");if(e&&u(e,"proto"))return e}if(h(e))try{let t=new URL(e.url);if("http:"===t.protocol||"https:"===t.protocol)return t.protocol.slice(0,-1)}catch{}let o=g(e,r);return o&&("localhost"===(i=o.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||i.endsWith(".localhost")||"::1"===i||i.startsWith("127."))?"http":"https"}(r,e.protocol,a)}://${i}`,t);if(e.fallback)return d(e.fallback,t);throw new l.p(`Host "${i}" 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?d(e.fallback,t):f(void 0,t,void 0,i,a)}let o=h(r)?r:void 0;return"string"==typeof e?f(e,t,o,i,a):f(void 0,t,o,i,a)}],96481),e.s(["z",0,y,"d",0,w],67850);var b=e.i(97858);class E{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if((0,b.v)(e),(0,b.B)(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),(0,b.f)(i)}update(e){return(0,b.s)(this),this.iHash.update(e),this}digestInto(e){(0,b.s)(this),(0,b.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:i,destroyed:a,blockLen:o,outputLen:n,canXOF:s}=this;return e.finished=i,e.destroyed=a,e.blockLen=o,e.outputLen=n,e.canXOF=s,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 A=((i=(e,t,r)=>new E(e,t).update(r).digest()).create=(e,t)=>new E(e,t),i),I=Uint8Array.of(0),T=Uint8Array.of(),_=(e,t,r,i,a)=>{(0,b.v)(e),void 0===r&&(r=new Uint8Array(e.outputLen));let o=A.create(e,r).update(t);return function(e,t,r,i=32,a){(0,b.v)(e),(0,b.N)(i,"length"),(0,b.B)(t,void 0,"prk");let o=e.outputLen;if(t.length<o)throw Error('"prk" must be at least HashLen octets');if(i>255*o)throw Error("Length must be <= 255*HashLen");let n=Math.ceil(i/o);if(void 0===r?r=T:(0,b.B)(r,void 0,"info"),!n)return a&&(0,b.f)(t),new Uint8Array;let s=a&&1===n?t:new Uint8Array(n*o),{iHash:l,oHash:c}=A.create(e,t),d=a?t:new Uint8Array(o),u=n>1?a?.iHash||e.create():void 0;for(let e=0;e<n-1;e++){I[0]=e+1;let t=l._cloneInto(u);e&&t.update(d),t.update(r).update(I).digestInto(d),c._cloneInto(u).update(d).digestInto(d),s.set(d,o*e)}if(I[0]=n,n>1&&l.update(d),l.update(r).update(I).digestInto(d),c.update(d).digestInto(d),s.set(d,o*(n-1)),l.destroy(),c.destroy(),u?.destroy(),d!==s&&(0,b.f)(d),(0,b.f)(I),i===s.length)return s;let f=s.slice(0,i);return(0,b.f)(s),f}(e,o.digest(),i,a,o)};e.s(["f",0,_],69381);let v=BigInt(0xffffffff),O=BigInt(32);class R{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=(0,b.y)(this.buffer)}update(e){(0,b.s)(this),(0,b.B)(e);let{view:t,buffer:r,blockLen:i}=this,a=e.length,o=!1;for(let n=0;n<a;){let s=Math.min(i-this.pos,a-n);if(s===i){let t=(0,b.y)(e);for(;i<=a-n;n+=i)this.process(t,n);o=!0;continue}r.set(0===n&&s===a?e:e.subarray(n,n+s),this.pos),this.pos+=s,n+=s,this.pos===i&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){var t,r,i,a;let o,n;(0,b.s)(this),(0,b.W)(e,this),this.finished=!0;let{buffer:s,view:l,blockLen:c,isLE:d}=this,{pos:u}=this;s[u++]=128,s.fill(0,u),this.padOffset>c-u&&(this.process(l,0),s.fill(0)),t=l,r=c-8,i=8*this.length,a=d,o=i/0x100000000|0,n=i>>>0,t.setUint32(r,a?n:o,a),t.setUint32(r+4,a?o:n,a),this.process(l,0),this.roundClean();let f=e===s?l:(0,b.y)(e),p=this.outputLen,m=p/4,h=this.get();if(p%4||m>h.length)throw Error("invalid outputLen");for(let e=0;e<m;e++)f.setUint32(4*e,h[e],d)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}}let k=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),x=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),S=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),U=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),N=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]),D=new Uint32Array(64);class L extends R{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=0|t[0],this.B=0|t[1],this.C=0|t[2],this.D=0|t[3],this.E=0|t[4],this.F=0|t[5],this.G=0|t[6],this.H=0|t[7]}get(){let{A:e,B:t,C:r,D:i,E:a,F:o,G:n,H:s}=this;return[e,t,r,i,a,o,n,s]}set(e,t,r,i,a,o,n,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|i,this.E=0|a,this.F=0|o,this.G=0|n,this.H=0|s}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let r=0;r<16;r++,t+=4)D[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=D[e-15],r=D[e-2],i=(0,b.M)(t,7)^(0,b.M)(t,18)^t>>>3,a=(0,b.M)(r,17)^(0,b.M)(r,19)^r>>>10;D[e]=a+D[e-7]+i+D[e-16]|0}let{A:r,B:i,C:a,D:o,E:n,F:s,G:l,H:c}=this;for(let e=0;e<64;e++){var d,u,f,p;let t=c+((0,b.M)(n,6)^(0,b.M)(n,11)^(0,b.M)(n,25))+((d=n)&s^~d&l)+N[e]+D[e]|0,m=((0,b.M)(r,2)^(0,b.M)(r,13)^(0,b.M)(r,22))+((u=r)&(f=i)^u&(p=a)^f&p)|0;c=l,l=s,s=n,n=o+t|0,o=a,a=i,i=r,r=t+m|0}r=r+this.A|0,i=i+this.B|0,a=a+this.C|0,o=o+this.D|0,n=n+this.E|0,s=s+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,i,a,o,n,s,l,c)}roundClean(){(0,b.f)(D)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),(0,b.f)(this.buffer)}}class C extends L{constructor(){super(32,k)}}let z=function(e,t=!1){let r=e.length,i=new Uint32Array(r),a=new Uint32Array(r);for(let o=0;o<r;o++){let{h:r,l:n}=function(e,t=!1){return t?{h:Number(e&v),l:Number(e>>O&v)}:{h:0|Number(e>>O&v),l:0|Number(e&v)}}(e[o],t);[i[o],a[o]]=[r,n]}return[i,a]}(["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))),j=z[0],P=z[1],B=new Uint32Array(80),M=new Uint32Array(80),$=(0,b.O)(()=>new C,(0,b.Y)(1));e.s(["f",0,$],1083);let q=new TextEncoder,H=new TextDecoder,F=new TextDecoder("utf-8",{fatal:!0});function V(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let i of e)t.set(i,r),r+=i.length;return t}function W(e,t,r){if(t<0||t>=0x100000000)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function K(e){let t=Math.floor(e/0x100000000),r=new Uint8Array(8);return W(r,t,0),W(r,e%0x100000000,4),r}function G(e){let t=new Uint8Array(4);return W(t,e),t}let J=/[^\x00-\x7f]/;function Q(e){if("string"==typeof e&&e.length>=128){if(J.test(e))throw TypeError("non-ASCII string encountered in encode()");return q.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=i}return t}function Y(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=[];for(let t=0;t<e.length;t+=32768)r.push(String.fromCharCode.apply(null,e.subarray(t,t+32768)));let i=btoa(r.join(""));return t?i.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):i}function Z(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}async function X(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}function ee(e){try{return Z("string"==typeof e?e:H.decode(e),!0)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function et(e){return Y("string"==typeof e?q.encode(e):e,!0)}e.s(["w",0,V,"F",0,Z,"P",0,H,"X",0,X,"q",0,Q,"Y",0,Y,"h",0,q,"L",0,F,"T",0,G,"U",0,K],32802),e.s(["decode",0,ee,"encode",0,et],63370);class er 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 ei extends er{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.claim=r,this.reason=i,this.payload=t}}class ea extends er{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.claim=r,this.reason=i,this.payload=t}}class eo extends er{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class en extends er{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class es extends er{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class el extends er{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class ec extends er{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class ed extends er{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class eu extends er{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class ef extends er{[Symbol.asyncIterator]=async function*(){};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 ep extends er{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function em(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function eh(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function eg(...e){let t=new Set;for(let r of e)if(r)for(let e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}function ey(e,t){if(void 0!==e)throw TypeError(`${t} can only be called once`)}function ew(e,t,r){try{return ee(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}function eb(e,t,r){try{return Q(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}function eE(e,t,r){let i;try{i=JSON.parse(F.decode(ee(e)))}catch(e){throw new t(r,{cause:e})}if(!eh(i))throw new t(r);return i}e.s(["JOSEAlgNotAllowed",0,eo,"JOSEError",0,er,"JOSENotSupported",0,en,"JWEDecryptionFailed",0,es,"JWEInvalid",0,el,"JWKInvalid",0,eu,"JWKSInvalid",0,class extends er{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},"JWKSMultipleMatchingKeys",0,ef,"JWKSNoMatchingKey",0,class extends er{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)}},"JWKSTimeout",0,class extends er{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},"JWSInvalid",0,ec,"JWSSignatureVerificationFailed",0,ep,"JWTClaimValidationFailed",0,ei,"JWTExpired",0,ea,"JWTInvalid",0,ed],65466);let eA={__proto__:null,b64:!0},eI={__proto__:null};function eT(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`);return void 0===t?void 0:new Set(t)}function e_(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function ev(e,t,r,i,a){if(void 0!==a.crit&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return[];if(!Array.isArray(i.crit)||0===i.crit.length||i.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');let o=void 0===r?t:{__proto__:null,...r,...t};for(let t of i.crit){if(!(t in o))throw new en(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(a,t)||void 0===a[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o[t]&&(!Object.hasOwn(i,t)||void 0===i[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return i.crit}function eO(e,t){if(t.includes("b64")){let t=e.b64;if("boolean"!=typeof t)throw new ec('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}function eR(e,t){let r,i;try{r=JSON.stringify(t),i=JSON.parse(r)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!eh(i))throw new e("JOSE Header is not a JSON object");return[i,r]}async function ek(e,r,i){let a,o,{alg:n,secret:s}=e,l="decrypt"===i||"sign"===i;if(s&&r instanceof Uint8Array)return r;if(eh(r)){if("string"!=typeof(a=eq(r)).kty)throw ez(n,r,s);if(!(s?"oct"===a.kty&&"string"==typeof a.k:"oct"!==a.kty&&(l?"AKP"===a.kty&&"string"==typeof a.priv||"string"==typeof a.d:void 0===a.d&&void 0===a.priv)))throw TypeError(s?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${l?"private":"public"} JWK`);if(((e,t,r)=>{let{alg:i}=e;if(void 0!==t.use){let e="sign"===r||"verify"===r?"sig":"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!==i)throw TypeError(`Invalid key for this operation, its "alg" must be "${i}" when present`);if(Array.isArray(t.key_ops)){let i="encrypt"===r||"decrypt"===r?e.ops?.[+("encrypt"!==r)]:r;if(i&&!t.key_ops.includes(i))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}})(e,a,i),"oct"===a.kty)return ee(a.k);if(!Object.isFrozen(r)){let{key_ops:e}=r;Array.isArray(e)&&Object.freeze(e),Object.freeze(r)}}else{if(!eD(r))throw ez(n,r,s);let e=s?"secret":l?"private":"public";if(r.type!==e&&(s||["secret","public","private"].includes(r.type)))throw TypeError(`${r[Symbol.toStringTag]} instances must be of type "${e}" for the ${n} algorithm`);if(eU(r))return r;if("secret"===(o=r).type)return o.export()}let c=(t||=new WeakMap).get(r);if(c?.[n])return c[n];if(c||t.set(r,c={}),o&&"function"==typeof o.toCryptoKey){let t="public"===o.type,r=ex[o.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:r,asymmetricKeyType:o.asymmetricKeyType})??e.subtle;return c[n]=o.toCryptoKey(i,t,e.usages[+!t])}return(a??=o.export({format:"jwk"})).alg=n,c[n]=await eF(e,a)}e.s(["F",0,eI,"U",0,eA,"x",0,ey,"_",0,em,"n",0,ew,"E",0,eb,"J",0,eg,"q",0,function(e){return eh(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(eh)},"C",0,eh,"H",0,eE,"M",0,eR,"L",0,eT,"e",0,eO,"l",0,ev,"h",0,e_],83817);let ex={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function eS(e){if(!eU(e))throw Error("CryptoKey instance expected")}let eU=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},eN=e=>e?.[Symbol.toStringTag]==="KeyObject",eD=e=>eU(e)||eN(e);function eL(e,t,...r){if(r.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 eC=(e,...t)=>eL("Key must be ",e,...t);function ez(e,t,r){let i=["CryptoKey","KeyObject","JSON Web Key"];return r&&i.push("Uint8Array"),TypeError(eL(`Key for the ${e} algorithm must be `,t,...i))}let ej=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function eP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function eB(e,t){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function eM(e,t,r){let i=e.algorithm;if(i.name!==t.name)throw ej(t.name);if(t.hash&&i.hash?.name!==t.hash)throw ej(t.hash,"algorithm.hash");if(t.namedCurve&&i.namedCurve!==t.namedCurve)throw ej(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&i.length!==t.length)throw ej(t.length,"algorithm.length");eP(e,r)}function e$(e){return{__proto__:null,...e}}function eq(e){let t=e$(e);if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){let e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}function eH(e){if(void 0!==e&&"boolean"!=typeof e)throw TypeError('"extractable" option must be a boolean');return e}async function eF(e,t,r){if(!e.kty.includes(t.kty))throw new en('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let i=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,a=!!(t.d||t.priv),o={...t,ext:r??t.ext};return"AKP"!==o.kty&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,i,o.ext??!a,t.key_ops??e.usages[+!!a])}async function eV(e,t,r,i=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,i,[r])),eM(e,t,r),e}e.s(["w",0,eS,"U",0,eM,"y",0,eB,"V",0,eP,"W",0,eC,"L",0,eU,"e",0,eD,"o",0,eN,"f",0,eF,"P",0,eq,"X",0,ek,"c",0,eV,"C",0,e$,"T",0,eH],92449);let eW=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function eK(e,t){let r=e.byteLength<<3;if(r!==t)throw new el(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function eG(e,t){if(t.length<<3!==e.ivBits)throw new el("Invalid Initialization Vector length")}async function eJ(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(eC(t,"Uint8Array"));let i=e.cekBits>>1;return[await crypto.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,[r]),await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),i]}async function eQ(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function eY(e,t,r,i,a){let[o,n,s]=await eJ(e,r,"encrypt"),l=new Uint8Array(await crypto.subtle.encrypt({iv:i,name:"AES-CBC"},o,t)),c=K(8*a.length),d=V(a,i,l,c);return{ciphertext:l,tag:await eQ(n,d,s),iv:i}}async function eZ(e,t){let r={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.generateKey(r,!1,["sign","verify"]),a=await crypto.subtle.sign(r,i,e);return crypto.subtle.verify(r,i,a,t)}async function eX(e,t,r,i,a,o){let[n,s,l]=await eJ(e,t,"decrypt"),c=K(8*o.length),d=V(o,i,r,c),u=await eQ(s,d,l);try{if(await eZ(a,u))return new Uint8Array(await crypto.subtle.decrypt({iv:i,name:"AES-CBC"},n,r))}catch{}throw new es}async function e0(e,t,r,i,a){if(!eU(r)&&!(r instanceof Uint8Array))throw TypeError(eC(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(i?eG(e,i):i=crypto.getRandomValues(new Uint8Array(e.ivBits>>3)),r instanceof Uint8Array&&eK(r,e.cekBits),e.cbc)return eY(e,t,r,i,a);let o=await eV(r,e.subtle,"encrypt"),n=new Uint8Array(await crypto.subtle.encrypt({additionalData:a,iv:i,name:"AES-GCM",tagLength:128},o,t));return{ciphertext:n.subarray(0,-16),tag:n.subarray(-16),iv:i}}async function e1(e,t,r,i,a,o){if(!eU(t)&&!(t instanceof Uint8Array))throw TypeError(eC(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!i)throw new el("JWE Initialization Vector missing");if(!a)throw new el("JWE Authentication Tag missing");if(!e.cbc&&16!==a.length)throw new el("Invalid Authentication Tag length");if(eG(e,i),t instanceof Uint8Array&&eK(t,e.cekBits),e.cbc)return eX(e,t,r,i,a,o);let n=await eV(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:i,name:"AES-GCM",tagLength:128},n,V(r,a)))}catch{throw new es}}function e2(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}let e5=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],e6=[[],["deriveBits"]],e8=[[],[]];function e4(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:e5,ops:["wrapKey","unwrapKey"]}}function e3(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new en('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:e6,ops:[void 0,"deriveBits"]}}function e9(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:e8,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function e7(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:e8,ops:["deriveBits","deriveBits"]}}let te=e2({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:e8,ops:["encrypt","decrypt"]},"RSA-OAEP":e4(1),"RSA-OAEP-256":e4(256),"RSA-OAEP-384":e4(384),"RSA-OAEP-512":e4(512),"ECDH-ES":e3("direct-key-agreement"),"ECDH-ES+A128KW":e3("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":e3("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":e3("key-agreement-with-key-wrapping"),A128KW:e9(128),A192KW:e9(192),A256KW:e9(256),A128GCMKW:e9(128,!0),A192GCMKW:e9(192,!0),A256GCMKW:e9(256,!0),"PBES2-HS256+A128KW":e7(),"PBES2-HS384+A192KW":e7(),"PBES2-HS512+A256KW":e7()}),tt=["encrypt","decrypt"];function tr(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:e8,ops:tt,cekBits:e,ivBits:t?128:96,cbc:t}}let ti=e2({A128GCM:tr(128),A192GCM:tr(192),A256GCM:tr(256),"A128CBC-HS256":tr(256,!0),"A192CBC-HS384":tr(384,!0),"A256CBC-HS512":tr(512,!0)});function ta(e,t){throw new en(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function to(e){return("string"==typeof e?te[e]:void 0)??ta("alg","Algorithm")}function tn(e){return"key-wrapping"===e.mode||"key-encryption"===e.mode||"key-agreement-with-key-wrapping"===e.mode}function ts(e){return("string"==typeof e?ti[e]:void 0)??ta("enc","Encryption Algorithm")}function tl(e,t){if("ECDH"!==e.algorithm.name&&"X25519"!==e.algorithm.name)throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");eP(e,t)}async function tc(e,t,r){let i=await eV(t,to(e).subtle,"wrapKey",!0),a=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",a,i,"AES-KW"))}async function td(e,t,r){let i=await eV(t,to(e).subtle,"unwrapKey",!0),a=await crypto.subtle.unwrapKey("raw",r,i,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",a))}function tu(e,t,r){eM(t,to(e).subtle,r),eB(e,t)}async function tf(e,t,r,i){if(!(e instanceof Uint8Array)||e.length<8)throw new el("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||1!==Math.sign(r))throw new el("PBES2 Count Input must be a positive integer");let a=V(Q(t),Uint8Array.of(0),e),o=parseInt(t.slice(13,16),10),n={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:a},s=await eV(i,to(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(n,s,o))}function tp(e){return V(G(e.length),e)}async function tm(e,t,r){let i=t>>3,a=Math.ceil(i/32),o=new Uint8Array(32*a);for(let t=1;t<=a;t++){let i=await X("sha256",V(G(t),e,r));o.set(i,(t-1)*32)}return o.slice(0,i)}async function th(e,t,r,i,a=new Uint8Array,o=new Uint8Array){tl(e),tl(t,"deriveBits");let n=V(tp(Q(r)),tp(a),tp(o),G(i));return tm(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,"X25519"===e.algorithm.name?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),i,n)}function tg(e){eS(e);let t=e.algorithm.namedCurve;if("P-256"!==t&&"P-384"!==t&&"P-521"!==t&&"X25519"!==e.algorithm.name)throw new en("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ty(e,t){let r=e[t];if(void 0!==r){if("string"!=typeof r)throw new el(`JOSE Header "${t}" (Agreement Party${"apu"===t?"U":"V"}Info) invalid`);return ew(r,t,el)}}function tw(e,t){if(void 0!==e&&void 0!==t&&e.byteLength===t.byteLength){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new el('JOSE Header "apu" and "apv" values must be distinct')}}function tb(e){if(void 0!==e)throw new el("Encountered unexpected JWE Encrypted Key")}async function tE(e,t,r,i,a,o){let{alg:n}=e,s=e.mode;if("direct-encryption"===s)return tb(i),r;let l="direct-key-agreement"===s;switch(l?tb(i):function(e){if(void 0===e)throw new el("JWE Encrypted Key missing")}(i),e.subtle.name){case"ECDH":{let{epk:i}=a;if(!eh(i)||["d","k","p","q","dp","dq","qi","oth","priv"].some(e=>Object.hasOwn(i,e)))throw new el('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');tg(r);let o=await eF(e,i),s=ty(a,"apu"),c=ty(a,"apv");tw(s,c);let d=await th(o,r,l?t.alg:n,l?t.cekBits:parseInt(n.slice(-5,-2),10),s,c);if(l)return d;r=d;break}case"RSA-OAEP":return eS(r),tu(n,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,i));case"PBKDF2":{if("number"!=typeof a.p2c)throw new el('JOSE Header "p2c" (PBES2 Count) missing or invalid');if(a.p2c>(o??1e4))throw new el('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof a.p2s)throw new el('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let e=ew(a.p2s,"p2s",el);r=await tf(e,n,a.p2c,r);break}case"AES-GCM":{if("string"!=typeof a.iv)throw new el('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof a.tag)throw new el('JOSE Header "tag" (Authentication Tag) missing or invalid');let e=ew(a.iv,"iv",el),t=ew(a.tag,"tag",el);if(12!==e.byteLength)throw new el("Invalid Initialization Vector length");if(16!==t.byteLength)throw new el("Invalid Authentication Tag length");return e1(ts(n.slice(0,-2)),r,i,e,t,new Uint8Array)}}return td(n.slice(-6),r,i)}async function tA(e,t,r,i,a,o={}){let n,s,{alg:l,mode:c}=e,d=tn(e);if(void 0!==a&&!d)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);let u=await ek("direct-encryption"===c?t:e,r,"encrypt");if("direct-encryption"===c)return[u,void 0,void 0];let f=d?a??eW(t):void 0;switch(f&&eK(f,t.cekBits),e.subtle.name){case"ECDH":{let r;tg(u);let{apu:a,apv:n}=o;void 0!==a&&em(a,'"apu"'),void 0!==n&&em(n,'"apv"');let d=a??ty(i,"apu"),f=n??ty(i,"apv");tw(d,f),r=void 0!==o.epk?await ek(e,o.epk,"decrypt"):(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let p=crypto.subtle,m=r;if(!m.extractable){if("function"!=typeof p.getPublicKey)throw TypeError('CryptoKey for "epk" must be extractable');m=await p.getPublicKey(r,[])}let{x:h,y:g,crv:y,kty:w}=await p.exportKey("jwk",m),b="direct-key-agreement"===c,E=await th(u,r,b?t.alg:l,b?t.cekBits:parseInt(l.slice(-5,-2),10),d,f),A={x:h,crv:y,kty:w};if("EC"===w&&(A.y=g),s={epk:A},void 0!==a&&(s.apu=et(a)),void 0!==n&&(s.apv=et(n)),b)return[E,void 0,s];u=E;break}case"RSA-OAEP":eS(u),tu(l,u,"encrypt"),n=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,f));break;case"PBKDF2":{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=o;u=await tf(t,l,e,u),s={p2c:e,p2s:et(t)};break}case"AES-GCM":{let e=void 0===o.iv?crypto.getRandomValues(new Uint8Array(12)):o.iv;if(!(e instanceof Uint8Array))throw TypeError('"iv" must be an instance of Uint8Array');let t=await e0(ts(l.slice(0,-2)),f,u,e,new Uint8Array);n=t.ciphertext,s={iv:et(t.iv),tag:et(t.tag)}}}if(!((n??=await tc(l.slice(-6),u,f))instanceof Uint8Array)||!n.byteLength)throw TypeError("JWE key management algorithm did not produce an Encrypted Key");return[f,n,s]}function tI(e,t){if(void 0!==e.zip&&"DEF"!==e.zip)throw new en('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==e.zip&&!t?.zip)throw new el('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function tT(e){if(typeof globalThis[e]>"u")throw new en(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function t_(e,t,r=1/0){let i=e.writable.getWriter();i.write(t).catch(()=>{}),i.close().catch(()=>{});let a=[],o=0,n=e.readable.getReader();for(;;){let{value:e,done:t}=await n.read();if(t)break;if(a.push(e),o+=e.byteLength,1/0!==r&&o>r)throw await n.cancel().catch(()=>{}),new el("Decompressed plaintext exceeded the configured limit")}return V(...a)}async function tv(e){return tT("CompressionStream"),t_(new CompressionStream("deflate-raw"),e)}async function tO(e,t){return tT("DecompressionStream"),t_(new DecompressionStream("deflate-raw"),e,t)}function tR(e,t,r){if(!eg(e,t,r))throw new el("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}async function tk(e,t,r){let i,a,o,n,s,l,[c,d,u]=t,[f,p,m,h,g,y,w,b,,E]=e,A=p,I=m,T=u??to(c.alg);"integrated-encryption"===T.mode?o=await ek(T,r,"encrypt"):[o,i,a]=await tA(T,d,r,c,y,b),a&&(E?I=I?{...I,...a}:a:A=A?{...A,...a}:a,tR(A,I,h));let _=A?et(JSON.stringify(A)):"",v=g?.byteLength?et(g):void 0,O=Q(v?`${_}.${v}`:_),R=f;"DEF"===c.zip&&(R=await tv(R).catch(e=>{throw new el("Failed to compress plaintext",{cause:e})})),"integrated-encryption"===T.mode?[i,n]=await T.encrypt(o,R,O,A,c,b):{ciphertext:n,tag:s,iv:l}=await e0(d,R,o,w,O);let k={ciphertext:et(n)};return l&&(k.iv=et(l)),s&&(k.tag=et(s)),i?.byteLength&&(k.encrypted_key=et(i)),v&&(k.aad=v),A&&(k.protected=_),h&&(k.unprotected=h),I&&(k.header=I),k}async function tx(e,t,r){return tk(e,function(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new el("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");void 0!==t&&(e[8]=t?.crit);let[,i,a,o,n,s,l,c,d]=e;if(void 0!==n&&em(n,"JWE Additional Authenticated Data"),void 0!==s&&em(s,"JWE Content Encryption Key"),void 0!==l&&em(l,"JWE Initialization Vector"),r||void 0===i||(i=eR(el,i)[0],e[1]=i),void 0!==a&&(a=eR(el,a)[0],e[2]=a),r||void 0===o||(o=eR(el,o)[0],e[3]=o),void 0!==c&&!eh(c))throw TypeError("JWE Key Management Parameters must be an object");tR(i,a,o);let u={...i,...a,...o};e_(el,i),ev(el,eI,d,i,u),tI(u,i);let{alg:f,enc:p}=u;if("string"!=typeof f||!f)throw new el('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=te[f];if(m?.mode==="integrated-encryption"){if(void 0!==p)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(void 0!==s)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(void 0!==l)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[u,void 0,m]}if("string"!=typeof p||!p)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[u,ts(p),m]}(e,r),t)}let tS=e=>Math.floor(e.getTime()/1e3),tU={s:1,m:60,h:3600,d:86400,w:604800,y:0x1e187e0},tN=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,tD="check_failed";function tL(){throw TypeError("Invalid time period format")}function tC(e){"string"!=typeof e&&tL();let t=tN.exec(e);(!t||t[4]&&t[1])&&tL();let r=Math.round(parseFloat(t[2])*tU[t[3][0].toLowerCase()]);return Number.isFinite(r)||tL(),"-"===t[1]||"ago"===t[4]?-r:r}function tz(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function tj(e,t){if("string"!=typeof t)throw TypeError(`"${e}" claim must be a string`)}function tP(e,t){return"number"==typeof e?tz(t,e):e instanceof Date?tz(t,tS(e)):tS(new Date)+tC(e)}let tB=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function tM(e,t,r=!1){let i=e[t];if(!(void 0===i&&!r)){if("number"!=typeof i)throw new ei(`"${t}" claim must be a number`,e,t,"invalid");return i}}function t$(e,t){throw new ei(`unexpected "${t}" claim value`,e,t,tD)}function tq(e,t,r={}){let i,a,o;try{i=JSON.parse(F.decode(t))}catch(e){throw new ed("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!eh(i))throw new ed("JWT Claims Set must be a top-level JSON object");let{typ:n}=r;if(void 0!==n&&("string"!=typeof e.typ||tB(e.typ)!==tB(n)))throw new ei('unexpected "typ" JWT header value',i,"typ",tD);let{requiredClaims:s=[],issuer:l,subject:c,audience:d,maxTokenAge:u}=r,f=[...s];for(let e of(void 0!==u&&f.push("iat"),void 0!==d&&f.push("aud"),void 0!==c&&f.push("sub"),void 0!==l&&f.push("iss"),new Set(f.reverse())))if(!Object.hasOwn(i,e))throw new ei(`missing required "${e}" claim`,i,e,"missing");void 0===l||(Array.isArray(l)?l:[l]).includes(i.iss)||t$(i,"iss"),void 0!==c&&i.sub!==c&&t$(i,"sub"),void 0===d||(a=i.aud,o="string"==typeof d?[d]:d,"string"==typeof a?o.includes(a):!!Array.isArray(a)&&o.some(e=>a.includes(e)))||t$(i,"aud");let{clockTolerance:p}=r,m=0;if("string"==typeof p)m=tC(p);else if(void 0!==p){if("number"!=typeof p)throw TypeError("Invalid clockTolerance option type");m=p}if(tz("clockTolerance option",m),m<0)throw TypeError("Invalid clockTolerance option input");let{currentDate:h}=r,g=tz("currentDate option",tS(void 0===h?new Date:h)),y=tM(i,"iat",void 0!==u),w=tM(i,"nbf");if(void 0!==w&&w>g+m)throw new ei('"nbf" claim timestamp check failed',i,"nbf",tD);let b=tM(i,"exp");if(void 0!==b&&b<=g-m)throw new ea('"exp" claim timestamp check failed',i,"exp",tD);if(void 0!==u){let e=g-y,t=tz("maxTokenAge option","number"==typeof u?u:tC(u));if(t<0)throw TypeError("Invalid maxTokenAge option input");if(e-m>t)throw new ea('"iat" claim timestamp check failed (too far in the past)',i,"iat",tD);if(e<-m)throw new ei('"iat" claim timestamp check failed (it should be in the past)',i,"iat",tD)}return i}function tH(e){return r.get(e)}function tF(e){let t=tH(e);for(let e of["iat","nbf","exp"]){let r=t[e];if("number"==typeof r&&!Number.isFinite(r))throw TypeError(`"${e}" claim must be a finite number`)}return q.encode(JSON.stringify(t))}function tV(e,t){return tH(e)[t]}class tW{constructor(e={}){if(!eh(e))throw TypeError("JWT Claims Set MUST be an object");(r||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return tj("iss",e),tH(this).iss=e,this}setSubject(e){return tj("sub",e),tH(this).sub=e,this}setAudience(e){return function(e){if("string"!=typeof e&&(!Array.isArray(e)||Array.from(e).some(e=>"string"!=typeof e)))throw TypeError('"aud" claim must be a string or an array of strings')}(e),tH(this).aud=e,this}setJti(e){return tj("jti",e),tH(this).jti=e,this}setNotBefore(e){return tH(this).nbf=tP(e,"setNotBefore"),this}setExpirationTime(e){return tH(this).exp=tP(e,"setExpirationTime"),this}setIssuedAt(e){let t=tH(this);return void 0===e?t.iat=tS(new Date):"string"==typeof e?t.iat=tz("setIssuedAt",tS(new Date)+tC(e)):t.iat=tP(e,"setIssuedAt"),this}}e.s(["C",0,tW,"o",0,tV,"w",0,tF,"L",0,tq],24472);let tK=tW;class tG extends tK{#e=[void 0];#t;#r;#i;setProtectedHeader(e){return ey(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return ey(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}setContentEncryptionKey(e){return ey(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return ey(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#r=!0,this}replicateAudienceAsHeader(){return this.#i=!0,this}async encrypt(e,t){var r;let i=tF(this);this.#e[1]&&(this.#t||this.#r||this.#i)&&(this.#e[1]={...this.#e[1],iss:this.#t?tV(this,"iss"):void 0,sub:this.#r?tV(this,"sub"):void 0,aud:this.#i?tV(this,"aud"):void 0});let a=[...this.#e];return a[0]=i,[(r=await tx(a,e,t)).protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}let tJ=[["verify"],["sign"]];function tQ(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:tJ}}function tY(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:tJ,minRsaBits:2048}}function tZ(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:tJ}}function tX(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:tJ}}function t0(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:tJ}}let t1=e2({HS256:tQ(256),HS384:tQ(384),HS512:tQ(512),RS256:tY(256),RS384:tY(384),RS512:tY(512),PS256:tY(256,32),PS384:tY(384,48),PS512:tY(512,64),ES256:tZ("P-256",256),ES384:tZ("P-384",384),ES512:tZ("P-521",512),EdDSA:tX(),Ed25519:tX(),"ML-DSA-44":t0(44),"ML-DSA-65":t0(65),"ML-DSA-87":t0(87)});function t2(e){let t="string"==typeof e?t1[e]:void 0;if(!t)throw new en(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}async function t5(e,t,r){let[i,a,o,n]=e,s="";if(void 0!==a){let e=eR(ec,a);a=e[0],s=et(e[1])}if(void 0!==o&&(o=eR(ec,o)[0]),!a&&!o)throw new ec("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eg(a,o))throw new ec("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...a,...o};e_(ec,a);let c=eO(a,ev(ec,eA,n,a,l));c||r?.();let{alg:d}=l;if("string"!=typeof d||!d)throw new ec('JWS "alg" (Algorithm) Header Parameter missing or invalid');let u=t2(d),f="",p=i,m;if(c){let t=e[4];t?(f=t[0]??=et(i),p=t[1]??=Q(f)):(f=et(i),m=q.encode(`${s}.${f}`))}m??=V(Q(s),Q("."),p);let h=await eV(await ek(u,t,"sign"),u.subtle,"sign");u.minRsaBits&&eB(u.alg,h);let g={signature:et(new Uint8Array(await crypto.subtle.sign(u.signing,h,m))),payload:f};return a&&(g.protected=s),o&&(g.header=o),[g,c]}async function t6(e,t,r,i,a){let[o]=await t5([e,t,void 0,r],i,a);return`${o.protected}.${o.payload}.${o.signature}`}e.s(["K",0,t1,"l",0,t2],16760);let t8=tW;class t4 extends t8{#a;setProtectedHeader(e){return ey(this.#a,"setProtectedHeader"),this.#a=e,this}async sign(e,t){return t6(tF(this),this.#a,t?.crit,e,()=>{throw new ed("JWTs MUST NOT use unencoded payload")})}}e.s(["f",0,t4],27957);var t3=e.i(63370);e.s(["f",0,t3],1889);var t3=t3;let t9='"alg" (Algorithm)';function t7(e='JWK "alg" (Algorithm) Parameter'){throw new en(`Invalid or unsupported ${e} value`)}function re(e,t){return("string"==typeof e?t1[e]??te[e]:void 0)??t7(t)}let rt=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},rr=e=>{let t=e.data[e.pos++];if(void 0===t)throw Error("Unexpected end of ASN.1 input");return t},ri=e=>{let t=rr(e);if(128&t){let r=127&t,i=0;for(let t=0;t<r;t++)i=i<<8|rr(e);return i}return t},ra=(e,t,r)=>{if(rr(e)!==t)throw Error(r)},ro=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},rn=async(e,t,r,i)=>{let a,o=eH(i?.extractable),n=re(r,t9);n.secret&&t7(t9);let s="spki"===e;if(n.resolve)try{let r={data:t,pos:0};(function(e,t){if(ra(e,48,`Invalid ${"spki"===t?"SPKI":"PKCS#8"} structure`),ri(e),"pkcs8"===t){ra(e,2,"Expected version field");let t=ri(e);e.pos+=t}ra(e,48,"Expected algorithm identifier"),ri(e)})(r,e),a=n.resolve({crv:(e=>{let t,r=(ra(e,6,"Expected algorithm OID"),t=ri(e),ro(e,t));if(rt(r,[43,101,110]))return"X25519";if(!rt(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");ra(e,6,"Expected curve OID");let i=ri(e),a=ro(e,i);if(rt(a,[42,134,72,206,61,3,1,7]))return"P-256";if(rt(a,[43,129,4,0,34]))return"P-384";if(rt(a,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")})(r)})}catch(e){throw new en("Invalid or unsupported key format",{cause:e})}else a=n.subtle;return crypto.subtle.importKey(e,t,a,o??s,n.usages[+!s])};async function rs(e){if(eN(e))if("secret"!==e.type)return e.export({format:"jwk"});else e=e.export();if(e instanceof Uint8Array)return{kty:"oct",k:et(e)};if(!eU(e))throw TypeError(eC(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);for(let e of(delete t.ext,delete t.key_ops,delete t.use,"AKP"!==t.kty&&delete t.alg,Object.keys(t)))void 0===t[e]&&delete t[e];return t}let rl=(e,t)=>{if("string"!=typeof e||!e)throw new eu(`${t} missing or invalid`)};async function rc(e,t){let r,i;if(eh(e)){if("string"!=typeof(r=e$(e)).kty)throw TypeError(eC(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(eD(e))r=e$(await rs(e));else throw TypeError(eC(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":rl(r.alg,'"alg" (Algorithm) Parameter'),rl(r.pub,'"pub" (Public key) Parameter'),i={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":rl(r.crv,'"crv" (Curve) Parameter'),rl(r.x,'"x" (X Coordinate) Parameter'),rl(r.y,'"y" (Y Coordinate) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":rl(r.crv,'"crv" (Subtype of Key Pair) Parameter'),rl(r.x,'"x" (Public Key) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":rl(r.e,'"e" (Exponent) Parameter'),rl(r.n,'"n" (Modulus) Parameter'),i={e:r.e,kty:r.kty,n:r.n};break;case"oct":if("string"!=typeof r.k)throw new eu('"k" (Key Value) Parameter missing or invalid');i={k:r.k,kty:r.kty};break;default:throw new en('"kty" (Key Type) Parameter missing or unsupported')}let a=Q(JSON.stringify(i));return et(await X(t,a))}function rd(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");let r="Invalid Token or Protected Header formatting";if("string"!=typeof t||!t)throw TypeError(r);return eE(t,TypeError,r)}async function ru(e,t,r,i=function(e){let t,{protected:r,ciphertext:i,iv:a,tag:o,aad:n}=e;return void 0!==r&&(t=eE(r,el,"JWE Protected Header is invalid")),[t,ew(i,"ciphertext",el),void 0!==a?ew(a,"iv",el):void 0,void 0!==o?ew(o,"tag",el):void 0,eb((r??"")+(void 0!==n?`.${n}`:""),"aad",el)]}(e)){let a,o,n,s,[l,c,d,u,f]=i,{header:p,unprotected:m,aad:h}=e;if(void 0!==p||void 0!==m){if(!eg(l,p,m))throw new el("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");a={...l,...p,...m}}else a=l??{};let[g,y,w,b,E]=t,{encrypted_key:A}=e;ev(el,eI,w,l,a),tI(a,l);let{alg:I,enc:T}=a;if("string"!=typeof I||!I)throw new el("missing JWE Algorithm (alg) in JWE Header");let _=te[I];if(""===A&&(!_||!tn(_)))throw new el("JWE Encrypted Key incorrect type");let v=_?.mode==="integrated-encryption";if(!v&&("string"!=typeof T||!T))throw new el("missing JWE Encryption Algorithm (enc) in JWE Header");if(g&&!g.has(I)||!g&&I.startsWith("PBES2"))throw new eo('"alg" (Algorithm) Header Parameter value not allowed');if(v){if(void 0!==T)throw new el('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(d?.byteLength)throw new el("JWE Initialization Vector must be empty for integrated encryption");if(u?.byteLength)throw new el("JWE Authentication Tag must be empty for integrated encryption")}else{if(y&&!y.has(T))throw new eo('"enc" (Encryption Algorithm) Header Parameter value not allowed');o=ts(T)}if(void 0!==A)try{n=ew(A,"encrypted_key",el)}catch(e){if(!_||!tn(_))throw e;n=new Uint8Array}let O=!1;"function"==typeof r&&(r=await r(l,e),O=!0);let R=_??to(I);tn(R)&&void 0===n&&(n=new Uint8Array);let k=await ek("direct-encryption"===R.mode?o:R,r,"decrypt");if("integrated-encryption"===R.mode)s=await R.decrypt(k,n,c,f,l,a);else{let e,t=o;try{e=await tE(R,t,k,n,a,b),tn(R)&&e instanceof Uint8Array&&e.byteLength<<3!==t.cekBits&&(e=eW(t))}catch(r){if(r instanceof TypeError||r instanceof el||r instanceof en)throw r;e=eW(t)}s=await e1(t,e,c,d,u,f)}if("DEF"===a.zip){let e=E??25e4;if(0===e)throw new en('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');s=await tO(s,e).catch(e=>{throw e instanceof el?e:new el("Failed to decompress plaintext",{cause:e})})}return{plaintext:s,...l&&{protectedHeader:l},...void 0!==h&&{additionalAuthenticatedData:ew(h,"aad",el)},...m&&{sharedUnprotectedHeader:m},...p&&{unprotectedHeader:p},...O&&{key:k}}}async function rf(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),"string"!=typeof e)throw new el("Compact JWE must be a string or Uint8Array");let{0:i,1:a,2:o,3:n,4:s,length:l}=e.split(".");if(5!==l)throw new el("Invalid Compact JWE");return ru({ciphertext:n,iv:o||void 0,protected:i,tag:s||void 0,encrypted_key:a||void 0},t,r)}async function rp(e,t,r){let{plaintext:i,...a}=await rf(e,function(e){let t=e&&eT("keyManagementAlgorithms",e.keyManagementAlgorithms),r=e&&eT("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),{crit:i,maxPBES2Count:a,maxDecompressedLength:o}=e??{};if(void 0!==a&&1/0!==a&&(!Number.isSafeInteger(a)||a<1))throw TypeError("maxPBES2Count must be a positive safe integer or Infinity");let n=o??25e4;if(0!==n&&1/0!==n&&(!Number.isSafeInteger(n)||n<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");return[t,r,i,a,o]}(r),t),{protectedHeader:o}=a,n=tq(o,i,r);for(let e of["iss","sub","aud"])if(void 0!==o[e]&&("aud"===e?JSON.stringify(o.aud)!==JSON.stringify(n.aud):o[e]!==n[e]))throw new ei(`replicated "${e}" claim header parameter mismatch`,n,e,"mismatch");return{payload:n,...a}}function rm(e){try{return Q(e)}catch(e){throw new ec("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}async function rh(e,t,r,i,a){let{protected:o,header:n,payload:s}=e,l=a??(void 0===o?{}:eE(o,ec,"JWS Protected Header is invalid"));if(!eg(l,n))throw new ec("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...l,...n},d=eO(l,ev(ec,eA,t[1],l,c)),{alg:u}=c;if("string"!=typeof u||!u)throw new ec('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(u))throw new eo('"alg" (Algorithm) Header Parameter value not allowed');if(d){if("string"!=typeof s)throw new ec("JWS Payload must be a string")}else if("string"!=typeof s&&!(s instanceof Uint8Array))throw new ec("JWS Payload must be a string or an Uint8Array instance");let f=d||"string"!=typeof s?s:i(s),p=!1;"function"==typeof r&&(r=await r(l,e),p=!0);let m=t2(u),h=V(void 0!==o?Q(o):new Uint8Array,Q("."),"string"==typeof f?t[2]??=eb(f,"payload",ec):f),g=ew(e.signature,"signature",ec),y=await ek(m,r,"verify"),w=await eV(y,m.subtle,"verify");m.minRsaBits&&eB(m.alg,w);let b=!1;try{b=await crypto.subtle.verify(m.signing,w,g,h)}catch(e){throw new ep(void 0,{cause:e})}if(!b)throw new ep;let E={payload:"string"==typeof f?ew(f,"payload",ec):f};return void 0!==o&&(E.protectedHeader=l),void 0!==n&&(E.unprotectedHeader=n),p?[{...E,key:y},d]:[E,d]}async function rg(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),"string"!=typeof e)throw new ec("Compact JWS must be a string or Uint8Array");let{0:i,1:a,2:o,length:n}=e.split(".");if(3!==n)throw new ec("Invalid Compact JWS");return rh({payload:a,protected:i,signature:o},t,r,rm)}async function ry(e,t,r){let[i,a]=await rg(e,[r&&eT("algorithms",r.algorithms),r?.crit],t);if(!a)throw new ed("JWTs MUST NOT use unencoded payload");let o=tq(i.protectedHeader,i.payload,r);return{...i,payload:o}}async function rw(e,t,r=3600){return await new t4(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function rb(e,t){try{return(await ry(e,new TextEncoder().encode(t))).payload}catch{return null}}e.s(["f",0,rc],12319),e.s(["f",0,rd],41242),e.s(["f",0,ry],9939);let rE=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]),rA="A256CBC-HS512";function rI(e,t){return _($,new TextEncoder().encode(e),new TextEncoder().encode(t),rE,64)}function rT(e){if("string"==typeof e)return[{version:0,value:e}];let t=[];for(let[r,i]of e.keys)t.push({version:r,value:i});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function r_(e,t,r,i=3600){let a=rI(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),o=await rc({kty:"oct",k:t3.encode(a)},"sha256");return await new tG(e).setProtectedHeader({alg:"dir",enc:rA,kid:o}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+i).setJti(crypto.randomUUID()).encrypt(a)}let rv={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[rA,"A256GCM"]};async function rO(e,t,r){if(!e)return null;let i=!1;try{i=void 0!==rd(e).kid}catch{return null}try{let i=rT(t),{payload:a}=await rp(e,async e=>{let t=e.kid;if(void 0!==t){for(let e of i){let i=rI(e.value,r);if(t===await rc({kty:"oct",k:t3.encode(i)},"sha256"))return i}throw Error("no matching decryption secret")}return i.length,rI(i[0].value,r)},rv);return a}catch{if(i)return null;let a=rT(t);if(a.length<=1)return null;for(let t=1;t<a.length;t++)try{let i=a[t],o=rI(i.value,r),{payload:n}=await rp(e,o,rv);return n}catch{continue}return null}}e.s(["X",0,rw,"y",0,rO,"h",0,r_,"u",0,rb],75742);var rR=e.i(69774),rk=e.i(10228);function rx(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}),{})}e.s(["f",0,rx],74285);let rS=new WeakMap;function rU(e,t,r){let i=`${t}:${r}`;rS.has(e)||rS.set(e,new Map);let a=rS.get(e);if(a.has(i))return a.get(i);let o="output"===r?(0,rR.R)(e)[t]?.fields??{}:{},n="user"===t||"session"===t||"account"===t?e[t]?.additionalFields:void 0,s={...o,...n??{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(s={...s,...r.schema[t].fields});return a.set(i,s),s}function rN(e,t){return rx(t,rU(e,"user","output"))}function rD(e,t){return rx(t,rU(e,"session","output"))}function rL(e,t){let r=t.action||"create",i=t.fields,a=Object.create(null);for(let t in i){if(t in e){if(!1===i[t].input){if(void 0!==i[t].defaultValue&&"update"!==r){a[t]=i[t].defaultValue;continue}if(e[t])throw l.E.from("BAD_REQUEST",{...rk.f.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(i[t].validator?.input&&void 0!==e[t]){let r=i[t].validator.input["~standard"].validate(e[t]);if(r instanceof Promise)throw l.E.from("INTERNAL_SERVER_ERROR",rk.f.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in r&&r.issues)throw l.E.from("BAD_REQUEST",{...rk.f.VALIDATION_ERROR,message:r.issues[0]?.message||"Validation Error"});a[t]=r.value;continue}if(i[t].transform?.input&&void 0!==e[t]){a[t]=i[t].transform?.input(e[t]);continue}a[t]=e[t];continue}if(void 0!==i[t].defaultValue&&"create"===r){if("function"==typeof i[t].defaultValue){a[t]=i[t].defaultValue();continue}a[t]=i[t].defaultValue;continue}if(i[t].required&&"create"===r)throw l.E.from("BAD_REQUEST",{...rk.f.MISSING_FIELD,message:`${t} is required`})}return a}e.s(["g",0,function(e,t){let r=rU(e,"user","output"),i={};for(let e in r){let a=r[e];!1!==a.returned&&(e in t&&void 0!==t[e]?i[e]=t[e]:void 0!==a.defaultValue?i[e]="function"==typeof a.defaultValue?a.defaultValue():a.defaultValue:a.required||(i[e]=null))}return"id"in t&&(i.id=t.id),i},"P",0,function(e){let t=rU(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},"s",0,function(e,t){let{accessToken:r,refreshToken:i,idToken:a,accessTokenExpiresAt:o,refreshTokenExpiresAt:n,password:s,...l}=rx(t,rU(e,"account","output"));return l},"W",0,function(e,t={},r){let i=rU(e,"user","input"),a=Object.create(null);for(let e of Object.keys(t))i[e]?.input!==!1&&(a[e]=t[e]);return rL(a,{fields:i,action:r})},"z",0,function(e,t,r){return rL(t,{fields:rU(e,"session","input"),action:r})},"Q",0,rD,"R",0,function(e,t={},r){return rL(t,{fields:rU(e,"user","input"),action:r})},"$",0,rN],56023);let rC=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e));function rz(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.s(["f",0,rC],42158),e.s(["f",0,rz],76660);let rj=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;var rP=e.i(7855);let rB=rP.object({id:rP.string(),createdAt:rP.date().default(()=>new Date),updatedAt:rP.date().default(()=>new Date)});var rM=e.i(62061);e.s(["bigint",0,function(e){return rM.Br(rP.ZodBigInt,e)},"boolean",0,function(e){return rM.HN(rP.ZodBoolean,e)},"date",0,function(e){return rM.fj(rP.ZodDate,e)},"number",0,function(e){return rM.NE(rP.ZodNumber,e)},"string",0,function(e){return rM.jK(rP.ZodString,e)}],34512);var r$=e.i(34512);e.s(["f",0,r$],54257);var r$=r$;let rq=rB.extend({userId:r$.string(),expiresAt:rP.date(),token:rP.string(),ipAddress:rP.string().nullish(),userAgent:rP.string().nullish()}),rH=rB.extend({email:rP.string().transform(e=>e.toLowerCase()),emailVerified:rP.boolean().default(!1),name:rP.string(),image:rP.string().nullish()});var rF=e.i(90126),rV=e.i(30283);let rW=rP.looseObject({session:rq.loose(),user:rH.loose(),updatedAt:rP.number(),version:rP.string().optional()}),rK=rP.object({session:rP.record(rP.string(),rP.unknown()),expiresAt:rP.number(),signature:rP.string()});function rG(e){let t=(0,rV.f)(e);if(null===t)return null;let r=rW.safeParse(t);return r.success?r.data:(rF.y.warn("Cookie cache payload failed schema validation",{issues:r.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}var rJ=e.i(46754);async function rQ(e,t,r){let i;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return rn("pkcs8",(i=/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,Z(e.replace(i,""))),t,r)}async function rY(e,t,r){if(!eh(e))throw TypeError("JWK must be an object");let i=eq(e),a=eH(r?.extractable),{alg:o}=i;if(t??=o,"oct"!==i.kty&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(i.kty){case"oct":if("string"!=typeof i.k)throw TypeError('missing "k" (Key Value) Parameter value');return ee(i.k);case"AKP":if("string"!=typeof o||!o)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==o)throw TypeError("JWK alg and alg option value mismatch");return eF(re(t),i,a);case"RSA":case"EC":case"OKP":return eF(re(t),i,a);default:throw new en('Unsupported "kty" (Key Type) Parameter value')}}e.s(["g",0,rY,"r",0,rQ],97554),e.i(18069);var rZ=e.i(44336),r$=r$;function rX(e,t){let r=`${e}.`;if(!t.startsWith(r))return null;let i=t.slice(r.length),a=Number(i);return!Number.isSafeInteger(a)||a<0||String(a)!==i?null:a}let r0=e=>(t,r,i)=>{let a=function(e,t){let r={};for(let[i,a]of(0,rJ.X)(t.headers?.get("cookie")||""))(i===e||null!==rX(e,i))&&(r[i]=a);return r}(t,i),o=i.context.logger,n=()=>{let e=function(e,t){let r={};for(let i in e)r[i]={name:i,value:"",attributes:{...t,maxAge:0}};return r}(a,r);for(let e in a)delete a[e];return e};return{chunk(i,s){let l=n();for(let n of function(e,t,r,i){var a,o;let n=(a=`${t.name}.99`,o=t.attributes,4050-(0,rZ.j)(a,"",{...o}).length),s=n>0?Math.ceil(t.value.length/n):1/0;if(s<=1)return r[t.name]=t.value,[t];if(s>100)return i.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let l=[];for(let e=0;e<s;e++){let i=`${t.name}.${e}`,a=e*n,o=t.value.substring(a,a+n);l.push({...t,name:i,value:o}),r[i]=o}return i.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the 4050 byte limit and was split into ${s} chunks.`,valueSize:t.value.length,chunkCount:s,chunkSizes:l.map(e=>e.value.length)}),l}(e,{name:t,value:i,attributes:{...r,...s}},a,o))l[n.name]=n;return Object.values(l)},clean:()=>Object.values(n()),setCookies(e){for(let t of e)i.setCookie(t.name,t.value,t.attributes)}}},r1=r0("Session"),r2=r0("Account");function r5(e,t){let r=e.getCookie(t);if(r)return r;let i=[],a=e.headers?.get("cookie");if(!a)return null;for(let[e,r]of(0,rJ.X)(a)){let a=rX(t,e);null!==a&&i.push({index:a,value:r})}return i.length>0?(i.sort((e,t)=>e.index-t.index),i.map(e=>e.value).join("")):null}async function r6(e,t){let r=e.context.authCookies.accountData,i={maxAge:300,...r.attributes},a=await r_(t,e.context.secretConfig,"better-auth-account",i.maxAge),o=r2(r.name,i,e);o.setCookies(o.chunk(a,i))}async function r8(e){let t=r5(e,e.context.authCookies.accountData.name);if(t){let r=(0,rV.f)(await rO(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}let r4=rP.optional(rP.object({disableCookieCache:r$.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:r$.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));e.s(["v",0,r2,"X",0,r1,"q",0,r8,"K",0,r5,"H",0,r4,"L",0,r6],96161);var r3=e.i(30501);let r9=new Map;new TextEncoder;var r7=e.i(96101),ie=e.i(16029),it=e.i(72381);let ir=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>(0,r7.f)().importKey("raw",(0,ie.Y)(t),{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,i)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let a=await (0,r7.f)().sign("HMAC",e,(0,ie.Y)(i));return"hex"===t?it.f.encode(a):"base64"===t?r3.t.encode(a):"base64url"===t||"base64urlnopad"===t?r3.W.encode(a,{padding:"base64urlnopad"!==t}):a},verify:async(e,i,a)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(a="string"==typeof a?it.f.toBytes(a):a),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(a=await r3.t.decode(a)),(0,r7.f)().verify("HMAC",e,(0,ie.Y)(a),(0,ie.Y)(i)))};return r};function ii(e){let t="string"==typeof e.baseURL?e.baseURL:void 0,r="object"==typeof e.baseURL&&null!==e.baseURL?e.baseURL.protocol:void 0,i=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:"https"===r||"http"!==r&&(t?t.startsWith("https://"):s.C))?rJ.d:"",a=!!e.advanced?.crossSubDomainCookies?.enabled,o=a?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(a&&!o&&!m(e.baseURL))throw new l.p("baseURL is required when crossSubdomainCookies are enabled.");return function(t,r={}){let n=e.advanced?.cookiePrefix||"better-auth",s=e.advanced?.cookies?.[t]?.name||`${n}.${t}`,l=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${i}${s}`,attributes:{secure:!!i,sameSite:"lax",path:"/",httpOnly:!0,...a?{domain:o}:{},...e.advanced?.defaultCookieAttributes,...r,...l}}}}async function ia(e,t,r){let i;if(!e.context.options.session?.cookieCache?.enabled)return;let a=rx(t.session,e.context.options.session?.additionalFields),o=rN(e.context.options,t.user),n=e.context.options.session?.cookieCache?.version,s="1";if(n){if("string"==typeof n)s=n;else if("function"==typeof n){let e=n(t.session,t.user);s=rz(e)?await e:e}}let l={session:a,user:o,updatedAt:Date.now(),version:s},c={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},d=rC(c.maxAge||60,"sec").getTime(),u=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===u)i=await r_(l,e.context.secretConfig,"better-auth-session",c.maxAge||300);else if("jwt"===u){let t=e.context.sessionConfig.cookieCacheSigner;i=t?await t.sign(e,l,c.maxAge||300):await rw(l,e.context.secret,c.maxAge||300)}else i=r3.W.encode(JSON.stringify({session:l,expiresAt:d,signature:await ir("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...l,expiresAt:d}))}),{padding:!1});let f=r1(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(i,c)),e.context.options.account?.storeAccountCookie&&!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if(("function"==typeof e.getSetCookie?e.getSetCookie():(0,rJ.Z)(e.get("set-cookie")||"")).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}(e,e.context.authCookies.accountData.name)){let r=await r8(e);if(r)if(w(e.context.options)&&r.userId!==t.user.id){il(e,e.context.authCookies.accountData);let t=r2(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}else await r6(e,r)}}async function io(e,t){var r;let i,a=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===a){let r=await rO(t,e.context.secretConfig,"better-auth-session"),i=rG(r);return i?{session:i,expiresAt:r?.exp?1e3*r.exp:Date.now()}:null}if("jwt"===a){let r=e.context.sessionConfig.cookieCacheSigner;if(r){let i=await r.verify(e,t);return i?{session:i.payload,expiresAt:i.expiresAt}:null}let i=await rb(t,e.context.secret),a=rG(i);return a?{session:a,expiresAt:i?.exp?1e3*i.exp:Date.now()}:null}let o=(r=(0,rV.f)(((e,t="utf-8")=>(r9.has(t)||r9.set(t,new TextDecoder(t)),r9.get(t).decode(e)))(r3.W.decode(t))),(i=rK.safeParse(r)).success?i.data:null);if(!o||!await ir("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature))return null;let n=rG(o.session);return n?{session:n,expiresAt:o.expiresAt}:null}async function is(e,t,r,i){let a=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!a;let o=e.context.authCookies.sessionToken.attributes,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...o,maxAge:n,...i}),r?await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes):a&&il(e,e.context.authCookies.dontRememberToken),await ia(e,t,r),e.context.setNewSession(t)}function il(e,t){!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t="function"==typeof e.getSetCookie?e.getSetCookie():(0,rJ.Z)(e.get("set-cookie")||"");if(!t.length)continue;let r=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));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 ic(e,t){if(il(e,e.context.authCookies.sessionToken),il(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){il(e,e.context.authCookies.accountData);let t=r2(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),r=t.clean();t.setCookies(r)}"cookie"===e.context.oauthConfig.storeStateStrategy&&il(e,e.context.createAuthCookie("oauth_state"));let r=r1(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),i=r.clean();r.setCookies(i),t||il(e,e.context.authCookies.dontRememberToken)}e.s(["g",0,ii,"J",0,io,"Q",0,ic,"c",0,il,"e",0,function(e){let t=ii(e),r=t("session_token",{maxAge:e.session?.expiresIn||Math.round(function(){let e,t=rj.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]),i=t[3].toLowerCase();switch(i){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: "${i}"`)}return"-"===t[1]||"ago"===t[4]?-e:e}()/1e3)}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),a=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),o=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:i.name,attributes:i.attributes},dontRememberToken:{name:o.name,attributes:o.attributes},accountData:{name:a.name,attributes:a.attributes}}},"b",0,ia,"V",0,is],70728),e.s(["f",0,function(e,t){return{digest:async r=>{let i=(0,ie.Y)(r),a=await (0,r7.f)().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")?r3.W.encode(a,{padding:"base64urlnopad"!==t}):r3.t.encode(a):a}}}],82318);var id=e.i(73278),iu=e.i(14268),ip=e.i(95934);let im=async()=>{let e=(0,iu.l)(),t=e.context.adapterAsyncStorage;if(t)return t;let r=await (0,ip.f)();return e.context.adapterAsyncStorage??=new r,e.context.adapterAsyncStorage},ih=async e=>im().then(t=>t.getStore()?.adapter||e).catch(()=>e),ig=async(e,t)=>{let r=!1;return im().then(async i=>{let a,o;r=!0;let n=[],s=!1;try{a=await i.run({adapter:e,pendingHooks:n,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of n)await e();if(s)throw o;return a}).catch(e=>{if(!r)return t();throw e})},iy=async(e,t,r)=>{let i=!1;return im().then(async a=>{let o,n;if(i=!0,a.getStore()?.isTransactionActive)return t();let s=(0,id.f)(e)?.();s&&await s;let l=[],c=!1;try{o=await e.transaction(async e=>(l=[],a.run({adapter:e,pendingHooks:l,isTransactionActive:!0},t)))}catch(e){c=!0,n=e}let d=async e=>{for(let t of l)try{await t()}catch(t){if(!r?.onAfterCommitHookError){if("throw"===e)throw t;try{rF.y.error("Failed to run an after-commit hook for work that could not roll back",t)}catch{}continue}try{await r.onAfterCommitHookError(t)}catch{}}};if(c)throw e.options?.adapterConfig.transaction===!1&&await d("log"),n;return await d("throw"),o}).catch(e=>{if(!i)return t();throw e})},iw=async(e,t)=>{let r,i=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}};try{r=await im()}catch{return i()}let a=r.getStore();if(!a?.isTransactionActive)return i();a.pendingHooks.push(i)};e.s(["g",0,ih,"A",0,iw,"Q",0,ig,"n",0,iy],73436);var ib=e.i(86198),iE=e.i(80849),iA=e.i(90659);let iI=()=>(0,iA.g)("/get-session",{method:["GET","POST"],operationId:"getSession",query:r4,requireHeaders:!0,disableBody:!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=>{e.setHeader("cache-control","no-store"),e.setHeader("pragma","no-cache"),e.context.session=null;let t=e.context.options.session?.deferSessionRefresh,r="POST"===e.method;if(r&&!t)throw l.E.from("METHOD_NOT_ALLOWED",rk.f.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let i=e.context.options.session?.cookieCache?.enabled===!0,a=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!a&&i)return null;let o=r5(e,e.context.authCookies.sessionData.name);if(o&&!i){let t=r1(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!a)return null;let n=i&&!e.query?.disableCookieCache,s=n&&o?await io(e,o):null;n&&o&&!s&&il(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,r=t.session.token!==a;if(!r){let i=e.context.options.session?.cookieCache?.version,a="1";if(i){if("string"==typeof i)a=i;else if("function"==typeof i){let e=i(t.session,t.user);a=e instanceof Promise?await e:e}}r=(t.version||"1")!==a}if(!r){let e=Date.now(),i=new Date(t.session.expiresAt).getTime();r=s.expiresAt<e||!Number.isFinite(i)||i<e}if(r)il(e,e.context.authCookies.sessionData);else{let r=e.context.sessionConfig.cookieRefreshCache;if(!1===r){e.context.session=t;let r=rD(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),i=rN(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:r,user:i})}let i=s.expiresAt-Date.now(),a=1e3*r.updateAge,o=await (0,iE.T)();if(i<a&&!o){let r={session:{...t.session},user:t.user,updatedAt:Date.now()};await ia(e,r,!1);let i=e.context.authCookies.sessionToken.attributes,a=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:a});let o=rD(e.context.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),n=rN(e.context.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)});return e.context.session={session:o,user:n},e.json({session:o,user:n})}let n=rD(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=rN(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:n,user:l},e.json({session:n,user:l})}}let d=await e.context.internalAdapter.findSession(a);if(!d||d.session.expiresAt<new Date)return ic(e),d&&(!t||r)&&await e.context.internalAdapter.deleteSession(d.session.token),e.json(null);if(e.context.session=d,c||e.query?.disableRefresh){let t=rD(e.context.options,d.session),r=rN(e.context.options,d.user);return e.json({session:t,user:r})}let u=e.context.sessionConfig.expiresIn,f=e.context.sessionConfig.updateAge,p=d.session.expiresAt.valueOf()-1e3*u+1e3*f<=Date.now(),m=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,h=await (0,iE.T)(),g=p&&!m&&!h;if(t&&!r){await ia(e,d,!!c);let t=rD(e.context.options,d.session),r=rN(e.context.options,d.user);return e.json({session:t,user:r,needsRefresh:g})}if(g){let t=await e.context.internalAdapter.updateSession(d.session.token,{expiresAt:rC(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)throw ic(e),l.E.from("UNAUTHORIZED",rk.f.FAILED_TO_GET_SESSION);let r=e.context.sessionConfig.expiresIn;await is(e,{session:t,user:d.user},!1,{maxAge:r});let i=rD(e.context.options,t),a=rN(e.context.options,d.user);return e.json({session:i,user:a})}await ia(e,d,!!c);let y=rD(e.context.options,d.session),w=rN(e.context.options,d.user);return e.json({session:y,user:w})}catch(t){if(e.context.session=null,(0,ib.f)(t))throw t;throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),l.E.from("INTERNAL_SERVER_ERROR",rk.f.FAILED_TO_GET_SESSION,{cause:t})}}),iT=e=>y(e.context.options),i_=async(e,t)=>{if(e.context.session)return e.context.session;let r=await iI()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return r?(r.headers&&r.headers.forEach((t,r)=>{let i=r.toLowerCase();"cache-control"!==i&&"pragma"!==i&&("set-cookie"===i?e.responseHeaders.append(r,t):e.responseHeaders.set(r,t))}),e.context.session=r.response,r.response):(e.context.session=null,null)},iv=async e=>iT(e)?(e.context.session=null,i_(e,{disableCookieCache:!0})):i_(e),iO=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),iR=(0,iA.a)(async e=>{let t=await iv(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),ik=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session&&(e.request||e.headers))throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),ix=(0,iA.a)(async e=>{let t=await i_(e);if(!t?.session)throw l.E.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw l.E.from("FORBIDDEN",rk.f.SESSION_NOT_FRESH)}return{session:t}}),iS=(0,iA.g)("/revoke-session",{method:"POST",body:rP.object({token:rP.string().meta({description:"The token to revoke"})}),use:[iR],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),l.E.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t===e.context.session.session.token&&ic(e),e.json({status:!0})}),iU=(0,iA.g)("/revoke-sessions",{method:"POST",use:[iR],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),l.E.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return ic(e),e.json({status:!0})}),iN=(0,iA.g)("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[iR],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 l.E.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})});e.s(["h",0,ix,"M",0,iv,"v",0,iI,"D",0,i_,"f",0,iT,"T",0,()=>(0,iA.g)("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[ix],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=>rD(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),"b",0,ik,"Y",0,iN,"G",0,iS,"$",0,iU,"i",0,iR,"Z",0,iO],12996)},72003,e=>{"use strict";e.s(["f",0,"1.7.25"],72003)},18516,e=>e.a(async(t,r)=>{try{var i=e.i(60338),a=e.i(75225),o=e.i(24924),n=e.i(92335),s=e.i(45967),l=t([o]);async function c(e){return o.r.transaction(async t=>1!==((await t.select({n:(0,i.H)()}).from(s.organization))[0]?.n??0)?0:(await t.update(n.c).set({organizationId:e}).where((0,a.M)(n.c.organizationId)).returning({id:n.c.id})).length)}[o]=l.then?(await l)():l,e.s(["f",0,c]),r()}catch(e){r(e)}},!1),18188,e=>e.a(async(t,r)=>{try{var i=e.i(71616),a=e.i(75225),o=e.i(60338),n=e.i(24924),s=e.i(92335),l=e.i(45967),c=e.i(120),d=e.i(81822),u=e.i(82283),f=t([n,c,d]);[n,c,d]=f.then?(await f)():f;let g=["queued","running","waiting_approval"];async function p(e){let t=await n.r.select({id:l.organization.id,name:l.organization.name,role:l.member.role}).from(l.member).innerJoin(l.organization,(0,a.u)(l.organization.id,l.member.organizationId)).where((0,a.u)(l.member.userId,e)),r={deleted:[],left:[],blocked:[]};for(let i of t){if(((await n.r.select({n:(0,o.H)()}).from(l.member).where((0,a.b)((0,a.u)(l.member.organizationId,i.id),(0,a.c)(l.member.userId,e))))[0]?.n??0)>0){"owner"===i.role?r.blocked.push(u.f.auth.deleteBlockedOwner(i.name)):r.left.push({id:i.id,name:i.name});continue}let t=(await n.r.select({id:s.c.id}).from(s.c).where((0,a.u)(s.c.organizationId,i.id))).map(e=>e.id),c=t.length?await n.r.select({status:s.B.status}).from(s.B).where((0,a.y)(s.B.projectId,t)):[];c.some(e=>g.includes(e.status))&&r.blocked.push(u.f.auth.deleteBlockedLive(i.name)),r.deleted.push({id:i.id,name:i.name,projects:t.length,tasks:c.length})}return r}async function m(e){for(let t of(await n.r.select({id:s.c.id,repoPath:s.c.repoPath}).from(s.c).where((0,a.u)(s.c.organizationId,e)))){for(let e of(await n.r.select({id:s.B.id}).from(s.B).where((0,a.u)(s.B.projectId,t.id))))await (0,d.O)(e.id);(0,c.F)(t.id,t.repoPath)}await n.r.delete(l.organization).where((0,a.u)(l.organization.id,e))}async function h(e){let t=await p(e);if(t.blocked.length)throw new i.E("BAD_REQUEST",{message:t.blocked.join(" ")});for(let e of t.deleted)await m(e.id)}e.s(["C",0,h,"j",0,p]),r()}catch(e){r(e)}},!1),3087,e=>e.a(async(t,r)=>{try{var i=e.i(66680),a=e.i(2157),o=e.i(50227),n=e.i(4721),s=e.i(36254),l=e.i(49599),c=e.i(89171),d=e.i(34975),u=e.i(49129),f=e.i(75225),p=e.i(24924);e.i(92335);var m=e.i(45967),h=e.i(18516),g=e.i(62626),y=e.i(44030),w=e.i(18188),b=e.i(91138),E=t([p,h,g,w]);[p,h,g,w]=E.then?(await E)():E;let A=process.env.BETTER_AUTH_URL??"http://127.0.0.1:4100",I=process.env.GITHUB_CLIENT_ID&&process.env.GITHUB_CLIENT_SECRET?{clientId:process.env.GITHUB_CLIENT_ID,clientSecret:process.env.GITHUB_CLIENT_SECRET}:null,T=(0,n.f)({baseURL:A,secret:function(){if(process.env.BETTER_AUTH_SECRET)return process.env.BETTER_AUTH_SECRET;if(process.env.VITEST)return"test-secret-test-secret-test-secret-00";if(process.env.FACTORY_HOSTED)throw Error("BETTER_AUTH_SECRET is not set.");let e=(0,o.join)(b.f,"auth-secret");if((0,a.existsSync)(e)){let t=(0,a.readFileSync)(e,"utf8").trim();if(t.length>=32)return t}let t=(0,i.randomBytes)(32).toString("hex");return(0,a.mkdirSync)((0,o.dirname)(e),{recursive:!0}),(0,a.writeFileSync)(e,t,{mode:384}),t}(),trustedOrigins:[A,A.replace("127.0.0.1","localhost")],database:(0,s.f)(p.r,{provider:"pg",schema:{user:m.user,session:m.session,account:m.account,verification:m.verification,organization:m.organization,member:m.member,invitation:m.invitation}}),emailAndPassword:{enabled:!0,minPasswordLength:8},user:{deleteUser:{enabled:!0,beforeDelete:async e=>void await (0,w.C)(e.id)}},socialProviders:I?{github:I}:{},databaseHooks:{session:{create:{before:async e=>{let t=(await p.r.select({id:m.member.organizationId}).from(m.member).where((0,f.u)(m.member.userId,e.userId)).orderBy((0,u.M)(m.member.createdAt)).limit(1))[0];return{data:{...e,activeOrganizationId:t?.id??null}}}}}},plugins:[(0,d.f)({invitationExpiresIn:604800,cancelPendingInvitationsOnReInvite:!0,organizationHooks:{afterCreateOrganization:async({organization:e})=>{await (0,h.f)(e.id),(0,y.M)()&&(0,c.after)(()=>(0,g.f)(e.id).then(()=>void 0,e=>console.warn("Organization database not made yet:",e instanceof Error?e.message:e)))}}}),(0,l.A)()]});e.s(["f",0,T]),r()}catch(e){r(e)}},!1),81822,e=>e.a(async(t,r)=>{try{var i=e.i(74533),a=e.i(2157),o=e.i(50227),n=e.i(75225),s=e.i(24924),l=e.i(92335),c=e.i(82461),d=e.i(20195),u=e.i(69608),f=e.i(92835),p=e.i(18536),m=e.i(82283),h=e.i(64950),g=e.i(65272),y=t([s,c,d,u,f,h]);[s,c,d,u,f,h]=y.then?(await y)():y;class A extends Error{status;constructor(e,t){super(e),this.status=t,this.name="RunDeleteError"}}let I=new Set(["queued","running","waiting_approval"]);function w(e,t){let r=(0,o.relative)((0,o.resolve)(e),(0,o.resolve)(t));return""!==r&&!r.startsWith("..")&&!r.startsWith(o.sep)&&!r.includes(`..${o.sep}`)}async function b(e,t,r={}){(0,d.D)(e.id),await (0,f.i)(e.id,r.snapshotDir??u.P).catch(()=>void 0);let o=r.worktreeRoot??p.U,n=e.worktreePath;if(n&&w(o,n)&&(0,a.existsSync)(n)){try{t&&(0,i.execFileSync)("git",["worktree","remove","--force",n],{cwd:t,stdio:"ignore"})}catch{}if((0,a.rmSync)(n,{recursive:!0,force:!0}),t)try{(0,i.execFileSync)("git",["worktree","prune"],{cwd:t,stdio:"ignore"})}catch{}}}async function E(e,t={}){let r=(await s.r.select().from(l.B).where((0,n.u)(l.B.id,e)))[0];if(!r)throw new A(m.f.errors.runNotFound,404);if(I.has(r.status))throw new A(m.f.history.stillLive,409);let i=(await (0,h.I)(r.projectId))?.repoPath??null,p=await s.r.select({id:l.K.id,path:l.K.path}).from(l.K).where((0,n.u)(l.K.runId,e)),y=p.map(e=>e.path);(0,d.D)(e),await (0,f.i)(e,t.snapshotDir??u.P).catch(()=>void 0),await s.r.delete(l.B).where((0,n.u)(l.B.id,e)),await b(r,i,t);let T=t.attachmentDir??c.o;for(let e of y)w(T,e)&&(0,a.rmSync)(e,{force:!0});/^[0-9A-Z]{26}$/i.test(e)&&(0,a.rmSync)((0,o.join)(t.snapshotDir??u.P,e),{recursive:!0,force:!0});let _=(0,g.h)();if(_&&/^[0-9A-Z]{26}$/i.test(e))for(let t of(await _.deletePrefix(`snapshots/${e}/`),p))await _.deletePrefix((0,g._)(t.id,(0,o.extname)(t.path).slice(1)||"png"))}e.s(["N",0,A,"O",0,E,"R",0,b]),r()}catch(e){r(e)}},!1)];
|
|
483
483
|
|
|
484
484
|
//# sourceMappingURL=_0w3v4t4p9vsb-._.js.map
|