cocobase 1.2.0 → 1.3.1

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,300 @@
1
+ import { CocobaseConfig, AppUser, AppUserList, Query, GoogleLoginResponse } 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
+ /**
20
+ * Creates a new AuthHandler instance.
21
+ *
22
+ * @param config - Cocobase configuration
23
+ */
24
+ constructor(config: CocobaseConfig);
25
+ /**
26
+ * Gets the current authentication token.
27
+ *
28
+ * @returns The current JWT token, or undefined if not authenticated
29
+ */
30
+ getToken(): string | undefined;
31
+ /**
32
+ * Sets the authentication token and stores it in local storage.
33
+ *
34
+ * @param token - JWT authentication token
35
+ */
36
+ setToken(token: string): void;
37
+ /**
38
+ * Updates the current user object.
39
+ *
40
+ * @param user - User object to set
41
+ */
42
+ setUser(user: AppUser): void;
43
+ /**
44
+ * Gets the current user object.
45
+ *
46
+ * @returns The current user, or undefined if not authenticated
47
+ */
48
+ getUser(): AppUser | undefined;
49
+ /**
50
+ * Makes an authenticated request to the API.
51
+ *
52
+ * @private
53
+ * @param method - HTTP method
54
+ * @param path - API endpoint path
55
+ * @param body - Request body
56
+ * @param useDataKey - Whether to wrap body in data key
57
+ * @returns Promise resolving to response data
58
+ */
59
+ private request;
60
+ /**
61
+ * Provides error suggestions based on HTTP status codes.
62
+ *
63
+ * @private
64
+ * @param status - HTTP status code
65
+ * @param method - HTTP method used
66
+ * @returns Suggestion string
67
+ */
68
+ private getErrorSuggestion;
69
+ /**
70
+ * Initializes authentication by restoring the session from local storage.
71
+ * Call this method when your application loads to restore user sessions.
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * await db.auth.initAuth();
76
+ * if (db.auth.isAuthenticated()) {
77
+ * console.log('User is logged in:', db.auth.getUser());
78
+ * }
79
+ * ```
80
+ */
81
+ initAuth(): Promise<void>;
82
+ /**
83
+ * Authenticates a user with email and password.
84
+ *
85
+ * @param email - User's email address
86
+ * @param password - User's password
87
+ * @returns Promise that resolves when login is complete
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * await db.auth.login('user@example.com', 'password123');
92
+ * console.log('Logged in as:', db.auth.getUser()?.email);
93
+ * ```
94
+ */
95
+ login(email: string, password: string): Promise<void>;
96
+ /**
97
+ * Registers a new user with email, password, and optional additional data.
98
+ *
99
+ * @param email - User's email address
100
+ * @param password - User's password
101
+ * @param data - Optional additional user data
102
+ * @returns Promise that resolves when registration is complete
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * await db.auth.register('user@example.com', 'password123', {
107
+ * username: 'johndoe',
108
+ * fullName: 'John Doe'
109
+ * });
110
+ * ```
111
+ */
112
+ register(email: string, password: string, data?: Record<string, any>): Promise<void>;
113
+ /**
114
+ * Initiates Google OAuth login flow.
115
+ *
116
+ * @returns Promise resolving to an object with the Google OAuth URL
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const { url } = await db.auth.loginWithGoogle();
121
+ * window.location.href = url; // Redirect to Google login
122
+ * ```
123
+ */
124
+ loginWithGoogle(): Promise<GoogleLoginResponse>;
125
+ /**
126
+ * Completes the Google OAuth login flow after redirect.
127
+ *
128
+ * @param token - JWT token received from OAuth callback
129
+ * @returns Promise that resolves when login is complete
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * // After Google redirects back to your app with a token
134
+ * const token = new URLSearchParams(window.location.search).get('token');
135
+ * if (token) {
136
+ * await db.auth.completeGoogleLogin(token);
137
+ * }
138
+ * ```
139
+ */
140
+ completeGoogleLogin(token: string): Promise<void>;
141
+ /**
142
+ * Register a new user with file uploads (avatar, cover photo, etc.)
143
+ *
144
+ * @param email - User email
145
+ * @param password - User password
146
+ * @param data - Additional user data (optional)
147
+ * @param files - Object mapping field names to File objects (optional)
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * // Register with avatar
152
+ * await db.auth.registerWithFiles(
153
+ * 'john@example.com',
154
+ * 'password123',
155
+ * { username: 'johndoe', full_name: 'John Doe' },
156
+ * { avatar: avatarFile }
157
+ * );
158
+ *
159
+ * // Register with avatar and cover photo
160
+ * await db.auth.registerWithFiles(
161
+ * 'john@example.com',
162
+ * 'password123',
163
+ * { username: 'johndoe' },
164
+ * { avatar: avatarFile, cover_photo: coverFile }
165
+ * );
166
+ * ```
167
+ */
168
+ registerWithFiles(email: string, password: string, data?: Record<string, any>, files?: Record<string, File | File[]>): Promise<AppUser>;
169
+ /**
170
+ * Logs out the current user by clearing the token and user data.
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * db.auth.logout();
175
+ * console.log('User logged out');
176
+ * ```
177
+ */
178
+ logout(): void;
179
+ /**
180
+ * Checks if a user is currently authenticated.
181
+ *
182
+ * @returns True if user is authenticated, false otherwise
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * if (db.auth.isAuthenticated()) {
187
+ * console.log('User is logged in');
188
+ * }
189
+ * ```
190
+ */
191
+ isAuthenticated(): boolean;
192
+ /**
193
+ * Fetches the current authenticated user's data from the server.
194
+ *
195
+ * @returns Promise resolving to the current user object
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const user = await db.auth.getCurrentUser();
200
+ * console.log('Current user:', user.email);
201
+ * ```
202
+ */
203
+ getCurrentUser(): Promise<AppUser>;
204
+ /**
205
+ * Updates the current user's profile data.
206
+ *
207
+ * @param data - User data to update (optional)
208
+ * @param email - New email address (optional)
209
+ * @param password - New password (optional)
210
+ * @returns Promise resolving to the updated user object
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * await db.auth.updateUser({
215
+ * bio: 'Updated bio',
216
+ * website: 'https://example.com'
217
+ * });
218
+ * ```
219
+ */
220
+ updateUser(data?: Record<string, any> | null, email?: string | null, password?: string | null): Promise<AppUser>;
221
+ /**
222
+ * Update current user with file uploads
223
+ *
224
+ * @param data - User data to update (optional)
225
+ * @param email - New email (optional)
226
+ * @param password - New password (optional)
227
+ * @param files - Object mapping field names to File objects (optional)
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * // Update only avatar
232
+ * await db.auth.updateUserWithFiles(
233
+ * undefined, undefined, undefined,
234
+ * { avatar: newAvatarFile }
235
+ * );
236
+ *
237
+ * // Update bio and avatar
238
+ * await db.auth.updateUserWithFiles(
239
+ * { bio: 'Updated bio' },
240
+ * undefined, undefined,
241
+ * { avatar: newAvatarFile }
242
+ * );
243
+ *
244
+ * // Update multiple fields and files
245
+ * await db.auth.updateUserWithFiles(
246
+ * { username: 'newusername', bio: 'New bio' },
247
+ * 'newemail@example.com',
248
+ * undefined,
249
+ * { avatar: newAvatar, cover_photo: newCover }
250
+ * );
251
+ * ```
252
+ */
253
+ updateUserWithFiles(data?: Record<string, any> | null, email?: string | null, password?: string | null, files?: Record<string, File | File[]>): Promise<AppUser>;
254
+ /**
255
+ * Checks if the current user has a specific role.
256
+ *
257
+ * @param role - Role to check for
258
+ * @returns True if user has the role, false otherwise
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * if (db.auth.hasRole('admin')) {
263
+ * console.log('User is an admin');
264
+ * }
265
+ * ```
266
+ */
267
+ hasRole(role: string): boolean;
268
+ /**
269
+ * Lists users from the auth collection with optional filtering and pagination.
270
+ *
271
+ * @template T - The type of user data
272
+ * @param query - Optional query parameters for filtering, sorting, and pagination
273
+ * @returns Promise resolving to a list of users
274
+ *
275
+ * @example
276
+ * ```typescript
277
+ * const users = await db.auth.listUsers({
278
+ * filters: { status: 'active' },
279
+ * limit: 10
280
+ * });
281
+ * ```
282
+ */
283
+ listUsers<T = any>(query?: Query): Promise<AppUserList>;
284
+ /**
285
+ * Gets a user by their ID.
286
+ *
287
+ * @template T - The type of user data
288
+ * @param userId - Unique ID of the user
289
+ * @returns Promise resolving to the user object
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * const user = await db.auth.getUserById('user-123');
294
+ * console.log('User:', user.email);
295
+ * ```
296
+ */
297
+ getUserById<T = any>(userId: string): Promise<AppUser>;
298
+ }
299
+ export default AuthHandler;
300
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/core/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,OAAO,EACP,WAAW,EACX,KAAK,EACL,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAQ3B;;;;;;;;;;;GAWG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,IAAI,CAAC,CAAU;IAEvB;;;;OAIG;gBACS,MAAM,EAAE,cAAc;IAKlC;;;;OAIG;IACH,QAAQ,IAAI,MAAM,GAAG,SAAS;IAI9B;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM;IAKtB;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,OAAO;IAKrB;;;;OAIG;IACH,OAAO,IAAI,OAAO,GAAG,SAAS;IAI9B;;;;;;;;;OASG;YACW,OAAO;IAqDrB;;;;;;;OAOG;IACH,OAAO,CAAC,kBAAkB;IAiB1B;;;;;;;;;;;OAWG;IACG,QAAQ;IAgBd;;;;;;;;;;;;OAYG;IACG,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAY3C;;;;;;;;;;;;;;;OAeG;IACG,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAY1E;;;;;;;;;;OAUG;IACG,eAAe;IAOrB;;;;;;;;;;;;;;OAcG;IACG,mBAAmB,CAAC,KAAK,EAAE,MAAM;IAKvC;;;;;;;;;;;;;;;;;;;;;;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