@urbackend/sdk 0.1.0 → 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,32 @@
1
+ import { expect, test, vi, beforeEach } from 'vitest';
2
+ import urBackend from '../src/index';
3
+
4
+ const mockApiKey = 'pk_live_test';
5
+ const client = urBackend({ apiKey: mockApiKey });
6
+
7
+ beforeEach(() => {
8
+ vi.resetAllMocks();
9
+ });
10
+
11
+ test('getSchema returns collection schema', async () => {
12
+ const mockSchema = {
13
+ name: 'products',
14
+ model: [
15
+ { key: 'name', type: 'String', required: true },
16
+ { key: 'price', type: 'Number', required: true }
17
+ ]
18
+ };
19
+
20
+ vi.stubGlobal(
21
+ 'fetch',
22
+ vi.fn().mockResolvedValue({
23
+ ok: true,
24
+ headers: new Headers({ 'content-type': 'application/json' }),
25
+ json: () => Promise.resolve({ message: 'Schema exists', collection: mockSchema }),
26
+ }),
27
+ );
28
+
29
+ const schema = await client.schema.getSchema('products');
30
+ expect(schema).toEqual(mockSchema);
31
+ expect(schema.name).toBe('products');
32
+ });
@@ -0,0 +1,62 @@
1
+ /// <reference types="node" />
2
+ import { expect, test, vi } from 'vitest';
3
+ import urBackend from '../src/index';
4
+
5
+ const mockApiKey = 'test-api-key';
6
+ const client = urBackend({ apiKey: mockApiKey });
7
+
8
+ test('upload sends FormData and returns { url, path }', async () => {
9
+ const mockResponse = { url: 'http://cdn.com/file.jpg', path: '/uploads/file.jpg' };
10
+ const fetchMock = vi.fn().mockResolvedValue({
11
+ ok: true,
12
+ headers: new Headers({ 'content-type': 'application/json' }),
13
+ json: () => Promise.resolve({ success: true, data: mockResponse }),
14
+ });
15
+ vi.stubGlobal('fetch', fetchMock);
16
+
17
+ // In Node.js testing environment, use a Buffer as mock file
18
+ const result = await client.storage.upload(Buffer.from('mock binary data'), 'test.jpg');
19
+
20
+ expect(result).toEqual(mockResponse);
21
+ expect(fetchMock).toHaveBeenCalledWith(
22
+ expect.stringContaining('/api/storage/upload'),
23
+ expect.objectContaining({
24
+ method: 'POST',
25
+ body: expect.any(Object), // FormData
26
+ }),
27
+ );
28
+ });
29
+
30
+ test('deleteFile sends path in body', async () => {
31
+ const fetchMock = vi.fn().mockResolvedValue({
32
+ ok: true,
33
+ headers: new Headers({ 'content-type': 'application/json' }),
34
+ json: () => Promise.resolve({ success: true, data: { deleted: true } }),
35
+ });
36
+ vi.stubGlobal('fetch', fetchMock);
37
+
38
+ const result = await client.storage.deleteFile('/uploads/file.jpg');
39
+
40
+ expect(result.deleted).toBe(true);
41
+ expect(fetchMock).toHaveBeenCalledWith(
42
+ expect.stringContaining('/api/storage/file'),
43
+ expect.objectContaining({
44
+ method: 'DELETE',
45
+ body: JSON.stringify({ path: '/uploads/file.jpg' }),
46
+ }),
47
+ );
48
+ });
49
+
50
+ test('StorageError thrown on failure', async () => {
51
+ vi.stubGlobal(
52
+ 'fetch',
53
+ vi.fn().mockResolvedValue({
54
+ ok: false,
55
+ status: 500,
56
+ url: 'https://api.urbackend.bitbros.in/api/storage/upload',
57
+ json: () => Promise.resolve({ success: false, message: 'Upload failed' }),
58
+ }),
59
+ );
60
+
61
+ await expect(client.storage.upload(Buffer.from('data'))).rejects.toThrow('Upload failed');
62
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "..",
5
+ "outDir": "../dist-test",
6
+ "types": ["node", "vitest/globals"]
7
+ },
8
+ "include": ["./**/*", "../src/**/*"]
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "declaration": true,
10
+ "outDir": "dist",
11
+ "rootDir": "src",
12
+ "esModuleInterop": true,
13
+ "skipLibCheck": true,
14
+ "forceConsistentCasingInFileNames": true
15
+ },
16
+ "include": ["src/**/*"],
17
+ "exclude": ["node_modules", "dist", "tests"]
18
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: ['src/index.ts'],
5
+ format: ['cjs', 'esm'],
6
+ outExtension({ format }) {
7
+ return {
8
+ js: format === 'cjs' ? '.cjs' : '.mjs',
9
+ };
10
+ },
11
+ dts: true,
12
+ clean: true,
13
+ minify: false,
14
+ sourcemap: true,
15
+ target: 'es2020',
16
+ });
@@ -0,0 +1,12 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ coverage: {
8
+ provider: 'v8',
9
+ reporter: ['text', 'json', 'html'],
10
+ },
11
+ },
12
+ });
package/dist/index.cjs DELETED
@@ -1,315 +0,0 @@
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: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AuthError: () => AuthError,
24
- NotFoundError: () => NotFoundError,
25
- RateLimitError: () => RateLimitError,
26
- StorageError: () => StorageError,
27
- UrBackendClient: () => UrBackendClient,
28
- UrBackendError: () => UrBackendError,
29
- ValidationError: () => ValidationError,
30
- default: () => urBackend,
31
- parseApiError: () => parseApiError
32
- });
33
- module.exports = __toCommonJS(index_exports);
34
-
35
- // src/errors.ts
36
- var UrBackendError = class extends Error {
37
- constructor(message, statusCode, endpoint) {
38
- super(message);
39
- this.message = message;
40
- this.statusCode = statusCode;
41
- this.endpoint = endpoint;
42
- this.name = "UrBackendError";
43
- }
44
- };
45
- var AuthError = class extends UrBackendError {
46
- constructor(message, statusCode, endpoint) {
47
- super(message, statusCode, endpoint);
48
- this.name = "AuthError";
49
- }
50
- };
51
- var NotFoundError = class extends UrBackendError {
52
- constructor(message, endpoint) {
53
- super(message, 404, endpoint);
54
- this.name = "NotFoundError";
55
- }
56
- };
57
- var RateLimitError = class extends UrBackendError {
58
- constructor(message, endpoint, retryAfter) {
59
- super(message, 429, endpoint);
60
- this.name = "RateLimitError";
61
- this.retryAfter = retryAfter;
62
- }
63
- };
64
- var StorageError = class extends UrBackendError {
65
- constructor(message, statusCode, endpoint) {
66
- super(message, statusCode, endpoint);
67
- this.name = "StorageError";
68
- }
69
- };
70
- var ValidationError = class extends UrBackendError {
71
- constructor(message, endpoint) {
72
- super(message, 400, endpoint);
73
- this.name = "ValidationError";
74
- }
75
- };
76
- async function parseApiError(response) {
77
- const endpoint = new URL(response.url).pathname;
78
- let message = "An unexpected error occurred";
79
- let data;
80
- try {
81
- data = await response.json();
82
- if (typeof data === "object" && data !== null && "message" in data) {
83
- message = data.message || message;
84
- }
85
- } catch {
86
- message = response.statusText || message;
87
- }
88
- const status = response.status;
89
- if (status === 401 || status === 403) {
90
- return new AuthError(message, status, endpoint);
91
- }
92
- if (status === 404) {
93
- return new NotFoundError(message, endpoint);
94
- }
95
- if (status === 429) {
96
- const retryAfter = response.headers.get("Retry-After");
97
- return new RateLimitError(message, endpoint, retryAfter ? parseInt(retryAfter, 10) : void 0);
98
- }
99
- if (status === 400) {
100
- return new ValidationError(message, endpoint);
101
- }
102
- if (endpoint.includes("/api/storage")) {
103
- return new StorageError(message, status, endpoint);
104
- }
105
- return new UrBackendError(message, status, endpoint);
106
- }
107
-
108
- // src/modules/auth.ts
109
- var AuthModule = class {
110
- constructor(client) {
111
- this.client = client;
112
- }
113
- /**
114
- * Create a new user account
115
- */
116
- async signUp(payload) {
117
- return this.client.request("POST", "/api/userAuth/signup", { body: payload });
118
- }
119
- /**
120
- * Log in an existing user and store the session token
121
- */
122
- async login(payload) {
123
- const response = await this.client.request("POST", "/api/userAuth/login", {
124
- body: payload
125
- });
126
- this.sessionToken = response.token;
127
- return response;
128
- }
129
- /**
130
- * Get the current authenticated user's profile
131
- */
132
- async me(token) {
133
- const activeToken = token || this.sessionToken;
134
- if (!activeToken) {
135
- throw new AuthError("Authentication token is required for /me endpoint", 401, "/api/userAuth/me");
136
- }
137
- return this.client.request("GET", "/api/userAuth/me", { token: activeToken });
138
- }
139
- /**
140
- * Clear the local session token
141
- */
142
- logout() {
143
- this.sessionToken = void 0;
144
- }
145
- };
146
-
147
- // src/modules/database.ts
148
- var DatabaseModule = class {
149
- constructor(client) {
150
- this.client = client;
151
- }
152
- /**
153
- * Fetch all documents from a collection
154
- */
155
- async getAll(collection) {
156
- try {
157
- return await this.client.request("GET", `/api/data/${collection}`);
158
- } catch (e) {
159
- if (e instanceof NotFoundError) {
160
- return [];
161
- }
162
- throw e;
163
- }
164
- }
165
- /**
166
- * Fetch a single document by its ID
167
- */
168
- async getOne(collection, id) {
169
- return this.client.request("GET", `/api/data/${collection}/${id}`);
170
- }
171
- /**
172
- * Insert a new document into a collection
173
- */
174
- async insert(collection, data) {
175
- return this.client.request("POST", `/api/data/${collection}`, { body: data });
176
- }
177
- /**
178
- * Update an existing document by its ID
179
- */
180
- async update(collection, id, data) {
181
- return this.client.request("PUT", `/api/data/${collection}/${id}`, { body: data });
182
- }
183
- /**
184
- * Delete a document by its ID
185
- */
186
- async delete(collection, id) {
187
- return this.client.request("DELETE", `/api/data/${collection}/${id}`);
188
- }
189
- };
190
-
191
- // src/modules/storage.ts
192
- var StorageModule = class {
193
- constructor(client) {
194
- this.client = client;
195
- }
196
- /**
197
- * Upload a file to storage
198
- */
199
- async upload(file, filename) {
200
- const formData = new FormData();
201
- if (typeof window === "undefined" && typeof Buffer !== "undefined" && Buffer.isBuffer(file)) {
202
- const blob = new Blob([file]);
203
- formData.append("file", blob, filename || "file");
204
- } else {
205
- formData.append("file", file, filename);
206
- }
207
- return this.client.request("POST", "/api/storage/upload", {
208
- body: formData,
209
- isMultipart: true
210
- });
211
- }
212
- /**
213
- * Delete a file from storage by its path
214
- */
215
- async deleteFile(path) {
216
- return this.client.request("DELETE", "/api/storage/file", {
217
- body: { path }
218
- });
219
- }
220
- };
221
-
222
- // src/client.ts
223
- var UrBackendClient = class {
224
- constructor(config) {
225
- this.apiKey = config.apiKey;
226
- this.baseUrl = config.baseUrl || "https://api.urbackend.bitbros.in";
227
- if (typeof window !== "undefined") {
228
- console.warn(
229
- "\u26A0\uFE0F urbackend-sdk: Avoid exposing your API key in client-side code. This can lead to unauthorized access to your account and data."
230
- );
231
- }
232
- }
233
- get auth() {
234
- if (!this._auth) {
235
- this._auth = new AuthModule(this);
236
- }
237
- return this._auth;
238
- }
239
- get db() {
240
- if (!this._db) {
241
- this._db = new DatabaseModule(this);
242
- }
243
- return this._db;
244
- }
245
- get storage() {
246
- if (!this._storage) {
247
- this._storage = new StorageModule(this);
248
- }
249
- return this._storage;
250
- }
251
- /**
252
- * Internal request handler
253
- */
254
- async request(method, path, options = {}) {
255
- const url = `${this.baseUrl}${path}`;
256
- const headers = {
257
- "x-api-key": this.apiKey,
258
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
259
- "Origin": "https://urbackend.bitbros.in",
260
- "Referer": "https://urbackend.bitbros.in/"
261
- };
262
- if (options.token) {
263
- headers["Authorization"] = `Bearer ${options.token}`;
264
- }
265
- let requestBody;
266
- if (options.isMultipart) {
267
- requestBody = options.body;
268
- } else if (options.body) {
269
- headers["Content-Type"] = "application/json";
270
- requestBody = JSON.stringify(options.body);
271
- }
272
- try {
273
- const response = await fetch(url, {
274
- method,
275
- headers,
276
- body: requestBody
277
- });
278
- if (!response.ok) {
279
- throw await parseApiError(response);
280
- }
281
- const contentType = response.headers.get("content-type");
282
- if (contentType && contentType.includes("application/json")) {
283
- const json = await response.json();
284
- return json.data !== void 0 ? json.data : json;
285
- }
286
- return await response.text();
287
- } catch (error) {
288
- if (error instanceof UrBackendError) {
289
- throw error;
290
- }
291
- throw new UrBackendError(
292
- error instanceof Error ? error.message : "Network request failed",
293
- 0,
294
- path
295
- );
296
- }
297
- }
298
- };
299
-
300
- // src/index.ts
301
- function urBackend(config) {
302
- return new UrBackendClient(config);
303
- }
304
- // Annotate the CommonJS export names for ESM import in node:
305
- 0 && (module.exports = {
306
- AuthError,
307
- NotFoundError,
308
- RateLimitError,
309
- StorageError,
310
- UrBackendClient,
311
- UrBackendError,
312
- ValidationError,
313
- parseApiError
314
- });
315
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/modules/auth.ts","../src/modules/database.ts","../src/modules/storage.ts","../src/client.ts"],"sourcesContent":["import { UrBackendClient } from './client';\r\nimport { UrBackendConfig } from './types';\r\n\r\nexport * from './types';\r\nexport * from './errors';\r\nexport { UrBackendClient };\r\n\r\n/**\r\n * Factory function to create a new urBackend client\r\n */\r\nexport default function urBackend(config: UrBackendConfig): UrBackendClient {\r\n return new UrBackendClient(config);\r\n}\r\n","export class UrBackendError extends Error {\r\n constructor(\r\n public message: string,\r\n public statusCode: number,\r\n public endpoint: string,\r\n ) {\r\n super(message);\r\n this.name = 'UrBackendError';\r\n }\r\n}\r\n\r\nexport class AuthError extends UrBackendError {\r\n constructor(message: string, statusCode: number, endpoint: string) {\r\n super(message, statusCode, endpoint);\r\n this.name = 'AuthError';\r\n }\r\n}\r\n\r\nexport class NotFoundError extends UrBackendError {\r\n constructor(message: string, endpoint: string) {\r\n super(message, 404, endpoint);\r\n this.name = 'NotFoundError';\r\n }\r\n}\r\n\r\nexport class RateLimitError extends UrBackendError {\r\n public retryAfter?: number;\r\n\r\n constructor(message: string, endpoint: string, retryAfter?: number) {\r\n super(message, 429, endpoint);\r\n this.name = 'RateLimitError';\r\n this.retryAfter = retryAfter;\r\n }\r\n}\r\n\r\nexport class StorageError extends UrBackendError {\r\n constructor(message: string, statusCode: number, endpoint: string) {\r\n super(message, statusCode, endpoint);\r\n this.name = 'StorageError';\r\n }\r\n}\r\n\r\nexport class ValidationError extends UrBackendError {\r\n constructor(message: string, endpoint: string) {\r\n super(message, 400, endpoint);\r\n this.name = 'ValidationError';\r\n }\r\n}\r\n\r\nexport async function parseApiError(response: Response): Promise<UrBackendError> {\r\n const endpoint = new URL(response.url).pathname;\r\n let message = 'An unexpected error occurred';\r\n let data: unknown;\r\n\r\n try {\r\n data = await response.json();\r\n if (typeof data === 'object' && data !== null && 'message' in data) {\r\n message = (data as { message: string }).message || message;\r\n }\r\n } catch {\r\n // If not JSON, use status text\r\n message = response.statusText || message;\r\n }\r\n\r\n const status = response.status;\r\n\r\n if (status === 401 || status === 403) {\r\n return new AuthError(message, status, endpoint);\r\n }\r\n\r\n if (status === 404) {\r\n return new NotFoundError(message, endpoint);\r\n }\r\n\r\n if (status === 429) {\r\n const retryAfter = response.headers.get('Retry-After');\r\n return new RateLimitError(message, endpoint, retryAfter ? parseInt(retryAfter, 10) : undefined);\r\n }\r\n\r\n if (status === 400) {\r\n return new ValidationError(message, endpoint);\r\n }\r\n\r\n // Default for 5xx or other 4xx\r\n if (endpoint.includes('/api/storage')) {\r\n return new StorageError(message, status, endpoint);\r\n }\r\n\r\n return new UrBackendError(message, status, endpoint);\r\n}\r\n","import { UrBackendClient } from '../client';\r\nimport { AuthUser, AuthResponse, SignUpPayload, LoginPayload } from '../types';\r\nimport { AuthError } from '../errors';\r\n\r\nexport class AuthModule {\r\n private sessionToken?: string;\r\n\r\n constructor(private client: UrBackendClient) {}\r\n\r\n /**\r\n * Create a new user account\r\n */\r\n public async signUp(payload: SignUpPayload): Promise<AuthUser> {\r\n return this.client.request<AuthUser>('POST', '/api/userAuth/signup', { body: payload });\r\n }\r\n\r\n /**\r\n * Log in an existing user and store the session token\r\n */\r\n public async login(payload: LoginPayload): Promise<AuthResponse> {\r\n const response = await this.client.request<AuthResponse>('POST', '/api/userAuth/login', {\r\n body: payload,\r\n });\r\n this.sessionToken = response.token;\r\n return response;\r\n }\r\n\r\n /**\r\n * Get the current authenticated user's profile\r\n */\r\n public async me(token?: string): Promise<AuthUser> {\r\n const activeToken = token || this.sessionToken;\r\n\r\n if (!activeToken) {\r\n throw new AuthError('Authentication token is required for /me endpoint', 401, '/api/userAuth/me');\r\n }\r\n\r\n return this.client.request<AuthUser>('GET', '/api/userAuth/me', { token: activeToken });\r\n }\r\n\r\n /**\r\n * Clear the local session token\r\n */\r\n public logout(): void {\r\n this.sessionToken = undefined;\r\n }\r\n}\r\n","import { UrBackendClient } from '../client';\r\nimport { DocumentData, InsertPayload, UpdatePayload } from '../types';\r\nimport { NotFoundError } from '../errors';\r\n\r\nexport class DatabaseModule {\r\n constructor(private client: UrBackendClient) {}\r\n\r\n /**\r\n * Fetch all documents from a collection\r\n */\r\n public async getAll<T extends DocumentData>(collection: string): Promise<T[]> {\r\n try {\r\n return await this.client.request<T[]>('GET', `/api/data/${collection}`);\r\n } catch (e) {\r\n if (e instanceof NotFoundError) {\r\n return [] as T[];\r\n }\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * Fetch a single document by its ID\r\n */\r\n public async getOne<T extends DocumentData>(collection: string, id: string): Promise<T> {\r\n return this.client.request<T>('GET', `/api/data/${collection}/${id}`);\r\n }\r\n\r\n /**\r\n * Insert a new document into a collection\r\n */\r\n public async insert<T extends DocumentData>(collection: string, data: InsertPayload): Promise<T> {\r\n return this.client.request<T>('POST', `/api/data/${collection}`, { body: data });\r\n }\r\n\r\n /**\r\n * Update an existing document by its ID\r\n */\r\n public async update<T extends DocumentData>(\r\n collection: string,\r\n id: string,\r\n data: UpdatePayload,\r\n ): Promise<T> {\r\n return this.client.request<T>('PUT', `/api/data/${collection}/${id}`, { body: data });\r\n }\r\n\r\n /**\r\n * Delete a document by its ID\r\n */\r\n public async delete(collection: string, id: string): Promise<{ deleted: boolean }> {\r\n return this.client.request<{ deleted: boolean }>('DELETE', `/api/data/${collection}/${id}`);\r\n }\r\n}\r\n","/// <reference lib=\"dom\" />\r\nimport { UrBackendClient } from '../client';\r\nimport { UploadResponse } from '../types';\r\n\r\nexport class StorageModule {\r\n constructor(private client: UrBackendClient) {}\r\n\r\n /**\r\n * Upload a file to storage\r\n */\r\n public async upload(file: unknown, filename?: string): Promise<UploadResponse> {\r\n const formData = new FormData();\r\n\r\n if (\r\n typeof window === 'undefined' &&\r\n typeof Buffer !== 'undefined' &&\r\n Buffer.isBuffer(file)\r\n ) {\r\n // In Node.js environment, convert Buffer to Blob for standard FormData\r\n const blob = new Blob([file as unknown as BlobPart]);\r\n formData.append('file', blob, filename || 'file');\r\n } else {\r\n // Browser File/Blob or Node.js Blob/File\r\n formData.append('file', file as unknown as Blob, filename);\r\n }\r\n\r\n return this.client.request<UploadResponse>('POST', '/api/storage/upload', {\r\n body: formData,\r\n isMultipart: true,\r\n });\r\n }\r\n\r\n /**\r\n * Delete a file from storage by its path\r\n */\r\n public async deleteFile(path: string): Promise<{ deleted: boolean }> {\r\n return this.client.request<{ deleted: boolean }>('DELETE', '/api/storage/file', {\r\n body: { path },\r\n });\r\n }\r\n}\r\n","import { UrBackendConfig, RequestOptions } from './types';\r\nimport { UrBackendError, parseApiError } from './errors';\r\nimport { AuthModule } from './modules/auth';\r\nimport { DatabaseModule } from './modules/database';\r\nimport { StorageModule } from './modules/storage';\r\n\r\nexport class UrBackendClient {\r\n private apiKey: string;\r\n private baseUrl: string;\r\n private _auth?: AuthModule;\r\n private _db?: DatabaseModule;\r\n private _storage?: StorageModule;\r\n\r\n constructor(config: UrBackendConfig) {\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = config.baseUrl || 'https://api.urbackend.bitbros.in';\r\n\r\n if (typeof window !== 'undefined') {\r\n console.warn(\r\n '⚠️ urbackend-sdk: Avoid exposing your API key in client-side code. This can lead to unauthorized access to your account and data.',\r\n );\r\n }\r\n }\r\n\r\n get auth(): AuthModule {\r\n if (!this._auth) {\r\n this._auth = new AuthModule(this);\r\n }\r\n return this._auth;\r\n }\r\n\r\n get db(): DatabaseModule {\r\n if (!this._db) {\r\n this._db = new DatabaseModule(this);\r\n }\r\n return this._db;\r\n }\r\n\r\n get storage(): StorageModule {\r\n if (!this._storage) {\r\n this._storage = new StorageModule(this);\r\n }\r\n return this._storage;\r\n }\r\n\r\n /**\r\n * Internal request handler\r\n */\r\n public async request<T>(\r\n method: string,\r\n path: string,\r\n options: RequestOptions = {},\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${path}`;\r\n const headers: Record<string, string> = {\r\n 'x-api-key': this.apiKey,\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',\r\n 'Origin': 'https://urbackend.bitbros.in',\r\n 'Referer': 'https://urbackend.bitbros.in/',\r\n };\r\n\r\n if (options.token) {\r\n headers['Authorization'] = `Bearer ${options.token}`;\r\n }\r\n\r\n let requestBody: BodyInit | undefined;\r\n\r\n if (options.isMultipart) {\r\n // Fetch handles FormData content type and boundary\r\n requestBody = options.body as FormData;\r\n } else if (options.body) {\r\n headers['Content-Type'] = 'application/json';\r\n requestBody = JSON.stringify(options.body);\r\n }\r\n\r\n try {\r\n const response = await fetch(url, {\r\n method,\r\n headers,\r\n body: requestBody,\r\n });\r\n\r\n if (!response.ok) {\r\n throw await parseApiError(response);\r\n }\r\n\r\n const contentType = response.headers.get('content-type');\r\n if (contentType && contentType.includes('application/json')) {\r\n const json = await response.json();\r\n // The API returns { data, success, message }\r\n return json.data !== undefined ? json.data : json;\r\n }\r\n\r\n return (await response.text()) as unknown as T;\r\n } catch (error) {\r\n if (error instanceof UrBackendError) {\r\n throw error;\r\n }\r\n throw new UrBackendError(\r\n error instanceof Error ? error.message : 'Network request failed',\r\n 0,\r\n path,\r\n );\r\n }\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACS,SACA,YACA,UACP;AACA,UAAM,OAAO;AAJN;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,YAAN,cAAwB,eAAe;AAAA,EAC5C,YAAY,SAAiB,YAAoB,UAAkB;AACjE,UAAM,SAAS,YAAY,QAAQ;AACnC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,eAAe;AAAA,EAChD,YAAY,SAAiB,UAAkB;AAC7C,UAAM,SAAS,KAAK,QAAQ;AAC5B,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EAGjD,YAAY,SAAiB,UAAkB,YAAqB;AAClE,UAAM,SAAS,KAAK,QAAQ;AAC5B,SAAK,OAAO;AACZ,SAAK,aAAa;AAAA,EACpB;AACF;AAEO,IAAM,eAAN,cAA2B,eAAe;AAAA,EAC/C,YAAY,SAAiB,YAAoB,UAAkB;AACjE,UAAM,SAAS,YAAY,QAAQ;AACnC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,eAAe;AAAA,EAClD,YAAY,SAAiB,UAAkB;AAC7C,UAAM,SAAS,KAAK,QAAQ;AAC5B,SAAK,OAAO;AAAA,EACd;AACF;AAEA,eAAsB,cAAc,UAA6C;AAC/E,QAAM,WAAW,IAAI,IAAI,SAAS,GAAG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MAAa,QACX,QACA,MACA,UAA0B,CAAC,GACf;AACZ,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,IAAI;AAClC,UAAM,UAAkC;AAAA,MACtC,aAAa,KAAK;AAAA,MAClB,cAAc;AAAA,MACd,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAEA,QAAI,QAAQ,OAAO;AACjB,cAAQ,eAAe,IAAI,UAAU,QAAQ,KAAK;AAAA,IACpD;AAEA,QAAI;AAEJ,QAAI,QAAQ,aAAa;AAEvB,oBAAc,QAAQ;AAAA,IACxB,WAAW,QAAQ,MAAM;AACvB,cAAQ,cAAc,IAAI;AAC1B,oBAAc,KAAK,UAAU,QAAQ,IAAI;AAAA,IAC3C;AAEA,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,KAAK;AAAA,QAChC;AAAA,QACA;AAAA,QACA,MAAM;AAAA,MACR,CAAC;AAED,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,MAAM,cAAc,QAAQ;AAAA,MACpC;AAEA,YAAM,cAAc,SAAS,QAAQ,IAAI,cAAc;AACvD,UAAI,eAAe,YAAY,SAAS,kBAAkB,GAAG;AAC3D,cAAM,OAAO,MAAM,SAAS,KAAK;AAEjC,eAAO,KAAK,SAAS,SAAY,KAAK,OAAO;AAAA,MAC/C;AAEA,aAAQ,MAAM,SAAS,KAAK;AAAA,IAC9B,SAAS,OAAO;AACd,UAAI,iBAAiB,gBAAgB;AACnC,cAAM;AAAA,MACR;AACA,YAAM,IAAI;AAAA,QACR,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QACzC;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AL/Fe,SAAR,UAA2B,QAA0C;AAC1E,SAAO,IAAI,gBAAgB,MAAM;AACnC;","names":[]}
package/dist/index.d.mts DELETED
@@ -1,158 +0,0 @@
1
- interface UrBackendConfig {
2
- apiKey: string;
3
- baseUrl?: string;
4
- }
5
- interface RequestOptions {
6
- body?: unknown;
7
- token?: string;
8
- isMultipart?: boolean;
9
- }
10
- interface SignUpPayload {
11
- email: string;
12
- password: string;
13
- name?: string;
14
- }
15
- interface LoginPayload {
16
- email: string;
17
- password: string;
18
- }
19
- interface AuthUser {
20
- _id: string;
21
- email: string;
22
- name?: string;
23
- [key: string]: unknown;
24
- }
25
- interface AuthResponse {
26
- token: string;
27
- user: AuthUser;
28
- }
29
- interface DocumentData {
30
- _id: string;
31
- [key: string]: unknown;
32
- }
33
- interface InsertPayload {
34
- [key: string]: unknown;
35
- }
36
- interface UpdatePayload {
37
- [key: string]: unknown;
38
- }
39
- interface UploadResponse {
40
- url: string;
41
- path: string;
42
- }
43
- interface ApiResponse<T> {
44
- data: T;
45
- success: boolean;
46
- message?: string;
47
- }
48
-
49
- declare class AuthModule {
50
- private client;
51
- private sessionToken?;
52
- constructor(client: UrBackendClient);
53
- /**
54
- * Create a new user account
55
- */
56
- signUp(payload: SignUpPayload): Promise<AuthUser>;
57
- /**
58
- * Log in an existing user and store the session token
59
- */
60
- login(payload: LoginPayload): Promise<AuthResponse>;
61
- /**
62
- * Get the current authenticated user's profile
63
- */
64
- me(token?: string): Promise<AuthUser>;
65
- /**
66
- * Clear the local session token
67
- */
68
- logout(): void;
69
- }
70
-
71
- declare class DatabaseModule {
72
- private client;
73
- constructor(client: UrBackendClient);
74
- /**
75
- * Fetch all documents from a collection
76
- */
77
- getAll<T extends DocumentData>(collection: string): Promise<T[]>;
78
- /**
79
- * Fetch a single document by its ID
80
- */
81
- getOne<T extends DocumentData>(collection: string, id: string): Promise<T>;
82
- /**
83
- * Insert a new document into a collection
84
- */
85
- insert<T extends DocumentData>(collection: string, data: InsertPayload): Promise<T>;
86
- /**
87
- * Update an existing document by its ID
88
- */
89
- update<T extends DocumentData>(collection: string, id: string, data: UpdatePayload): Promise<T>;
90
- /**
91
- * Delete a document by its ID
92
- */
93
- delete(collection: string, id: string): Promise<{
94
- deleted: boolean;
95
- }>;
96
- }
97
-
98
- declare class StorageModule {
99
- private client;
100
- constructor(client: UrBackendClient);
101
- /**
102
- * Upload a file to storage
103
- */
104
- upload(file: unknown, filename?: string): Promise<UploadResponse>;
105
- /**
106
- * Delete a file from storage by its path
107
- */
108
- deleteFile(path: string): Promise<{
109
- deleted: boolean;
110
- }>;
111
- }
112
-
113
- declare class UrBackendClient {
114
- private apiKey;
115
- private baseUrl;
116
- private _auth?;
117
- private _db?;
118
- private _storage?;
119
- constructor(config: UrBackendConfig);
120
- get auth(): AuthModule;
121
- get db(): DatabaseModule;
122
- get storage(): StorageModule;
123
- /**
124
- * Internal request handler
125
- */
126
- request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
127
- }
128
-
129
- declare class UrBackendError extends Error {
130
- message: string;
131
- statusCode: number;
132
- endpoint: string;
133
- constructor(message: string, statusCode: number, endpoint: string);
134
- }
135
- declare class AuthError extends UrBackendError {
136
- constructor(message: string, statusCode: number, endpoint: string);
137
- }
138
- declare class NotFoundError extends UrBackendError {
139
- constructor(message: string, endpoint: string);
140
- }
141
- declare class RateLimitError extends UrBackendError {
142
- retryAfter?: number;
143
- constructor(message: string, endpoint: string, retryAfter?: number);
144
- }
145
- declare class StorageError extends UrBackendError {
146
- constructor(message: string, statusCode: number, endpoint: string);
147
- }
148
- declare class ValidationError extends UrBackendError {
149
- constructor(message: string, endpoint: string);
150
- }
151
- declare function parseApiError(response: Response): Promise<UrBackendError>;
152
-
153
- /**
154
- * Factory function to create a new urBackend client
155
- */
156
- declare function urBackend(config: UrBackendConfig): UrBackendClient;
157
-
158
- export { type ApiResponse, AuthError, type AuthResponse, type AuthUser, type DocumentData, type InsertPayload, type LoginPayload, NotFoundError, RateLimitError, type RequestOptions, type SignUpPayload, StorageError, type UpdatePayload, type UploadResponse, UrBackendClient, type UrBackendConfig, UrBackendError, ValidationError, urBackend as default, parseApiError };