@take-out/better-auth-utils 0.0.28

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 (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -0
  3. package/dist/cjs/createAuthClient.cjs +172 -0
  4. package/dist/cjs/createAuthClient.js +153 -0
  5. package/dist/cjs/createAuthClient.js.map +6 -0
  6. package/dist/cjs/createAuthClient.native.js +161 -0
  7. package/dist/cjs/createAuthClient.native.js.map +6 -0
  8. package/dist/cjs/index.cjs +18 -0
  9. package/dist/cjs/index.js +15 -0
  10. package/dist/cjs/index.js.map +6 -0
  11. package/dist/cjs/index.native.js +20 -0
  12. package/dist/cjs/index.native.js.map +6 -0
  13. package/dist/esm/createAuthClient.js +143 -0
  14. package/dist/esm/createAuthClient.js.map +6 -0
  15. package/dist/esm/createAuthClient.mjs +149 -0
  16. package/dist/esm/createAuthClient.mjs.map +1 -0
  17. package/dist/esm/createAuthClient.native.js +164 -0
  18. package/dist/esm/createAuthClient.native.js.map +1 -0
  19. package/dist/esm/index.js +2 -0
  20. package/dist/esm/index.js.map +6 -0
  21. package/dist/esm/index.mjs +2 -0
  22. package/dist/esm/index.mjs.map +1 -0
  23. package/dist/esm/index.native.js +2 -0
  24. package/dist/esm/index.native.js.map +1 -0
  25. package/package.json +64 -0
  26. package/src/createAuthClient.ts +324 -0
  27. package/src/index.ts +1 -0
  28. package/types/client.d.ts +10 -0
  29. package/types/client.d.ts.map +11 -0
  30. package/types/createAuthClient.d.ts +81 -0
  31. package/types/createAuthClient.d.ts.map +18 -0
  32. package/types/hooks/useAuthSession.d.ts +8 -0
  33. package/types/hooks/useAuthSession.d.ts.map +13 -0
  34. package/types/hooks/useAuthState.d.ts +7 -0
  35. package/types/hooks/useAuthState.d.ts.map +13 -0
  36. package/types/hooks/useAuthUser.d.ts +8 -0
  37. package/types/hooks/useAuthUser.d.ts.map +13 -0
  38. package/types/index.d.ts +3 -0
  39. package/types/index.d.ts.map +11 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 vxrn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # @take-out/better-auth-utils
2
+
3
+ Better Auth utilities and helpers for React/React Native applications.
4
+
5
+ ## Features
6
+
7
+ - JWT support for Zero, Tauri, and React Native
8
+ - Session persistence in local storage
9
+ - Token validation and refresh
10
+ - State management with emitters
11
+ - Automatic retry on authentication errors
12
+ - TypeScript support with full type safety
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ bun add @take-out/better-auth-utils
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ### Basic Setup
23
+
24
+ ```typescript
25
+ import { createBetterAuthClient } from '@take-out/better-auth-utils'
26
+ import { adminClient, magicLinkClient } from 'better-auth/client/plugins'
27
+
28
+ const authClient = createBetterAuthClient({
29
+ baseURL: 'https://your-app.com',
30
+ plugins: [adminClient(), magicLinkClient()],
31
+ // Optional callbacks
32
+ onAuthStateChange: (state) => {
33
+ console.info('Auth state changed:', state)
34
+ },
35
+ onAuthError: (error) => {
36
+ console.error('Auth error:', error)
37
+ },
38
+ })
39
+
40
+ // Export for use throughout your app
41
+ export const {
42
+ authClient,
43
+ useAuth,
44
+ getAuth,
45
+ setAuthClientToken,
46
+ clearAuthClientToken,
47
+ } = authClient
48
+ ```
49
+
50
+ ### Using in React Components
51
+
52
+ ```tsx
53
+ import { useAuth } from './auth'
54
+
55
+ function UserProfile() {
56
+ const { user, state } = useAuth()
57
+
58
+ if (state === 'loading') return <div>Loading...</div>
59
+ if (state === 'logged-out') return <div>Please log in</div>
60
+
61
+ return <div>Welcome, {user?.name}!</div>
62
+ }
63
+ ```
64
+
65
+ ### Custom User Types
66
+
67
+ ```typescript
68
+ import type { User } from '@take-out/better-auth-utils'
69
+
70
+ interface MyUser extends User {
71
+ role?: 'admin' | 'user'
72
+ preferences?: {
73
+ theme: 'light' | 'dark'
74
+ }
75
+ }
76
+
77
+ const authClient = createBetterAuthClient<any, MyUser>({
78
+ baseURL: 'https://your-app.com',
79
+ })
80
+ ```
81
+
82
+ ### Configuration Options
83
+
84
+ - `baseURL` - The base URL for your auth server
85
+ - `plugins` - Array of better-auth plugins
86
+ - `onAuthStateChange` - Callback when auth state changes
87
+ - `onAuthError` - Callback for handling auth errors
88
+ - `storagePrefix` - Prefix for local storage keys (default: 'auth')
89
+ - `retryDelay` - Delay in ms after auth errors (default: 4000)
90
+ - `tokenValidationEndpoint` - Custom token validation endpoint (default:
91
+ '/api/auth/validateToken')
92
+
93
+ ## API
94
+
95
+ ### `createBetterAuthClient(options)`
96
+
97
+ Creates a new authentication client with the provided options.
98
+
99
+ ### `useAuth()`
100
+
101
+ React hook that returns the current authentication state.
102
+
103
+ ### `getAuth()`
104
+
105
+ Gets the current authentication state (non-reactive).
106
+
107
+ ### `setAuthClientToken({ token, session })`
108
+
109
+ Sets the authentication token and session.
110
+
111
+ ### `clearAuthClientToken()`
112
+
113
+ Clears the stored authentication token.
114
+
115
+ ### `clearState()`
116
+
117
+ Clears all authentication state and storage.
118
+
119
+ ## Development
120
+
121
+ ```bash
122
+ # Install dependencies
123
+ bun install
124
+
125
+ # Build the package
126
+ bun run build
127
+
128
+ # Run in watch mode
129
+ bun run watch
130
+
131
+ # Lint the code
132
+ bun run lint:fix
133
+ ```
134
+
135
+ ## License
136
+
137
+ MIT
@@ -0,0 +1,172 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: !0
9
+ });
10
+ },
11
+ __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
13
+ get: () => from[key],
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ return to;
17
+ };
18
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
19
+ value: !0
20
+ }), mod);
21
+ var createAuthClient_exports = {};
22
+ __export(createAuthClient_exports, {
23
+ createBetterAuthClient: () => createBetterAuthClient
24
+ });
25
+ module.exports = __toCommonJS(createAuthClient_exports);
26
+ var import_helpers = require("@take-out/helpers"),
27
+ import_client = require("better-auth/client");
28
+ function createBetterAuthClient(options) {
29
+ const {
30
+ onAuthStateChange,
31
+ onAuthError,
32
+ createUser,
33
+ storagePrefix = "auth",
34
+ retryDelay = 4e3,
35
+ tokenValidationEndpoint = "/api/auth/validateToken",
36
+ ...authClientOptions
37
+ } = options,
38
+ empty = {
39
+ state: "logged-out",
40
+ session: null,
41
+ user: null,
42
+ token: null
43
+ },
44
+ createAuthClientWithSession = session => (0, import_client.createAuthClient)({
45
+ ...authClientOptions,
46
+ fetchOptions: {
47
+ headers: {
48
+ Authorization: `Bearer ${session}`
49
+ }
50
+ }
51
+ }),
52
+ keysStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-keys`),
53
+ stateStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-state`);
54
+ let authClient = (() => {
55
+ const existingSession = keysStorage.get()?.session;
56
+ return existingSession ? createAuthClientWithSession(existingSession) : (0, import_client.createAuthClient)(authClientOptions);
57
+ })();
58
+ const authState = (0, import_helpers.createEmitter)("authState", stateStorage.get() || empty, {
59
+ comparator: import_helpers.isEqualDeepLite
60
+ }),
61
+ authClientVersion = (0, import_helpers.createEmitter)("authClientVersion", 0),
62
+ setState = update => {
63
+ const next = {
64
+ ...authState.value,
65
+ ...update
66
+ };
67
+ stateStorage.set(next), authState.emit(next), next.token && next.session ? keysStorage.set({
68
+ token: next.token,
69
+ session: next.session.token
70
+ }) : keysStorage.set({
71
+ token: "",
72
+ session: ""
73
+ }), onAuthStateChange?.(next);
74
+ },
75
+ setAuthClientToken = async props => {
76
+ keysStorage.set(props), updateAuthClient(props.session);
77
+ };
78
+ function updateAuthClient(session) {
79
+ authClient = createAuthClientWithSession(session), authClientVersion.emit(Math.random()), subscribeToAuthEffect();
80
+ }
81
+ let dispose = null,
82
+ retryTimer = null;
83
+ function subscribeToAuthEffect() {
84
+ dispose?.(), dispose = authClient.useSession.subscribe(async props => {
85
+ const {
86
+ data: dataGeneric,
87
+ isPending,
88
+ error
89
+ } = props;
90
+ if (error) {
91
+ onAuthError?.(error), scheduleAuthRetry(retryDelay);
92
+ return;
93
+ }
94
+ const data = dataGeneric;
95
+ setState({
96
+ state: isPending ? "loading" : data?.session ? "logged-in" : "logged-out",
97
+ session: data?.session,
98
+ user: data?.user ? createUser ? createUser(data.user) : data.user : null
99
+ }), data?.session && !authState.value.token && getValidToken().then(token => {
100
+ token && setState({
101
+ token
102
+ });
103
+ });
104
+ });
105
+ }
106
+ function scheduleAuthRetry(delayMs) {
107
+ retryTimer && clearTimeout(retryTimer), retryTimer = setTimeout(() => {
108
+ retryTimer = null, subscribeToAuthEffect();
109
+ }, delayMs);
110
+ }
111
+ async function getValidToken() {
112
+ const existing = keysStorage.get()?.token;
113
+ if (existing) try {
114
+ if ((await fetch(tokenValidationEndpoint, {
115
+ method: "POST",
116
+ headers: {
117
+ "Content-Type": "application/json"
118
+ },
119
+ body: JSON.stringify({
120
+ token: existing
121
+ })
122
+ }).then(res2 => res2.json()))?.valid) return existing;
123
+ } catch (error) {
124
+ console.error("Error validating token:", error);
125
+ }
126
+ const res = await authClient.$fetch("/token");
127
+ if (res.error) {
128
+ console.error(`Error fetching token: ${res.error.statusText}`);
129
+ return;
130
+ }
131
+ return res.data?.token;
132
+ }
133
+ const clearAuthClientToken = () => {
134
+ keysStorage.remove();
135
+ },
136
+ getAuth = () => {
137
+ const state = authState?.value || empty;
138
+ return {
139
+ ...state,
140
+ loggedIn: !!state.session
141
+ };
142
+ },
143
+ useAuth = () => (0, import_helpers.useEmitterValue)(authState) || empty;
144
+ function clearState() {
145
+ keysStorage.clear(), stateStorage.clear(), setState(empty);
146
+ }
147
+ if (subscribeToAuthEffect(), typeof window < "u" && window.addEventListener) {
148
+ const cleanup = () => {
149
+ dispose?.(), retryTimer && clearTimeout(retryTimer);
150
+ };
151
+ window.addEventListener("beforeunload", cleanup);
152
+ }
153
+ const proxiedAuthClient = new Proxy(authClient, {
154
+ get(_target, key) {
155
+ return key === "signOut" ? async () => {
156
+ clearState(), await authClient.signOut?.(), typeof window < "u" && window.location?.reload?.();
157
+ } : Reflect.get(authClient, key);
158
+ }
159
+ });
160
+ return {
161
+ authClientVersion,
162
+ clearState,
163
+ authState,
164
+ authClient: proxiedAuthClient,
165
+ setAuthClientToken,
166
+ clearAuthClientToken,
167
+ useAuth,
168
+ getAuth,
169
+ getValidToken,
170
+ updateAuthClient
171
+ };
172
+ }
@@ -0,0 +1,153 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: !0 });
8
+ }, __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from == "object" || typeof from == "function")
10
+ for (let key of __getOwnPropNames(from))
11
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
15
+ var createAuthClient_exports = {};
16
+ __export(createAuthClient_exports, {
17
+ createBetterAuthClient: () => createBetterAuthClient
18
+ });
19
+ module.exports = __toCommonJS(createAuthClient_exports);
20
+ var import_helpers = require("@take-out/helpers"), import_client = require("better-auth/client");
21
+ function createBetterAuthClient(options) {
22
+ const {
23
+ onAuthStateChange,
24
+ onAuthError,
25
+ createUser,
26
+ storagePrefix = "auth",
27
+ retryDelay = 4e3,
28
+ tokenValidationEndpoint = "/api/auth/validateToken",
29
+ ...authClientOptions
30
+ } = options, empty = {
31
+ state: "logged-out",
32
+ session: null,
33
+ user: null,
34
+ token: null
35
+ }, createAuthClientWithSession = (session) => (0, import_client.createAuthClient)({
36
+ ...authClientOptions,
37
+ fetchOptions: {
38
+ headers: {
39
+ Authorization: `Bearer ${session}`
40
+ }
41
+ }
42
+ }), keysStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-keys`), stateStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-state`);
43
+ let authClient = (() => {
44
+ const existingSession = keysStorage.get()?.session;
45
+ return existingSession ? createAuthClientWithSession(existingSession) : (0, import_client.createAuthClient)(authClientOptions);
46
+ })();
47
+ const authState = (0, import_helpers.createEmitter)(
48
+ "authState",
49
+ stateStorage.get() || empty,
50
+ {
51
+ comparator: import_helpers.isEqualDeepLite
52
+ }
53
+ ), authClientVersion = (0, import_helpers.createEmitter)("authClientVersion", 0), setState = (update) => {
54
+ const next = { ...authState.value, ...update };
55
+ stateStorage.set(next), authState.emit(next), next.token && next.session ? keysStorage.set({
56
+ token: next.token,
57
+ session: next.session.token
58
+ }) : keysStorage.set({
59
+ token: "",
60
+ session: ""
61
+ }), onAuthStateChange?.(next);
62
+ }, setAuthClientToken = async (props) => {
63
+ keysStorage.set(props), updateAuthClient(props.session);
64
+ };
65
+ function updateAuthClient(session) {
66
+ authClient = createAuthClientWithSession(session), authClientVersion.emit(Math.random()), subscribeToAuthEffect();
67
+ }
68
+ let dispose = null, retryTimer = null;
69
+ function subscribeToAuthEffect() {
70
+ dispose?.(), dispose = authClient.useSession.subscribe(async (props) => {
71
+ const { data: dataGeneric, isPending, error } = props;
72
+ if (error) {
73
+ onAuthError?.(error), scheduleAuthRetry(retryDelay);
74
+ return;
75
+ }
76
+ const data = dataGeneric;
77
+ setState({
78
+ state: isPending ? "loading" : data?.session ? "logged-in" : "logged-out",
79
+ session: data?.session,
80
+ user: data?.user ? createUser ? createUser(data.user) : data.user : null
81
+ }), data?.session && !authState.value.token && getValidToken().then((token) => {
82
+ token && setState({ token });
83
+ });
84
+ });
85
+ }
86
+ function scheduleAuthRetry(delayMs) {
87
+ retryTimer && clearTimeout(retryTimer), retryTimer = setTimeout(() => {
88
+ retryTimer = null, subscribeToAuthEffect();
89
+ }, delayMs);
90
+ }
91
+ async function getValidToken() {
92
+ const existing = keysStorage.get()?.token;
93
+ if (existing)
94
+ try {
95
+ if ((await fetch(tokenValidationEndpoint, {
96
+ method: "POST",
97
+ headers: {
98
+ "Content-Type": "application/json"
99
+ },
100
+ body: JSON.stringify({
101
+ token: existing
102
+ })
103
+ }).then((res2) => res2.json()))?.valid)
104
+ return existing;
105
+ } catch (error) {
106
+ console.error("Error validating token:", error);
107
+ }
108
+ const res = await authClient.$fetch("/token");
109
+ if (res.error) {
110
+ console.error(`Error fetching token: ${res.error.statusText}`);
111
+ return;
112
+ }
113
+ return res.data?.token;
114
+ }
115
+ const clearAuthClientToken = () => {
116
+ keysStorage.remove();
117
+ }, getAuth = () => {
118
+ const state = authState?.value || empty;
119
+ return {
120
+ ...state,
121
+ loggedIn: !!state.session
122
+ };
123
+ }, useAuth = () => (0, import_helpers.useEmitterValue)(authState) || empty;
124
+ function clearState() {
125
+ keysStorage.clear(), stateStorage.clear(), setState(empty);
126
+ }
127
+ if (subscribeToAuthEffect(), typeof window < "u" && window.addEventListener) {
128
+ const cleanup = () => {
129
+ dispose?.(), retryTimer && clearTimeout(retryTimer);
130
+ };
131
+ window.addEventListener("beforeunload", cleanup);
132
+ }
133
+ const proxiedAuthClient = new Proxy(authClient, {
134
+ get(_target, key) {
135
+ return key === "signOut" ? async () => {
136
+ clearState(), await authClient.signOut?.(), typeof window < "u" && window.location?.reload?.();
137
+ } : Reflect.get(authClient, key);
138
+ }
139
+ });
140
+ return {
141
+ authClientVersion,
142
+ clearState,
143
+ authState,
144
+ authClient: proxiedAuthClient,
145
+ setAuthClientToken,
146
+ clearAuthClientToken,
147
+ useAuth,
148
+ getAuth,
149
+ getValidToken,
150
+ updateAuthClient
151
+ };
152
+ }
153
+ //# sourceMappingURL=createAuthClient.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/createAuthClient.ts"],
4
+ "mappings": ";;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,qBAMO,8BAEP,gBAA+D;AAkExD,SAAS,uBACd,SACoF;AAEpF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB,aAAa;AAAA,IACb,0BAA0B;AAAA,IAC1B,GAAG;AAAA,EACL,IAAI,SAEE,QAA0B;AAAA,IAC9B,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,IACN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M,UAAU,MAAM;AACpB,UAAM,QAAQ,WAAW,SAAS;AAClC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,UAAU,CAAC,CAAC,MAAM;AAAA,IACpB;AAAA,EACF,GAEM,UAAU,UACP,gCAAgB,SAAS,KAAK;AAGvC,WAAS,aAAa;AACpB,gBAAY,MAAM,GAClB,aAAa,MAAM,GACnB,SAAS,KAAK;AAAA,EAChB;AAMA,MAHA,sBAAsB,GAGlB,OAAO,SAAW,OAAe,OAAO,kBAAkB;AAC5D,UAAM,UAAU,MAAM;AACpB,gBAAU,GACN,cACF,aAAa,UAAU;AAAA,IAE3B;AACA,WAAO,iBAAiB,gBAAgB,OAAO;AAAA,EACjD;AAEA,QAAM,oBAAoB,IAAI,MAAM,YAAY;AAAA,IAC9C,IAAI,SAAS,KAAK;AAChB,aAAI,QAAQ,YACH,YAAY;AACjB,mBAAW,GAEX,MAAM,WAAW,UAAU,GAEvB,OAAO,SAAW,OACpB,OAAO,UAAU,SAAS;AAAA,MAE9B,IAGK,QAAQ,IAAI,YAAY,GAAG;AAAA,IACpC;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
5
+ "names": ["res"]
6
+ }
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: !0 });
9
+ }, __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from == "object" || typeof from == "function")
11
+ for (let key of __getOwnPropNames(from))
12
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ return to;
14
+ };
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
16
+ var createAuthClient_exports = {};
17
+ __export(createAuthClient_exports, {
18
+ createBetterAuthClient: () => createBetterAuthClient
19
+ });
20
+ module.exports = __toCommonJS(createAuthClient_exports);
21
+ var import_helpers = require("@take-out/helpers"), import_client = require("better-auth/client");
22
+ function createBetterAuthClient(options) {
23
+ var { onAuthStateChange, onAuthError, createUser, storagePrefix = "auth", retryDelay = 4e3, tokenValidationEndpoint = "/api/auth/validateToken", ...authClientOptions } = options, empty = {
24
+ state: "logged-out",
25
+ session: null,
26
+ user: null,
27
+ token: null
28
+ }, createAuthClientWithSession = function(session) {
29
+ return (0, import_client.createAuthClient)({
30
+ ...authClientOptions,
31
+ fetchOptions: {
32
+ headers: {
33
+ Authorization: `Bearer ${session}`
34
+ }
35
+ }
36
+ });
37
+ }, keysStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-keys`), stateStorage = (0, import_helpers.createLocalStorageValue)(`${storagePrefix}-state`), authClient = (function() {
38
+ var _keysStorage_get, existingSession = (_keysStorage_get = keysStorage.get()) === null || _keysStorage_get === void 0 ? void 0 : _keysStorage_get.session;
39
+ return existingSession ? createAuthClientWithSession(existingSession) : (0, import_client.createAuthClient)(authClientOptions);
40
+ })(), authState = (0, import_helpers.createEmitter)("authState", stateStorage.get() || empty, {
41
+ comparator: import_helpers.isEqualDeepLite
42
+ }), authClientVersion = (0, import_helpers.createEmitter)("authClientVersion", 0), setState = function(update) {
43
+ var current = authState.value, next = {
44
+ ...current,
45
+ ...update
46
+ };
47
+ stateStorage.set(next), authState.emit(next), next.token && next.session ? keysStorage.set({
48
+ token: next.token,
49
+ session: next.session.token
50
+ }) : keysStorage.set({
51
+ token: "",
52
+ session: ""
53
+ }), onAuthStateChange == null || onAuthStateChange(next);
54
+ }, setAuthClientToken = async function(props) {
55
+ keysStorage.set(props), updateAuthClient(props.session);
56
+ };
57
+ function updateAuthClient(session) {
58
+ authClient = createAuthClientWithSession(session), authClientVersion.emit(Math.random()), subscribeToAuthEffect();
59
+ }
60
+ var dispose = null, retryTimer = null;
61
+ function subscribeToAuthEffect() {
62
+ dispose == null || dispose(), dispose = authClient.useSession.subscribe(async function(props) {
63
+ var { data: dataGeneric, isPending, error } = props;
64
+ if (error) {
65
+ onAuthError == null || onAuthError(error), scheduleAuthRetry(retryDelay);
66
+ return;
67
+ }
68
+ var data = dataGeneric;
69
+ setState({
70
+ state: isPending ? "loading" : data != null && data.session ? "logged-in" : "logged-out",
71
+ session: data == null ? void 0 : data.session,
72
+ user: data != null && data.user ? createUser ? createUser(data.user) : data.user : null
73
+ }), data != null && data.session && !authState.value.token && getValidToken().then(function(token) {
74
+ token && setState({
75
+ token
76
+ });
77
+ });
78
+ });
79
+ }
80
+ function scheduleAuthRetry(delayMs) {
81
+ retryTimer && clearTimeout(retryTimer), retryTimer = setTimeout(function() {
82
+ retryTimer = null, subscribeToAuthEffect();
83
+ }, delayMs);
84
+ }
85
+ async function getValidToken() {
86
+ var _keysStorage_get, existing = (_keysStorage_get = keysStorage.get()) === null || _keysStorage_get === void 0 ? void 0 : _keysStorage_get.token;
87
+ if (existing)
88
+ try {
89
+ var response = await fetch(tokenValidationEndpoint, {
90
+ method: "POST",
91
+ headers: {
92
+ "Content-Type": "application/json"
93
+ },
94
+ body: JSON.stringify({
95
+ token: existing
96
+ })
97
+ }).then(function(res2) {
98
+ return res2.json();
99
+ });
100
+ if (response != null && response.valid)
101
+ return existing;
102
+ } catch (error) {
103
+ console.error("Error validating token:", error);
104
+ }
105
+ var res = await authClient.$fetch("/token");
106
+ if (res.error) {
107
+ console.error(`Error fetching token: ${res.error.statusText}`);
108
+ return;
109
+ }
110
+ var data = res.data;
111
+ return data == null ? void 0 : data.token;
112
+ }
113
+ var clearAuthClientToken = function() {
114
+ keysStorage.remove();
115
+ }, getAuth = function() {
116
+ var state = (authState == null ? void 0 : authState.value) || empty;
117
+ return {
118
+ ...state,
119
+ loggedIn: !!state.session
120
+ };
121
+ }, useAuth = function() {
122
+ return (0, import_helpers.useEmitterValue)(authState) || empty;
123
+ };
124
+ function clearState() {
125
+ keysStorage.clear(), stateStorage.clear(), setState(empty);
126
+ }
127
+ if (subscribeToAuthEffect(), typeof window < "u" && window.addEventListener) {
128
+ var cleanup = function() {
129
+ dispose == null || dispose(), retryTimer && clearTimeout(retryTimer);
130
+ };
131
+ window.addEventListener("beforeunload", cleanup);
132
+ }
133
+ var proxiedAuthClient = new Proxy(authClient, {
134
+ get(_target, key) {
135
+ return key === "signOut" ? async function() {
136
+ var _authClient_signOut;
137
+ if (clearState(), await ((_authClient_signOut = authClient.signOut) === null || _authClient_signOut === void 0 ? void 0 : _authClient_signOut.call(authClient)), typeof window < "u") {
138
+ var _window_location_reload, _window_location;
139
+ (_window_location = window.location) === null || _window_location === void 0 || (_window_location_reload = _window_location.reload) === null || _window_location_reload === void 0 || _window_location_reload.call(_window_location);
140
+ }
141
+ } : Reflect.get(authClient, key);
142
+ }
143
+ });
144
+ return {
145
+ authClientVersion,
146
+ clearState,
147
+ authState,
148
+ authClient: proxiedAuthClient,
149
+ setAuthClientToken,
150
+ clearAuthClientToken,
151
+ useAuth,
152
+ getAuth,
153
+ getValidToken,
154
+ updateAuthClient
155
+ };
156
+ }
157
+ // Annotate the CommonJS export names for ESM import in node:
158
+ 0 && (module.exports = {
159
+ createBetterAuthClient
160
+ });
161
+ //# sourceMappingURL=createAuthClient.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/createAuthClient.ts"],
4
+ "mappings": ";;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASI,qBAAyF,8BAC7F,gBAAiC;AAkBpB,SAAS,uBAAuB,SAAS;AAClD,MAAI,EAAE,mBAAmB,aAAa,YAAY,gBAAgB,QAAQ,aAAa,KAAM,0BAA0B,2BA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BAAiB,YAAY,QAAQ,4BAA4B,UAAkB,wBAAwB,KAAK,gBAAgB;AAAA,QACvP;AAAA,MACJ,IAGG,QAAQ,IAAI,YAAY,GAAG;AAAA,IACtC;AAAA,EACJ,CAAC;AACD,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;",
5
+ "names": ["res"]
6
+ }
@@ -0,0 +1,18 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
7
+ get: () => from[key],
8
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
9
+ });
10
+ return to;
11
+ },
12
+ __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
13
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
14
+ value: !0
15
+ }), mod);
16
+ var index_exports = {};
17
+ module.exports = __toCommonJS(index_exports);
18
+ __reExport(index_exports, require("./createAuthClient.cjs"), module.exports);