better-auth 0.0.8-beta.2 → 0.0.8-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/access.d.ts +3 -4
  2. package/dist/access.js +3 -13
  3. package/dist/access.js.map +1 -1
  4. package/dist/cli.d.ts +1 -2
  5. package/dist/cli.js +36 -44
  6. package/dist/cli.js.map +1 -1
  7. package/dist/client/plugins.d.ts +97 -2407
  8. package/dist/client/plugins.js +143 -203
  9. package/dist/client/plugins.js.map +1 -1
  10. package/dist/client.d.ts +159 -1213
  11. package/dist/client.js +125 -527
  12. package/dist/client.js.map +1 -1
  13. package/dist/{helper-B5_2Vzba.d.ts → helper-D8dhRz72.d.ts} +1 -4
  14. package/dist/{index-Dg4eEXZW.d.ts → index-B9jOjqnF.d.ts} +1 -1
  15. package/dist/{schema-BOszzrbQ.d.ts → index-CcxejJTH.d.ts} +172 -142
  16. package/dist/{client-CaF9eUcv.d.ts → index-Dwhjsk4l.d.ts} +2014 -1971
  17. package/dist/index.d.ts +1124 -6
  18. package/dist/index.js +737 -707
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal-adapter-CVKQ4XR9.d.ts +637 -0
  21. package/dist/next-js.d.ts +17 -7
  22. package/dist/next-js.js +20 -3
  23. package/dist/next-js.js.map +1 -1
  24. package/dist/plugins.d.ts +12 -883
  25. package/dist/plugins.js +743 -679
  26. package/dist/plugins.js.map +1 -1
  27. package/dist/react.d.ts +312 -12
  28. package/dist/react.js +138 -148
  29. package/dist/react.js.map +1 -1
  30. package/dist/social.d.ts +2 -2
  31. package/dist/social.js +179 -151
  32. package/dist/social.js.map +1 -1
  33. package/dist/solid-start.d.ts +7 -6
  34. package/dist/solid-start.js +3 -3
  35. package/dist/solid-start.js.map +1 -1
  36. package/dist/solid.d.ts +91 -2713
  37. package/dist/solid.js +130 -139
  38. package/dist/solid.js.map +1 -1
  39. package/dist/{statement-COylZd3J.d.ts → statement-D6SPoYOh.d.ts} +7 -7
  40. package/dist/svelte-kit.d.ts +6 -5
  41. package/dist/svelte-kit.js +10 -9
  42. package/dist/svelte-kit.js.map +1 -1
  43. package/dist/svelte.d.ts +89 -2713
  44. package/dist/svelte.js +124 -138
  45. package/dist/svelte.js.map +1 -1
  46. package/dist/types-D4WrjKeJ.d.ts +81 -0
  47. package/dist/types.d.ts +31 -5
  48. package/dist/types.js +2 -0
  49. package/dist/types.js.map +1 -1
  50. package/dist/vue.d.ts +313 -12
  51. package/dist/vue.js +131 -145
  52. package/dist/vue.js.map +1 -1
  53. package/package.json +8 -3
  54. package/dist/index-CGeV0d2g.d.ts +0 -1498
  55. package/dist/preact.d.ts +0 -8
  56. package/dist/preact.js +0 -291
  57. package/dist/preact.js.map +0 -1
  58. package/dist/type-tYx_kmry.d.ts +0 -5724
package/dist/svelte.js CHANGED
@@ -1,12 +1,7 @@
1
- // src/client/base.ts
2
- import { createFetch } from "@better-fetch/fetch";
1
+ import { createFetch, betterFetch } from '@better-fetch/fetch';
2
+ import { atom, computed, task } from 'nanostores';
3
3
 
4
- // src/error/better-auth-error.ts
5
- var BetterAuthError = class extends Error {
6
- constructor(message) {
7
- super(message);
8
- }
9
- };
4
+ // src/client/config.ts
10
5
 
11
6
  // src/utils/base-url.ts
