cocobase 1.2.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,10 @@ Go from idea to MVP in minutes, not weeks. No server configuration, no database
12
12
 
13
13
  ```typescript
14
14
  // This is literally all you need to start
15
- const db = new Cocobase({ apiKey: "your-key" });
15
+ const db = new Cocobase({
16
+ apiKey: "your-key", // From cocobase.buzz
17
+ projectId: "your-project-id" // From cocobase.buzz
18
+ });
16
19
  await db.createDocument("users", { name: "John" });
17
20
  ```
18
21
 
@@ -22,9 +25,11 @@ Built-in user management that actually works. Registration, login, sessions, and
22
25
 
23
26
  ```typescript
24
27
  // User registration + automatic login in one line
25
- await db.register("user@example.com", "password", { role: "admin" });
28
+ await db.auth.register("user@example.com", "password", { role: "admin" });
26
29
  ```
27
30
 
31
+ > 💡 **New in v1.3.1:** All auth methods now use the `db.auth.*` namespace for better organization. Old methods still work but are deprecated. See our [Migration Guide](docs/Migration-Guide.md).
32
+
28
33
  ### 📊 **Real-time Data Management**
29
34
 
30
35
  Store, retrieve, and manage your application data with a clean, intuitive API. No SQL knowledge required.
@@ -277,27 +282,71 @@ const posts = await db.listDocuments("posts");
277
282
 
278
283
  Ready to build something amazing? Here's how to get started:
279
284
 
