better-auth 1.0.21 → 1.0.22-beta.2

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.
Files changed (47) hide show
  1. package/dist/adapters/prisma.d.cts +1 -1
  2. package/dist/adapters/prisma.d.ts +1 -1
  3. package/dist/api.cjs +1 -1
  4. package/dist/api.js +1 -1
  5. package/dist/client/plugins.d.cts +1 -1
  6. package/dist/client/plugins.d.ts +1 -1
  7. package/dist/{index-Dt4lZbQi.d.ts → index-Dd3_WG87.d.ts} +105 -103
  8. package/dist/{index-CgaJXZ9u.d.cts → index-Dp04oxSM.d.cts} +105 -103
  9. package/dist/index.cjs +2 -2
  10. package/dist/index.js +2 -2
  11. package/dist/plugin/custom-session.cjs +4 -4
  12. package/dist/plugin/custom-session.js +2 -2
  13. package/dist/plugins/admin.cjs +1 -1
  14. package/dist/plugins/admin.js +1 -1
  15. package/dist/plugins/anonymous.cjs +1 -1
  16. package/dist/plugins/anonymous.js +1 -1
  17. package/dist/plugins/bearer.cjs +1 -1
  18. package/dist/plugins/bearer.js +1 -1
  19. package/dist/plugins/email-otp.cjs +1 -1
  20. package/dist/plugins/email-otp.js +1 -1
  21. package/dist/plugins/generic-oauth.cjs +1 -1
  22. package/dist/plugins/generic-oauth.js +1 -1
  23. package/dist/plugins/jwt.cjs +2 -2
  24. package/dist/plugins/jwt.js +2 -2
  25. package/dist/plugins/multi-session.cjs +1 -1
  26. package/dist/plugins/multi-session.js +1 -1
  27. package/dist/plugins/one-tap.cjs +1 -1
  28. package/dist/plugins/one-tap.js +1 -1
  29. package/dist/plugins/open-api.cjs +1 -1
  30. package/dist/plugins/open-api.js +1 -1
  31. package/dist/plugins/organization.cjs +4 -4
  32. package/dist/plugins/organization.d.cts +1 -1
  33. package/dist/plugins/organization.d.ts +1 -1
  34. package/dist/plugins/organization.js +2 -2
  35. package/dist/plugins/passkey.cjs +1 -1
  36. package/dist/plugins/passkey.js +1 -1
  37. package/dist/plugins/phone-number.cjs +1 -1
  38. package/dist/plugins/phone-number.js +1 -1
  39. package/dist/plugins/two-factor.cjs +1 -1
  40. package/dist/plugins/two-factor.js +1 -1
  41. package/dist/plugins/username.cjs +1 -1
  42. package/dist/plugins/username.js +1 -1
  43. package/dist/plugins.cjs +3 -3
  44. package/dist/plugins.d.cts +1 -1
  45. package/dist/plugins.d.ts +1 -1
  46. package/dist/plugins.js +4 -4
  47. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- "use strict";var nr=Object.create;var ce=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var cr=(e,r)=>{for(var t in r)ce(e,t,{get:r[t],enumerable:!0})},Be=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of sr(r))!dr.call(e,n)&&n!==t&&ce(e,n,{get:()=>r[n],enumerable:!(o=ir(r,n))||o.enumerable});return e};var _e=(e,r,t)=>(t=e!=null?nr(ar(e)):{},Be(r||!e||!e.__esModule?ce(t,"default",{value:e,enumerable:!0}):t,e)),lr=e=>Be(ce({},"__esModule",{value:!0}),e);var Uo={};cr(Uo,{organization:()=>To});module.exports=lr(Uo);var Ce=require("better-call"),ae=require("zod");var X=require("better-call"),Me=(0,X.createMiddleware)(async()=>({})),Y=(0,X.createMiddlewareCreator)({use:[Me,(0,X.createMiddleware)(async()=>({}))]}),u=(0,X.createEndpointCreator)({use:[Me]});var S=require("better-call"),I=require("zod");var hr=require("oslo"),Fe=require("oslo/encoding");var le=require("oslo/crypto");async function pr({value:e,secret:r}){return new le.HMAC("SHA-256").sign(new TextEncoder().encode(r),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function mr({value:e,signature:r,secret:t}){return new le.HMAC("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(r,"base64"),new TextEncoder().encode(e))}var ue={sign:pr,verify:mr};var F=class extends Error{constructor(r,t){super(r),this.name="BetterAuthError",this.message=r,this.cause=t,this.stack=""}};var q=(e,r="ms")=>new Date(Date.now()+(r==="sec"?e*1e3:e));var pe=Object.create(null),de=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?pe:globalThis),Ve=new Proxy(pe,{get(e,r){return de()[r]??pe[r]},has(e,r){let t=de();return r in t||r in pe},set(e,r,t){let o=de(!0);return o[r]=t,!0},deleteProperty(e,r){if(!r)return!1;let t=de(!0);return delete t[r],!0},ownKeys(){let e=de(!0);return Object.keys(e)}});function fr(e){return e?e!=="false":!1}var Ee=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Re=Ee==="dev"||Ee==="development",gr=Ee==="test"||fr(Ve.TEST);async function v(e,r,t,o){let n=e.context.authCookies.sessionToken.options,i=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,r.session.token,e.context.secret,{...n,maxAge:i,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let a=Fe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:r,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ue.sign({value:JSON.stringify(r),secret:e.context.secret})})),{includePadding:!1});if(a.length>4093)throw new F("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,a,e.context.authCookies.sessionData.options)}e.context.setNewSession(r),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(r.session.token,JSON.stringify({user:r.user,session:r.session}),Math.floor((new Date(r.session.expiresAt).getTime()-Date.now())/1e3))}function $(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Ye=require("@better-fetch/fetch"),Ke=require("better-call"),ee=require("jose"),Je=require("oslo/jwt");var qe=require("oslo/crypto"),$e=require("oslo/encoding");async function He(e){let r=await(0,qe.sha256)(new TextEncoder().encode(e));return $e.base64url.encode(new Uint8Array(r),{includePadding:!1})}function me(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:r,authorizationEndpoint:t,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a,duration:d}){let c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",r.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",r.redirectURI||a),n){let l=await He(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,h)=>(m[h]=null,m),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d&&c.searchParams.set("duration",d),c}var Ge=require("@better-fetch/fetch");async function b({code:e,codeVerifier:r,redirectURI:t,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),r&&s.set("code_verifier",r),s.set("redirect_uri",t),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,Ge.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return me(d)}var fe=require("oslo/oauth2"),H=require("zod"),Te=require("better-call");function Ze(e){try{return new URL(e).origin}catch{return null}}function We(e){return e.includes("://")?new URL(e).host:e}async function ge(e,r){let t=e.body?.callbackURL||(e.query?.currentURL?Ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new Te.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,fe.generateCodeVerifier)(),n=(0,fe.generateState)(),i=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:r,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Te.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Qe(e){let r=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(r);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=H.z.object({callbackURL:H.z.string(),codeVerifier:H.z.string(),errorURL:H.z.string().optional(),newUserURL:H.z.string().optional(),expiresAt:H.z.number(),link:H.z.object({email:H.z.string(),userId:H.z.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var Xe=e=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let n=(0,ee.decodeProtectedHeader)(t),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await yr(i),{payload:d}=await(0,ee.jwtVerify)(t,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Je.parseJWT)(t.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},yr=async e=>{let r="https://appleid.apple.com",t="/auth/keys",{data:o}=await(0,Ye.betterFetch)(`${r}${t}`);if(!o?.keys)throw new Ke.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,ee.importJWK)(n,n.alg)};var et=require("@better-fetch/fetch");var tt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${r}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,et.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(o)return null;if(t.avatar===null){let i=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${i}`}let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...n},data:t}}});var rt=require("@better-fetch/fetch");var ot=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,rt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...n},data:t}}});var Ue=require("@better-fetch/fetch");var nt=e=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>b({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await(0,Ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:d}=await(0,Ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(a.find(c=>c.primary)??a[0])?.email,i=a.find(c=>c.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var st=require("oslo/jwt");var it=require("consola"),Se=["info","success","warn","error","debug"];function wr(e,r){return Se.indexOf(r)<=Se.indexOf(e)}var br=(0,it.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Or=e=>{let r=e?.disabled!==!0,t=e?.level??"error",o=(n,i,s=[])=>{if(!(!r||!wr(t,n))){if(!e||typeof e.log!="function"){br[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(Se.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},M=Or();var at=require("@better-fetch/fetch"),dt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw M.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=t||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:r,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${r}`,{data:n}=await(0,at.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let t=(0,st.parseJWT)(r.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});var ct=require("@better-fetch/fetch"),lt=require("oslo/jwt");var ut=e=>{let r=e.tenantId||"common",t=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:t,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,lt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,ct.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let l=await d.response.clone().arrayBuffer(),m=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(c){M.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let a=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...a},data:i}}}};var pt=require("@better-fetch/fetch");var mt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){let i=t||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:r,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,pt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...n},data:t}}});var te={isAction:!1};var ft=require("nanoid"),G=e=>(0,ft.nanoid)(e);var gt=require("oslo/jwt");var ht=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let t=r.idToken;if(!t)return M.error("No idToken found in token"),null;let o=(0,gt.parseJWT)(t)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var yt=require("@better-fetch/fetch");var wt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let t=r.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,yt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...n},data:t}}});var bt=require("@better-fetch/fetch");var Ot=e=>{let r="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>await b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await(0,bt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var At=require("@better-fetch/fetch");var It=e=>{let r="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:r,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:n,error:i}=await(0,At.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var _t=require("@better-fetch/fetch");var ve=(e="")=>e.split("://").map(r=>r.replace(/\/{2,}/g,"/")).join("://"),Ar=e=>{let r=e||"https://gitlab.com";return{authorizationEndpoint:ve(`${r}/oauth/authorize`),tokenEndpoint:ve(`${r}/oauth/token`),userinfoEndpoint:ve(`${r}/api/v4/user`)}},Et=e=>{let{authorizationEndpoint:r,tokenEndpoint:t,userinfoEndpoint:o}=Ar(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:r,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:a,error:d}=await(0,_t.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(d||a.state!=="active"||a.locked)return null;let c=await e.mapProfileToUser?.(a);return{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0,...c},data:a}}}};var ke=require("@better-fetch/fetch");var Rt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:r,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:r,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:r,redirect_uri:e.redirectURI||t}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await(0,ke.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return me(i)},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,ke.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...n},data:t}}});var Ir={apple:Xe,discord:tt,facebook:ot,github:nt,microsoft:ut,google:dt,spotify:mt,twitch:ht,twitter:wt,dropbox:Ot,linkedin:It,gitlab:Et,reddit:Rt},he=Object.keys(Ir);var vt=require("oslo"),ye=require("oslo/jwt"),j=require("zod");var re=require("better-call");var Z=require("better-call");var K=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Ut=()=>u("/get-session",{method:"GET",query:K.z.optional(K.z.object({disableCookieCache:K.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(K.z.string().transform(e=>e==="true")).optional(),disableRefresh:K.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?Tt(Buffer.from(t,"base64").toString()):null;if(o&&!await ue.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(r);if(e.context.session=i,!i||i.session.expiresAt<new Date)return $(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(r){throw e.context.logger.error("INTERNAL_SERVER_ERROR",r),new Z.APIError("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),k=async(e,r)=>{if(e.context.session)return e.context.session;let t=await Ut()({...e,_flag:"json",headers:e.headers,query:r}).catch(o=>null);return e.context.session=t,t},C=Y(async e=>{let r=await k(e);if(!r?.session)throw new Z.APIError("UNAUTHORIZED");return{session:r}}),St=Y(async e=>{let r=await k(e);if(!r?.session)throw new Z.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:r};let t=e.context.sessionConfig.freshAge,o=r.session.createdAt.valueOf(),n=Date.now();if(!(o+t*1e3>n))throw new Z.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:r}});var _r=u("/revoke-session",{method:"POST",body:K.z.object({token:K.z.string({description:"The token to revoke"})}),use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let r=e.body.token,t=await e.context.internalAdapter.findSession(r);if(!t)throw new Z.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(r)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Er=u("/revoke-sessions",{method:"POST",use:[C],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"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(r){throw e.context.logger.error(r&&typeof r=="object"&&"name"in r?r.name:"",r),new Z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Rr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[C],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"}}}}}}}}}},async e=>{let r=e.context.session;if(!r.user)throw new Z.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(r.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function Q(e,r,t){return await(0,ye.createJWT)("HS256",Buffer.from(e),{email:r.toLowerCase(),updateTo:t},{expiresIn:new vt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[r],includeIssuedTimestamp:!0})}async function Tr(e,r){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new re.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await Q(e.context.secret,r.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:r,url:o,token:t},e.request)}var Ur=u("/send-verification-email",{method:"POST",query:j.z.object({currentURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:j.z.object({email:j.z.string({description:"The email to send the verification email to"}).email(),callbackURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new re.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(r);if(!t)throw new re.APIError("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await Tr(e,t.user),e.json({status:!0})}),Sr=u("/verify-email",{method:"GET",query:j.z.object({token:j.z.string({description:"The token to verify the email"}),callbackURL:j.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function r(a){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${a}`):e.redirect(`${e.query.callbackURL}?error=${a}`):new re.APIError("UNAUTHORIZED",{message:a})}let{token:t}=e.query,o;try{o=await(0,ye.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){return e.context.logger.error("Failed to verify email",a),r("invalid_token")}let i=j.z.object({email:j.z.string().email(),updateTo:j.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return r("user_not_found");if(i.updateTo){let a=await k(e);if(!a){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}if(a.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),c=await Q(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await k(e)){let d=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!d)throw new re.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(e,{session:d,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var oe=require("better-call");var zt=require("better-call");function ze(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function vr(e){let r="";for(let t=0;t<e.length;t++)r+=ze(e[t]);return r}function kt(e,r=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${kt(l,r)}$`).join("|")})`;let t="",o="",n=".";r===!0?(t="/",o="[/\\\\]",n="[^/\\\\]"):r&&(t=r,o=vr(t),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=r?`${o}+?`:"",s=r?`${o}*?`:"",a=r?e.split(t):[e],d="";for(let c=0;c<a.length;c++){let l=a[c],m=a[c+1],h="";if(!(!l&&c>0)){if(r&&(c===a.length-1?h=s:m!=="**"?h=i:h=""),r&&l==="**"){h&&(d+=c===0?"":h,d+=`(?:${n}*?${h})*?`);continue}for(let y=0;y<l.length;y++){let _=l[y];_==="\\"?y<l.length-1&&(d+=ze(l[y+1]),y++):_==="?"?d+=n:_==="*"?d+=`${n}*?`:d+=ze(_)}d+=h}}return d}function kr(e,r){if(typeof r!="string")throw new TypeError(`Sample must be a string, but ${typeof r} given`);return e.test(r)}function Ne(e,r){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof r=="string"||typeof r=="boolean")&&(r={separator:r}),arguments.length===2&&!(typeof r>"u"||typeof r=="object"&&r!==null&&!Array.isArray(r)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=kt(e,r.separator),o=new RegExp(`^${t}$`,r.flags),n=kr.bind(null,o);return n.options=r,n.pattern=e,n.regexp=o,n}var zr=Y(async e=>{if(e.request?.method!=="POST")return;let{body:r,query:t,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=r?.callbackURL||t?.callbackURL,s=r?.redirectTo,a=t?.currentURL,d=r?.errorCallbackURL,c=r?.newUserCallbackURL,l=o.trustedOrigins,m=e.headers?.has("cookie"),h=(_,N)=>_.startsWith("/")?!1:N.includes("*")?Ne(N)(We(_)):_.startsWith(N),y=(_,N)=>{if(!_)return;if(!l.some(Ae=>h(_,Ae)||_?.startsWith("/")&&N!=="origin"&&!_.includes(":")))throw e.context.logger.error(`Invalid ${N}: ${_}`),e.context.logger.info(`If it's a valid URL, please add ${_} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${l}`),new zt.APIError("FORBIDDEN",{message:`Invalid ${N}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&y(n,"origin"),i&&y(i,"callbackURL"),s&&y(s,"redirectURL"),a&&y(a,"currentURL"),d&&y(d,"errorCallbackURL"),c&&y(s,"newUserCallbackURL")});var Nr=u("/ok",{method:"GET",metadata:{...te,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Dr=require("zod");var xr=require("better-call");var g=require("zod"),Lr=require("better-call"),Gi=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Zi=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Wi=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Qi=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});var Cr=(e="Unknown")=>`<!DOCTYPE html>
1
+ "use strict";var nr=Object.create;var ce=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var cr=(e,r)=>{for(var t in r)ce(e,t,{get:r[t],enumerable:!0})},Be=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of sr(r))!dr.call(e,n)&&n!==t&&ce(e,n,{get:()=>r[n],enumerable:!(o=ir(r,n))||o.enumerable});return e};var _e=(e,r,t)=>(t=e!=null?nr(ar(e)):{},Be(r||!e||!e.__esModule?ce(t,"default",{value:e,enumerable:!0}):t,e)),lr=e=>Be(ce({},"__esModule",{value:!0}),e);var Uo={};cr(Uo,{organization:()=>To});module.exports=lr(Uo);var Ce=require("better-call"),ee=require("zod");var X=require("better-call"),Me=(0,X.createMiddleware)(async()=>({})),Y=(0,X.createMiddlewareCreator)({use:[Me,(0,X.createMiddleware)(async()=>({}))]}),u=(0,X.createEndpointCreator)({use:[Me]});var S=require("better-call"),I=require("zod");var hr=require("oslo"),Fe=require("oslo/encoding");var le=require("oslo/crypto");async function pr({value:e,secret:r}){return new le.HMAC("SHA-256").sign(new TextEncoder().encode(r),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function mr({value:e,signature:r,secret:t}){return new le.HMAC("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(r,"base64"),new TextEncoder().encode(e))}var ue={sign:pr,verify:mr};var F=class extends Error{constructor(r,t){super(r),this.name="BetterAuthError",this.message=r,this.cause=t,this.stack=""}};var q=(e,r="ms")=>new Date(Date.now()+(r==="sec"?e*1e3:e));var pe=Object.create(null),de=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?pe:globalThis),Ve=new Proxy(pe,{get(e,r){return de()[r]??pe[r]},has(e,r){let t=de();return r in t||r in pe},set(e,r,t){let o=de(!0);return o[r]=t,!0},deleteProperty(e,r){if(!r)return!1;let t=de(!0);return delete t[r],!0},ownKeys(){let e=de(!0);return Object.keys(e)}});function fr(e){return e?e!=="false":!1}var Ee=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Re=Ee==="dev"||Ee==="development",gr=Ee==="test"||fr(Ve.TEST);async function v(e,r,t,o){let n=e.context.authCookies.sessionToken.options,i=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,r.session.token,e.context.secret,{...n,maxAge:i,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let a=Fe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:r,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ue.sign({value:JSON.stringify(r),secret:e.context.secret})})),{includePadding:!1});if(a.length>4093)throw new F("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,a,e.context.authCookies.sessionData.options)}e.context.setNewSession(r),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(r.session.token,JSON.stringify({user:r.user,session:r.session}),Math.floor((new Date(r.session.expiresAt).getTime()-Date.now())/1e3))}function $(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Ye=require("@better-fetch/fetch"),Ke=require("better-call"),te=require("jose"),Je=require("oslo/jwt");var qe=require("oslo/crypto"),$e=require("oslo/encoding");async function He(e){let r=await(0,qe.sha256)(new TextEncoder().encode(e));return $e.base64url.encode(new Uint8Array(r),{includePadding:!1})}function me(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:r,authorizationEndpoint:t,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a,duration:d}){let c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",r.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",r.redirectURI||a),n){let l=await He(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,h)=>(m[h]=null,m),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d&&c.searchParams.set("duration",d),c}var Ge=require("@better-fetch/fetch");async function b({code:e,codeVerifier:r,redirectURI:t,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),r&&s.set("code_verifier",r),s.set("redirect_uri",t),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,Ge.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return me(d)}var fe=require("oslo/oauth2"),H=require("zod"),Te=require("better-call");function Ze(e){try{return new URL(e).origin}catch{return null}}function We(e){return e.includes("://")?new URL(e).host:e}async function ge(e,r){let t=e.body?.callbackURL||(e.query?.currentURL?Ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new Te.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,fe.generateCodeVerifier)(),n=(0,fe.generateState)(),i=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:r,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Te.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Qe(e){let r=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(r);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=H.z.object({callbackURL:H.z.string(),codeVerifier:H.z.string(),errorURL:H.z.string().optional(),newUserURL:H.z.string().optional(),expiresAt:H.z.number(),link:H.z.object({email:H.z.string(),userId:H.z.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var Xe=e=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let n=(0,te.decodeProtectedHeader)(t),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await yr(i),{payload:d}=await(0,te.jwtVerify)(t,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Je.parseJWT)(t.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},yr=async e=>{let r="https://appleid.apple.com",t="/auth/keys",{data:o}=await(0,Ye.betterFetch)(`${r}${t}`);if(!o?.keys)throw new Ke.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,te.importJWK)(n,n.alg)};var et=require("@better-fetch/fetch");var tt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${r}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,et.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(o)return null;if(t.avatar===null){let i=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${i}`}let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...n},data:t}}});var rt=require("@better-fetch/fetch");var ot=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,rt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...n},data:t}}});var Ue=require("@better-fetch/fetch");var nt=e=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>b({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await(0,Ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:d}=await(0,Ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(a.find(c=>c.primary)??a[0])?.email,i=a.find(c=>c.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var st=require("oslo/jwt");var it=require("consola"),Se=["info","success","warn","error","debug"];function wr(e,r){return Se.indexOf(r)<=Se.indexOf(e)}var br=(0,it.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Or=e=>{let r=e?.disabled!==!0,t=e?.level??"error",o=(n,i,s=[])=>{if(!(!r||!wr(t,n))){if(!e||typeof e.log!="function"){br[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(Se.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},M=Or();var at=require("@better-fetch/fetch"),dt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw M.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=t||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:r,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${r}`,{data:n}=await(0,at.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let t=(0,st.parseJWT)(r.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});var ct=require("@better-fetch/fetch"),lt=require("oslo/jwt");var ut=e=>{let r=e.tenantId||"common",t=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:t,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,lt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,ct.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let l=await d.response.clone().arrayBuffer(),m=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(c){M.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let a=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...a},data:i}}}};var pt=require("@better-fetch/fetch");var mt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){let i=t||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:r,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,pt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...n},data:t}}});var re={isAction:!1};var ft=require("nanoid"),G=e=>(0,ft.nanoid)(e);var gt=require("oslo/jwt");var ht=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let t=r.idToken;if(!t)return M.error("No idToken found in token"),null;let o=(0,gt.parseJWT)(t)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var yt=require("@better-fetch/fetch");var wt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let t=r.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,yt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...n},data:t}}});var bt=require("@better-fetch/fetch");var Ot=e=>{let r="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>await b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await(0,bt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var At=require("@better-fetch/fetch");var It=e=>{let r="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:r,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:n,error:i}=await(0,At.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var _t=require("@better-fetch/fetch");var ve=(e="")=>e.split("://").map(r=>r.replace(/\/{2,}/g,"/")).join("://"),Ar=e=>{let r=e||"https://gitlab.com";return{authorizationEndpoint:ve(`${r}/oauth/authorize`),tokenEndpoint:ve(`${r}/oauth/token`),userinfoEndpoint:ve(`${r}/api/v4/user`)}},Et=e=>{let{authorizationEndpoint:r,tokenEndpoint:t,userinfoEndpoint:o}=Ar(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:r,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:a,error:d}=await(0,_t.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(d||a.state!=="active"||a.locked)return null;let c=await e.mapProfileToUser?.(a);return{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0,...c},data:a}}}};var ke=require("@better-fetch/fetch");var Rt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:r,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:r,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:r,redirect_uri:e.redirectURI||t}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await(0,ke.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return me(i)},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await(0,ke.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...n},data:t}}});var Ir={apple:Xe,discord:tt,facebook:ot,github:nt,microsoft:ut,google:dt,spotify:mt,twitch:ht,twitter:wt,dropbox:Ot,linkedin:It,gitlab:Et,reddit:Rt},he=Object.keys(Ir);var vt=require("oslo"),ye=require("oslo/jwt"),j=require("zod");var oe=require("better-call");var Z=require("better-call");var K=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Ut=()=>u("/get-session",{method:"GET",query:K.z.optional(K.z.object({disableCookieCache:K.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(K.z.string().transform(e=>e==="true")).optional(),disableRefresh:K.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?Tt(Buffer.from(t,"base64").toString()):null;if(o&&!await ue.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(r);if(e.context.session=i,!i||i.session.expiresAt<new Date)return $(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(r){throw e.context.logger.error("INTERNAL_SERVER_ERROR",r),new Z.APIError("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),k=async(e,r)=>{if(e.context.session)return e.context.session;let t=await Ut()({...e,_flag:"json",headers:e.headers,query:r}).catch(o=>null);return e.context.session=t,t},C=Y(async e=>{let r=await k(e);if(!r?.session)throw new Z.APIError("UNAUTHORIZED");return{session:r}}),St=Y(async e=>{let r=await k(e);if(!r?.session)throw new Z.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:r};let t=e.context.sessionConfig.freshAge,o=r.session.updatedAt?.valueOf()||r.session.createdAt.valueOf();if(!(Date.now()-o<t*1e3))throw new Z.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:r}});var _r=u("/revoke-session",{method:"POST",body:K.z.object({token:K.z.string({description:"The token to revoke"})}),use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let r=e.body.token,t=await e.context.internalAdapter.findSession(r);if(!t)throw new Z.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(r)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Er=u("/revoke-sessions",{method:"POST",use:[C],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"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(r){throw e.context.logger.error(r&&typeof r=="object"&&"name"in r?r.name:"",r),new Z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Rr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[C],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"}}}}}}}}}},async e=>{let r=e.context.session;if(!r.user)throw new Z.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(r.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function Q(e,r,t){return await(0,ye.createJWT)("HS256",Buffer.from(e),{email:r.toLowerCase(),updateTo:t},{expiresIn:new vt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[r],includeIssuedTimestamp:!0})}async function Tr(e,r){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await Q(e.context.secret,r.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:r,url:o,token:t},e.request)}var Ur=u("/send-verification-email",{method:"POST",query:j.z.object({currentURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:j.z.object({email:j.z.string({description:"The email to send the verification email to"}).email(),callbackURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(r);if(!t)throw new oe.APIError("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await Tr(e,t.user),e.json({status:!0})}),Sr=u("/verify-email",{method:"GET",query:j.z.object({token:j.z.string({description:"The token to verify the email"}),callbackURL:j.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function r(a){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${a}`):e.redirect(`${e.query.callbackURL}?error=${a}`):new oe.APIError("UNAUTHORIZED",{message:a})}let{token:t}=e.query,o;try{o=await(0,ye.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){return e.context.logger.error("Failed to verify email",a),r("invalid_token")}let i=j.z.object({email:j.z.string().email(),updateTo:j.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return r("user_not_found");if(i.updateTo){let a=await k(e);if(!a){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}if(a.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),c=await Q(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await k(e)){let d=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!d)throw new oe.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(e,{session:d,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ne=require("better-call");var zt=require("better-call");function ze(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function vr(e){let r="";for(let t=0;t<e.length;t++)r+=ze(e[t]);return r}function kt(e,r=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${kt(l,r)}$`).join("|")})`;let t="",o="",n=".";r===!0?(t="/",o="[/\\\\]",n="[^/\\\\]"):r&&(t=r,o=vr(t),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=r?`${o}+?`:"",s=r?`${o}*?`:"",a=r?e.split(t):[e],d="";for(let c=0;c<a.length;c++){let l=a[c],m=a[c+1],h="";if(!(!l&&c>0)){if(r&&(c===a.length-1?h=s:m!=="**"?h=i:h=""),r&&l==="**"){h&&(d+=c===0?"":h,d+=`(?:${n}*?${h})*?`);continue}for(let y=0;y<l.length;y++){let _=l[y];_==="\\"?y<l.length-1&&(d+=ze(l[y+1]),y++):_==="?"?d+=n:_==="*"?d+=`${n}*?`:d+=ze(_)}d+=h}}return d}function kr(e,r){if(typeof r!="string")throw new TypeError(`Sample must be a string, but ${typeof r} given`);return e.test(r)}function Ne(e,r){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof r=="string"||typeof r=="boolean")&&(r={separator:r}),arguments.length===2&&!(typeof r>"u"||typeof r=="object"&&r!==null&&!Array.isArray(r)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=kt(e,r.separator),o=new RegExp(`^${t}$`,r.flags),n=kr.bind(null,o);return n.options=r,n.pattern=e,n.regexp=o,n}var zr=Y(async e=>{if(e.request?.method!=="POST")return;let{body:r,query:t,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=r?.callbackURL||t?.callbackURL,s=r?.redirectTo,a=t?.currentURL,d=r?.errorCallbackURL,c=r?.newUserCallbackURL,l=o.trustedOrigins,m=e.headers?.has("cookie"),h=(_,N)=>_.startsWith("/")?!1:N.includes("*")?Ne(N)(We(_)):_.startsWith(N),y=(_,N)=>{if(!_)return;if(!l.some(Ae=>h(_,Ae)||_?.startsWith("/")&&N!=="origin"&&!_.includes(":")))throw e.context.logger.error(`Invalid ${N}: ${_}`),e.context.logger.info(`If it's a valid URL, please add ${_} to trustedOrigins in your auth config
2
+ `,`Current list of trustedOrigins: ${l}`),new zt.APIError("FORBIDDEN",{message:`Invalid ${N}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&y(n,"origin"),i&&y(i,"callbackURL"),s&&y(s,"redirectURL"),a&&y(a,"currentURL"),d&&y(d,"errorCallbackURL"),c&&y(s,"newUserCallbackURL")});var Nr=u("/ok",{method:"GET",metadata:{...re,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Dr=require("zod");var xr=require("better-call");var g=require("zod"),Lr=require("better-call"),Gi=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Zi=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Wi=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Qi=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});var Cr=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8">
@@ -79,5 +79,5 @@
79
79
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
80
80
  </div>
81
81
  </body>
82
- </html>`,jr=u("/error",{method:"GET",metadata:{...te,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let r=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Cr(r),{headers:{"Content-Type":"text/html"}})});var Br=_e(require("defu"),1);var Mr=require("better-call");async function we(e,{userInfo:r,account:t,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(r.email.toLowerCase(),{includeAccounts:!0}).catch(d=>{throw M.error(`Better auth was unable to query your database.
83
- Error: `,d),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let d=n.accounts.find(c=>c.providerId===t.providerId);if(d){let c=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([l,m])=>m!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(d.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!r.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Re&&M.warn(`User already exist but account isn't linked to ${t.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:t.providerId,accountId:r.id.toString(),userId:n.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(m){return M.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...r,updatedAt:new Date})}}else if(i=await e.context.internalAdapter.createOAuthUser({...r,email:r.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:r.id.toString()}).then(d=>d?.user),!r.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await Q(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let a=await e.context.internalAdapter.createSession(i.id,e.request);return a?{data:{session:a,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Vr=u("/sign-in/social",{method:"POST",query:I.z.object({currentURL:I.z.string().optional()}).optional(),body:I.z.object({callbackURL:I.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:I.z.string().optional(),errorCallbackURL:I.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:I.z.enum(he,{description:"OAuth2 provider to use"}),disableRedirect:I.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:I.z.optional(I.z.object({token:I.z.string({description:"ID token from the provider"}),nonce:I.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:I.z.string({description:"Access token from the provider"}).optional(),refreshToken:I.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:I.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let r=e.context.socialProviders.find(i=>i.id===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}),new S.APIError("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new S.APIError("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await r.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_TOKEN});let d=await r.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.USER_EMAIL_NOT_FOUND});let c=await we(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:r.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new S.APIError("UNAUTHORIZED",{message:c.error});return await v(e,c.data),e.json({session:c.data.session,user:c.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await ge(e),n=await r.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Fr=u("/sign-in/email",{method:"POST",body:I.z.object({email:I.z.string({description:"Email of the user"}),password:I.z.string({description:"Password of the user"}),callbackURL:I.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:I.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},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!"),new S.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:r,password:t}=e.body;if(!I.z.string().email().safeParse(r).success)throw new S.APIError("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!n)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new S.APIError("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let c=await Q(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:c},e.request),e.context.logger.error("Email not verified",{email:r}),new S.APIError("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new S.APIError("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await v(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var ne=require("zod");var be=ne.z.object({code:ne.z.string().optional(),error:ne.z.string().optional(),error_description:ne.z.string().optional(),state:ne.z.string().optional()}),qr=u("/callback/:id",{method:["GET","POST"],body:be.optional(),query:be.optional(),metadata:te},async e=>{let r;try{if(e.method==="GET")r=be.parse(e.query);else if(e.method==="POST")r=be.parse(e.body);else throw new Error("Unsupported method")}catch(x){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",x),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:n,error_description:i}=r;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(x=>x.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:d,link:c,errorURL:l,newUserURL:m}=await Qe(e),h;try{h=await s.validateAuthorizationCode({code:t,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(x){throw e.context.logger.error("",x),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(h).then(x=>x?.user);function _(x){let V=l||d||`${e.context.baseURL}/error`;throw V.includes("?")?V=`${V}&error=${x}`:V=`${V}?error=${x}`,e.redirect(V)}if(!y)return e.context.logger.error("Unable to get user info"),_("unable_to_get_user_info");if(!y.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),_("email_not_found");if(!d)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==y.email.toLowerCase())return _("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:s.id,accountId:y.id}))return _("unable_to_link_account");let V;try{V=d.toString()}catch{V=d}throw e.redirect(V)}let N=await we(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...h,scope:h.scopes?.join(",")},callbackURL:d});if(N.error)return e.context.logger.error(N.error.split(" ").join("_")),_(N.error.split(" ").join("_"));let{session:je,user:Ae}=N.data;await v(e,{session:je,user:Ae});let Ie;try{Ie=(N.isRegister&&m||d).toString()}catch{Ie=N.isRegister&&m||d}throw e.redirect(Ie)});var Ys=require("zod");var Nt=require("better-call");var $r=u("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)throw $(e),new Nt.APIError("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(r),$(e),e.json({success:!0})});var D=require("zod");var ie=require("better-call");function Lt(e,r,t){let o=r?new URL(r,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function to(e,r,t){let o=new URL(r,e.baseURL);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Hr=u("/forget-password",{method:"POST",body:D.z.object({email:D.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.z.string({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:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ie.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:r,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:r}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=G(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Gr=u("/reset-password/:token",{method:"GET",query:D.z.object({callbackURL:D.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:r}=e.params,{callbackURL:t}=e.query;if(!r||!t)throw e.redirect(Lt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${r}`);throw!o||o.expiresAt<new Date?e.redirect(Lt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(to(e.context,t,{token:r}))}),Zr=u("/reset-password",{query:D.z.optional(D.z.object({token:D.z.string().optional(),currentURL:D.z.string().optional()})),method:"POST",body:D.z.object({newPassword:D.z.string({description:"The new password to set"}),token:D.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!r)throw new ie.APIError("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new ie.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(t.length>n)throw new ie.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${r}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ie.APIError("BAD_REQUEST",{message:f.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let a=s.value,d=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(a)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(a,d),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:d,accountId:a}),e.json({status:!0}))});var L=require("zod");var T=require("better-call");var ao=require("@noble/ciphers/chacha"),Pe=require("@noble/ciphers/utils"),co=require("@noble/ciphers/webcrypto"),lo=require("oslo/crypto"),uo=_e(require("uncrypto"),1);var Pt=require("oslo/encoding");var ro=require("@noble/hashes/scrypt"),oo=require("uncrypto");var Le=_e(require("uncrypto"),1);function no(e){return e.toString(2).padStart(8,"0")}function io(e){return[...e].map(r=>no(r)).join("")}function Dt(e){return parseInt(io(e),2)}function so(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let r=(e-1).toString(2).length,t=r%8,o=new Uint8Array(Math.ceil(r/8));Le.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let n=Dt(o);for(;n>=e;)Le.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),n=Dt(o);return n}function xt(e,r){let t="";for(let o=0;o<e;o++)t+=r[so(r.length)];return t}function Ct(...e){let r=new Set(e),t="";for(let o of r)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}var Wr=u("/change-password",{method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),currentPassword:L.z.string({description:"The current password"}),revokeOtherSessions:L.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[C],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:r,currentPassword:t,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(r.length<i)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(r.length>s)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!d||!d.password)throw new T.APIError("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(r);if(!await e.context.password.verify({hash:d.password,password:t}))throw new T.APIError("BAD_REQUEST",{message:f.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await v(e,{session:m,user:n.user})}return e.json(n.user)}),Qr=u("/set-password",{method:"POST",body:L.z.object({newPassword:L.z.string()}),metadata:{SERVER_ONLY:!0},use:[C]},async e=>{let{newPassword:r}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(r.length<o)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(r.length>n)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(r);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:a}),e.json(t.user);throw new T.APIError("BAD_REQUEST",{message:"user already has a password"})}),Yr=u("/delete-user",{method:"POST",use:[St],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new T.APIError("NOT_FOUND");let r=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=xt(32,Ct("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Kr=u("/delete-user/callback",{method:"GET",query:L.z.object({token:L.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new T.APIError("NOT_FOUND");let r=await k(e);if(!r)throw new T.APIError("NOT_FOUND",{message:f.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new T.APIError("NOT_FOUND",{message:f.INVALID_TOKEN});if(t.value!==r.user.id)throw new T.APIError("NOT_FOUND",{message:f.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),$(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Jr=u("/change-email",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({newEmail:L.z.string({description:"The new email to set"}).email(),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[C],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new T.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new T.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await Q(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});var se=require("zod");var De=require("better-call");var Xr=u("/list-accounts",{method:"GET",use:[C],metadata:{openapi:{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"},provider:{type:"string"}}}}}}}}}}},async e=>{let r=e.context.session,t=await e.context.internalAdapter.findAccounts(r.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),eo=u("/link-social",{method:"POST",requireHeaders:!0,query:se.z.object({currentURL:se.z.string().optional()}).optional(),body:se.z.object({callbackURL:se.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:se.z.enum(he,{description:"The OAuth2 provider to use"})}),use:[C],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let r=e.context.session;if((await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId===e.body.provider))throw new De.APIError("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new De.APIError("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await ge(e,{userId:r.user.id,email:r.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});var jt=(e,r)=>{let t={};for(let[o,n]of Object.entries(e))t[o]=i=>n({...i,context:{...r,...i.context}}),t[o].path=n.path,t[o].method=n.method,t[o].options=n.options,t[o].headers=n.headers;return t};function Oe(e){let r=e;return{newRole(t){return po(t)}}}function po(e){return{statements:e,authorize(r,t){for(let[o,n]of Object.entries(r)){let i=e[o];return i?(t==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var mo={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},xe=Oe(mo),fo=xe.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),go=xe.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),ho=xe.newRole({organization:[],member:[],invitation:[]}),Bt={admin:fo,owner:go,member:ho};var yo={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},wo=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Mt={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},bo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Oo(e){return e instanceof Date&&!isNaN(e.getTime())}function Ao(e){let r=bo.exec(e);if(!r)return null;let[,t,o,n,i,s,a,d,c,l,m]=r,h=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),d?parseInt(d.padEnd(3,"0"),10):0));if(c){let y=(parseInt(l,10)*60+parseInt(m,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+y)}return Oo(h)?h:null}function Io(e,r={}){let{strict:t=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=r;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in Mt)return Mt[a];if(!wo.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(yo).some(([c,l])=>{let m=l.test(s);return m&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${c} pattern`),m})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(l,m)=>{if(l==="__proto__"||l==="constructor"&&m&&typeof m=="object"&&"prototype"in m){o&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(i&&typeof m=="string"){let h=Ao(m);if(h)return h}return n?n(l,m):m})}catch(c){if(t)throw c;return e}}function _o(e,r={strict:!0}){return Io(e,r)}var Vt=_o;var R=(e,r)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await t.create({model:"member",data:{organizationId:n.id,userId:o.user.id,createdAt:new Date,role:r?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!n)return null;let i=await t.findOne({model:"member",where:[{field:"organizationId",value:o.organizationId},{field:"userId",value:n.id}]});return i?{...i,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},findMemberByOrgId:async o=>{let[n,i]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await t.findOne({model:"user",where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async o=>await t.create({model:"member",data:o}),updateMember:async(o,n)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>{let i=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...n,metadata:typeof n.metadata=="object"?JSON.stringify(n.metadata):n.metadata}});return i?{...i,metadata:i.metadata?Vt(i.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:n}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:n})=>{let i=await t.findOne({model:"organization",where:[{field:n?"slug":"id",value:o}]});if(!i)return null;let[s,a]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:i.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:i.id}]})]);if(!i)return null;let d=a.map(h=>h.userId),c=await t.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),l=new Map(c.map(h=>[h.id,h])),m=a.map(h=>{let y=l.get(h.userId);if(!y)throw new F("Unexpected error: User not found for member");return{...h,user:{id:y.id,name:y.name,email:y.email,image:y.image}}});return{...i,invitations:s,members:m}},listOrganizations:async o=>{let n=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let s=q(r?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};var nd=require("better-call");var U=Y(async e=>({})),z=Y({use:[C]},async e=>({session:e.context.session}));var P=require("zod");var O=require("zod");var Ft=O.z.string(),Eo=O.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),ld=O.z.object({id:O.z.string().default(G),name:O.z.string(),slug:O.z.string(),logo:O.z.string().nullish(),metadata:O.z.record(O.z.string()).or(O.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:O.z.date()}),ud=O.z.object({id:O.z.string().default(G),organizationId:O.z.string(),userId:O.z.string(),role:Ft,createdAt:O.z.date()}),pd=O.z.object({id:O.z.string().default(G),organizationId:O.z.string(),email:O.z.string(),role:Ft,status:Eo,inviterId:O.z.string(),expiresAt:O.z.date()});var E=require("better-call");var p={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_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_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only 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",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var qt=e=>u("/organization/invite-member",{method:"POST",use:[U,z],body:P.z.object({email:P.z.string({description:"The email address of the user to invite"}),role:P.z.string({description:"The role to assign to the user"}),organizationId:P.z.string({description:"The organization ID to invite the user to"}).optional(),resend:P.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user 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"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async r=>{if(!r.context.orgOptions.sendInvitationEmail)throw r.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new E.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let n=R(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)throw new E.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let s=r.context.roles[i.role];if(!s)throw new E.APIError("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await n.findMemberByEmail({email:r.body.email,organizationId:o}))throw new E.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await n.findPendingInvitation({email:r.body.email,organizationId:o})).length&&!r.body.resend)throw new E.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let l=await n.createInvitation({invitation:{role:r.body.role,email:r.body.email,organizationId:o},user:t.user}),m=await n.findOrganizationById(o);if(!m)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return await r.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:m,inviter:{...i,user:t.user}},r.request),r.json(l)}),$t=u("/organization/accept-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to accept"})}),use:[U,z],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 r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new E.APIError("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await t.createMember({organizationId:o.organizationId,userId:r.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(r.session.token,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:p.INVITATION_NOT_FOUND}})}),Ht=u("/organization/reject-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to reject"})}),use:[U,z],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:"null"}}}}}}}}}},async e=>{let r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new E.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),Gt=u("/organization/cancel-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to cancel"})}),use:[U,z],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new E.APIError("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:r.user.id,organizationId:o.organizationId});if(!n)throw new E.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),Zt=u("/organization/get-invitation",{method:"GET",use:[U],requireHeaders:!0,query:P.z.object({id:P.z.string({description:"The ID of the invitation to get"})}),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 k(e);if(!r)throw new E.APIError("UNAUTHORIZED",{message:"Not authenticated"});let t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new E.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.findOrganizationById(o.organizationId);if(!n)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let i=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new E.APIError("BAD_REQUEST",{message:p.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});var B=require("zod");var J=require("better-call");var Wt=()=>u("/organization/add-member",{method:"POST",body:B.z.object({userId:B.z.string(),role:B.z.string(),organizationId:B.z.string().optional()}),use:[U],metadata:{SERVER_ONLY:!0}},async e=>{let r=e.body.userId?await k(e).catch(a=>null):null,t=e.body.organizationId||r?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=R(e.context,e.context.orgOptions),n=await e.context.internalAdapter.findUserById(e.body.userId);if(!n)throw new J.APIError("BAD_REQUEST",{message:f.USER_NOT_FOUND});if(await o.findMemberByEmail({email:n.email,organizationId:t}))throw new J.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:G(),organizationId:t,userId:n.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Qt=u("/organization/remove-member",{method:"POST",body:B.z.object({memberIdOrEmail:B.z.string({description:"The ID or email of the member to remove"}),organizationId:B.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[U,z],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 r=e.context.session,t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)throw new J.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let i=e.context.roles[n.role];if(!i)throw new J.APIError("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});let s=r.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new J.APIError("BAD_REQUEST",{message:p.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||i.authorize({member:["delete"]}).success))throw new J.APIError("UNAUTHORIZED",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):c=await o.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==t)throw new J.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});return await o.deleteMember(c.id),r.user.id===c.userId&&r.session.activeOrganizationId===c.organizationId&&await o.setActiveOrganization(r.session.token,null),e.json({member:c})}),Yt=e=>u("/organization/update-member-role",{method:"POST",body:B.z.object({role:B.z.string(),memberId:B.z.string(),organizationId:B.z.string().optional()}),use:[U,z],metadata:{openapi:{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 r=>{let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)return r.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=R(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)return r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}});let s=r.context.roles[i.role];if(!s)return r.json(null,{status:400,body:{message:p.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||r.body.role==="owner"&&i.role!=="owner")return r.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(r.body.memberId,r.body.role);return d?r.json(d):r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})}),Kt=u("/organization/get-active-member",{method:"GET",use:[U,z],metadata:{openapi:{description:"Get the active member in the 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 r=e.context.session,t=r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=await R(e.context,e.context.orgOptions).findMemberByOrgId({userId:r.user.id,organizationId:t});return n?e.json(n):e.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})});var w=require("zod");var W=require("better-call");var Jt=u("/organization/create",{method:"POST",body:w.z.object({name:w.z.string({description:"The name of the organization"}),slug:w.z.string({description:"The slug of the organization"}),userId:w.z.string({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."}).optional(),logo:w.z.string({description:"The logo of the organization"}).optional(),metadata:w.z.record(w.z.string(),w.z.any(),{description:"The metadata of the organization"}).optional()}),use:[U],metadata:{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=await k(e);if(!r&&(e.request||e.headers))throw new W.APIError("UNAUTHORIZED");let t=r?.user||null;if(!t){if(!e.body.userId)throw new W.APIError("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new W.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let i=R(e.context,o),s=await i.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new W.APIError("FORBIDDEN",{message:p.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await i.findOrganizationBySlug(e.body.slug))throw new W.APIError("BAD_REQUEST",{message:p.ORGANIZATION_ALREADY_EXISTS});let c=await i.createOrganization({organization:{id:G(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await i.setActiveOrganization(e.context.session.session.token,c.id),e.json(c)}),Xt=u("/organization/update",{method:"POST",body:w.z.object({data:w.z.object({name:w.z.string({description:"The name of the organization"}).optional(),slug:w.z.string({description:"The slug of the organization"}).optional(),logo:w.z.string({description:"The logo of the organization"}).optional(),metadata:w.z.record(w.z.string(),w.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:w.z.string().optional()}),requireHeaders:!0,use:[U],metadata:{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 r=await e.context.getSession(e);if(!r)throw new W.APIError("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:p.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let a=await o.updateOrganization(t,e.body.data);return e.json(a)}),er=u("/organization/delete",{method:"POST",body:w.z.object({organizationId:w.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[U],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=>{let r=await e.context.getSession(e);if(!r)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new W.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.token,null),await o.deleteOrganization(t),e.json(t)}),tr=u("/organization/get-full-organization",{method:"GET",query:w.z.optional(w.z.object({organizationId:w.z.string({description:"The organization id to get"}).optional(),organizationSlug:w.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[U,z],metadata:{openapi:{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 r=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let n=await R(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!n)throw new W.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return e.json(n)}),rr=u("/organization/set-active",{method:"POST",body:w.z.object({organizationId:w.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:w.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[z,U],metadata:{openapi:{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 r=R(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let d=await r.setActiveOrganization(t.session.token,null);return await v(e,{session:d,user:t.user}),e.json(null)}if(!o){let a=t.session.activeOrganizationId;if(!a)return e.json(null);o=a}let n=await r.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!n?.members.find(a=>a.userId===t.user.id))throw await r.setActiveOrganization(t.session.token,null),new W.APIError("FORBIDDEN",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await r.setActiveOrganization(t.session.token,o);return await v(e,{session:s,user:t.user}),e.json(n)}),or=u("/organization/list",{method:"GET",use:[U,z],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,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var Ro=Oe({name:["action"]}),Wd=Ro.newRole({name:["action"]}),To=e=>{let r={createOrganization:Jt,updateOrganization:Xt,deleteOrganization:er,setActiveOrganization:rr,getFullOrganization:tr,listOrganizations:or,createInvitation:qt(e),cancelInvitation:Gt,acceptInvitation:$t,getInvitation:Zt,rejectInvitation:Ht,addMember:Wt(),removeMember:Qt,updateMemberRole:Yt(e),getActiveMember:Kt},t={...Bt,...e?.roles};return{id:"organization",endpoints:{...jt(r,{orgOptions:e||{},roles:t,getSession:async n=>await k(n)}),hasPermission:u("/organization/has-permission",{method:"POST",requireHeaders:!0,body:ae.z.object({permission:ae.z.record(ae.z.string(),ae.z.array(ae.z.string()))}),use:[z],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async n=>{if(!n.context.session.session.activeOrganizationId)throw new Ce.APIError("BAD_REQUEST",{message:p.NO_ACTIVE_ORGANIZATION});let s=await R(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!s)throw new Ce.APIError("UNAUTHORIZED",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let d=t[s.role].authorize(n.body.permission);return d.error?n.json({error:d.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}},$ERROR_CODES:p}};0&&(module.exports={organization});
82
+ </html>`,jr=u("/error",{method:"GET",metadata:{...re,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let r=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Cr(r),{headers:{"Content-Type":"text/html"}})});var Br=_e(require("defu"),1);var Mr=require("better-call");async function we(e,{userInfo:r,account:t,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(r.email.toLowerCase(),{includeAccounts:!0}).catch(d=>{throw M.error(`Better auth was unable to query your database.
83
+ Error: `,d),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let d=n.accounts.find(c=>c.providerId===t.providerId);if(d){let c=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([l,m])=>m!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(d.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!r.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Re&&M.warn(`User already exist but account isn't linked to ${t.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:t.providerId,accountId:r.id.toString(),userId:n.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(m){return M.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...r,updatedAt:new Date})}}else if(i=await e.context.internalAdapter.createOAuthUser({...r,email:r.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:r.id.toString()}).then(d=>d?.user),!r.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await Q(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let a=await e.context.internalAdapter.createSession(i.id,e.request);return a?{data:{session:a,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Vr=u("/sign-in/social",{method:"POST",query:I.z.object({currentURL:I.z.string().optional()}).optional(),body:I.z.object({callbackURL:I.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:I.z.string().optional(),errorCallbackURL:I.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:I.z.enum(he,{description:"OAuth2 provider to use"}),disableRedirect:I.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:I.z.optional(I.z.object({token:I.z.string({description:"ID token from the provider"}),nonce:I.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:I.z.string({description:"Access token from the provider"}).optional(),refreshToken:I.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:I.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let r=e.context.socialProviders.find(i=>i.id===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}),new S.APIError("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new S.APIError("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await r.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_TOKEN});let d=await r.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new S.APIError("UNAUTHORIZED",{message:f.USER_EMAIL_NOT_FOUND});let c=await we(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:r.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new S.APIError("UNAUTHORIZED",{message:c.error});return await v(e,c.data),e.json({session:c.data.session,user:c.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await ge(e),n=await r.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Fr=u("/sign-in/email",{method:"POST",body:I.z.object({email:I.z.string({description:"Email of the user"}),password:I.z.string({description:"Password of the user"}),callbackURL:I.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:I.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},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!"),new S.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:r,password:t}=e.body;if(!I.z.string().email().safeParse(r).success)throw new S.APIError("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!n)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:r}),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new S.APIError("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new S.APIError("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let c=await Q(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:c},e.request),e.context.logger.error("Email not verified",{email:r}),new S.APIError("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new S.APIError("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await v(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var ie=require("zod");var be=ie.z.object({code:ie.z.string().optional(),error:ie.z.string().optional(),error_description:ie.z.string().optional(),state:ie.z.string().optional()}),qr=u("/callback/:id",{method:["GET","POST"],body:be.optional(),query:be.optional(),metadata:re},async e=>{let r;try{if(e.method==="GET")r=be.parse(e.query);else if(e.method==="POST")r=be.parse(e.body);else throw new Error("Unsupported method")}catch(x){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",x),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:n,error_description:i}=r;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(x=>x.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:d,link:c,errorURL:l,newUserURL:m}=await Qe(e),h;try{h=await s.validateAuthorizationCode({code:t,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(x){throw e.context.logger.error("",x),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(h).then(x=>x?.user);function _(x){let V=l||d||`${e.context.baseURL}/error`;throw V.includes("?")?V=`${V}&error=${x}`:V=`${V}?error=${x}`,e.redirect(V)}if(!y)return e.context.logger.error("Unable to get user info"),_("unable_to_get_user_info");if(!y.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),_("email_not_found");if(!d)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==y.email.toLowerCase())return _("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:s.id,accountId:y.id}))return _("unable_to_link_account");let V;try{V=d.toString()}catch{V=d}throw e.redirect(V)}let N=await we(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...h,scope:h.scopes?.join(",")},callbackURL:d});if(N.error)return e.context.logger.error(N.error.split(" ").join("_")),_(N.error.split(" ").join("_"));let{session:je,user:Ae}=N.data;await v(e,{session:je,user:Ae});let Ie;try{Ie=(N.isRegister&&m||d).toString()}catch{Ie=N.isRegister&&m||d}throw e.redirect(Ie)});var Ys=require("zod");var Nt=require("better-call");var $r=u("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)throw $(e),new Nt.APIError("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(r),$(e),e.json({success:!0})});var D=require("zod");var se=require("better-call");function Lt(e,r,t){let o=r?new URL(r,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function to(e,r,t){let o=new URL(r,e.baseURL);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Hr=u("/forget-password",{method:"POST",body:D.z.object({email:D.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.z.string({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:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new se.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:r,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:r}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=G(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Gr=u("/reset-password/:token",{method:"GET",query:D.z.object({callbackURL:D.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:r}=e.params,{callbackURL:t}=e.query;if(!r||!t)throw e.redirect(Lt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${r}`);throw!o||o.expiresAt<new Date?e.redirect(Lt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(to(e.context,t,{token:r}))}),Zr=u("/reset-password",{query:D.z.optional(D.z.object({token:D.z.string().optional(),currentURL:D.z.string().optional()})),method:"POST",body:D.z.object({newPassword:D.z.string({description:"The new password to set"}),token:D.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!r)throw new se.APIError("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new se.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(t.length>n)throw new se.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${r}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new se.APIError("BAD_REQUEST",{message:f.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let a=s.value,d=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(a)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(a,d),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:d,accountId:a}),e.json({status:!0}))});var L=require("zod");var T=require("better-call");var ao=require("@noble/ciphers/chacha"),Pe=require("@noble/ciphers/utils"),co=require("@noble/ciphers/webcrypto"),lo=require("oslo/crypto"),uo=_e(require("uncrypto"),1);var Pt=require("oslo/encoding");var ro=require("@noble/hashes/scrypt"),oo=require("uncrypto");var Le=_e(require("uncrypto"),1);function no(e){return e.toString(2).padStart(8,"0")}function io(e){return[...e].map(r=>no(r)).join("")}function Dt(e){return parseInt(io(e),2)}function so(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let r=(e-1).toString(2).length,t=r%8,o=new Uint8Array(Math.ceil(r/8));Le.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let n=Dt(o);for(;n>=e;)Le.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),n=Dt(o);return n}function xt(e,r){let t="";for(let o=0;o<e;o++)t+=r[so(r.length)];return t}function Ct(...e){let r=new Set(e),t="";for(let o of r)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}var Wr=u("/change-password",{method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),currentPassword:L.z.string({description:"The current password"}),revokeOtherSessions:L.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[C],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:r,currentPassword:t,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(r.length<i)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(r.length>s)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!d||!d.password)throw new T.APIError("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(r);if(!await e.context.password.verify({hash:d.password,password:t}))throw new T.APIError("BAD_REQUEST",{message:f.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await v(e,{session:m,user:n.user})}return e.json(n.user)}),Qr=u("/set-password",{method:"POST",body:L.z.object({newPassword:L.z.string()}),metadata:{SERVER_ONLY:!0},use:[C]},async e=>{let{newPassword:r}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(r.length<o)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(r.length>n)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(r);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:a}),e.json(t.user);throw new T.APIError("BAD_REQUEST",{message:"user already has a password"})}),Yr=u("/delete-user",{method:"POST",use:[St],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new T.APIError("NOT_FOUND");let r=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=xt(32,Ct("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Kr=u("/delete-user/callback",{method:"GET",query:L.z.object({token:L.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new T.APIError("NOT_FOUND");let r=await k(e);if(!r)throw new T.APIError("NOT_FOUND",{message:f.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new T.APIError("NOT_FOUND",{message:f.INVALID_TOKEN});if(t.value!==r.user.id)throw new T.APIError("NOT_FOUND",{message:f.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),$(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Jr=u("/change-email",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({newEmail:L.z.string({description:"The new email to set"}).email(),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[C],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new T.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new T.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await Q(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});var ae=require("zod");var De=require("better-call");var Xr=u("/list-accounts",{method:"GET",use:[C],metadata:{openapi:{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"},provider:{type:"string"}}}}}}}}}}},async e=>{let r=e.context.session,t=await e.context.internalAdapter.findAccounts(r.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),eo=u("/link-social",{method:"POST",requireHeaders:!0,query:ae.z.object({currentURL:ae.z.string().optional()}).optional(),body:ae.z.object({callbackURL:ae.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:ae.z.enum(he,{description:"The OAuth2 provider to use"})}),use:[C],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let r=e.context.session;if((await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId===e.body.provider))throw new De.APIError("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new De.APIError("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await ge(e,{userId:r.user.id,email:r.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});var jt=(e,r)=>{let t={};for(let[o,n]of Object.entries(e))t[o]=i=>n({...i,context:{...r,...i.context}}),t[o].path=n.path,t[o].method=n.method,t[o].options=n.options,t[o].headers=n.headers;return t};function Oe(e){let r=e;return{newRole(t){return po(t)}}}function po(e){return{statements:e,authorize(r,t){for(let[o,n]of Object.entries(r)){let i=e[o];return i?(t==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var mo={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},xe=Oe(mo),fo=xe.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),go=xe.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),ho=xe.newRole({organization:[],member:[],invitation:[]}),Bt={admin:fo,owner:go,member:ho};var yo={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},wo=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Mt={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},bo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Oo(e){return e instanceof Date&&!isNaN(e.getTime())}function Ao(e){let r=bo.exec(e);if(!r)return null;let[,t,o,n,i,s,a,d,c,l,m]=r,h=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),d?parseInt(d.padEnd(3,"0"),10):0));if(c){let y=(parseInt(l,10)*60+parseInt(m,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+y)}return Oo(h)?h:null}function Io(e,r={}){let{strict:t=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=r;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in Mt)return Mt[a];if(!wo.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(yo).some(([c,l])=>{let m=l.test(s);return m&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${c} pattern`),m})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(l,m)=>{if(l==="__proto__"||l==="constructor"&&m&&typeof m=="object"&&"prototype"in m){o&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(i&&typeof m=="string"){let h=Ao(m);if(h)return h}return n?n(l,m):m})}catch(c){if(t)throw c;return e}}function _o(e,r={strict:!0}){return Io(e,r)}var Vt=_o;var R=(e,r)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await t.create({model:"member",data:{organizationId:n.id,userId:o.user.id,createdAt:new Date,role:r?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!n)return null;let i=await t.findOne({model:"member",where:[{field:"organizationId",value:o.organizationId},{field:"userId",value:n.id}]});return i?{...i,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},findMemberByOrgId:async o=>{let[n,i]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await t.findOne({model:"user",where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async o=>await t.create({model:"member",data:o}),updateMember:async(o,n)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>{let i=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...n,metadata:typeof n.metadata=="object"?JSON.stringify(n.metadata):n.metadata}});return i?{...i,metadata:i.metadata?Vt(i.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:n}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:n})=>{let i=await t.findOne({model:"organization",where:[{field:n?"slug":"id",value:o}]});if(!i)return null;let[s,a]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:i.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:i.id}]})]);if(!i)return null;let d=a.map(h=>h.userId),c=await t.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),l=new Map(c.map(h=>[h.id,h])),m=a.map(h=>{let y=l.get(h.userId);if(!y)throw new F("Unexpected error: User not found for member");return{...h,user:{id:y.id,name:y.name,email:y.email,image:y.image}}});return{...i,invitations:s,members:m}},listOrganizations:async o=>{let n=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let s=q(r?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};var nd=require("better-call");var U=Y(async e=>({})),z=Y({use:[C]},async e=>({session:e.context.session}));var P=require("zod");var O=require("zod");var Ft=O.z.string(),Eo=O.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),ld=O.z.object({id:O.z.string().default(G),name:O.z.string(),slug:O.z.string(),logo:O.z.string().nullish(),metadata:O.z.record(O.z.string()).or(O.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:O.z.date()}),ud=O.z.object({id:O.z.string().default(G),organizationId:O.z.string(),userId:O.z.string(),role:Ft,createdAt:O.z.date()}),pd=O.z.object({id:O.z.string().default(G),organizationId:O.z.string(),email:O.z.string(),role:Ft,status:Eo,inviterId:O.z.string(),expiresAt:O.z.date()});var E=require("better-call");var p={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_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_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only 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",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var qt=e=>u("/organization/invite-member",{method:"POST",use:[U,z],body:P.z.object({email:P.z.string({description:"The email address of the user to invite"}),role:P.z.string({description:"The role to assign to the user"}),organizationId:P.z.string({description:"The organization ID to invite the user to"}).optional(),resend:P.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user 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"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async r=>{if(!r.context.orgOptions.sendInvitationEmail)throw r.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new E.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let n=R(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)throw new E.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let s=r.context.roles[i.role];if(!s)throw new E.APIError("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await n.findMemberByEmail({email:r.body.email,organizationId:o}))throw new E.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await n.findPendingInvitation({email:r.body.email,organizationId:o})).length&&!r.body.resend)throw new E.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let l=await n.createInvitation({invitation:{role:r.body.role,email:r.body.email,organizationId:o},user:t.user}),m=await n.findOrganizationById(o);if(!m)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return await r.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:m,inviter:{...i,user:t.user}},r.request),r.json(l)}),$t=u("/organization/accept-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to accept"})}),use:[U,z],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 r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new E.APIError("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await t.createMember({organizationId:o.organizationId,userId:r.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(r.session.token,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:p.INVITATION_NOT_FOUND}})}),Ht=u("/organization/reject-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to reject"})}),use:[U,z],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:"null"}}}}}}}}}},async e=>{let r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new E.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),Gt=u("/organization/cancel-invitation",{method:"POST",body:P.z.object({invitationId:P.z.string({description:"The ID of the invitation to cancel"})}),use:[U,z],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let r=e.context.session,t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new E.APIError("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:r.user.id,organizationId:o.organizationId});if(!n)throw new E.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),Zt=u("/organization/get-invitation",{method:"GET",use:[U],requireHeaders:!0,query:P.z.object({id:P.z.string({description:"The ID of the invitation to get"})}),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 k(e);if(!r)throw new E.APIError("UNAUTHORIZED",{message:"Not authenticated"});let t=R(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new E.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new E.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.findOrganizationById(o.organizationId);if(!n)throw new E.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let i=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new E.APIError("BAD_REQUEST",{message:p.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});var B=require("zod");var J=require("better-call");var Wt=()=>u("/organization/add-member",{method:"POST",body:B.z.object({userId:B.z.string(),role:B.z.string(),organizationId:B.z.string().optional()}),use:[U],metadata:{SERVER_ONLY:!0}},async e=>{let r=e.body.userId?await k(e).catch(a=>null):null,t=e.body.organizationId||r?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=R(e.context,e.context.orgOptions),n=await e.context.internalAdapter.findUserById(e.body.userId);if(!n)throw new J.APIError("BAD_REQUEST",{message:f.USER_NOT_FOUND});if(await o.findMemberByEmail({email:n.email,organizationId:t}))throw new J.APIError("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:G(),organizationId:t,userId:n.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Qt=u("/organization/remove-member",{method:"POST",body:B.z.object({memberIdOrEmail:B.z.string({description:"The ID or email of the member to remove"}),organizationId:B.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[U,z],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 r=e.context.session,t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)throw new J.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let i=e.context.roles[n.role];if(!i)throw new J.APIError("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});let s=r.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new J.APIError("BAD_REQUEST",{message:p.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||i.authorize({member:["delete"]}).success))throw new J.APIError("UNAUTHORIZED",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):c=await o.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==t)throw new J.APIError("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});return await o.deleteMember(c.id),r.user.id===c.userId&&r.session.activeOrganizationId===c.organizationId&&await o.setActiveOrganization(r.session.token,null),e.json({member:c})}),Yt=e=>u("/organization/update-member-role",{method:"POST",body:B.z.object({role:B.z.string(),memberId:B.z.string(),organizationId:B.z.string().optional()}),use:[U,z],metadata:{openapi:{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 r=>{let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)return r.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=R(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)return r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}});let s=r.context.roles[i.role];if(!s)return r.json(null,{status:400,body:{message:p.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||r.body.role==="owner"&&i.role!=="owner")return r.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(r.body.memberId,r.body.role);return d?r.json(d):r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})}),Kt=u("/organization/get-active-member",{method:"GET",use:[U,z],metadata:{openapi:{description:"Get the active member in the 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 r=e.context.session,t=r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=await R(e.context,e.context.orgOptions).findMemberByOrgId({userId:r.user.id,organizationId:t});return n?e.json(n):e.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})});var w=require("zod");var W=require("better-call");var Jt=u("/organization/create",{method:"POST",body:w.z.object({name:w.z.string({description:"The name of the organization"}),slug:w.z.string({description:"The slug of the organization"}),userId:w.z.string({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."}).optional(),logo:w.z.string({description:"The logo of the organization"}).optional(),metadata:w.z.record(w.z.string(),w.z.any(),{description:"The metadata of the organization"}).optional()}),use:[U],metadata:{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=await k(e);if(!r&&(e.request||e.headers))throw new W.APIError("UNAUTHORIZED");let t=r?.user||null;if(!t){if(!e.body.userId)throw new W.APIError("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new W.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let i=R(e.context,o),s=await i.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new W.APIError("FORBIDDEN",{message:p.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await i.findOrganizationBySlug(e.body.slug))throw new W.APIError("BAD_REQUEST",{message:p.ORGANIZATION_ALREADY_EXISTS});let c=await i.createOrganization({organization:{id:G(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await i.setActiveOrganization(e.context.session.session.token,c.id),e.json(c)}),Xt=u("/organization/update",{method:"POST",body:w.z.object({data:w.z.object({name:w.z.string({description:"The name of the organization"}).optional(),slug:w.z.string({description:"The slug of the organization"}).optional(),logo:w.z.string({description:"The logo of the organization"}).optional(),metadata:w.z.record(w.z.string(),w.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:w.z.string().optional()}),requireHeaders:!0,use:[U],metadata:{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 r=await e.context.getSession(e);if(!r)throw new W.APIError("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:p.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let a=await o.updateOrganization(t,e.body.data);return e.json(a)}),er=u("/organization/delete",{method:"POST",body:w.z.object({organizationId:w.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[U],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=>{let r=await e.context.getSession(e);if(!r)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=R(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new W.APIError("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.token,null),await o.deleteOrganization(t),e.json(t)}),tr=u("/organization/get-full-organization",{method:"GET",query:w.z.optional(w.z.object({organizationId:w.z.string({description:"The organization id to get"}).optional(),organizationSlug:w.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[U,z],metadata:{openapi:{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 r=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let n=await R(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!n)throw new W.APIError("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return e.json(n)}),rr=u("/organization/set-active",{method:"POST",body:w.z.object({organizationId:w.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:w.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[z,U],metadata:{openapi:{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 r=R(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let d=await r.setActiveOrganization(t.session.token,null);return await v(e,{session:d,user:t.user}),e.json(null)}if(!o){let a=t.session.activeOrganizationId;if(!a)return e.json(null);o=a}let n=await r.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!n?.members.find(a=>a.userId===t.user.id))throw await r.setActiveOrganization(t.session.token,null),new W.APIError("FORBIDDEN",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await r.setActiveOrganization(t.session.token,o);return await v(e,{session:s,user:t.user}),e.json(n)}),or=u("/organization/list",{method:"GET",use:[U,z],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,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var Ro=Oe({name:["action"]}),Qd=Ro.newRole({name:["action"]}),To=e=>{let r={createOrganization:Jt,updateOrganization:Xt,deleteOrganization:er,setActiveOrganization:rr,getFullOrganization:tr,listOrganizations:or,createInvitation:qt(e),cancelInvitation:Gt,acceptInvitation:$t,getInvitation:Zt,rejectInvitation:Ht,addMember:Wt(),removeMember:Qt,updateMemberRole:Yt(e),getActiveMember:Kt},t={...Bt,...e?.roles};return{id:"organization",endpoints:{...jt(r,{orgOptions:e||{},roles:t,getSession:async n=>await k(n)}),hasPermission:u("/organization/has-permission",{method:"POST",requireHeaders:!0,body:ee.z.object({organizationId:ee.z.string().optional(),permission:ee.z.record(ee.z.string(),ee.z.array(ee.z.string()))}),use:[z],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async n=>{let i=n.body.organizationId||n.context.session.session.activeOrganizationId;if(!i)throw new Ce.APIError("BAD_REQUEST",{message:p.NO_ACTIVE_ORGANIZATION});let a=await R(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:i});if(!a)throw new Ce.APIError("UNAUTHORIZED",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let c=t[a.role].authorize(n.body.permission);return c.error?n.json({error:c.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}},$ERROR_CODES:p}};0&&(module.exports={organization});
@@ -1,4 +1,4 @@
1
- export { O as OrganizationOptions, o as organization } from '../index-CgaJXZ9u.cjs';
1
+ export { O as OrganizationOptions, o as organization } from '../index-Dp04oxSM.cjs';
2
2
  import 'zod';
3
3
  import '../schema-DG_8mn16.cjs';
4
4
  import 'better-call';
@@ -1,4 +1,4 @@
1
- export { O as OrganizationOptions, o as organization } from '../index-Dt4lZbQi.js';
1
+ export { O as OrganizationOptions, o as organization } from '../index-Dd3_WG87.js';
2
2
  import 'zod';
3
3
  import '../schema-DG_8mn16.js';
4
4
  import 'better-call';