12
7
  function checkHasPath(url) {
@@ -21,47 +16,43 @@ function checkHasPath(url) {
21
16
  function withPath(url, path = "/api/auth") {
22
17
  const hasPath = checkHasPath(url);
23
18
  if (hasPath) {
24
- return {
25
- baseURL: new URL(url).origin,
26
- withPath: url
27
- };
19
+ return url;
28
20
  }
29
21
  path = path.startsWith("/") ? path : `/${path}`;
30
- return {
31
- baseURL: url,
32
- withPath: `${url}${path}`
33
- };
22
+ return `${url}${path}`;
34
23
  }
35
24
  function getBaseURL(url, path) {
36
25
  if (url) {
37
26
  return withPath(url, path);
38
27
  }
39
28
  const env = typeof process !== "undefined" ? process.env : {};
40
- const fromEnv = env.BETTER_AUTH_URL || env.AUTH_URL || env.NEXT_PUBLIC_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL;
29
+ const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL;
41
30
  if (fromEnv) {
42
31
  return withPath(fromEnv, path);
43
32
  }
44
- const isDev = !fromEnv && (env.NODE_ENV === "development" || env.NODE_ENV === "test");
45
- if (isDev) {
46
- return {
47
- baseURL: "http://localhost:3000",
48
- withPath: "http://localhost:3000/api/auth"
49
- };
33
+ if (typeof window !== "undefined") {
34
+ return withPath(window.location.origin, path);
50
35
  }
51
- throw new BetterAuthError(
52
- "Could not infer baseURL from environment variables"
53
- );
36
+ return void 0;
54
37
  }
55
38
 
39
+ // src/error/better-auth-error.ts
40
+ var BetterAuthError = class extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ }
44
+ };
45
+
56
46
  // src/client/fetch-plugins.ts
57
- import { betterFetch } from "@better-fetch/fetch";
58
47
  var redirectPlugin = {
59
48
  id: "redirect",
60
49
  name: "Redirect",
61
50
  hooks: {
62
51
  onSuccess(context) {
63
52
  if (context.data?.url && context.data?.redirect) {
64
- window.location.href = context.data.url;
53
+ if (typeof window !== "undefined") {
54
+ window.location.href = context.data.url;
55
+ }
65
56
  }
66
57
  }
67
58
  }
@@ -84,6 +75,17 @@ var csrfPlugin = {
84
75
  id: "csrf",
85
76
  name: "CSRF Check",
86
77
  async init(url, options) {
78
+ if (typeof window !== "undefined") {
79
+ const isTheSameOrigin = new URL(options?.baseURL || url).origin === window.location.origin;
80
+ if (isTheSameOrigin) {
81
+ return { url, options };
82
+ }
83
+ }
84
+ if (!options?.baseURL) {
85
+ throw new BetterAuthError(
86
+ "API Base URL on the auth client isn't configured. Please pass it directly to the client `baseURL`"
87
+ );
88
+ }
87
89
  if (options?.method !== "GET") {
88
90
  options = options || {};
89
91
  const { data, error } = await betterFetch("/csrf", {
@@ -91,7 +93,8 @@ var csrfPlugin = {
91
93
  baseURL: options.baseURL,
92
94
  plugins: [],
93
95
  method: "GET",
94
- credentials: "include"
96
+ credentials: "include",
97
+ customFetchImpl: options.customFetchImpl
95
98
  });
96
99
  if (error?.status === 404) {
97
100
  throw new BetterAuthError(
@@ -111,6 +114,61 @@ var csrfPlugin = {
111
114
  }
112
115
  };
113
116
 
117
+ // src/client/config.ts
118
+ var getClientConfig = (options) => {
119
+ const $fetch = createFetch({
120
+ baseURL: getBaseURL(options?.fetchOptions?.baseURL || options?.baseURL),
121
+ ...options?.fetchOptions,
122
+ plugins: [
123
+ csrfPlugin,
124
+ redirectPlugin,
125
+ addCurrentURL,
126
+ ...options?.fetchOptions?.plugins || [],
127
+ ...options?.plugins?.flatMap((plugin) => plugin.fetchPlugins).filter((pl) => pl !== void 0) || []
128
+ ]
129
+ });
130
+ const plugins = options?.plugins || [];
131
+ let pluginsActions = {};
132
+ let pluginsAtoms = {};
133
+ let pluginPathMethods = {
134
+ "/sign-out": "POST"
135
+ };
136
+ const atomListeners = [
137
+ {
138
+ signal: "_sessionSignal",
139
+ matcher(path) {
140
+ return path === "/sign-out" || path === "sign-up/email";
141
+ }
142
+ }
143
+ ];
144
+ for (const plugin of plugins) {
145
+ if (plugin.getActions) {
146
+ Object.assign(pluginsActions, plugin.getActions?.($fetch));
147
+ }
148
+ if (plugin.getAtoms) {
149
+ Object.assign(pluginsAtoms, plugin.getAtoms?.($fetch));
150
+ }
151
+ if (plugin.pathMethods) {
152
+ Object.assign(pluginPathMethods, plugin.pathMethods);
153
+ }
154
+ if (plugin.atomListeners) {
155
+ atomListeners.push(...plugin.atomListeners);
156
+ }
157
+ }
158
+ return {
159
+ pluginsActions,
160
+ pluginsAtoms,
161
+ pluginPathMethods,
162
+ atomListeners,
163
+ $fetch
164
+ };
165
+ };
166
+
167
+ // src/utils/misc.ts
168
+ function capitalizeFirstLetter(str) {
169
+ return str.charAt(0).toUpperCase() + str.slice(1);
170
+ }
171
+
114
172
  // src/client/proxy.ts
115
173
  function getMethod(path, knownPathMethods, args) {
116
174
  const method = knownPathMethods[path];
@@ -126,7 +184,7 @@ function getMethod(path, knownPathMethods, args) {
126
184
  }
127
185
  return "GET";
128
186
  }
129
- function createDynamicPathProxy(routes, client, knownPathMethods, $signal, $signals) {
187
+ function createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {
130
188
  function createProxy(path = []) {
131
189
  return new Proxy(function() {
132
190
  }, {
@@ -155,16 +213,21 @@ function createDynamicPathProxy(routes, client, knownPathMethods, $signal, $sign
155
213
  const { query, options, ...body } = arg;
156
214
  return await client(routePath, {
157
215
  ...options,
158
- body: method === "GET" ? void 0 : body,
216
+ body: method === "GET" ? void 0 : {
217
+ ...body,
218
+ ...options?.body || {}
219
+ },
159
220
  query,
160
221
  method,
161
222
  async onSuccess(context) {
162
- const signal = $signal?.find((s) => s.matcher(routePath));
163
- if (!signal) return;
164
- const signalAtom = $signals?.[signal.atom];
165
- if (!signalAtom) return;
166
- signalAtom.set(!signalAtom.get());
167
223
  await options?.onSuccess?.(context);
224
+ const matches = atomListeners?.find((s) => s.matcher(routePath));
225
+ if (!matches) return;
226
+ const signal = atoms[matches.signal];
227
+ if (!signal) return;
228
+ setTimeout(() => {
229
+ signal.set(!signal.get());
230
+ }, 0);
168
231
  }
169
232
  });
170
233
  }
@@ -172,9 +235,6 @@ function createDynamicPathProxy(routes, client, knownPathMethods, $signal, $sign
172
235
  }
173
236
  return createProxy();
174
237
  }
175
-
176
- // src/client/session-atom.ts
177
- import { atom, computed, task } from "nanostores";
178
238
  function getSessionAtom(client) {
179
239
  const $signal = atom(false);
180
240
  const $session = computed(
@@ -187,115 +247,41 @@ function getSessionAtom(client) {
187
247
  return session.data;
188
248
  })
189
249
  );
190
- return { $session, $sessionSignal: $signal };
250
+ return { $session, _sessionSignal: $signal };
191
251
  }
192
252
 
193
- // src/client/base.ts
194
- var createAuthFetch = (options) => {
195
- const $baseFetch = createFetch();
196
- return createFetch({
197
- method: "GET",
198
- ...options,
199
- baseURL: getBaseURL(options?.baseURL).withPath,
200
- plugins: [
201
- ...options?.plugins || [],
202
- ...options?.authPlugins?.flatMap((plugin) => plugin($baseFetch).fetchPlugins).filter((plugin) => plugin !== void 0) || [],
203
- ...options?.csrfPlugin !== false ? [csrfPlugin] : [],
204
- redirectPlugin,
205
- addCurrentURL
206
- ]
207
- });
208
- };
209
- var createAuthClient = (options, additionalActions = {}) => {
210
- const $fetch = createAuthFetch(options);
211
- const { $session, $sessionSignal } = getSessionAtom($fetch);
212
- let pluginsActions = {};
213
- const pluginProxySignals = [];
214
- let pluginSignals = {};
215
- let pluginPathMethods = {};
216
- for (const plugin of options?.authPlugins || []) {
217
- const pl = plugin($fetch);
218
- if (pl.authProxySignal) {
219
- pluginProxySignals.push(...pl.authProxySignal);
220
- }
221
- if (pl.actions) {
222
- pluginsActions = {
223
- ...pluginsActions,
224
- ...pl.actions
225
- };
226
- }
227
- if (pl.signals) {
228
- pluginSignals = {
229
- ...pluginSignals,
230
- ...pl.signals
231
- };
232
- }
233
- if (pl.pathMethods) {
234
- pluginPathMethods = {
235
- ...pluginPathMethods,
236
- ...pl.pathMethods
237
- };
238
- }
239
- }
240
- const actions = {
241
- $atoms: {
242
- $session
243
- },
253
+ // src/client/svelte.ts
254
+ function createAuthClient(options) {
255
+ const {
256
+ pluginPathMethods,
257
+ pluginsActions,
258
+ pluginsAtoms,
244
259
  $fetch,
260
+ atomListeners
261
+ } = getClientConfig(options);
262
+ let resolvedHooks = {};
263
+ for (const [key, value] of Object.entries(pluginsAtoms)) {
264
+ resolvedHooks[`use${capitalizeFirstLetter(key)}`] = value;
265
+ }
266
+ const { $session, _sessionSignal } = getSessionAtom($fetch);
267
+ const routes = {
245
268
  ...pluginsActions,
246
- ...additionalActions
269
+ ...resolvedHooks,
270
+ useSession: $session
247
271
  };
248
272
  const proxy = createDynamicPathProxy(
249
- actions,
273
+ routes,
250
274
  $fetch,
275
+ pluginPathMethods,
251
276
  {
252
- ...pluginPathMethods,
253
- "/sign-out": "POST"
277
+ ...pluginsAtoms,
278
+ _sessionSignal
254
279
  },
255
- [
256
- {
257
- matcher: (path) => path === "/organization/create",
258
- atom: "$listOrg"
259
- },
260
- {
261
- matcher: (path) => path.startsWith("/organization"),
262
- atom: "$activeOrgSignal"
263
- },
264
- {
265
- matcher: (path) => path === "/sign-out" || path.startsWith("/sign-up") || path.startsWith("/sign-in"),
266
- atom: "$sessionSignal"
267
- },
268
- ...pluginProxySignals
269
- ],
270
- {
271
- $sessionSignal,
272
- ...pluginSignals
273
- }
280
+ atomListeners
274
281
  );
275
282
  return proxy;
276
- };
283
+ }
277
284
 
278
- // src/client/svelte.ts
279
- var createAuthClient2 = (options) => {
280
- const $fetch = createAuthFetch(options);
281
- const signals = options?.authPlugins?.reduce(
282
- (acc, plugin) => {
283
- return {
284
- ...acc,
285
- ...plugin($fetch).integrations?.svelte?.() || {}
286
- };
287
- },
288
- {}
289
- );
290
- const client = createAuthClient(options, {
291
- ...signals
292
- });
293
- const obj = Object.assign(client, {
294
- $session: client.$atoms.$session
295
- });
296
- return obj;
297
- };
298
- export {
299
- createAuthClient2 as createAuthClient
300
- };
285
+ export { createAuthClient };
286
+ //# sourceMappingURL=svelte.js.map
301
287
  //# sourceMappingURL=svelte.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/base.ts","../src/error/better-auth-error.ts","../src/utils/base-url.ts","../src/client/fetch-plugins.ts","../src/client/proxy.ts","../src/client/session-atom.ts","../src/client/svelte.ts"],"sourcesContent":["import { createFetch } from \"@better-fetch/fetch\";\nimport type { Auth } from \"../auth\";\nimport { getBaseURL } from \"../utils/base-url\";\nimport { addCurrentURL, csrfPlugin, redirectPlugin } from \"./fetch-plugins\";\nimport type { InferRoutes } from \"./path-to-object\";\nimport { createDynamicPathProxy, type AuthProxySignal } from \"./proxy\";\nimport { getSessionAtom } from \"./session-atom\";\nimport type { AuthPlugin, ClientOptions } from \"./type\";\nimport type { UnionToIntersection } from \"../types/helper\";\nimport type { PreinitializedWritableAtom } from \"nanostores\";\nimport type { BetterAuthPlugin } from \"../types/plugins\";\n\n/**\n * used for plugins only\n */\n\nexport const createAuthFetch = (options?: ClientOptions) => {\n\tconst $baseFetch = createFetch();\n\treturn createFetch({\n\t\tmethod: \"GET\",\n\t\t...options,\n\t\tbaseURL: getBaseURL(options?.baseURL).withPath,\n\t\tplugins: [\n\t\t\t...(options?.plugins || []),\n\t\t\t...(options?.authPlugins\n\t\t\t\t?.flatMap((plugin) => plugin($baseFetch).fetchPlugins)\n\t\t\t\t.filter((plugin) => plugin !== undefined) || []),\n\t\t\t...(options?.csrfPlugin !== false ? [csrfPlugin] : []),\n\t\t\tredirectPlugin,\n\t\t\taddCurrentURL,\n\t\t],\n\t});\n};\n\nexport const createAuthClient = <\n\tO extends ClientOptions = ClientOptions,\n\tAT extends Record<string, any> = {},\n>(\n\toptions?: O,\n\tadditionalActions = {} as AT,\n) => {\n\ttype API = O[\"authPlugins\"] extends Array<any>\n\t\t? (O[\"authPlugins\"] extends Array<infer Pl>\n\t\t\t\t? UnionToIntersection<\n\t\t\t\t\t\t//@ts-expect-error\n\t\t\t\t\t\tReturnType<Pl> extends {\n\t\t\t\t\t\t\tplugin: infer Plug;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t? Plug extends BetterAuthPlugin\n\t\t\t\t\t\t\t\t? Plug[\"endpoints\"]\n\t\t\t\t\t\t\t\t: {}\n\t\t\t\t\t\t\t: {}\n\t\t\t\t\t>\n\t\t\t\t: {}) &\n\t\t\t\tAuth[\"api\"]\n\t\t: Auth[\"api\"];\n\n\tconst $fetch = createAuthFetch(options);\n\n\ttype Plugins = O[\"authPlugins\"] extends Array<AuthPlugin>\n\t\t? Array<ReturnType<O[\"authPlugins\"][number]>[\"plugin\"]>\n\t\t: undefined;\n\t//@ts-expect-error\n\tconst { $session, $sessionSignal } = getSessionAtom<{\n\t\thandler: any;\n\t\tapi: any;\n\t\toptions: {\n\t\t\tdatabase: any;\n\t\t\tplugins: Plugins;\n\t\t};\n\t}>($fetch);\n\n\tlet pluginsActions = {} as Record<string, any>;\n\ttype PluginActions = UnionToIntersection<\n\t\tO[\"authPlugins\"] extends Array<infer Pl>\n\t\t\t? //@ts-expect-error\n\t\t\t\tReturnType<Pl> extends {\n\t\t\t\t\tactions?: infer R;\n\t\t\t\t}\n\t\t\t\t? R\n\t\t\t\t: {}\n\t\t\t: {}\n\t>;\n\n\tconst pluginProxySignals: AuthProxySignal[] = [];\n\tlet pluginSignals: Record<string, PreinitializedWritableAtom<boolean>> = {};\n\tlet pluginPathMethods: Record<string, \"POST\" | \"GET\"> = {};\n\n\tfor (const plugin of options?.authPlugins || []) {\n\t\tconst pl = plugin($fetch);\n\t\tif (pl.authProxySignal) {\n\t\t\tpluginProxySignals.push(...pl.authProxySignal);\n\t\t}\n\t\tif (pl.actions) {\n\t\t\tpluginsActions = {\n\t\t\t\t...pluginsActions,\n\t\t\t\t...pl.actions,\n\t\t\t};\n\t\t}\n\t\tif (pl.signals) {\n\t\t\tpluginSignals = {\n\t\t\t\t...pluginSignals,\n\t\t\t\t...pl.signals,\n\t\t\t};\n\t\t}\n\t\tif (pl.pathMethods) {\n\t\t\tpluginPathMethods = {\n\t\t\t\t...pluginPathMethods,\n\t\t\t\t...pl.pathMethods,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst actions = {\n\t\t$atoms: {\n\t\t\t$session,\n\t\t},\n\t\t$fetch,\n\t\t...(pluginsActions as object),\n\t\t...additionalActions,\n\t};\n\n\ttype Actions = typeof actions & PluginActions;\n\n\tconst proxy = createDynamicPathProxy(\n\t\tactions,\n\t\t$fetch,\n\t\t{\n\t\t\t...pluginPathMethods,\n\t\t\t\"/sign-out\": \"POST\",\n\t\t},\n\t\t[\n\t\t\t{\n\t\t\t\tmatcher: (path) => path === \"/organization/create\",\n\t\t\t\tatom: \"$listOrg\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tmatcher: (path) => path.startsWith(\"/organization\"),\n\t\t\t\tatom: \"$activeOrgSignal\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tmatcher: (path) =>\n\t\t\t\t\tpath === \"/sign-out\" ||\n\t\t\t\t\tpath.startsWith(\"/sign-up\") ||\n\t\t\t\t\tpath.startsWith(\"/sign-in\"),\n\t\t\t\tatom: \"$sessionSignal\",\n\t\t\t},\n\t\t\t...pluginProxySignals,\n\t\t],\n\t\t{\n\t\t\t$sessionSignal,\n\t\t\t...pluginSignals,\n\t\t},\n\t) as unknown as InferRoutes<API> & Actions;\n\treturn proxy;\n};\n","export class BetterAuthError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t}\n}\n","import { BetterAuthError } from \"../error/better-auth-error\";\n\nfunction checkHasPath(url: string): boolean {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.pathname !== \"/\";\n\t} catch (error) {\n\t\tconsole.error(\"Invalid URL:\", error);\n\t\treturn false;\n\t}\n}\n\nfunction withPath(url: string, path = \"/api/auth\") {\n\tconst hasPath = checkHasPath(url);\n\tif (hasPath) {\n\t\treturn {\n\t\t\tbaseURL: new URL(url).origin,\n\t\t\twithPath: url,\n\t\t};\n\t}\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn {\n\t\tbaseURL: url,\n\t\twithPath: `${url}${path}`,\n\t};\n}\n\nexport function getBaseURL(url?: string, path?: string) {\n\tif (url) {\n\t\treturn withPath(url, path);\n\t}\n\tconst env: any = typeof process !== \"undefined\" ? process.env : {};\n\tconst fromEnv =\n\t\tenv.BETTER_AUTH_URL ||\n\t\tenv.AUTH_URL ||\n\t\tenv.NEXT_PUBLIC_AUTH_URL ||\n\t\tenv.NEXT_PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.PUBLIC_AUTH_URL ||\n\t\tenv.PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.NUXT_PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.NUXT_PUBLIC_AUTH_URL;\n\tif (fromEnv) {\n\t\treturn withPath(fromEnv, path);\n\t}\n\n\tconst isDev =\n\t\t!fromEnv && (env.NODE_ENV === \"development\" || env.NODE_ENV === \"test\");\n\tif (isDev) {\n\t\treturn {\n\t\t\tbaseURL: \"http://localhost:3000\",\n\t\t\twithPath: \"http://localhost:3000/api/auth\",\n\t\t};\n\t}\n\tthrow new BetterAuthError(\n\t\t\"Could not infer baseURL from environment variables\",\n\t);\n}\n","import { type BetterFetchPlugin, betterFetch } from \"@better-fetch/fetch\";\nimport { BetterAuthError } from \"../error/better-auth-error\";\n\nexport const redirectPlugin = {\n\tid: \"redirect\",\n\tname: \"Redirect\",\n\thooks: {\n\t\tonSuccess(context) {\n\t\t\tif (context.data?.url && context.data?.redirect) {\n\t\t\t\twindow.location.href = context.data.url;\n\t\t\t}\n\t\t},\n\t},\n} satisfies BetterFetchPlugin;\n\nexport const addCurrentURL = {\n\tid: \"add-current-url\",\n\tname: \"Add current URL\",\n\thooks: {\n\t\tonRequest(context) {\n\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\tconst url = new URL(context.url);\n\t\t\t\turl.searchParams.set(\"currentURL\", window.location.href);\n\t\t\t\tcontext.url = url;\n\t\t\t}\n\t\t\treturn context;\n\t\t},\n\t},\n} satisfies BetterFetchPlugin;\n\nexport const csrfPlugin = {\n\tid: \"csrf\",\n\tname: \"CSRF Check\",\n\tasync init(url, options) {\n\t\tif (options?.method !== \"GET\") {\n\t\t\toptions = options || {};\n\t\t\tconst { data, error } = await betterFetch<{\n\t\t\t\tcsrfToken: string;\n\t\t\t}>(\"/csrf\", {\n\t\t\t\tbody: undefined,\n\t\t\t\tbaseURL: options.baseURL,\n\t\t\t\tplugins: [],\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tcredentials: \"include\",\n\t\t\t});\n\t\t\tif (error?.status === 404) {\n\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t\"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).\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (error) {\n\t\t\t\tthrow new BetterAuthError(error.message || \"Failed to get CSRF token.\");\n\t\t\t}\n\t\t\toptions.body = {\n\t\t\t\t...options?.body,\n\t\t\t\tcsrfToken: data.csrfToken,\n\t\t\t};\n\t\t}\n\t\toptions.credentials = \"include\";\n\t\treturn { url, options };\n\t},\n} satisfies BetterFetchPlugin;\n","import type { BetterFetch } from \"@better-fetch/fetch\";\nimport type { PreinitializedWritableAtom } from \"nanostores\";\nimport type { ProxyRequest } from \"./path-to-object\";\nimport type { LiteralUnion } from \"../types/helper\";\n\nfunction getMethod(\n\tpath: string,\n\tknownPathMethods: Record<string, \"POST\" | \"GET\">,\n\targs?: ProxyRequest,\n) {\n\tconst method = knownPathMethods[path];\n\tconst { options, query, ...body } = args || {};\n\tif (method) {\n\t\treturn method;\n\t}\n\tif (options?.method) {\n\t\treturn options.method;\n\t}\n\tif (body && Object.keys(body).length > 0) {\n\t\treturn \"POST\";\n\t}\n\treturn \"GET\";\n}\n\nexport type AuthProxySignal = {\n\tatom: LiteralUnion<string, \"$sessionSignal\">;\n\tmatcher: (path: string) => boolean;\n};\n\nexport function createDynamicPathProxy<T extends Record<string, any>>(\n\troutes: T,\n\tclient: BetterFetch,\n\tknownPathMethods: Record<string, \"POST\" | \"GET\">,\n\t$signal?: AuthProxySignal[],\n\t$signals?: Record<string, PreinitializedWritableAtom<boolean>>,\n): T {\n\tfunction createProxy(path: string[] = []): any {\n\t\treturn new Proxy(function () {}, {\n\t\t\tget(target, prop: string) {\n\t\t\t\tconst fullPath = [...path, prop];\n\t\t\t\tlet current: any = routes;\n\t\t\t\tfor (const segment of fullPath) {\n\t\t\t\t\tif (current && typeof current === \"object\" && segment in current) {\n\t\t\t\t\t\tcurrent = current[segment];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrent = undefined;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (typeof current === \"function\") {\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\n\t\t\t\treturn createProxy(fullPath);\n\t\t\t},\n\t\t\tapply: async (_, __, args) => {\n\t\t\t\tconst routePath =\n\t\t\t\t\t\"/\" +\n\t\t\t\t\tpath\n\t\t\t\t\t\t.map((segment) =>\n\t\t\t\t\t\t\tsegment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"/\");\n\n\t\t\t\tconst arg = (args[0] || {}) as ProxyRequest;\n\t\t\t\tconst method = getMethod(routePath, knownPathMethods, arg);\n\t\t\t\tconst { query, options, ...body } = arg;\n\n\t\t\t\treturn await client(routePath, {\n\t\t\t\t\t...options,\n\t\t\t\t\tbody: method === \"GET\" ? undefined : body,\n\t\t\t\t\tquery: query,\n\t\t\t\t\tmethod,\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tconst signal = $signal?.find((s) => s.matcher(routePath));\n\t\t\t\t\t\tif (!signal) return;\n\t\t\t\t\t\tconst signalAtom = $signals?.[signal.atom];\n\t\t\t\t\t\tif (!signalAtom) return;\n\t\t\t\t\t\tsignalAtom.set(!signalAtom.get());\n\t\t\t\t\t\tawait options?.onSuccess?.(context);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\treturn createProxy() as T;\n}\n","import type { BetterFetch } from \"@better-fetch/fetch\";\nimport { atom, computed, task } from \"nanostores\";\nimport type { Auth as BetterAuth } from \"../auth\";\nimport type { Prettify } from \"../types/helper\";\nimport type { InferSession, InferUser } from \"../types/models\";\n\nexport function getSessionAtom<Auth extends BetterAuth>(client: BetterFetch) {\n\ttype UserWithAdditionalFields = InferUser<Auth[\"options\"]>;\n\ttype SessionWithAdditionalFields = InferSession<Auth[\"options\"]>;\n\tconst $signal = atom<boolean>(false);\n\tconst $session = computed($signal, () =>\n\t\ttask(async () => {\n\t\t\tconst session = await client(\"/session\", {\n\t\t\t\tcredentials: \"include\",\n\t\t\t\tmethod: \"GET\",\n\t\t\t});\n\t\t\treturn session.data as {\n\t\t\t\tuser: Prettify<UserWithAdditionalFields>;\n\t\t\t\tsession: Prettify<SessionWithAdditionalFields>;\n\t\t\t} | null;\n\t\t}),\n\t);\n\treturn { $session, $sessionSignal: $signal };\n}\n","import type { UnionToIntersection } from \"../types/helper\";\nimport { createAuthFetch, createAuthClient as createClient } from \"./base\";\nimport type { AuthPlugin, ClientOptions } from \"./type\";\n\nexport const createAuthClient = <Option extends ClientOptions>(\n\toptions?: Option,\n) => {\n\tconst $fetch = createAuthFetch(options);\n\tconst signals = options?.authPlugins?.reduce(\n\t\t(acc, plugin) => {\n\t\t\treturn {\n\t\t\t\t...acc,\n\t\t\t\t...(plugin($fetch).integrations?.svelte?.() || {}),\n\t\t\t};\n\t\t},\n\t\t{} as Record<string, any>,\n\t) as Option[\"authPlugins\"] extends Array<infer Pl>\n\t\t? Pl extends AuthPlugin\n\t\t\t? UnionToIntersection<\n\t\t\t\t\tReturnType<Pl>[\"integrations\"] extends\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tsvelte?: () => infer R;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| undefined\n\t\t\t\t\t\t? R\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\ttest1: ReturnType<Pl>[\"integrations\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t: {}\n\t\t: {};\n\tconst client = createClient(options, {\n\t\t...signals,\n\t});\n\n\tconst obj = Object.assign(client, {\n\t\t$session: client.$atoms.$session,\n\t});\n\treturn obj;\n};\n"],"mappings":";AAAA,SAAS,mBAAmB;;;ACArB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC5B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M,SAAS,iBAAa,SAAS;AAAA,IACpC,GAAG;AAAA,EACJ,CAAC;AAED,QAAM,MAAM,OAAO,OAAO,QAAQ;AAAA,IACjC,UAAU,OAAO,OAAO;AAAA,EACzB,CAAC;AACD,SAAO;AACR;","names":["createAuthClient"]}
1
+ {"version":3,"sources":["../src/utils/base-url.ts","../src/error/better-auth-error.ts","../src/client/fetch-plugins.ts","../src/client/config.ts","../src/utils/misc.ts","../src/client/proxy.ts","../src/client/session-atom.ts","../src/client/svelte.ts"],"names":[],"mappings":";;;;;;AAAA,SAAS,aAAa,GAAsB,EAAA;AAC3C,EAAI,IAAA;AACH,IAAM,MAAA,SAAA,GAAY,IAAI,GAAA,CAAI,GAAG,CAAA,CAAA;AAC7B,IAAA,OAAO,UAAU,QAAa,KAAA,GAAA,CAAA;AAAA,WACtB,KAAO,EAAA;AACf,IAAQ,OAAA,CAAA,KAAA,CAAM,gBAAgB,KAAK,CAAA,CAAA;AACnC,IAAO,OAAA,KAAA,CAAA;AAAA,GACR;AACD,CAAA;AAEA,SAAS,QAAA,CAAS,GAAa,EAAA,IAAA,GAAO,WAAa,EAAA;AAClD,EAAM,MAAA,OAAA,GAAU,aAAa,GAAG,CAAA,CAAA;AAChC,EAAA,IAAI,OAAS,EAAA;AACZ,IAAO,OAAA,GAAA,CAAA;AAAA,GACR;AACA,EAAA,IAAA,GAAO,KAAK,UAAW,CAAA,GAAG,CAAI,GAAA,IAAA,GAAO,IAAI,IAAI,CAAA,CAAA,CAAA;AAC7C,EAAO,OAAA,CAAA,EAAG,GAAG,CAAA,EAAG,IAAI,CAAA,CAAA,CAAA;AACrB,CAAA;AAEO,SAAS,UAAA,CAAW,KAAc,IAAe,EAAA;AACvD,EAAA,IAAI,GAAK,EAAA;AACR,IAAO,OAAA,QAAA,CAAS,KAAK,IAAI,CAAA,CAAA;AAAA,GAC1B;AACA,EAAA,MAAM,MAAW,OAAO,OAAA,KAAY,WAAc,GAAA,OAAA,CAAQ,MAAM,EAAC,CAA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AA;AAAA,IACA;AAAA,MACC,GAAG,YAAA;AAAA,MACH,cAAA;AAAA,KACD;AAAA,IACA,aAAA;AAAA,GACD,CAAA;AACA,EAAO,OAAA,KAAA,CAAA;AAKR","file":"svelte.js","sourcesContent":["function checkHasPath(url: string): boolean {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.pathname !== \"/\";\n\t} catch (error) {\n\t\tconsole.error(\"Invalid URL:\", error);\n\t\treturn false;\n\t}\n}\n\nfunction withPath(url: string, path = \"/api/auth\") {\n\tconst hasPath = checkHasPath(url);\n\tif (hasPath) {\n\t\treturn url;\n\t}\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${url}${path}`;\n}\n\nexport function getBaseURL(url?: string, path?: string) {\n\tif (url) {\n\t\treturn withPath(url, path);\n\t}\n\tconst env: any = typeof process !== \"undefined\" ? process.env : {};\n\tconst fromEnv =\n\t\tenv.BETTER_AUTH_URL ||\n\t\tenv.NEXT_PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.NUXT_PUBLIC_BETTER_AUTH_URL ||\n\t\tenv.NUXT_PUBLIC_AUTH_URL;\n\tif (fromEnv) {\n\t\treturn withPath(fromEnv, path);\n\t}\n\n\tif (typeof window !== \"undefined\") {\n\t\treturn withPath(window.location.origin, path);\n\t}\n\n\treturn undefined;\n}\n","export class BetterAuthError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t}\n}\n","import { type BetterFetchPlugin, betterFetch } from \"@better-fetch/fetch\";\nimport { BetterAuthError } from \"../error/better-auth-error\";\n\nexport const redirectPlugin = {\n\tid: \"redirect\",\n\tname: \"Redirect\",\n\thooks: {\n\t\tonSuccess(context) {\n\t\t\tif (context.data?.url && context.data?.redirect) {\n\t\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\t\twindow.location.href = context.data.url;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t},\n} satisfies BetterFetchPlugin;\n\nexport const addCurrentURL = {\n\tid: \"add-current-url\",\n\tname: \"Add current URL\",\n\thooks: {\n\t\tonRequest(context) {\n\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\tconst url = new URL(context.url);\n\t\t\t\turl.searchParams.set(\"currentURL\", window.location.href);\n\t\t\t\tcontext.url = url;\n\t\t\t}\n\t\t\treturn context;\n\t\t},\n\t},\n} satisfies BetterFetchPlugin;\n\nexport const csrfPlugin = {\n\tid: \"csrf\",\n\tname: \"CSRF Check\",\n\tasync init(url, options) {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\t/**\n\t\t\t * If origin is the same as baseURL\n\t\t\t * then we don't need to check the CSRF token.\n\t\t\t */\n\t\t\tconst isTheSameOrigin =\n\t\t\t\tnew URL(options?.baseURL || url).origin === window.location.origin;\n\t\t\tif (isTheSameOrigin) {\n\t\t\t\treturn { url, options };\n\t\t\t}\n\t\t}\n\n\t\tif (!options?.baseURL) {\n\t\t\tthrow new BetterAuthError(\n\t\t\t\t\"API Base URL on the auth client isn't configured. Please pass it directly to the client `baseURL`\",\n\t\t\t);\n\t\t}\n\n\t\tif (options?.method !== \"GET\") {\n\t\t\toptions = options || {};\n\t\t\tconst { data, error } = await betterFetch<{\n\t\t\t\tcsrfToken: string;\n\t\t\t}>(\"/csrf\", {\n\t\t\t\tbody: undefined,\n\t\t\t\tbaseURL: options.baseURL,\n\t\t\t\tplugins: [],\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tcredentials: \"include\",\n\t\t\t\tcustomFetchImpl: options.customFetchImpl,\n\t\t\t});\n\t\t\tif (error?.status === 404) {\n\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t\"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).\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (error) {\n\t\t\t\tthrow new BetterAuthError(error.message || \"Failed to get CSRF token.\");\n\t\t\t}\n\t\t\toptions.body = {\n\t\t\t\t...options?.body,\n\t\t\t\tcsrfToken: data.csrfToken,\n\t\t\t};\n\t\t}\n\t\toptions.credentials = \"include\";\n\t\treturn { url, options };\n\t},\n} satisfies BetterFetchPlugin;\n","import { createFetch } from \"@better-fetch/fetch\";\nimport { getBaseURL } from \"../utils/base-url\";\nimport { type Atom } from \"nanostores\";\nimport type { AtomListener, ClientOptions } from \"./types\";\n\nimport { addCurrentURL, csrfPlugin, redirectPlugin } from \"./fetch-plugins\";\n\nexport const getClientConfig = <O extends ClientOptions>(options?: O) => {\n\tconst $fetch = createFetch({\n\t\tbaseURL: getBaseURL(options?.fetchOptions?.baseURL || options?.baseURL),\n\t\t...options?.fetchOptions,\n\t\tplugins: [\n\t\t\tcsrfPlugin,\n\t\t\tredirectPlugin,\n\t\t\taddCurrentURL,\n\t\t\t...(options?.fetchOptions?.plugins || []),\n\t\t\t...(options?.plugins\n\t\t\t\t?.flatMap((plugin) => plugin.fetchPlugins)\n\t\t\t\t.filter((pl) => pl !== undefined) || []),\n\t\t],\n\t});\n\tconst plugins = options?.plugins || [];\n\tlet pluginsActions = {} as Record<string, any>;\n\tlet pluginsAtoms = {} as Record<string, Atom<any>>;\n\tlet pluginPathMethods: Record<string, \"POST\" | \"GET\"> = {\n\t\t\"/sign-out\": \"POST\",\n\t};\n\tconst atomListeners: AtomListener[] = [\n\t\t{\n\t\t\tsignal: \"_sessionSignal\",\n\t\t\tmatcher(path) {\n\t\t\t\treturn path === \"/sign-out\" || path === \"sign-up/email\";\n\t\t\t},\n\t\t},\n\t];\n\tfor (const plugin of plugins) {\n\t\tif (plugin.getActions) {\n\t\t\tObject.assign(pluginsActions, plugin.getActions?.($fetch));\n\t\t}\n\t\tif (plugin.getAtoms) {\n\t\t\tObject.assign(pluginsAtoms, plugin.getAtoms?.($fetch));\n\t\t}\n\t\tif (plugin.pathMethods) {\n\t\t\tObject.assign(pluginPathMethods, plugin.pathMethods);\n\t\t}\n\t\tif (plugin.atomListeners) {\n\t\t\tatomListeners.push(...plugin.atomListeners);\n\t\t}\n\t}\n\treturn {\n\t\tpluginsActions,\n\t\tpluginsAtoms,\n\t\tpluginPathMethods,\n\t\tatomListeners,\n\t\t$fetch,\n\t};\n};\n","export function capitalizeFirstLetter(str: string) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n","import type { BetterFetch } from \"@better-fetch/fetch\";\nimport type { Atom, PreinitializedWritableAtom } from \"nanostores\";\nimport type { ProxyRequest } from \"./path-to-object\";\nimport type { AuthClientPlugin } from \"./types\";\n\nfunction getMethod(\n\tpath: string,\n\tknownPathMethods: Record<string, \"POST\" | \"GET\">,\n\targs?: ProxyRequest,\n) {\n\tconst method = knownPathMethods[path];\n\tconst { options, query, ...body } = args || {};\n\tif (method) {\n\t\treturn method;\n\t}\n\tif (options?.method) {\n\t\treturn options.method;\n\t}\n\tif (body && Object.keys(body).length > 0) {\n\t\treturn \"POST\";\n\t}\n\treturn \"GET\";\n}\n\nexport type AuthProxySignal = {\n\tatom: PreinitializedWritableAtom<boolean>;\n\tmatcher: (path: string) => boolean;\n};\n\nexport function createDynamicPathProxy<T extends Record<string, any>>(\n\troutes: T,\n\tclient: BetterFetch,\n\tknownPathMethods: Record<string, \"POST\" | \"GET\">,\n\tatoms: Record<string, Atom>,\n\tatomListeners: AuthClientPlugin[\"atomListeners\"],\n): T {\n\tfunction createProxy(path: string[] = []): any {\n\t\treturn new Proxy(function () {}, {\n\t\t\tget(target, prop: string) {\n\t\t\t\tconst fullPath = [...path, prop];\n\t\t\t\tlet current: any = routes;\n\t\t\t\tfor (const segment of fullPath) {\n\t\t\t\t\tif (current && typeof current === \"object\" && segment in current) {\n\t\t\t\t\t\tcurrent = current[segment];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrent = undefined;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (typeof current === \"function\") {\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t\treturn createProxy(fullPath);\n\t\t\t},\n\t\t\tapply: async (_, __, args) => {\n\t\t\t\tconst routePath =\n\t\t\t\t\t\"/\" +\n\t\t\t\t\tpath\n\t\t\t\t\t\t.map((segment) =>\n\t\t\t\t\t\t\tsegment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"/\");\n\n\t\t\t\tconst arg = (args[0] || {}) as ProxyRequest;\n\t\t\t\tconst method = getMethod(routePath, knownPathMethods, arg);\n\t\t\t\tconst { query, options, ...body } = arg;\n\n\t\t\t\treturn await client(routePath, {\n\t\t\t\t\t...options,\n\t\t\t\t\tbody:\n\t\t\t\t\t\tmethod === \"GET\"\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t\t\t...(options?.body || {}),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\tquery: query,\n\t\t\t\t\tmethod,\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tawait options?.onSuccess?.(context);\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * We trigger listeners\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconst matches = atomListeners?.find((s) => s.matcher(routePath));\n\t\t\t\t\t\tif (!matches) return;\n\t\t\t\t\t\tconst signal = atoms[matches.signal];\n\t\t\t\t\t\tif (!signal) return;\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * To avoid race conditions we set the signal in a setTimeout\n\t\t\t\t\t\t */\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t//@ts-expect-error\n\t\t\t\t\t\t\tsignal.set(!signal.get());\n\t\t\t\t\t\t}, 0);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\treturn createProxy() as T;\n}\n","import type { BetterFetch } from \"@better-fetch/fetch\";\nimport { atom, computed, task } from \"nanostores\";\nimport type { Auth as BetterAuth } from \"../auth\";\nimport type { Prettify } from \"../types/helper\";\nimport type { InferSession, InferUser } from \"../types/models\";\nimport type { AuthClientPlugin, ClientOptions } from \"./types\";\n\nexport function getSessionAtom<Option extends ClientOptions>(\n\tclient: BetterFetch,\n) {\n\ttype Plugins = Option[\"plugins\"] extends Array<AuthClientPlugin>\n\t\t? Array<Option[\"plugins\"][number][\"$InferServerPlugin\"]>\n\t\t: undefined;\n\n\ttype Auth = {\n\t\thandler: any;\n\t\tapi: any;\n\t\toptions: {\n\t\t\tdatabase: any;\n\t\t\tplugins: Plugins;\n\t\t};\n\t};\n\n\ttype UserWithAdditionalFields = InferUser<\n\t\tAuth extends BetterAuth ? Auth : never\n\t>;\n\n\t//@ts-expect-error\n\ttype SessionWithAdditionalFields = InferSession<Auth[\"options\"]>;\n\tconst $signal = atom<boolean>(false);\n\tconst $session = computed($signal, () =>\n\t\ttask(async () => {\n\t\t\tconst session = await client(\"/session\", {\n\t\t\t\tcredentials: \"include\",\n\t\t\t\tmethod: \"GET\",\n\t\t\t});\n\t\t\treturn session.data as {\n\t\t\t\tuser: Prettify<UserWithAdditionalFields>;\n\t\t\t\tsession: Prettify<SessionWithAdditionalFields>;\n\t\t\t} | null;\n\t\t}),\n\t);\n\treturn { $session, _sessionSignal: $signal };\n}\n","import { getClientConfig } from \"./config\";\nimport { capitalizeFirstLetter } from \"../utils/misc\";\nimport type {\n\tAuthClientPlugin,\n\tClientOptions,\n\tInferActions,\n\tInferClientAPI,\n\tIsSignal,\n} from \"./types\";\nimport { createDynamicPathProxy } from \"./proxy\";\nimport { getSessionAtom } from \"./session-atom\";\nimport type { UnionToIntersection } from \"../types/helper\";\n\ntype InferResolvedHooks<O extends ClientOptions> = O[\"plugins\"] extends Array<\n\tinfer Plugin\n>\n\t? Plugin extends AuthClientPlugin\n\t\t? Plugin[\"getAtoms\"] extends (fetch: any) => infer Atoms\n\t\t\t? Atoms extends Record<string, any>\n\t\t\t\t? {\n\t\t\t\t\t\t[key in keyof Atoms as IsSignal<key> extends true\n\t\t\t\t\t\t\t? never\n\t\t\t\t\t\t\t: key extends string\n\t\t\t\t\t\t\t\t? `use${Capitalize<key>}`\n\t\t\t\t\t\t\t\t: never]: Atoms[key];\n\t\t\t\t\t}\n\t\t\t\t: {}\n\t\t\t: {}\n\t\t: {}\n\t: {};\n\nexport function createAuthClient<Option extends ClientOptions>(\n\toptions?: Option,\n) {\n\tconst {\n\t\tpluginPathMethods,\n\t\tpluginsActions,\n\t\tpluginsAtoms,\n\t\t$fetch,\n\t\tatomListeners,\n\t} = getClientConfig(options);\n\tlet resolvedHooks: Record<string, any> = {};\n\tfor (const [key, value] of Object.entries(pluginsAtoms)) {\n\t\tresolvedHooks[`use${capitalizeFirstLetter(key)}`] = value;\n\t}\n\tconst { $session, _sessionSignal } = getSessionAtom<Option>($fetch);\n\tconst routes = {\n\t\t...pluginsActions,\n\t\t...resolvedHooks,\n\t\tuseSession: $session,\n\t};\n\tconst proxy = createDynamicPathProxy(\n\t\troutes,\n\t\t$fetch,\n\t\tpluginPathMethods,\n\t\t{\n\t\t\t...pluginsAtoms,\n\t\t\t_sessionSignal,\n\t\t},\n\t\tatomListeners,\n\t);\n\treturn proxy as UnionToIntersection<InferResolvedHooks<Option>> &\n\t\tInferClientAPI<Option> &\n\t\tInferActions<Option> & {\n\t\t\tuseSession: typeof $session;\n\t\t};\n}\n"]}
@@ -0,0 +1,81 @@
1
+ import { BetterFetchResponse, BetterFetchOption, BetterFetch, BetterFetchPlugin } from '@better-fetch/fetch';
2
+ import { a as BetterAuthPlugin } from './internal-adapter-CVKQ4XR9.js';
3
+ import { Atom } from 'nanostores';
4
+ import { U as UnionToIntersection, H as HasRequiredKeys, P as Prettify, L as LiteralString } from './helper-D8dhRz72.js';
5
+ import { Auth } from './index.js';
6
+ import { Endpoint, Context } from 'better-call';
7
+
8
+ type CamelCase<S extends string> = S extends `${infer P1}-${infer P2}${infer P3}` ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}` : Lowercase<S>;
9
+ type PathToObject<T extends string, Fn extends (...args: any[]) => any> = T extends `/${infer Segment}/${infer Rest}` ? {
10
+ [K in CamelCase<Segment>]: PathToObject<`/${Rest}`, Fn>;
11
+ } : T extends `/${infer Segment}` ? {
12
+ [K in CamelCase<Segment>]: Fn;
13
+ } : never;
14
+ type InferCtx<C extends Context<any, any>> = C["body"] extends Record<string, any> ? C["body"] & {
15
+ options?: BetterFetchOption<undefined, C["query"], C["params"]>;
16
+ } : C["query"] extends Record<string, any> ? {
17
+ query: C["query"];
18
+ options?: Omit<BetterFetchOption<C["body"], C["query"], C["params"]>, "query">;
19
+ } : {
20
+ options?: BetterFetchOption<C["body"], C["query"], C["params"]>;
21
+ };
22
+ type MergeRoutes<T> = UnionToIntersection<T>;
23
+ type InferRoute<API> = API extends {
24
+ [key: string]: infer T;
25
+ } ? T extends Endpoint ? T["options"]["metadata"] extends {
26
+ onClient: "hide";
27
+ } ? {} : PathToObject<T["path"], T extends (ctx: infer C) => infer R ? C extends Context<any, any> ? (...data: HasRequiredKeys<InferCtx<C>> extends true ? [Prettify<InferCtx<C>>] : [Prettify<InferCtx<C>>?]) => Promise<BetterFetchResponse<Awaited<R>>> : never : never> : never : never;
28
+ type InferRoutes<API extends Record<string, Endpoint>> = MergeRoutes<InferRoute<API>>;
29
+
30
+ type AtomListener = {
31
+ matcher: (path: string) => boolean;
32
+ signal: string;
33
+ };
34
+ interface AuthClientPlugin {
35
+ id: LiteralString;
36
+ /**
37
+ * only used for type inference. don't pass the
38
+ * actual plugin
39
+ */
40
+ $InferServerPlugin?: BetterAuthPlugin;
41
+ /**
42
+ * Custom actions
43
+ */
44
+ getActions?: ($fetch: BetterFetch) => Record<string, any>;
45
+ /**
46
+ * State atoms that'll be resolved by each framework
47
+ * auth store.
48
+ */
49
+ getAtoms?: ($fetch: BetterFetch) => Record<string, Atom<any>>;
50
+ /**
51
+ * specify path methods for server plugin inferred
52
+ * endpoints to force a specific method.
53
+ */
54
+ pathMethods?: Record<string, "POST" | "GET">;
55
+ /**
56
+ * Better fetch plugins
57
+ */
58
+ fetchPlugins?: BetterFetchPlugin[];
59
+ /**
60
+ * a list of recaller based on a matcher function.
61
+ * The signal name needs to match a signal in this
62
+ * plugin or any plugin the user might have added.
63
+ */
64
+ atomListeners?: AtomListener[];
65
+ }
66
+ interface ClientOptions {
67
+ fetchOptions?: BetterFetchOption;
68
+ plugins?: AuthClientPlugin[];
69
+ baseURL?: string;
70
+ }
71
+ type InferClientAPI<O extends ClientOptions> = InferRoutes<O["plugins"] extends Array<any> ? (O["plugins"] extends Array<infer Pl> ? UnionToIntersection<Pl extends {
72
+ $InferServerPlugin: infer Plug;
73
+ } ? Plug extends BetterAuthPlugin ? Plug["endpoints"] : {} : {}> : {}) & Auth["api"] : Auth["api"]>;
74
+ type InferActions<O extends ClientOptions> = O["plugins"] extends Array<infer Plugin> ? UnionToIntersection<Plugin extends AuthClientPlugin ? Plugin["getActions"] extends ($fetch: BetterFetch) => infer Actions ? Actions : {} : {}> : {};
75
+ /**
76
+ * signals are just used to recall a computed value. as a
77
+ * convention they start with "_"
78
+ */
79
+ type IsSignal<T> = T extends `_${infer _}` ? true : false;
80
+
81
+ export type { AuthClientPlugin as A, ClientOptions as C, InferClientAPI as I, InferActions as a, IsSignal as b };
package/dist/types.d.ts CHANGED
@@ -1,7 +1,33 @@
1
- export { a as BetterAuthOptions, c as InferSession, b as InferUser } from './index-CGeV0d2g.js';
2
- import 'better-call';
1
+ import { B as BetterAuthOptions, F as FieldAttribute, I as InferFieldOutput } from './internal-adapter-CVKQ4XR9.js';
2
+ import { U as User, S as Session } from './index-CcxejJTH.js';
3
+ import { Auth } from './index.js';
4
+ import { U as UnionToIntersection, P as Prettify } from './helper-D8dhRz72.js';
5
+ import 'kysely';
3
6
  import 'zod';
4
- import './helper-B5_2Vzba.js';
5
- import './schema-BOszzrbQ.js';
7
+ import 'better-call';
6
8
  import 'arctic';
7
- import 'kysely';
9
+
10
+ type AdditionalSessionFields<Options extends BetterAuthOptions> = Options["plugins"] extends Array<infer T> ? T extends {
11
+ schema: {
12
+ session: {
13
+ fields: infer Field;
14
+ };
15
+ };
16
+ } ? Field extends Record<string, FieldAttribute> ? {
17
+ [key in keyof Field]: InferFieldOutput<Field[key]>;
18
+ } : {} : {} : {};
19
+ type AdditionalUserFields<Options extends BetterAuthOptions> = Options["plugins"] extends Array<infer T> ? T extends {
20
+ schema: {
21
+ user: {
22
+ fields: infer Field;
23
+ };
24
+ };
25
+ } ? Field extends Record<infer Key, FieldAttribute> ? Prettify<{
26
+ [key in Key as Field[key]["required"] extends false ? never : Field[key]["defaultValue"] extends boolean | string | number | Date | Function ? key : never]: InferFieldOutput<Field[key]>;
27
+ } & {
28
+ [key in Key as Field[key]["returned"] extends false ? never : key]?: InferFieldOutput<Field[key]>;
29
+ }> : {} : {} : {};
30
+ type InferUser<O extends BetterAuthOptions | Auth> = UnionToIntersection<User & (O extends BetterAuthOptions ? AdditionalUserFields<O> : O extends Auth ? AdditionalUserFields<O["options"]> : {})>;
31
+ type InferSession<O extends BetterAuthOptions | Auth> = UnionToIntersection<Session & (O extends BetterAuthOptions ? AdditionalSessionFields<O> : O extends Auth ? AdditionalSessionFields<O["options"]> : {})>;
32
+
33
+ export { BetterAuthOptions, type InferSession, type InferUser };
package/dist/types.js CHANGED
@@ -1 +1,3 @@
1
+
2
+ //# sourceMappingURL=types.js.map
1
3
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"types.js"}