better-auth 0.5.2-beta.11 → 0.5.2-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)T(e,s,{get:t[s],enumerable:!0})},V=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of G(t))!H.call(e,r)&&r!==s&&T(e,r,{get:()=>t[r],enumerable:!(i=M(t,r))||i.enumerable});return e};var z=e=>V(T({},"__esModule",{value:!0}),e);var K={};j(K,{capitalizeFirstLetter:()=>$,createAuthClient:()=>D,useAuthQuery:()=>J});module.exports=z(K);var P=require("@nanostores/react");var x=require("@better-fetch/fetch");var d=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function N(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function O(e,t="/api/auth"){return N(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function F(e,t){if(e)return O(e,t);let s=typeof process<"u"?process.env:{},i=s.BETTER_AUTH_URL||s.NEXT_PUBLIC_BETTER_AUTH_URL||s.PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_AUTH_URL||(s.BASE_URL!=="/"?s.BASE_URL:void 0);if(i)return O(i,t);if(typeof window<"u")return O(window.location.origin,t)}var ie=require("nanostores");var B=require("@better-fetch/fetch");var C={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},L={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},S={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,B.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var w=e=>{let t=(0,x.createFetch)({baseURL:F(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[S],C,L,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function Q(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function I(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(R=>R.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)).join("/"),f=l[0]||{},U=l[1]||{},{query:p,fetchOptions:g,...v}=f,h={...U,...g},b=Q(a,s,f);return await t(a,{...h,body:b==="GET"?void 0:{...v,...h?.body||{}},query:p||h?.query,method:b,async onSuccess(R){await h?.onSuccess?.(R);let m=r?.find(q=>q.matcher(a));if(!m)return;let A=i[m.signal];if(!A)return;let W=A.get();setTimeout(()=>{A.set(!W)},10)}})}})}return u()}var k=require("nanostores");var ue=require("@better-fetch/fetch"),y=require("nanostores"),E=(e,t,s,i)=>{let r=(0,y.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,y.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function _(e){let t=(0,k.atom)(!1);return{$session:E(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function X(e){return`use${$(e)}`}function $(e){return e.charAt(0).toUpperCase()+e.slice(1)}function D(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=w(e),o={};for(let[p,g]of Object.entries(i))o[X(p)]=()=>(0,P.useStore)(g);let{$session:n,_sessionSignal:c,$Infer:l}=_(r);function a(p){return(0,P.useStore)(n)}let f={...s,...o,useSession:a};return I(f,r,t,{...i,_sessionSignal:c},u)}var J=P.useStore;0&&(module.exports={capitalizeFirstLetter,createAuthClient,useAuthQuery});
1
+ "use strict";var O=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var s in t)O(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of H(t))!j.call(e,r)&&r!==s&&O(e,r,{get:()=>t[r],enumerable:!(i=G(t,r))||i.enumerable});return e};var N=e=>z(O({},"__esModule",{value:!0}),e);var Z={};V(Z,{capitalizeFirstLetter:()=>v,createAuthClient:()=>J,useAuthQuery:()=>K});module.exports=N(Z);var R=require("@nanostores/react");var w=require("@better-fetch/fetch");var f=require("std-env");var p=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function Q(e){try{return new URL(e).pathname!=="/"}catch{throw new p(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function U(e,t="/api/auth"){return Q(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function B(e,t){if(e)return U(e,t);let s=f.env.BETTER_AUTH_URL||f.env.NEXT_PUBLIC_BETTER_AUTH_URL||f.env.PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_AUTH_URL||(f.env.BASE_URL!=="/"?f.env.BASE_URL:void 0);if(s)return U(s,t);if(typeof window<"u")return U(window.location.origin,t)}var oe=require("nanostores");var C=require("@better-fetch/fetch");var L={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},S={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},x={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,C.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new p("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new p("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var I=e=>{let t=(0,w.createFetch)({baseURL:B(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[x],L,S,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function X(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function E(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let d of l)if(a&&typeof a=="object"&&d in a)a=a[d];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(A=>A.replace(/[A-Z]/g,y=>`-${y.toLowerCase()}`)).join("/"),d=l[0]||{},b=l[1]||{},{query:g,fetchOptions:h,...W}=d,m={...b,...h},F=X(a,s,d);return await t(a,{...m,body:F==="GET"?void 0:{...W,...m?.body||{}},query:g||m?.query,method:F,async onSuccess(A){await m?.onSuccess?.(A);let y=r?.find(M=>M.matcher(a));if(!y)return;let T=i[y.signal];if(!T)return;let q=T.get();setTimeout(()=>{T.set(!q)},10)}})}})}return u()}var _=require("nanostores");var le=require("@better-fetch/fetch"),P=require("nanostores"),k=(e,t,s,i)=>{let r=(0,P.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,P.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function $(e){let t=(0,_.atom)(!1);return{$session:k(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function D(e){return`use${v(e)}`}function v(e){return e.charAt(0).toUpperCase()+e.slice(1)}function J(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=I(e),o={};for(let[g,h]of Object.entries(i))o[D(g)]=()=>(0,R.useStore)(h);let{$session:n,_sessionSignal:c,$Infer:l}=$(r);function a(g){return(0,R.useStore)(n)}let d={...s,...o,useSession:a};return E(d,r,t,{...i,_sessionSignal:c},u)}var K=R.useStore;0&&(module.exports={capitalizeFirstLetter,createAuthClient,useAuthQuery});
package/dist/react.d.cts CHANGED
@@ -226,7 +226,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
226
226
  hooks: {
227
227
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
228
228
  };
229
- })[] | undefined;
229
+ })[];
230
230
  cache?: RequestCache;
231
231
  credentials: RequestCredentials;
232
232
  headers?: (HeadersInit & (HeadersInit | {
@@ -289,7 +289,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
289
289
  output?: zod.ZodType | typeof Blob | typeof File;
290
290
  errorSchema?: zod.ZodType;
291
291
  disableValidation?: boolean;
292
- }, unknown, unknown, unknown>;
292
+ }, unknown, unknown, {}>;
293
293
  };
294
294
  declare const useAuthQuery: typeof useStore;
295
295
 
package/dist/react.d.ts CHANGED
@@ -226,7 +226,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
226
226
  hooks: {
227
227
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
228
228
  };
229
- })[] | undefined;
229
+ })[];
230
230
  cache?: RequestCache;
231
231
  credentials: RequestCredentials;
232
232
  headers?: (HeadersInit & (HeadersInit | {
@@ -289,7 +289,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
289
289
  output?: zod.ZodType | typeof Blob | typeof File;
290
290
  errorSchema?: zod.ZodType;
291
291
  disableValidation?: boolean;
292
- }, unknown, unknown, unknown>;
292
+ }, unknown, unknown, {}>;
293
293
  };
294
294
  declare const useAuthQuery: typeof useStore;
295
295
 
package/dist/react.js CHANGED
@@ -1 +1 @@
1
- import{useStore as A}from"@nanostores/react";import{createFetch as $}from"@better-fetch/fetch";var d=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function k(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function R(e,t="/api/auth"){return k(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function U(e,t){if(e)return R(e,t);let r=typeof process<"u"?process.env:{},i=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(i)return R(i,t);if(typeof window<"u")return R(window.location.origin,t)}import"nanostores";import{betterFetch as _}from"@better-fetch/fetch";var b={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},F={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},B={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:r,error:i}=await _("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+i.message)}let s=r?.csrfToken;t.body={...t?.body,csrfToken:s}}return t.credentials="include",{url:e,options:t}}};var C=e=>{let t=$({baseURL:U(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[B],b,F,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),r=e?.plugins||[],i={},s={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of r)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(s,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:s,pluginPathMethods:u,atomListeners:o,$fetch:t}};function v(e,t,r){let i=t[e],{fetchOptions:s,query:u,...o}=r||{};return i||(s?.method?s.method:o&&Object.keys(o).length>0?"POST":"GET")}function L(e,t,r,i,s){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(y=>y.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)).join("/"),f=l[0]||{},T=l[1]||{},{query:p,fetchOptions:g,...w}=f,h={...T,...g},O=v(a,r,f);return await t(a,{...h,body:O==="GET"?void 0:{...w,...h?.body||{}},query:p||h?.query,method:O,async onSuccess(y){await h?.onSuccess?.(y);let m=s?.find(E=>E.matcher(a));if(!m)return;let P=i[m.signal];if(!P)return;let I=P.get();setTimeout(()=>{P.set(!I)},10)}})}})}return u()}import{atom as M}from"nanostores";import"@better-fetch/fetch";import{atom as W,onMount as q}from"nanostores";var S=(e,t,r,i)=>{let s=W({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):i;return r(t,{...n,onSuccess:async c=>{s.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){s.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=s.get();s.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():q(s,()=>(u(),o=!0,()=>{s.off(),n.off()}))});return s};function x(e){let t=M(!1);return{$session:S(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function G(e){return`use${H(e)}`}function H(e){return e.charAt(0).toUpperCase()+e.slice(1)}function de(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:i,$fetch:s,atomListeners:u}=C(e),o={};for(let[p,g]of Object.entries(i))o[G(p)]=()=>A(g);let{$session:n,_sessionSignal:c,$Infer:l}=x(s);function a(p){return A(n)}let f={...r,...o,useSession:a};return L(f,s,t,{...i,_sessionSignal:c},u)}var pe=A;export{H as capitalizeFirstLetter,de as createAuthClient,pe as useAuthQuery};
1
+ import{useStore as T}from"@nanostores/react";import{createFetch as v}from"@better-fetch/fetch";import{env as p}from"std-env";var d=class extends Error{constructor(t,i){super(t),this.name="BetterAuthError",this.message=t,this.cause=i,this.stack=""}};function _(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function A(e,t="/api/auth"){return _(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function b(e,t){if(e)return A(e,t);let i=p.BETTER_AUTH_URL||p.NEXT_PUBLIC_BETTER_AUTH_URL||p.PUBLIC_BETTER_AUTH_URL||p.NUXT_PUBLIC_BETTER_AUTH_URL||p.NUXT_PUBLIC_AUTH_URL||(p.BASE_URL!=="/"?p.BASE_URL:void 0);if(i)return A(i,t);if(typeof window<"u")return A(window.location.origin,t)}import"nanostores";import{betterFetch as $}from"@better-fetch/fetch";var F={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},B={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},C={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:i,error:s}=await $("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(s){if(s.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(s.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+s.message)}let r=i?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var L=e=>{let t=v({baseURL:b(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[C],F,B,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),i=e?.plugins||[],s={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of i)n.getActions&&Object.assign(s,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:s,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function W(e,t,i){let s=t[e],{fetchOptions:r,query:u,...o}=i||{};return s||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function S(e,t,i,s,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(P=>P.replace(/[A-Z]/g,y=>`-${y.toLowerCase()}`)).join("/"),f=l[0]||{},O=l[1]||{},{query:g,fetchOptions:h,...I}=f,m={...O,...h},U=W(a,i,f);return await t(a,{...m,body:U==="GET"?void 0:{...I,...m?.body||{}},query:g||m?.query,method:U,async onSuccess(P){await m?.onSuccess?.(P);let y=r?.find(k=>k.matcher(a));if(!y)return;let R=s[y.signal];if(!R)return;let E=R.get();setTimeout(()=>{R.set(!E)},10)}})}})}return u()}import{atom as G}from"nanostores";import"@better-fetch/fetch";import{atom as q,onMount as M}from"nanostores";var x=(e,t,i,s)=>{let r=q({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof s=="function"?s({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):s;return i(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():M(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function w(e){let t=G(!1);return{$session:x(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function H(e){return`use${j(e)}`}function j(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ge(e){let{pluginPathMethods:t,pluginsActions:i,pluginsAtoms:s,$fetch:r,atomListeners:u}=L(e),o={};for(let[g,h]of Object.entries(s))o[H(g)]=()=>T(h);let{$session:n,_sessionSignal:c,$Infer:l}=w(r);function a(g){return T(n)}let f={...i,...o,useSession:a};return S(f,r,t,{...s,_sessionSignal:c},u)}var he=T;export{j as capitalizeFirstLetter,ge as createAuthClient,he as useAuthQuery};
package/dist/social.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var h=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var W=(r,t)=>{for(var e in t)h(r,e,{get:t[e],enumerable:!0})},X=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of J(t))!q.call(r,o)&&o!==e&&h(r,o,{get:()=>t[o],enumerable:!(i=M(t,o))||i.enumerable});return r};var K=r=>X(h({},"__esModule",{value:!0}),r);var ie={};W(ie,{apple:()=>b,discord:()=>y,facebook:()=>_,github:()=>A,google:()=>P,microsoft:()=>x,socialProviderList:()=>te,socialProviders:()=>N,spotify:()=>U,twitch:()=>w,twitter:()=>R});module.exports=K(ie);var L=require("oslo/jwt");var k=require("oslo/crypto");var m=class extends Error{constructor(t,e){super(t),this.name="BetterAuthError",this.message=t,this.cause=e,this.stack=""}};var O=require("oslo/encoding");async function z(r){let t=await(0,k.sha256)(new TextEncoder().encode(r));return O.base64url.encode(new Uint8Array(t),{includePadding:!1})}function I(r){return{tokenType:r.token_type,accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:r.expires_at?new Date((Date.now()+r.expires_in)*1e3):void 0,scopes:r?.scope?typeof r.scope=="string"?r.scope.split(" "):r.scope:[],idToken:r.id_token}}async function c({id:r,options:t,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:l,redirectURI:d}){let p=new URL(e);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("state",i),p.searchParams.set("scope",n.join(" ")),p.searchParams.set("redirect_uri",t.redirectURI||d),!l&&o){let g=await z(o);p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((T,H)=>(T[H]=null,T),{});p.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return p}var E=require("@better-fetch/fetch");async function a({code:r,codeVerifier:t,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",r),t&&n.set("code_verifier",t),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:l}=await(0,E.betterFetch)(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(l)throw l;return I(s)}var Q=require("oslo/oauth2"),Y=require("zod");var Z=require("oslo/crypto");var Ae=require("better-call");var b=r=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=r.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:t}),async getUserInfo(e){if(!e.idToken)return null;let i=(0,L.parseJWT)(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};var B=require("@better-fetch/fetch");var y=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,B.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});var S=require("@better-fetch/fetch");var _=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["email","public_profile"];return await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:e,error:i}=await(0,S.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});var v=require("@better-fetch/fetch");var A=r=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=r.scope||i||["user:email"];return c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:t}),async getUserInfo(e){let{data:i,error:o}=await(0,v.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:l}=await(0,v.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});l||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var $=require("oslo/jwt");var C=require("consola"),u=(0,C.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ee=r=>({log:(...t)=>{!r?.disabled&&u.log("",...t)},error:(...t)=>{!r?.disabled&&u.error("",...t)},warn:(...t)=>{!r?.disabled&&u.warn("",...t)},info:(...t)=>{!r?.disabled&&u.info("",...t)},debug:(...t)=>{!r?.disabled&&u.debug("",...t)},box:(...t)=>{!r?.disabled&&u.box("",...t)},success:(...t)=>{!r?.disabled&&u.success("",...t)},break:(...t)=>{!r?.disabled&&console.log(`
2
- `)}}),f=ee();var P=r=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new m("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new m("codeVerifier is required for Google");let n=r.scope||e||["email","profile"];return c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let e=(0,$.parseJWT)(t.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});var V=require("@better-fetch/fetch"),D=require("oslo/jwt");var x=r=>{let t=r.tenantId||"common",e=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let n=r.scope||o.scopes||["openid","profile","email","User.Read"];return c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:n,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:n,redirectURI:s}){return a({code:o,codeVerifier:n,redirectURI:r.redirectURI||s,options:r,tokenEndpoint:i})},async getUserInfo(o){if(!o.idToken)return null;let n=(0,D.parseJWT)(o.idToken)?.payload,s=r.profilePhotoSize||48;return await(0,V.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(l){if(!(r.disableProfilePhoto||!l.response.ok))try{let p=await l.response.clone().arrayBuffer(),g=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var F=require("@better-fetch/fetch");var U=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){let n=r.scope||e||["user-read-email"];return c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,F.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});var lr=require("@better-fetch/fetch");var re=require("nanoid");var G=require("oslo/jwt");var w=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["user:read:email","openid"];return c({id:"twitch",redirectURI:i,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let e=t.idToken;if(!e)return f.error("No idToken found in token"),null;let i=(0,G.parseJWT)(e)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var j=require("@better-fetch/fetch");var R=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let e=r.scope||t.scopes||["account_info.read"];return c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,j.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var N={apple:b,discord:y,facebook:_,github:A,microsoft:x,google:P,spotify:U,twitch:w,twitter:R},te=Object.keys(N);0&&(module.exports={apple,discord,facebook,github,google,microsoft,socialProviderList,socialProviders,spotify,twitch,twitter});
1
+ "use strict";var h=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var W=(r,t)=>{for(var e in t)h(r,e,{get:t[e],enumerable:!0})},X=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of J(t))!q.call(r,o)&&o!==e&&h(r,o,{get:()=>t[o],enumerable:!(i=M(t,o))||i.enumerable});return r};var K=r=>X(h({},"__esModule",{value:!0}),r);var oe={};W(oe,{apple:()=>b,discord:()=>y,facebook:()=>_,github:()=>A,google:()=>P,microsoft:()=>x,socialProviderList:()=>ie,socialProviders:()=>N,spotify:()=>U,twitch:()=>w,twitter:()=>R});module.exports=K(oe);var L=require("oslo/jwt");var k=require("oslo/crypto");var Z=require("std-env");var m=class extends Error{constructor(t,e){super(t),this.name="BetterAuthError",this.message=t,this.cause=e,this.stack=""}};var O=require("oslo/encoding");async function z(r){let t=await(0,k.sha256)(new TextEncoder().encode(r));return O.base64url.encode(new Uint8Array(t),{includePadding:!1})}function I(r){return{tokenType:r.token_type,accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:r.expires_at?new Date((Date.now()+r.expires_in)*1e3):void 0,scopes:r?.scope?typeof r.scope=="string"?r.scope.split(" "):r.scope:[],idToken:r.id_token}}async function c({id:r,options:t,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:p,redirectURI:d}){let l=new URL(e);if(l.searchParams.set("response_type","code"),l.searchParams.set("client_id",t.clientId),l.searchParams.set("state",i),l.searchParams.set("scope",n.join(" ")),l.searchParams.set("redirect_uri",t.redirectURI||d),!p&&o){let g=await z(o);l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((T,H)=>(T[H]=null,T),{});l.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return l}var E=require("@better-fetch/fetch");async function a({code:r,codeVerifier:t,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",r),t&&n.set("code_verifier",t),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:p}=await(0,E.betterFetch)(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(p)throw p;return I(s)}var Y=require("oslo/oauth2"),ee=require("zod");var Q=require("oslo/crypto");var Pe=require("better-call");var b=r=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=r.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:t}),async getUserInfo(e){if(!e.idToken)return null;let i=(0,L.parseJWT)(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};var B=require("@better-fetch/fetch");var y=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,B.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});var S=require("@better-fetch/fetch");var _=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["email","public_profile"];return await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:e,error:i}=await(0,S.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});var v=require("@better-fetch/fetch");var A=r=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=r.scope||i||["user:email"];return c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:t}),async getUserInfo(e){let{data:i,error:o}=await(0,v.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:p}=await(0,v.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});p||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var $=require("oslo/jwt");var C=require("consola"),u=(0,C.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),re=r=>({log:(...t)=>{!r?.disabled&&u.log("",...t)},error:(...t)=>{!r?.disabled&&u.error("",...t)},warn:(...t)=>{!r?.disabled&&u.warn("",...t)},info:(...t)=>{!r?.disabled&&u.info("",...t)},debug:(...t)=>{!r?.disabled&&u.debug("",...t)},box:(...t)=>{!r?.disabled&&u.box("",...t)},success:(...t)=>{!r?.disabled&&u.success("",...t)},break:(...t)=>{!r?.disabled&&console.log(`
2
+ `)}}),f=re();var P=r=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new m("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new m("codeVerifier is required for Google");let n=r.scope||e||["email","profile"];return c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let e=(0,$.parseJWT)(t.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});var V=require("@better-fetch/fetch"),D=require("oslo/jwt");var x=r=>{let t=r.tenantId||"common",e=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let n=r.scope||o.scopes||["openid","profile","email","User.Read"];return c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:n,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:n,redirectURI:s}){return a({code:o,codeVerifier:n,redirectURI:r.redirectURI||s,options:r,tokenEndpoint:i})},async getUserInfo(o){if(!o.idToken)return null;let n=(0,D.parseJWT)(o.idToken)?.payload,s=r.profilePhotoSize||48;return await(0,V.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(p){if(!(r.disableProfilePhoto||!p.response.ok))try{let l=await p.response.clone().arrayBuffer(),g=Buffer.from(l).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var F=require("@better-fetch/fetch");var U=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){let n=r.scope||e||["user-read-email"];return c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,F.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});var dr=require("@better-fetch/fetch");var te=require("nanoid");var G=require("oslo/jwt");var w=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["user:read:email","openid"];return c({id:"twitch",redirectURI:i,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let e=t.idToken;if(!e)return f.error("No idToken found in token"),null;let i=(0,G.parseJWT)(e)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var j=require("@better-fetch/fetch");var R=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let e=r.scope||t.scopes||["account_info.read"];return c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await(0,j.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var N={apple:b,discord:y,facebook:_,github:A,microsoft:x,google:P,spotify:U,twitch:w,twitter:R},ie=Object.keys(N);0&&(module.exports={apple,discord,facebook,github,google,microsoft,socialProviderList,socialProviders,spotify,twitch,twitter});
package/dist/social.js CHANGED
@@ -1,2 +1,2 @@
1
- import{parseJWT as L}from"oslo/jwt";import{sha256 as z}from"oslo/crypto";var m=class extends Error{constructor(t,e){super(t),this.name="BetterAuthError",this.message=t,this.cause=e,this.stack=""}};import{base64url as I}from"oslo/encoding";async function b(r){let t=await z(new TextEncoder().encode(r));return I.encode(new Uint8Array(t),{includePadding:!1})}function y(r){return{tokenType:r.token_type,accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:r.expires_at?new Date((Date.now()+r.expires_in)*1e3):void 0,scopes:r?.scope?typeof r.scope=="string"?r.scope.split(" "):r.scope:[],idToken:r.id_token}}async function c({id:r,options:t,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:l,redirectURI:d}){let p=new URL(e);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("state",i),p.searchParams.set("scope",n.join(" ")),p.searchParams.set("redirect_uri",t.redirectURI||d),!l&&o){let g=await b(o);p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((h,O)=>(h[O]=null,h),{});p.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return p}import{betterFetch as E}from"@better-fetch/fetch";async function a({code:r,codeVerifier:t,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",r),t&&n.set("code_verifier",t),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:l}=await E(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(l)throw l;return y(s)}import{generateState as ue}from"oslo/oauth2";import{z as fe}from"zod";import{sha256 as se}from"oslo/crypto";import"better-call";var _=r=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=r.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:t}),async getUserInfo(e){if(!e.idToken)return null;let i=L(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};import{betterFetch as B}from"@better-fetch/fetch";var v=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await B("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as S}from"@better-fetch/fetch";var A=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["email","public_profile"];return await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:e,error:i}=await S("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});import{betterFetch as P}from"@better-fetch/fetch";var x=r=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=r.scope||i||["user:email"];return c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:t}),async getUserInfo(e){let{data:i,error:o}=await P("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:l}=await P("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});l||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};import{parseJWT as V}from"oslo/jwt";import{createConsola as C}from"consola";var u=C({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$=r=>({log:(...t)=>{!r?.disabled&&u.log("",...t)},error:(...t)=>{!r?.disabled&&u.error("",...t)},warn:(...t)=>{!r?.disabled&&u.warn("",...t)},info:(...t)=>{!r?.disabled&&u.info("",...t)},debug:(...t)=>{!r?.disabled&&u.debug("",...t)},box:(...t)=>{!r?.disabled&&u.box("",...t)},success:(...t)=>{!r?.disabled&&u.success("",...t)},break:(...t)=>{!r?.disabled&&console.log(`
2
- `)}}),f=$();var U=r=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new m("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new m("codeVerifier is required for Google");let n=r.scope||e||["email","profile"];return c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let e=V(t.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});import{betterFetch as D}from"@better-fetch/fetch";import{parseJWT as F}from"oslo/jwt";var w=r=>{let t=r.tenantId||"common",e=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let n=r.scope||o.scopes||["openid","profile","email","User.Read"];return c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:n,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:n,redirectURI:s}){return a({code:o,codeVerifier:n,redirectURI:r.redirectURI||s,options:r,tokenEndpoint:i})},async getUserInfo(o){if(!o.idToken)return null;let n=F(o.idToken)?.payload,s=r.profilePhotoSize||48;return await D(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(l){if(!(r.disableProfilePhoto||!l.response.ok))try{let p=await l.response.clone().arrayBuffer(),g=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as G}from"@better-fetch/fetch";var R=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){let n=r.scope||e||["user-read-email"];return c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:e,error:i}=await G("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});import"@better-fetch/fetch";import{nanoid as sr}from"nanoid";import{parseJWT as j}from"oslo/jwt";var T=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["user:read:email","openid"];return c({id:"twitch",redirectURI:i,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let e=t.idToken;if(!e)return f.error("No idToken found in token"),null;let i=j(e)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});import{betterFetch as N}from"@better-fetch/fetch";var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let e=r.scope||t.scopes||["account_info.read"];return c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await N("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var H={apple:_,discord:v,facebook:A,github:x,microsoft:w,google:U,spotify:R,twitch:T,twitter:k},Br=Object.keys(H);export{_ as apple,v as discord,A as facebook,x as github,U as google,w as microsoft,Br as socialProviderList,H as socialProviders,R as spotify,T as twitch,k as twitter};
1
+ import{parseJWT as L}from"oslo/jwt";import{sha256 as z}from"oslo/crypto";import{env as q}from"std-env";var m=class extends Error{constructor(t,e){super(t),this.name="BetterAuthError",this.message=t,this.cause=e,this.stack=""}};import{base64url as I}from"oslo/encoding";async function b(r){let t=await z(new TextEncoder().encode(r));return I.encode(new Uint8Array(t),{includePadding:!1})}function y(r){return{tokenType:r.token_type,accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:r.expires_at?new Date((Date.now()+r.expires_in)*1e3):void 0,scopes:r?.scope?typeof r.scope=="string"?r.scope.split(" "):r.scope:[],idToken:r.id_token}}async function c({id:r,options:t,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:p,redirectURI:d}){let l=new URL(e);if(l.searchParams.set("response_type","code"),l.searchParams.set("client_id",t.clientId),l.searchParams.set("state",i),l.searchParams.set("scope",n.join(" ")),l.searchParams.set("redirect_uri",t.redirectURI||d),!p&&o){let g=await b(o);l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((h,O)=>(h[O]=null,h),{});l.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return l}import{betterFetch as E}from"@better-fetch/fetch";async function a({code:r,codeVerifier:t,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",r),t&&n.set("code_verifier",t),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:p}=await E(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(p)throw p;return y(s)}import{generateState as fe}from"oslo/oauth2";import{z as he}from"zod";import{sha256 as le}from"oslo/crypto";import"better-call";var _=r=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=r.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:t}),async getUserInfo(e){if(!e.idToken)return null;let i=L(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};import{betterFetch as B}from"@better-fetch/fetch";var v=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await B("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as S}from"@better-fetch/fetch";var A=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["email","public_profile"];return await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:e,error:i}=await S("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});import{betterFetch as P}from"@better-fetch/fetch";var x=r=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=r.scope||i||["user:email"];return c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:t}),async getUserInfo(e){let{data:i,error:o}=await P("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:p}=await P("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});p||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};import{parseJWT as V}from"oslo/jwt";import{createConsola as C}from"consola";var u=C({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$=r=>({log:(...t)=>{!r?.disabled&&u.log("",...t)},error:(...t)=>{!r?.disabled&&u.error("",...t)},warn:(...t)=>{!r?.disabled&&u.warn("",...t)},info:(...t)=>{!r?.disabled&&u.info("",...t)},debug:(...t)=>{!r?.disabled&&u.debug("",...t)},box:(...t)=>{!r?.disabled&&u.box("",...t)},success:(...t)=>{!r?.disabled&&u.success("",...t)},break:(...t)=>{!r?.disabled&&console.log(`
2
+ `)}}),f=$();var U=r=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new m("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new m("codeVerifier is required for Google");let n=r.scope||e||["email","profile"];return c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let e=V(t.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});import{betterFetch as D}from"@better-fetch/fetch";import{parseJWT as F}from"oslo/jwt";var w=r=>{let t=r.tenantId||"common",e=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let n=r.scope||o.scopes||["openid","profile","email","User.Read"];return c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:n,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:n,redirectURI:s}){return a({code:o,codeVerifier:n,redirectURI:r.redirectURI||s,options:r,tokenEndpoint:i})},async getUserInfo(o){if(!o.idToken)return null;let n=F(o.idToken)?.payload,s=r.profilePhotoSize||48;return await D(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(p){if(!(r.disableProfilePhoto||!p.response.ok))try{let l=await p.response.clone().arrayBuffer(),g=Buffer.from(l).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as G}from"@better-fetch/fetch";var R=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:e,codeVerifier:i,redirectURI:o}){let n=r.scope||e||["user-read-email"];return c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:e,error:i}=await G("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});import"@better-fetch/fetch";import{nanoid as lr}from"nanoid";import{parseJWT as j}from"oslo/jwt";var T=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:e,redirectURI:i}){let o=r.scope||e||["user:read:email","openid"];return c({id:"twitch",redirectURI:i,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:e})=>a({code:t,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let e=t.idToken;if(!e)return f.error("No idToken found in token"),null;let i=j(e)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});import{betterFetch as N}from"@better-fetch/fetch";var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let e=r.scope||t.scopes||["account_info.read"];return c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:e,redirectURI:i})=>a({code:t,codeVerifier:e,redirectURI:r.redirectURI||i,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:e,error:i}=await N("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var H={apple:_,discord:v,facebook:A,github:x,microsoft:w,google:U,spotify:R,twitch:T,twitter:k},Cr=Object.keys(H);export{_ as apple,v as discord,A as facebook,x as github,U as google,w as microsoft,Cr as socialProviderList,H as socialProviders,R as spotify,T as twitch,k as twitter};
package/dist/solid.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var R=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var s in t)R(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of j(t))!G.call(e,r)&&r!==s&&R(e,r,{get:()=>t[r],enumerable:!(i=M(t,r))||i.enumerable});return e};var N=e=>z(R({},"__esModule",{value:!0}),e);var K={};H(K,{createAuthClient:()=>J});module.exports=N(K);var O=require("@nanostores/solid");var w=require("@better-fetch/fetch");var d=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function X(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function T(e,t="/api/auth"){return X(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function F(e,t){if(e)return T(e,t);let s=typeof process<"u"?process.env:{},i=s.BETTER_AUTH_URL||s.NEXT_PUBLIC_BETTER_AUTH_URL||s.PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_AUTH_URL||(s.BASE_URL!=="/"?s.BASE_URL:void 0);if(i)return T(i,t);if(typeof window<"u")return T(window.location.origin,t)}var se=require("nanostores");var L=require("@better-fetch/fetch");var B={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},C={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},S={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,L.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var x=e=>{let t=(0,w.createFetch)({baseURL:F(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[S],B,C,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function D(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function E(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(P=>P.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)).join("/"),f=l[0]||{},U=l[1]||{},{query:m,fetchOptions:y,...v}=f,p={...U,...y},b=D(a,s,f);return await t(a,{...p,body:b==="GET"?void 0:{...v,...p?.body||{}},query:m||p?.query,method:b,async onSuccess(P){await p?.onSuccess?.(P);let g=r?.find(q=>q.matcher(a));if(!g)return;let A=i[g.signal];if(!A)return;let W=A.get();setTimeout(()=>{A.set(!W)},10)}})}})}return u()}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}var _=require("nanostores");var ue=require("@better-fetch/fetch"),h=require("nanostores"),I=(e,t,s,i)=>{let r=(0,h.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,h.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function $(e){let t=(0,_.atom)(!1);return{$session:I(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function Q(e){return`use${k(e)}`}function J(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=x(e),o={};for(let[m,y]of Object.entries(i))o[Q(m)]=()=>(0,O.useStore)(y);let{$session:n,_sessionSignal:c,$Infer:l}=$(r);function a(){return(0,O.useStore)(n)}let f={...s,...o,useSession:a};return E(f,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
1
+ "use strict";var T=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var z=(e,t)=>{for(var s in t)T(e,s,{get:t[s],enumerable:!0})},N=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of G(t))!H.call(e,r)&&r!==s&&T(e,r,{get:()=>t[r],enumerable:!(i=j(t,r))||i.enumerable});return e};var X=e=>N(T({},"__esModule",{value:!0}),e);var V={};z(V,{createAuthClient:()=>K});module.exports=X(V);var U=require("@nanostores/solid");var x=require("@better-fetch/fetch");var f=require("std-env");var p=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function Q(e){try{return new URL(e).pathname!=="/"}catch{throw new p(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function O(e,t="/api/auth"){return Q(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function L(e,t){if(e)return O(e,t);let s=f.env.BETTER_AUTH_URL||f.env.NEXT_PUBLIC_BETTER_AUTH_URL||f.env.PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_AUTH_URL||(f.env.BASE_URL!=="/"?f.env.BASE_URL:void 0);if(s)return O(s,t);if(typeof window<"u")return O(window.location.origin,t)}var ie=require("nanostores");var B=require("@better-fetch/fetch");var C={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},S={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},w={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,B.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new p("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new p("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var E=e=>{let t=(0,x.createFetch)({baseURL:L(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[w],C,S,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function D(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function k(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let d of l)if(a&&typeof a=="object"&&d in a)a=a[d];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(A=>A.replace(/[A-Z]/g,h=>`-${h.toLowerCase()}`)).join("/"),d=l[0]||{},b=l[1]||{},{query:y,fetchOptions:P,...W}=d,g={...b,...P},F=D(a,s,d);return await t(a,{...g,body:F==="GET"?void 0:{...W,...g?.body||{}},query:y||g?.query,method:F,async onSuccess(A){await g?.onSuccess?.(A);let h=r?.find(M=>M.matcher(a));if(!h)return;let R=i[h.signal];if(!R)return;let q=R.get();setTimeout(()=>{R.set(!q)},10)}})}})}return u()}function I(e){return e.charAt(0).toUpperCase()+e.slice(1)}var $=require("nanostores");var le=require("@better-fetch/fetch"),m=require("nanostores"),_=(e,t,s,i)=>{let r=(0,m.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,m.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function v(e){let t=(0,$.atom)(!1);return{$session:_(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function J(e){return`use${I(e)}`}function K(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=E(e),o={};for(let[y,P]of Object.entries(i))o[J(y)]=()=>(0,U.useStore)(P);let{$session:n,_sessionSignal:c,$Infer:l}=v(r);function a(){return(0,U.useStore)(n)}let d={...s,...o,useSession:a};return k(d,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
package/dist/solid.d.cts CHANGED
@@ -208,7 +208,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
208
208
  hooks: {
209
209
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
210
210
  };
211
- })[] | undefined;
211
+ })[];
212
212
  cache?: RequestCache;
213
213
  credentials: RequestCredentials;
214
214
  headers?: (HeadersInit & (HeadersInit | {
@@ -271,7 +271,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
271
271
  output?: zod.ZodType | typeof Blob | typeof File;
272
272
  errorSchema?: zod.ZodType;
273
273
  disableValidation?: boolean;
274
- }, unknown, unknown, unknown>;
274
+ }, unknown, unknown, {}>;
275
275
  };
276
276
 
277
277
  export { createAuthClient };
package/dist/solid.d.ts CHANGED
@@ -208,7 +208,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
208
208
  hooks: {
209
209
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
210
210
  };
211
- })[] | undefined;
211
+ })[];
212
212
  cache?: RequestCache;
213
213
  credentials: RequestCredentials;
214
214
  headers?: (HeadersInit & (HeadersInit | {
@@ -271,7 +271,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
271
271
  output?: zod.ZodType | typeof Blob | typeof File;
272
272
  errorSchema?: zod.ZodType;
273
273
  disableValidation?: boolean;
274
- }, unknown, unknown, unknown>;
274
+ }, unknown, unknown, {}>;
275
275
  };
276
276
 
277
277
  export { createAuthClient };
package/dist/solid.js CHANGED
@@ -1 +1 @@
1
- import{useStore as x}from"@nanostores/solid";import{createFetch as v}from"@better-fetch/fetch";var d=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function _(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function A(e,t="/api/auth"){return _(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function O(e,t){if(e)return A(e,t);let r=typeof process<"u"?process.env:{},i=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(i)return A(i,t);if(typeof window<"u")return A(window.location.origin,t)}import"nanostores";import{betterFetch as $}from"@better-fetch/fetch";var U={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},b={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},F={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:r,error:i}=await $("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+i.message)}let s=r?.csrfToken;t.body={...t?.body,csrfToken:s}}return t.credentials="include",{url:e,options:t}}};var L=e=>{let t=v({baseURL:O(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[F],U,b,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),r=e?.plugins||[],i={},s={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of r)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(s,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:s,pluginPathMethods:u,atomListeners:o,$fetch:t}};function W(e,t,r){let i=t[e],{fetchOptions:s,query:u,...o}=r||{};return i||(s?.method?s.method:o&&Object.keys(o).length>0?"POST":"GET")}function B(e,t,r,i,s){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(y=>y.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)).join("/"),f=l[0]||{},R=l[1]||{},{query:h,fetchOptions:m,...E}=f,p={...R,...m},T=W(a,r,f);return await t(a,{...p,body:T==="GET"?void 0:{...E,...p?.body||{}},query:h||p?.query,method:T,async onSuccess(y){await p?.onSuccess?.(y);let g=s?.find(I=>I.matcher(a));if(!g)return;let P=i[g.signal];if(!P)return;let k=P.get();setTimeout(()=>{P.set(!k)},10)}})}})}return u()}function C(e){return e.charAt(0).toUpperCase()+e.slice(1)}import{atom as j}from"nanostores";import"@better-fetch/fetch";import{atom as q,onMount as M}from"nanostores";var S=(e,t,r,i)=>{let s=q({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):i;return r(t,{...n,onSuccess:async c=>{s.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){s.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=s.get();s.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():M(s,()=>(u(),o=!0,()=>{s.off(),n.off()}))});return s};function w(e){let t=j(!1);return{$session:S(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function G(e){return`use${C(e)}`}function ge(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:i,$fetch:s,atomListeners:u}=L(e),o={};for(let[h,m]of Object.entries(i))o[G(h)]=()=>x(m);let{$session:n,_sessionSignal:c,$Infer:l}=w(s);function a(){return x(n)}let f={...r,...o,useSession:a};return B(f,s,t,{...i,_sessionSignal:c},u)}export{ge as createAuthClient};
1
+ import{useStore as E}from"@nanostores/solid";import{createFetch as W}from"@better-fetch/fetch";import{env as p}from"std-env";var d=class extends Error{constructor(t,i){super(t),this.name="BetterAuthError",this.message=t,this.cause=i,this.stack=""}};function $(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function R(e,t="/api/auth"){return $(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function U(e,t){if(e)return R(e,t);let i=p.BETTER_AUTH_URL||p.NEXT_PUBLIC_BETTER_AUTH_URL||p.PUBLIC_BETTER_AUTH_URL||p.NUXT_PUBLIC_BETTER_AUTH_URL||p.NUXT_PUBLIC_AUTH_URL||(p.BASE_URL!=="/"?p.BASE_URL:void 0);if(i)return R(i,t);if(typeof window<"u")return R(window.location.origin,t)}import"nanostores";import{betterFetch as v}from"@better-fetch/fetch";var b={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},F={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},L={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:i,error:s}=await v("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(s){if(s.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(s.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+s.message)}let r=i?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var B=e=>{let t=W({baseURL:U(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[L],b,F,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),i=e?.plugins||[],s={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of i)n.getActions&&Object.assign(s,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:s,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function q(e,t,i){let s=t[e],{fetchOptions:r,query:u,...o}=i||{};return s||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function C(e,t,i,s,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let f of l)if(a&&typeof a=="object"&&f in a)a=a[f];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(P=>P.replace(/[A-Z]/g,h=>`-${h.toLowerCase()}`)).join("/"),f=l[0]||{},T=l[1]||{},{query:m,fetchOptions:y,...k}=f,g={...T,...y},O=q(a,i,f);return await t(a,{...g,body:O==="GET"?void 0:{...k,...g?.body||{}},query:m||g?.query,method:O,async onSuccess(P){await g?.onSuccess?.(P);let h=r?.find(_=>_.matcher(a));if(!h)return;let A=s[h.signal];if(!A)return;let I=A.get();setTimeout(()=>{A.set(!I)},10)}})}})}return u()}function S(e){return e.charAt(0).toUpperCase()+e.slice(1)}import{atom as G}from"nanostores";import"@better-fetch/fetch";import{atom as M,onMount as j}from"nanostores";var w=(e,t,i,s)=>{let r=M({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof s=="function"?s({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):s;return i(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():j(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function x(e){let t=G(!1);return{$session:w(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function H(e){return`use${S(e)}`}function me(e){let{pluginPathMethods:t,pluginsActions:i,pluginsAtoms:s,$fetch:r,atomListeners:u}=B(e),o={};for(let[m,y]of Object.entries(s))o[H(m)]=()=>E(y);let{$session:n,_sessionSignal:c,$Infer:l}=x(r);function a(){return E(n)}let f={...i,...o,useSession:a};return C(f,r,t,{...s,_sessionSignal:c},u)}export{me as createAuthClient};
package/dist/svelte.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var A=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var s in t)A(e,s,{get:t[s],enumerable:!0})},j=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of M(t))!G.call(e,r)&&r!==s&&A(e,r,{get:()=>t[r],enumerable:!(i=q(t,r))||i.enumerable});return e};var z=e=>j(A({},"__esModule",{value:!0}),e);var Q={};H(Q,{createAuthClient:()=>D});module.exports=z(Q);var C=require("@better-fetch/fetch");var f=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function N(e){try{return new URL(e).pathname!=="/"}catch{throw new f(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function T(e,t="/api/auth"){return N(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function U(e,t){if(e)return T(e,t);let s=typeof process<"u"?process.env:{},i=s.BETTER_AUTH_URL||s.NEXT_PUBLIC_BETTER_AUTH_URL||s.PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_AUTH_URL||(s.BASE_URL!=="/"?s.BASE_URL:void 0);if(i)return T(i,t);if(typeof window<"u")return T(window.location.origin,t)}var ne=require("nanostores");var b=require("@better-fetch/fetch");var F={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},L={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},B={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,b.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new f("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new f("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var S=e=>{let t=(0,C.createFetch)({baseURL:U(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[B],F,L,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function w(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function x(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let d of l)if(a&&typeof a=="object"&&d in a)a=a[d];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(P=>P.replace(/[A-Z]/g,h=>`-${h.toLowerCase()}`)).join("/"),d=l[0]||{},m=l[1]||{},{query:y,fetchOptions:_,...$}=d,p={...m,..._},O=X(a,s,d);return await t(a,{...p,body:O==="GET"?void 0:{...$,...p?.body||{}},query:y||p?.query,method:O,async onSuccess(P){await p?.onSuccess?.(P);let h=r?.find(W=>W.matcher(a));if(!h)return;let R=i[h.signal];if(!R)return;let v=R.get();setTimeout(()=>{R.set(!v)},10)}})}})}return u()}var k=require("nanostores");var ae=require("@better-fetch/fetch"),g=require("nanostores"),E=(e,t,s,i)=>{let r=(0,g.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,g.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function I(e){let t=(0,k.atom)(!1);return{$session:E(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function D(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=S(e),o={};for(let[m,y]of Object.entries(i))o[`use${w(m)}`]=()=>y;let{$session:n,_sessionSignal:c,$Infer:l}=I(r),a={...s,...o,useSession:()=>n};return x(a,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
1
+ "use strict";var T=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)T(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of G(t))!H.call(e,r)&&r!==s&&T(e,r,{get:()=>t[r],enumerable:!(i=M(t,r))||i.enumerable});return e};var N=e=>z(T({},"__esModule",{value:!0}),e);var J={};j(J,{createAuthClient:()=>D});module.exports=N(J);var S=require("@better-fetch/fetch");var f=require("std-env");var d=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function X(e){try{return new URL(e).pathname!=="/"}catch{throw new d(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function O(e,t="/api/auth"){return X(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function b(e,t){if(e)return O(e,t);let s=f.env.BETTER_AUTH_URL||f.env.NEXT_PUBLIC_BETTER_AUTH_URL||f.env.PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_BETTER_AUTH_URL||f.env.NUXT_PUBLIC_AUTH_URL||(f.env.BASE_URL!=="/"?f.env.BASE_URL:void 0);if(s)return O(s,t);if(typeof window<"u")return O(window.location.origin,t)}var re=require("nanostores");var F=require("@better-fetch/fetch");var L={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},B={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},C={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,F.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new d("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new d("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var w=e=>{let t=(0,S.createFetch)({baseURL:b(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[C],L,B,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function x(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Q(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function E(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let p of l)if(a&&typeof a=="object"&&p in a)a=a[p];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(R=>R.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)).join("/"),p=l[0]||{},y=l[1]||{},{query:P,fetchOptions:$,...v}=p,h={...y,...$},U=Q(a,s,p);return await t(a,{...h,body:U==="GET"?void 0:{...v,...h?.body||{}},query:P||h?.query,method:U,async onSuccess(R){await h?.onSuccess?.(R);let g=r?.find(q=>q.matcher(a));if(!g)return;let A=i[g.signal];if(!A)return;let W=A.get();setTimeout(()=>{A.set(!W)},10)}})}})}return u()}var I=require("nanostores");var ce=require("@better-fetch/fetch"),m=require("nanostores"),k=(e,t,s,i)=>{let r=(0,m.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,m.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function _(e){let t=(0,I.atom)(!1);return{$session:k(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function D(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=w(e),o={};for(let[y,P]of Object.entries(i))o[`use${x(y)}`]=()=>P;let{$session:n,_sessionSignal:c,$Infer:l}=_(r),a={...s,...o,useSession:()=>n};return E(a,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
package/dist/svelte.d.cts CHANGED
@@ -207,7 +207,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
207
207
  hooks: {
208
208
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
209
209
  };
210
- })[] | undefined;
210
+ })[];
211
211
  cache?: RequestCache;
212
212
  credentials: RequestCredentials;
213
213
  headers?: (HeadersInit & (HeadersInit | {
@@ -270,7 +270,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
270
270
  output?: zod.ZodType | typeof Blob | typeof File;
271
271
  errorSchema?: zod.ZodType;
272
272
  disableValidation?: boolean;
273
- }, unknown, unknown, unknown>;
273
+ }, unknown, unknown, {}>;
274
274
  };
275
275
 
276
276
  export { createAuthClient };
package/dist/svelte.d.ts CHANGED
@@ -207,7 +207,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
207
207
  hooks: {
208
208
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
209
209
  };
210
- })[] | undefined;
210
+ })[];
211
211
  cache?: RequestCache;
212
212
  credentials: RequestCredentials;
213
213
  headers?: (HeadersInit & (HeadersInit | {
@@ -270,7 +270,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
270
270
  output?: zod.ZodType | typeof Blob | typeof File;
271
271
  errorSchema?: zod.ZodType;
272
272
  disableValidation?: boolean;
273
- }, unknown, unknown, unknown>;
273
+ }, unknown, unknown, {}>;
274
274
  };
275
275
 
276
276
  export { createAuthClient };
package/dist/svelte.js CHANGED
@@ -1 +1 @@
1
- import{createFetch as $}from"@better-fetch/fetch";var f=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function I(e){try{return new URL(e).pathname!=="/"}catch{throw new f(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function R(e,t="/api/auth"){return I(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function T(e,t){if(e)return R(e,t);let r=typeof process<"u"?process.env:{},i=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(i)return R(i,t);if(typeof window<"u")return R(window.location.origin,t)}import"nanostores";import{betterFetch as _}from"@better-fetch/fetch";var O={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},U={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},b={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:r,error:i}=await _("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new f("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new f("Failed to fetch CSRF token: "+i.message)}let s=r?.csrfToken;t.body={...t?.body,csrfToken:s}}return t.credentials="include",{url:e,options:t}}};var F=e=>{let t=$({baseURL:T(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[b],O,U,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),r=e?.plugins||[],i={},s={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of r)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(s,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:s,pluginPathMethods:u,atomListeners:o,$fetch:t}};function L(e){return e.charAt(0).toUpperCase()+e.slice(1)}function v(e,t,r){let i=t[e],{fetchOptions:s,query:u,...o}=r||{};return i||(s?.method?s.method:o&&Object.keys(o).length>0?"POST":"GET")}function B(e,t,r,i,s){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let d of l)if(a&&typeof a=="object"&&d in a)a=a[d];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(y=>y.replace(/[A-Z]/g,h=>`-${h.toLowerCase()}`)).join("/"),d=l[0]||{},g=l[1]||{},{query:m,fetchOptions:w,...x}=d,p={...g,...w},A=v(a,r,d);return await t(a,{...p,body:A==="GET"?void 0:{...x,...p?.body||{}},query:m||p?.query,method:A,async onSuccess(y){await p?.onSuccess?.(y);let h=s?.find(k=>k.matcher(a));if(!h)return;let P=i[h.signal];if(!P)return;let E=P.get();setTimeout(()=>{P.set(!E)},10)}})}})}return u()}import{atom as M}from"nanostores";import"@better-fetch/fetch";import{atom as W,onMount as q}from"nanostores";var C=(e,t,r,i)=>{let s=W({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):i;return r(t,{...n,onSuccess:async c=>{s.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){s.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=s.get();s.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():q(s,()=>(u(),o=!0,()=>{s.off(),n.off()}))});return s};function S(e){let t=M(!1);return{$session:C(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function fe(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:i,$fetch:s,atomListeners:u}=F(e),o={};for(let[g,m]of Object.entries(i))o[`use${L(g)}`]=()=>m;let{$session:n,_sessionSignal:c,$Infer:l}=S(s),a={...r,...o,useSession:()=>n};return B(a,s,t,{...i,_sessionSignal:c},u)}export{fe as createAuthClient};
1
+ import{createFetch as v}from"@better-fetch/fetch";import{env as d}from"std-env";var f=class extends Error{constructor(t,i){super(t),this.name="BetterAuthError",this.message=t,this.cause=i,this.stack=""}};function _(e){try{return new URL(e).pathname!=="/"}catch{throw new f(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function A(e,t="/api/auth"){return _(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function O(e,t){if(e)return A(e,t);let i=d.BETTER_AUTH_URL||d.NEXT_PUBLIC_BETTER_AUTH_URL||d.PUBLIC_BETTER_AUTH_URL||d.NUXT_PUBLIC_BETTER_AUTH_URL||d.NUXT_PUBLIC_AUTH_URL||(d.BASE_URL!=="/"?d.BASE_URL:void 0);if(i)return A(i,t);if(typeof window<"u")return A(window.location.origin,t)}import"nanostores";import{betterFetch as $}from"@better-fetch/fetch";var U={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},b={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},F={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:i,error:s}=await $("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(s){if(s.status===404)throw new f("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(s.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new f("Failed to fetch CSRF token: "+s.message)}let r=i?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var L=e=>{let t=v({baseURL:O(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[F],U,b,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),i=e?.plugins||[],s={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of i)n.getActions&&Object.assign(s,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:s,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function B(e){return e.charAt(0).toUpperCase()+e.slice(1)}function W(e,t,i){let s=t[e],{fetchOptions:r,query:u,...o}=i||{};return s||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function C(e,t,i,s,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let l=[...o,c],a=e;for(let p of l)if(a&&typeof a=="object"&&p in a)a=a[p];else{a=void 0;break}return typeof a=="function"?a:u(l)},apply:async(n,c,l)=>{let a="/"+o.map(P=>P.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)).join("/"),p=l[0]||{},m=l[1]||{},{query:y,fetchOptions:x,...E}=p,h={...m,...x},T=W(a,i,p);return await t(a,{...h,body:T==="GET"?void 0:{...E,...h?.body||{}},query:y||h?.query,method:T,async onSuccess(P){await h?.onSuccess?.(P);let g=r?.find(I=>I.matcher(a));if(!g)return;let R=s[g.signal];if(!R)return;let k=R.get();setTimeout(()=>{R.set(!k)},10)}})}})}return u()}import{atom as G}from"nanostores";import"@better-fetch/fetch";import{atom as q,onMount as M}from"nanostores";var S=(e,t,i,s)=>{let r=q({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof s=="function"?s({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):s;return i(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let l=r.get();r.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():M(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function w(e){let t=G(!1);return{$session:S(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function pe(e){let{pluginPathMethods:t,pluginsActions:i,pluginsAtoms:s,$fetch:r,atomListeners:u}=L(e),o={};for(let[m,y]of Object.entries(s))o[`use${B(m)}`]=()=>y;let{$session:n,_sessionSignal:c,$Infer:l}=w(r),a={...i,...o,useSession:()=>n};return C(a,r,t,{...s,_sessionSignal:c},u)}export{pe as createAuthClient};
package/dist/types.d.cts CHANGED
@@ -106,7 +106,6 @@ interface ClientOptions {
106
106
  plugins?: BetterAuthClientPlugin[];
107
107
  baseURL?: string;
108
108
  disableCSRFTokenCheck?: boolean;
109
- disableDefaultFetchPlugins?: boolean;
110
109
  }
111
110
  type InferClientAPI<O extends ClientOptions> = InferRoutes<O["plugins"] extends Array<any> ? (O["plugins"] extends Array<infer Pl> ? UnionToIntersection<Pl extends {
112
111
  $InferServerPlugin: infer Plug;
package/dist/types.d.ts CHANGED
@@ -106,7 +106,6 @@ interface ClientOptions {
106
106
  plugins?: BetterAuthClientPlugin[];
107
107
  baseURL?: string;
108
108
  disableCSRFTokenCheck?: boolean;
109
- disableDefaultFetchPlugins?: boolean;
110
109
  }
111
110
  type InferClientAPI<O extends ClientOptions> = InferRoutes<O["plugins"] extends Array<any> ? (O["plugins"] extends Array<infer Pl> ? UnionToIntersection<Pl extends {
112
111
  $InferServerPlugin: infer Plug;
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var O=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)O(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of G(t))!H.call(e,r)&&r!==s&&O(e,r,{get:()=>t[r],enumerable:!(i=M(t,r))||i.enumerable});return e};var D=e=>z(O({},"__esModule",{value:!0}),e);var K={};j(K,{createAuthClient:()=>J});module.exports=D(K);var A=require("@nanostores/vue");var w=require("@better-fetch/fetch");var p=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function N(e){try{return new URL(e).pathname!=="/"}catch{throw new p(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function b(e,t="/api/auth"){return N(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function S(e,t){if(e)return b(e,t);let s=typeof process<"u"?process.env:{},i=s.BETTER_AUTH_URL||s.NEXT_PUBLIC_BETTER_AUTH_URL||s.PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_BETTER_AUTH_URL||s.NUXT_PUBLIC_AUTH_URL||(s.BASE_URL!=="/"?s.BASE_URL:void 0);if(i)return b(i,t);if(typeof window<"u")return b(window.location.origin,t)}var se=require("nanostores");var L=require("@better-fetch/fetch");var B={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},C={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},x={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,L.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new p("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new p("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var E=e=>{let t=(0,w.createFetch)({baseURL:S(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?e.fetchOptions?.plugins:[...e?.disableCSRFTokenCheck?[]:[x],B,C,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function I(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let f=[...o,c],a=e;for(let l of f)if(a&&typeof a=="object"&&l in a)a=a[l];else{a=void 0;break}return typeof a=="function"?a:u(f)},apply:async(n,c,f)=>{let a="/"+o.map(h=>h.replace(/[A-Z]/g,R=>`-${R.toLowerCase()}`)).join("/"),l=f[0]||{},T=f[1]||{},{query:F,fetchOptions:g,...m}=l,d={...T,...g},y=X(a,s,l);return await t(a,{...d,body:y==="GET"?void 0:{...m,...d?.body||{}},query:F||d?.query,method:y,async onSuccess(h){await d?.onSuccess?.(h);let R=r?.find(q=>q.matcher(a));if(!R)return;let U=i[R.signal];if(!U)return;let W=U.get();setTimeout(()=>{U.set(!W)},10)}})}})}return u()}var $=require("nanostores");var ue=require("@better-fetch/fetch"),P=require("nanostores"),_=(e,t,s,i)=>{let r=(0,P.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let f=r.get();r.set({isPending:f.data===null,data:f.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,P.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function v(e){let t=(0,$.atom)(!1);return{$session:_(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function Q(e){return`use${k(e)}`}function J(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=E(e),o={};for(let[g,m]of Object.entries(i))o[Q(g)]=()=>(0,A.useStore)(m);let{$session:n,_sessionSignal:c,$Infer:f}=v(r);function a(){return(0,A.useStore)(n)}function l(g){if(g){let m=(0,A.useStore)(c),d=e?.fetchOptions?.baseURL||e?.baseURL,y=d?new URL(d).pathname:"/api/auth";return g(`${y}/session`,{ref:m}).then(h=>({data:h.data,isPending:!1,error:h.error}))}return a()}let T={...s,...o,useSession:l};return I(T,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
1
+ "use strict";var b=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var z=(e,t)=>{for(var s in t)b(e,s,{get:t[s],enumerable:!0})},D=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of H(t))!j.call(e,r)&&r!==s&&b(e,r,{get:()=>t[r],enumerable:!(i=G(t,r))||i.enumerable});return e};var N=e=>D(b({},"__esModule",{value:!0}),e);var V={};z(V,{createAuthClient:()=>K});module.exports=N(V);var T=require("@nanostores/vue");var E=require("@better-fetch/fetch");var l=require("std-env");var g=class extends Error{constructor(t,s){super(t),this.name="BetterAuthError",this.message=t,this.cause=s,this.stack=""}};function X(e){try{return new URL(e).pathname!=="/"}catch{throw new g(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function F(e,t="/api/auth"){return X(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function L(e,t){if(e)return F(e,t);let s=l.env.BETTER_AUTH_URL||l.env.NEXT_PUBLIC_BETTER_AUTH_URL||l.env.PUBLIC_BETTER_AUTH_URL||l.env.NUXT_PUBLIC_BETTER_AUTH_URL||l.env.NUXT_PUBLIC_AUTH_URL||(l.env.BASE_URL!=="/"?l.env.BASE_URL:void 0);if(s)return F(s,t);if(typeof window<"u")return F(window.location.origin,t)}var ie=require("nanostores");var B=require("@better-fetch/fetch");var C={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&(window.location.href=e.data.url)}}},x={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"){let t=new URL(e.url);t.searchParams.set("currentURL",window.location.href),e.url=t}return e}}},w={id:"csrf",name:"CSRF Check",async init(e,t){if(t?.method!=="GET"){t=t||{};let{data:s,error:i}=await(0,B.betterFetch)("/csrf",{body:void 0,baseURL:t.baseURL,plugins:[],method:"GET",credentials:"include",customFetchImpl:t.customFetchImpl});if(i){if(i.status===404)throw new g("CSRF route not found. Make sure the server is running and the base URL is correct and includes the path (e.g. http://localhost:3000/api/auth).");if(i.status===429)return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests"});throw new g("Failed to fetch CSRF token: "+i.message)}let r=s?.csrfToken;t.body={...t?.body,csrfToken:r}}return t.credentials="include",{url:e,options:t}}};var k=e=>{let t=(0,E.createFetch)({baseURL:L(e?.fetchOptions?.baseURL||e?.baseURL),credentials:"include",method:"GET",...e?.fetchOptions,plugins:[...e?.disableCSRFTokenCheck?[]:[w],C,x,...e?.fetchOptions?.plugins?.filter(n=>n!==void 0)||[],...e?.plugins?.flatMap(n=>n.fetchPlugins).filter(n=>n!==void 0)||[]]}),s=e?.plugins||[],i={},r={},u={"/sign-out":"POST","/user/revoke-sessions":"POST"},o=[{signal:"_sessionSignal",matcher(n){return n==="/sign-out"||n==="/user/update"||n.startsWith("/sign-in")||n.startsWith("/sign-up")}}];for(let n of s)n.getActions&&Object.assign(i,n.getActions?.(t)),n.getAtoms&&Object.assign(r,n.getAtoms?.(t)),n.pathMethods&&Object.assign(u,n.pathMethods),n.atomListeners&&o.push(...n.atomListeners);return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:u,atomListeners:o,$fetch:t}};function I(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Q(e,t,s){let i=t[e],{fetchOptions:r,query:u,...o}=s||{};return i||(r?.method?r.method:o&&Object.keys(o).length>0?"POST":"GET")}function _(e,t,s,i,r){function u(o=[]){return new Proxy(function(){},{get(n,c){let f=[...o,c],a=e;for(let d of f)if(a&&typeof a=="object"&&d in a)a=a[d];else{a=void 0;break}return typeof a=="function"?a:u(f)},apply:async(n,c,f)=>{let a="/"+o.map(m=>m.replace(/[A-Z]/g,P=>`-${P.toLowerCase()}`)).join("/"),d=f[0]||{},U=f[1]||{},{query:S,fetchOptions:h,...y}=d,p={...U,...h},R=Q(a,s,d);return await t(a,{...p,body:R==="GET"?void 0:{...y,...p?.body||{}},query:S||p?.query,method:R,async onSuccess(m){await p?.onSuccess?.(m);let P=r?.find(M=>M.matcher(a));if(!P)return;let O=i[P.signal];if(!O)return;let q=O.get();setTimeout(()=>{O.set(!q)},10)}})}})}return u()}var v=require("nanostores");var fe=require("@better-fetch/fetch"),A=require("nanostores"),$=(e,t,s,i)=>{let r=(0,A.atom)({data:null,error:null,isPending:!1,isRefetching:!1}),u=()=>{let n=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return s(t,{...n,onSuccess:async c=>{r.set({data:c.data,error:null,isPending:!1,isRefetching:!1}),await n?.onSuccess?.(c)},async onError(c){r.set({error:c.error,data:null,isPending:!1,isRefetching:!1}),await n?.onError?.(c)},async onRequest(c){let f=r.get();r.set({isPending:f.data===null,data:f.data,error:null,isRefetching:!0}),await n?.onRequest?.(c)}})};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?u():(0,A.onMount)(r,()=>(u(),o=!0,()=>{r.off(),n.off()}))});return r};function W(e){let t=(0,v.atom)(!1);return{$session:$(t,"/session",e,{method:"GET"}),_sessionSignal:t,$Infer:{}}}function J(e){return`use${I(e)}`}function K(e){let{pluginPathMethods:t,pluginsActions:s,pluginsAtoms:i,$fetch:r,atomListeners:u}=k(e),o={};for(let[h,y]of Object.entries(i))o[J(h)]=()=>(0,T.useStore)(y);let{$session:n,_sessionSignal:c,$Infer:f}=W(r);function a(){return(0,T.useStore)(n)}function d(h){if(h){let y=(0,T.useStore)(c),p=e?.fetchOptions?.baseURL||e?.baseURL,R=p?new URL(p).pathname:"/api/auth";return h(`${R}/session`,{ref:y}).then(m=>({data:m.data,isPending:!1,error:m.error}))}return a()}let U={...s,...o,useSession:d};return _(U,r,t,{...i,_sessionSignal:c},u)}0&&(module.exports={createAuthClient});
package/dist/vue.d.cts CHANGED
@@ -258,7 +258,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
258
258
  hooks: {
259
259
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
260
260
  };
261
- })[] | undefined;
261
+ })[];
262
262
  cache?: RequestCache;
263
263
  credentials: RequestCredentials;
264
264
  headers?: (HeadersInit & (HeadersInit | {
@@ -321,7 +321,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
321
321
  output?: zod.ZodType | typeof Blob | typeof File;
322
322
  errorSchema?: zod.ZodType;
323
323
  disableValidation?: boolean;
324
- }, unknown, unknown, unknown>;
324
+ }, unknown, unknown, {}>;
325
325
  };
326
326
 
327
327
  export { createAuthClient };
package/dist/vue.d.ts CHANGED
@@ -258,7 +258,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
258
258
  hooks: {
259
259
  onRequest<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>): _better_fetch_fetch.RequestContext<T>;
260
260
  };
261
- })[] | undefined;
261
+ })[];
262
262
  cache?: RequestCache;
263
263
  credentials: RequestCredentials;
264
264
  headers?: (HeadersInit & (HeadersInit | {
@@ -321,7 +321,7 @@ declare function createAuthClient<Option extends ClientOptions>(options?: Option
321
321
  output?: zod.ZodType | typeof Blob | typeof File;
322
322
  errorSchema?: zod.ZodType;
323
323
  disableValidation?: boolean;
324
- }, unknown, unknown, unknown>;
324
+ }, unknown, unknown, {}>;
325
325
  };
326
326
 
327
327
  export { createAuthClient };