@terreno/rtk 0.0.18 → 0.2.0

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.
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Better Auth client factory for React Native/Expo applications.
3
+ *
4
+ * Provides a configured Better Auth client with Expo-specific storage
5
+ * and deep linking support.
6
+ */
7
+
8
+ import {expoClient} from "@better-auth/expo/client";
9
+ import AsyncStorage from "@react-native-async-storage/async-storage";
10
+ import {createAuthClient} from "better-auth/react";
11
+ import * as SecureStore from "expo-secure-store";
12
+ import type {BetterAuthClientConfig} from "./betterAuthTypes";
13
+ import {IsWeb} from "./platform";
14
+
15
+ // Re-export types for convenience
16
+ export type {
17
+ BetterAuthClientConfig,
18
+ BetterAuthOAuthProvider,
19
+ BetterAuthSession,
20
+ BetterAuthSessionData,
21
+ BetterAuthUser,
22
+ } from "./betterAuthTypes";
23
+
24
+ /**
25
+ * Storage adapter interface matching what Better Auth expects.
26
+ */
27
+ interface StorageAdapter {
28
+ setItem: (key: string, value: string) => void | Promise<void>;
29
+ getItem: (key: string) => string | null | Promise<string | null>;
30
+ removeItem?: (key: string) => void | Promise<void>;
31
+ }
32
+
33
+ /**
34
+ * Async storage adapter for Better Auth that works on both web and native.
35
+ * Uses SecureStore on native platforms and AsyncStorage on web.
36
+ */
37
+ const createStorageAdapter = (): StorageAdapter => {
38
+ if (IsWeb) {
39
+ return {
40
+ getItem: (key: string): Promise<string | null> => {
41
+ if (typeof window !== "undefined") {
42
+ return AsyncStorage.getItem(key);
43
+ }
44
+ return Promise.resolve(null);
45
+ },
46
+ removeItem: (key: string): Promise<void> => {
47
+ if (typeof window !== "undefined") {
48
+ return AsyncStorage.removeItem(key);
49
+ }
50
+ return Promise.resolve();
51
+ },
52
+ setItem: (key: string, value: string): Promise<void> => {
53
+ if (typeof window !== "undefined") {
54
+ return AsyncStorage.setItem(key, value);
55
+ }
56
+ return Promise.resolve();
57
+ },
58
+ };
59
+ }
60
+
61
+ // Native platform - use SecureStore
62
+ return {
63
+ getItem: (key: string) => SecureStore.getItemAsync(key),
64
+ removeItem: (key: string) => SecureStore.deleteItemAsync(key),
65
+ setItem: (key: string, value: string) => SecureStore.setItemAsync(key, value),
66
+ };
67
+ };
68
+
69
+ /**
70
+ * Creates a Better Auth client configured for Expo/React Native.
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const authClient = createBetterAuthClient({
75
+ * baseURL: "http://localhost:3000",
76
+ * scheme: "terreno",
77
+ * });
78
+ *
79
+ * // Use for social login
80
+ * await authClient.signIn.social({
81
+ * provider: "google",
82
+ * });
83
+ *
84
+ * // Get current session
85
+ * const session = await authClient.getSession();
86
+ * ```
87
+ */
88
+ export const createBetterAuthClient = (config: BetterAuthClientConfig) => {
89
+ const storage = createStorageAdapter();
90
+
91
+ return createAuthClient({
92
+ baseURL: config.baseURL,
93
+ plugins: [
94
+ expoClient({
95
+ scheme: config.scheme,
96
+ // biome-ignore lint/suspicious/noExplicitAny: Better Auth storage type is flexible
97
+ storage: storage as any,
98
+ storagePrefix: config.storagePrefix ?? "terreno",
99
+ }),
100
+ ],
101
+ });
102
+ };
103
+
104
+ /**
105
+ * Type of the Better Auth client returned by createBetterAuthClient.
106
+ */
107
+ export type BetterAuthClient = ReturnType<typeof createBetterAuthClient>;
@@ -0,0 +1,329 @@
1
+ import {beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {
3
+ type BetterAuthState,
4
+ generateBetterAuthSlice,
5
+ selectBetterAuthError,
6
+ selectBetterAuthIsAuthenticated,
7
+ selectBetterAuthIsLoading,
8
+ selectBetterAuthUser,
9
+ selectBetterAuthUserId,
10
+ } from "./betterAuthSlice";
11
+ import type {BetterAuthClientConfig, BetterAuthUser} from "./betterAuthTypes";
12
+
13
+ // Mock Better Auth client
14
+ const createMockAuthClient = () => ({
15
+ getSession: mock(() =>
16
+ Promise.resolve({
17
+ data: {
18
+ session: {
19
+ createdAt: new Date(),
20
+ expiresAt: new Date(Date.now() + 3600000),
21
+ id: "session-456",
22
+ ipAddress: null,
23
+ updatedAt: new Date(),
24
+ userAgent: null,
25
+ userId: "user-123",
26
+ },
27
+ user: {
28
+ createdAt: new Date(),
29
+ email: "test@example.com",
30
+ emailVerified: true,
31
+ id: "user-123",
32
+ image: null,
33
+ name: "Test User",
34
+ updatedAt: new Date(),
35
+ },
36
+ },
37
+ })
38
+ ),
39
+ signIn: {
40
+ email: mock(() => Promise.resolve({data: {user: {id: "user-123"}}})),
41
+ social: mock(() => Promise.resolve({data: {user: {id: "user-123"}}})),
42
+ },
43
+ signOut: mock(() => Promise.resolve()),
44
+ signUp: {
45
+ email: mock(() => Promise.resolve({data: {user: {id: "user-123"}}})),
46
+ },
47
+ });
48
+
49
+ describe("BetterAuthClientConfig", () => {
50
+ it("defines config interface correctly", () => {
51
+ const config: BetterAuthClientConfig = {
52
+ baseURL: "http://localhost:3000",
53
+ scheme: "terreno",
54
+ storagePrefix: "myapp",
55
+ };
56
+
57
+ expect(config.baseURL).toBe("http://localhost:3000");
58
+ expect(config.scheme).toBe("terreno");
59
+ expect(config.storagePrefix).toBe("myapp");
60
+ });
61
+
62
+ it("allows minimal config without storagePrefix", () => {
63
+ const config: BetterAuthClientConfig = {
64
+ baseURL: "http://localhost:3000",
65
+ scheme: "terreno",
66
+ };
67
+
68
+ expect(config.storagePrefix).toBeUndefined();
69
+ });
70
+ });
71
+
72
+ describe("generateBetterAuthSlice", () => {
73
+ let mockAuthClient: ReturnType<typeof createMockAuthClient>;
74
+
75
+ beforeEach(() => {
76
+ mockAuthClient = createMockAuthClient();
77
+ });
78
+
79
+ it("creates a slice with initial state", () => {
80
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
81
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
82
+
83
+ const initialState = betterAuthSlice.reducer(undefined, {type: "@@INIT"});
84
+
85
+ expect(initialState.isAuthenticated).toBe(false);
86
+ expect(initialState.userId).toBeNull();
87
+ expect(initialState.user).toBeNull();
88
+ expect(initialState.isLoading).toBe(true);
89
+ expect(initialState.error).toBeNull();
90
+ });
91
+
92
+ it("setSession action updates state correctly", () => {
93
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
94
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
95
+
96
+ const user: BetterAuthUser = {
97
+ createdAt: new Date(),
98
+ email: "test@example.com",
99
+ emailVerified: true,
100
+ id: "user-123",
101
+ image: null,
102
+ name: "Test User",
103
+ updatedAt: new Date(),
104
+ };
105
+
106
+ const state = betterAuthSlice.reducer(
107
+ undefined,
108
+ betterAuthSlice.actions.setSession({user, userId: "user-123"})
109
+ );
110
+
111
+ expect(state.isAuthenticated).toBe(true);
112
+ expect(state.userId).toBe("user-123");
113
+ expect(state.user?.email).toBe("test@example.com");
114
+ expect(state.isLoading).toBe(false);
115
+ expect(state.error).toBeNull();
116
+ });
117
+
118
+ it("clearSession action resets state", () => {
119
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
120
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
121
+
122
+ // First set a session
123
+ let state = betterAuthSlice.reducer(
124
+ undefined,
125
+ betterAuthSlice.actions.setSession({
126
+ user: {
127
+ createdAt: new Date(),
128
+ email: "test@example.com",
129
+ emailVerified: true,
130
+ id: "user-123",
131
+ image: null,
132
+ name: "Test",
133
+ updatedAt: new Date(),
134
+ },
135
+ userId: "user-123",
136
+ })
137
+ );
138
+
139
+ // Then clear it
140
+ state = betterAuthSlice.reducer(state, betterAuthSlice.actions.clearSession());
141
+
142
+ expect(state.isAuthenticated).toBe(false);
143
+ expect(state.userId).toBeNull();
144
+ expect(state.user).toBeNull();
145
+ });
146
+
147
+ it("setLoading action updates loading state", () => {
148
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
149
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
150
+
151
+ let state = betterAuthSlice.reducer(undefined, betterAuthSlice.actions.setLoading(true));
152
+ expect(state.isLoading).toBe(true);
153
+
154
+ state = betterAuthSlice.reducer(state, betterAuthSlice.actions.setLoading(false));
155
+ expect(state.isLoading).toBe(false);
156
+ });
157
+
158
+ it("setError action updates error state", () => {
159
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
160
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
161
+
162
+ const state = betterAuthSlice.reducer(
163
+ undefined,
164
+ betterAuthSlice.actions.setError("Something went wrong")
165
+ );
166
+
167
+ expect(state.error).toBe("Something went wrong");
168
+ expect(state.isLoading).toBe(false);
169
+ });
170
+
171
+ it("logout action clears session state", () => {
172
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
173
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
174
+
175
+ // First set a session
176
+ let state = betterAuthSlice.reducer(
177
+ undefined,
178
+ betterAuthSlice.actions.setSession({
179
+ user: {
180
+ createdAt: new Date(),
181
+ email: "test@example.com",
182
+ emailVerified: true,
183
+ id: "user-123",
184
+ image: null,
185
+ name: "Test",
186
+ updatedAt: new Date(),
187
+ },
188
+ userId: "user-123",
189
+ })
190
+ );
191
+
192
+ // Then logout
193
+ state = betterAuthSlice.reducer(state, betterAuthSlice.actions.logout());
194
+
195
+ expect(state.isAuthenticated).toBe(false);
196
+ expect(state.userId).toBeNull();
197
+ expect(state.user).toBeNull();
198
+ });
199
+
200
+ it("returns middleware array", () => {
201
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
202
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
203
+
204
+ expect(Array.isArray(betterAuthSlice.middleware)).toBe(true);
205
+ expect(betterAuthSlice.middleware.length).toBeGreaterThan(0);
206
+ });
207
+
208
+ it("returns authClient reference", () => {
209
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
210
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
211
+
212
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type comparison
213
+ expect(betterAuthSlice.authClient).toBe(mockAuthClient as any);
214
+ });
215
+
216
+ it("syncSession function updates state from auth client", async () => {
217
+ // biome-ignore lint/suspicious/noExplicitAny: Mock client type
218
+ const betterAuthSlice = generateBetterAuthSlice({authClient: mockAuthClient as any});
219
+
220
+ // biome-ignore lint/suspicious/noExplicitAny: Test mock for dispatched actions
221
+ const dispatchedActions: any[] = [];
222
+ // biome-ignore lint/suspicious/noExplicitAny: Test mock dispatch function
223
+ const mockDispatch = (action: any) => {
224
+ dispatchedActions.push(action);
225
+ };
226
+
227
+ await betterAuthSlice.syncSession(mockDispatch);
228
+
229
+ // Should dispatch setLoading(true) then setSession
230
+ expect(dispatchedActions.length).toBeGreaterThanOrEqual(2);
231
+ expect(dispatchedActions[0].type).toBe("betterAuth/setLoading");
232
+ });
233
+ });
234
+
235
+ describe("Better Auth selectors", () => {
236
+ // biome-ignore lint/suspicious/noExplicitAny: Test mock state factory
237
+ const createMockState = (betterAuth: Partial<BetterAuthState> = {}): any => ({
238
+ betterAuth: {
239
+ error: null,
240
+ isAuthenticated: false,
241
+ isLoading: false,
242
+ lastSyncTimestamp: null,
243
+ user: null,
244
+ userId: null,
245
+ ...betterAuth,
246
+ },
247
+ });
248
+
249
+ it("selectBetterAuthIsAuthenticated returns correct value", () => {
250
+ expect(selectBetterAuthIsAuthenticated(createMockState({isAuthenticated: true}))).toBe(true);
251
+ expect(selectBetterAuthIsAuthenticated(createMockState({isAuthenticated: false}))).toBe(false);
252
+ });
253
+
254
+ it("selectBetterAuthUserId returns correct value", () => {
255
+ expect(selectBetterAuthUserId(createMockState({userId: "user-123"}))).toBe("user-123");
256
+ expect(selectBetterAuthUserId(createMockState({userId: null}))).toBeNull();
257
+ });
258
+
259
+ it("selectBetterAuthUser returns correct value", () => {
260
+ const user: BetterAuthUser = {
261
+ createdAt: new Date(),
262
+ email: "test@example.com",
263
+ emailVerified: true,
264
+ id: "user-123",
265
+ image: null,
266
+ name: "Test",
267
+ updatedAt: new Date(),
268
+ };
269
+
270
+ expect(selectBetterAuthUser(createMockState({user}))?.email).toBe("test@example.com");
271
+ expect(selectBetterAuthUser(createMockState({user: null}))).toBeNull();
272
+ });
273
+
274
+ it("selectBetterAuthIsLoading returns correct value", () => {
275
+ expect(selectBetterAuthIsLoading(createMockState({isLoading: true}))).toBe(true);
276
+ expect(selectBetterAuthIsLoading(createMockState({isLoading: false}))).toBe(false);
277
+ });
278
+
279
+ it("selectBetterAuthError returns correct value", () => {
280
+ expect(selectBetterAuthError(createMockState({error: "Error message"}))).toBe("Error message");
281
+ expect(selectBetterAuthError(createMockState({error: null}))).toBeNull();
282
+ });
283
+
284
+ it("selectors handle missing betterAuth state gracefully", () => {
285
+ // biome-ignore lint/suspicious/noExplicitAny: Test empty state for selector edge case
286
+ const emptyState = {} as any;
287
+
288
+ expect(selectBetterAuthIsAuthenticated(emptyState)).toBe(false);
289
+ expect(selectBetterAuthUserId(emptyState)).toBeNull();
290
+ expect(selectBetterAuthUser(emptyState)).toBeNull();
291
+ expect(selectBetterAuthIsLoading(emptyState)).toBe(false);
292
+ expect(selectBetterAuthError(emptyState)).toBeNull();
293
+ });
294
+ });
295
+
296
+ describe("BetterAuthUser interface", () => {
297
+ it("defines user data structure correctly", () => {
298
+ const user: BetterAuthUser = {
299
+ createdAt: new Date("2024-01-01"),
300
+ email: "test@example.com",
301
+ emailVerified: true,
302
+ id: "user-123",
303
+ image: "https://example.com/avatar.jpg",
304
+ name: "Test User",
305
+ updatedAt: new Date("2024-01-02"),
306
+ };
307
+
308
+ expect(user.id).toBe("user-123");
309
+ expect(user.email).toBe("test@example.com");
310
+ expect(user.name).toBe("Test User");
311
+ expect(user.image).toBe("https://example.com/avatar.jpg");
312
+ expect(user.emailVerified).toBe(true);
313
+ });
314
+
315
+ it("allows null values for optional fields", () => {
316
+ const user: BetterAuthUser = {
317
+ createdAt: new Date(),
318
+ email: "test@example.com",
319
+ emailVerified: false,
320
+ id: "user-123",
321
+ image: null,
322
+ name: null,
323
+ updatedAt: new Date(),
324
+ };
325
+
326
+ expect(user.name).toBeNull();
327
+ expect(user.image).toBeNull();
328
+ });
329
+ });