280
- 1. **Visit** [cocobase.buzz](https://cocobase.buzz)
281
- 2. **Sign up** for a free account
282
- 3. **Create** your first project
283
- 4. **Install** the SDK: `npm install cocobase`
284
- 5. **Start building** awesome things!
285
+ ### 1. Get Your Credentials
286
+
287
+ 1. **Visit** [cocobase.buzz](https://cocobase.buzz) and sign up for a free account
288
+ 2. **Create** your first project in the dashboard
289
+ 3. **Copy your credentials** from the project dashboard:
290
+ - **API Key** - Used to authenticate your requests
291
+ - **Project ID** - Identifies your project
292
+
293
+ > 💡 **Where to find your credentials:**
294
+ > After creating a project on [cocobase.buzz](https://cocobase.buzz), you'll find your **API Key** and **Project ID** in your project's dashboard. Keep these secure and never commit them to version control!
295
+
296
+ ### 2. Install the SDK
297
+
298
+ ```bash
299
+ npm install cocobase
300
+ ```
301
+
302
+ ### 3. Start Building
285
303
 
286
304
  ```typescript
287
305
  import { Cocobase } from "cocobase";
288
306
 
289
- const db = new Cocobase({ apiKey: "your-api-key" });
307
+ const db = new Cocobase({
308
+ apiKey: "your-api-key", // Get from cocobase.buzz
309
+ projectId: "your-project-id" // Get from cocobase.buzz
310
+ });
290
311
 
291
312
  // You're ready to build! 🎉
292
313
  ```
293
314
 
315
+ ## 🆕 What's New in v1.3.1
316
+
317
+ ### New Authentication Handler Architecture
318
+
319
+ All authentication methods are now organized under the `db.auth.*` namespace for better code organization and maintainability:
320
+
321
+ ```typescript
322
+ // ✅ New way (recommended)
323
+ await db.auth.login("user@example.com", "password");
324
+ const user = db.auth.getUser();
325
+ const token = db.auth.getToken();
326
+
327
+ // ❌ Old way (deprecated but still works)
328
+ await db.login("user@example.com", "password");
329
+ const user = db.user;
330
+ const token = db.getToken();
331
+ ```
332
+
333
+ **Benefits:**
334
+ - 🏗️ Better code organization
335
+ - 📚 Comprehensive JSDoc documentation
336
+ - 🔄 Enhanced state management
337
+ - 🛡️ Improved error handling
338
+
339
+ **Migration:** Old methods still work but are deprecated. See our **[Migration Guide](docs/Migration-Guide.md)** for easy upgrade instructions.
340
+
294
341
  ## 📚 Resources
295
342
 
296
343
  - **[Documentation](https://docs.cocobase.buzz)** - Comprehensive guides and API reference
344
+ - **[Migration Guide](docs/Migration-Guide.md)** - Upgrade from deprecated auth methods
297
345
  - **[Examples](https://github.com/cocobase/examples)** - Sample projects and tutorials
298
346
  - **[Community](https://discord.gg/cocobase)** - Join our developer community
299
347
  - **[Blog](https://blog.cocobase.buzz)** - Tips, tutorials, and updates
300
348
  - **[Status](https://status.cocobase.buzz)** - Service status and uptime
349
+ - **[Changelog](CHANGELOG.md)** - See what's new in each version
301
350
 
302
351
  ## 🤝 Community & Support
303
352
 
@@ -0,0 +1,356 @@
1
+ import { CocobaseConfig, AppUser, AppUserList, Query, AuthCallbacks } from "../types/types.js";
2
+ /**
3
+ * Authentication handler for Cocobase client.
4
+ *
5
+ * Provides methods for user authentication, registration, and user management.
6
+ * This class handles all authentication-related operations and maintains user session state.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const db = new Cocobase({ apiKey: 'your-key' });
11
+ * await db.auth.login('user@example.com', 'password');
12
+ * ```
13
+ */
14
+ export declare class AuthHandler {
15
+ private baseURL;
16
+ private apiKey?;
17
+ private token?;
18
+ private user?;
19
+ private callbacks;
20
+ /**
21
+ * Creates a new AuthHandler instance.
22
+ *
23
+ * @param config - Cocobase configuration
24
+ */
25
+ constructor(config: CocobaseConfig);
26
+ /**
27
+ * Register callbacks for authentication events.
28
+ * This allows your application to respond to auth state changes in a framework-agnostic way.
29
+ *
30
+ * @param callbacks - Object containing callback functions for various auth events
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // React example
35
+ * db.auth.onAuthEvent({
36
+ * onLogin: (user, token) => {
37
+ * setUser(user);
38
+ * setIsAuthenticated(true);
39
+ * },
40
+ * onLogout: () => {
41
+ * setUser(null);
42
+ * setIsAuthenticated(false);
43
+ * },
44
+ * onUserUpdate: (user) => {
45
+ * setUser(user);
46
+ * }
47
+ * });
48
+ *
49
+ * // Vue example
50
+ * db.auth.onAuthEvent({
51
+ * onLogin: (user, token) => {
52
+ * store.commit('setUser', user);
53
+ * store.commit('setToken', token);
54
+ * },
55
+ * onLogout: () => {
56
+ * store.commit('clearAuth');
57
+ * }
58
+ * });
59
+ *
60
+ * // Svelte example
61
+ * db.auth.onAuthEvent({
62
+ * onLogin: (user, token) => {
63
+ * userStore.set(user);
64
+ * tokenStore.set(token);
65
+ * },
66
+ * onLogout: () => {
67
+ * userStore.set(null);
68
+ * tokenStore.set(null);
69
+ * }
70
+ * });
71
+ * ```
72
+ */
73
+ onAuthEvent(callbacks: AuthCallbacks): void;
74
+ /**
75
+ * Remove all registered callbacks.
76
+ */
77
+ clearAuthCallbacks(): void;
78
+ /**
79
+ * Gets the current authentication token.
80
+ *
81
+ * @returns The current JWT token, or undefined if not authenticated
82
+ */
83
+ getToken(): string | undefined;
84
+ /**
85
+ * Sets the authentication token and stores it in local storage.
86
+
87
+ * @param token - JWT authentication token
88
+ */
89
+ setToken(token: string): void;
90
+ /**
91
+ * Updates the current user object.
92
+ *
93
+ * @param user - User object to set
94
+ */
95
+ setUser(user: AppUser): void;
96
+ /**
97
+ * Gets the current user object.
98
+ *
99
+ * @returns The current user, or undefined if not authenticated
100
+ */
101
+ getUser(): AppUser | undefined;
102
+ /**
103
+ * Makes an authenticated request to the API.
104
+ *
105
+ * @private
106
+ * @param method - HTTP method
107
+ * @param path - API endpoint path
108
+ * @param body - Request body
109
+ * @param useDataKey - Whether to wrap body in data key
110
+ * @returns Promise resolving to response data
111
+ */
112
+ private request;
113
+ /**
114
+ * Provides error suggestions based on HTTP status codes.
115
+ *
116
+ * @private
117
+ * @param status - HTTP status code
118
+ * @param method - HTTP method used
119
+ * @returns Suggestion string
120
+ */
121
+ private getErrorSuggestion;
122
+ /**
123
+ * Initializes authentication by restoring the session from local storage.
124
+ * Call this method when your application loads to restore user sessions.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * await db.auth.initAuth();
129
+ * if (db.auth.isAuthenticated()) {
130
+ * console.log('User is logged in:', db.auth.getUser());
131
+ * }
132
+ * ```
133
+ */
134
+ initAuth(): Promise<void>;
135
+ /**
136
+ * Authenticates a user with email and password.
137
+ *
138
+ * @param email - User's email address
139
+ * @param password - User's password
140
+ * @returns Promise that resolves when login is complete
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * await db.auth.login('user@example.com', 'password123');
145
+ * console.log('Logged in as:', db.auth.getUser()?.email);
146
+ * ```
147
+ */
148
+ login(email: string, password: string): Promise<void>;
149
+ /**
150
+ * Registers a new user with email, password, and optional additional data.
151
+ *
152
+ * @param email - User's email address
153
+ * @param password - User's password
154
+ * @param data - Optional additional user data
155
+ * @returns Promise that resolves when registration is complete
156
+ *
157
+ * @example
158
+ * ```typescript
159
+ * await db.auth.register('user@example.com', 'password123', {
160
+ * username: 'johndoe',
161
+ * fullName: 'John Doe'
162
+ * });
163
+ * ```
164
+ */
165
+ register(email: string, password: string, data?: Record<string, any>): Promise<void>;
166
+ /**
167
+ * Authenticates a user using Google Sign-In with ID token.
168
+ *
169
+ * This method verifies the Google ID token and either creates a new user
170
+ * or logs in an existing user who registered with Google OAuth.
171
+ *
172
+ * @param idToken - Google ID token obtained from Google Sign-In
173
+ * @param platform - Optional platform identifier ('web', 'mobile', 'ios', 'android')
174
+ * @returns Promise resolving to the authenticated user object
175
+ *
176
+ * @throws {Error} If Google Sign-In is not enabled in project settings
177
+ * @throws {Error} If the Google ID token is invalid or expired
178
+ * @throws {Error} If email is already registered with password authentication
179
+ * @throws {Error} If email is already registered with Apple Sign-In
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * // Web - Using Google Identity Services
184
+ * google.accounts.id.initialize({
185
+ * client_id: 'YOUR_GOOGLE_CLIENT_ID',
186
+ * callback: async (response) => {
187
+ * const user = await db.auth.loginWithGoogle(response.credential, 'web');
188
+ * console.log('Logged in:', user.email);
189
+ * }
190
+ * });
191
+ *
192
+ * // Mobile - After getting ID token from Google Sign-In SDK
193
+ * const user = await db.auth.loginWithGoogle(idToken, 'mobile');
194
+ * ```
195
+ */
196
+ loginWithGoogle(idToken: string, platform?: "web" | "mobile" | "ios" | "android"): Promise<AppUser>;
197
+ /**
198
+ * Register a new user with file uploads (avatar, cover photo, etc.)
199
+ *
200
+ * @param email - User email
201
+ * @param password - User password
202
+ * @param data - Additional user data (optional)
203
+ * @param files - Object mapping field names to File objects (optional)
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * // Register with avatar
208
+ * await db.auth.registerWithFiles(
209
+ * 'john@example.com',
210
+ * 'password123',
211
+ * { username: 'johndoe', full_name: 'John Doe' },
212
+ * { avatar: avatarFile }
213
+ * );
214
+ *
215
+ * // Register with avatar and cover photo
216
+ * await db.auth.registerWithFiles(
217
+ * 'john@example.com',
218
+ * 'password123',
219
+ * { username: 'johndoe' },
220
+ * { avatar: avatarFile, cover_photo: coverFile }
221
+ * );
222
+ * ```
223
+ */
224
+ registerWithFiles(email: string, password: string, data?: Record<string, any>, files?: Record<string, File | File[]>): Promise<AppUser>;
225
+ /**
226
+ * Logs out the current user by clearing the token and user data.
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * db.auth.logout();
231
+ * console.log('User logged out');
232
+ * ```
233
+ */
234
+ logout(): void;
235
+ /**
236
+ * Checks if a user is currently authenticated.
237
+ *
238
+ * @returns True if user is authenticated, false otherwise
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * if (db.auth.isAuthenticated()) {
243
+ * console.log('User is logged in');
244
+ * }
245
+ * ```
246
+ */
247
+ isAuthenticated(): boolean;
248
+ /**
249
+ * Fetches the current authenticated user's data from the server.
250
+ *
251
+ * @returns Promise resolving to the current user object
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * const user = await db.auth.getCurrentUser();
256
+ * console.log('Current user:', user.email);
257
+ * ```
258
+ */
259
+ getCurrentUser(): Promise<AppUser>;
260
+ /**
261
+ * Updates the current user's profile data.
262
+ *
263
+ * @param data - User data to update (optional)
264
+ * @param email - New email address (optional)
265
+ * @param password - New password (optional)
266
+ * @returns Promise resolving to the updated user object
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * await db.auth.updateUser({
271
+ * bio: 'Updated bio',
272
+ * website: 'https://example.com'
273
+ * });
274
+ * ```
275
+ */
276
+ updateUser(data?: Record<string, any> | null, email?: string | null, password?: string | null): Promise<AppUser>;
277
+ /**
278
+ * Update current user with file uploads
279
+ *
280
+ * @param data - User data to update (optional)
281
+ * @param email - New email (optional)
282
+ * @param password - New password (optional)
283
+ * @param files - Object mapping field names to File objects (optional)
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * // Update only avatar
288
+ * await db.auth.updateUserWithFiles(
289
+ * undefined, undefined, undefined,
290
+ * { avatar: newAvatarFile }
291
+ * );
292
+ *
293
+ * // Update bio and avatar
294
+ * await db.auth.updateUserWithFiles(
295
+ * { bio: 'Updated bio' },
296
+ * undefined, undefined,
297
+ * { avatar: newAvatarFile }
298
+ * );
299
+ *
300
+ * // Update multiple fields and files
301
+ * await db.auth.updateUserWithFiles(
302
+ * { username: 'newusername', bio: 'New bio' },
303
+ * 'newemail@example.com',
304
+ * undefined,
305
+ * { avatar: newAvatar, cover_photo: newCover }
306
+ * );
307
+ * ```
308
+ */
309
+ updateUserWithFiles(data?: Record<string, any> | null, email?: string | null, password?: string | null, files?: Record<string, File | File[]>): Promise<AppUser>;
310
+ /**
311
+ * Checks if the current user has a specific role.
312
+ *
313
+ * @param role - Role to check for
314
+ * @returns True if user has the role, false otherwise
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * if (db.auth.hasRole('admin')) {
319
+ * console.log('User is an admin');
320
+ * }
321
+ * ```
322
+ */
323
+ hasRole(role: string): boolean;
324
+ /**
325
+ * Lists users from the auth collection with optional filtering and pagination.
326
+ *
327
+ * @template T - The type of user data
328
+ * @param query - Optional query parameters for filtering, sorting, and pagination
329
+ * @returns Promise resolving to a list of users
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * const users = await db.auth.listUsers({
334
+ * filters: { status: 'active' },
335
+ * limit: 10
336
+ * });
337
+ * ```
338
+ */
339
+ listUsers<T = any>(query?: Query): Promise<AppUserList>;
340
+ /**
341
+ * Gets a user by their ID.
342
+ *
343
+ * @template T - The type of user data
344
+ * @param userId - Unique ID of the user
345
+ * @returns Promise resolving to the user object
346
+ *
347
+ * @example
348
+ * ```typescript
349
+ * const user = await db.auth.getUserById('user-123');
350
+ * console.log('User:', user.email);
351
+ * ```
352
+ */
353
+ getUserById<T = any>(userId: string): Promise<AppUser>;
354
+ }
355
+ export default AuthHandler;
356
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"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