@withvlibe/base-sdk 1.0.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.
package/README.md ADDED
@@ -0,0 +1,369 @@
1
+ # @withvlibe/base-sdk
2
+
3
+ SDK for Vlibe Base Apps - build websites, SaaS applications, and e-commerce stores with authentication, database, and payments out of the box.
4
+
5
+ ## Features
6
+
7
+ - **Authentication** - SSO with Vlibe accounts
8
+ - **Database** - Managed database with CRUD operations and real-time subscriptions
9
+ - **Payments** - Stripe Connect integration with transaction fees (not revenue split)
10
+ - **React Hooks** - Ready-to-use hooks for React/Next.js applications
11
+ - **TypeScript** - Full type safety
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @withvlibe/base-sdk
17
+ # or
18
+ yarn add @withvlibe/base-sdk
19
+ # or
20
+ pnpm add @withvlibe/base-sdk
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ### 1. Environment Setup
26
+
27
+ Add these environment variables to your `.env` file:
28
+
29
+ ```env
30
+ # Vlibe Base App credentials
31
+ VLIBE_BASE_APP_ID=your_app_id
32
+ VLIBE_BASE_APP_SECRET=your_app_secret
33
+
34
+ # Database access
35
+ VLIBE_PROJECT_ID=your_project_id
36
+ VLIBE_DB_TOKEN=your_database_token
37
+
38
+ # Client-side variables (for Next.js)
39
+ NEXT_PUBLIC_VLIBE_PROJECT_ID=your_project_id
40
+ NEXT_PUBLIC_VLIBE_DB_TOKEN=your_database_token
41
+ NEXT_PUBLIC_VLIBE_BASE_APP_ID=your_app_id
42
+ ```
43
+
44
+ ### 2. Initialize Clients
45
+
46
+ ```typescript
47
+ import { VlibeBaseDatabase, VlibeBaseAuth, VlibeBasePayments } from '@withvlibe/base-sdk';
48
+
49
+ // Database client (can be used client-side or server-side)
50
+ export const db = new VlibeBaseDatabase({
51
+ projectId: process.env.VLIBE_PROJECT_ID!,
52
+ databaseToken: process.env.VLIBE_DB_TOKEN!,
53
+ });
54
+
55
+ // Auth client
56
+ export const auth = new VlibeBaseAuth({
57
+ appId: process.env.VLIBE_BASE_APP_ID!,
58
+ appSecret: process.env.VLIBE_BASE_APP_SECRET!,
59
+ });
60
+
61
+ // Payments client (SERVER-SIDE ONLY)
62
+ export const payments = new VlibeBasePayments({
63
+ appId: process.env.VLIBE_BASE_APP_ID!,
64
+ appSecret: process.env.VLIBE_BASE_APP_SECRET!,
65
+ });
66
+ ```
67
+
68
+ ## Database
69
+
70
+ ### CRUD Operations
71
+
72
+ ```typescript
73
+ // Insert a document
74
+ const doc = await db.insert('todos', {
75
+ title: 'Learn Vlibe Base',
76
+ completed: false,
77
+ });
78
+
79
+ // Query documents
80
+ const todos = await db.query('todos', {
81
+ where: { completed: false },
82
+ orderBy: 'created_at',
83
+ orderDirection: 'desc',
84
+ limit: 10,
85
+ });
86
+
87
+ // Get a single document
88
+ const todo = await db.get('todos', 'document-id');
89
+
90
+ // Update a document
91
+ await db.update('todos', 'document-id', {
92
+ completed: true,
93
+ });
94
+
95
+ // Delete a document
96
+ await db.delete('todos', 'document-id');
97
+
98
+ // Count documents
99
+ const count = await db.count('todos', { completed: false });
100
+ ```
101
+
102
+ ### Key-Value Store
103
+
104
+ ```typescript
105
+ // Set a value
106
+ await db.setKV('user-settings', {
107
+ theme: 'dark',
108
+ notifications: true,
109
+ });
110
+
111
+ // Get a value
112
+ const settings = await db.getKV<{ theme: string; notifications: boolean }>('user-settings');
113
+
114
+ // Delete a value
115
+ await db.deleteKV('user-settings');
116
+ ```
117
+
118
+ ### Real-time Subscriptions
119
+
120
+ ```typescript
121
+ // Subscribe to changes
122
+ const subscription = db.subscribe('todos', (payload) => {
123
+ console.log('Change detected:', payload.eventType);
124
+ console.log('New data:', payload.new);
125
+ console.log('Old data:', payload.old);
126
+ });
127
+
128
+ // Unsubscribe when done
129
+ subscription.unsubscribe();
130
+
131
+ // Unsubscribe all
132
+ db.unsubscribeAll();
133
+ ```
134
+
135
+ ## Authentication
136
+
137
+ ```typescript
138
+ // Verify a session token (from SSO callback)
139
+ const user = await auth.verifySession(token);
140
+
141
+ // Get login URL
142
+ const loginUrl = auth.getLoginUrl('/dashboard');
143
+
144
+ // Get logout URL
145
+ const logoutUrl = auth.getLogoutUrl('/');
146
+
147
+ // Check features/subscription
148
+ if (auth.hasFeature(user, 'premium-feature')) {
149
+ // Show premium content
150
+ }
151
+
152
+ if (auth.hasSubscription(user)) {
153
+ // User has active subscription
154
+ }
155
+ ```
156
+
157
+ ## Payments
158
+
159
+ Vlibe Base uses a transaction fee model:
160
+ - **Free plan**: 2% transaction fee
161
+ - **Premium plan**: 0.5% transaction fee
162
+
163
+ ```typescript
164
+ // Create a checkout session
165
+ const session = await payments.createCheckout({
166
+ amount: 1999, // $19.99 in cents
167
+ currency: 'usd',
168
+ userId: user.id,
169
+ userEmail: user.email,
170
+ description: 'Premium Subscription',
171
+ successUrl: 'https://myapp.com/success',
172
+ cancelUrl: 'https://myapp.com/cancel',
173
+ });
174
+
175
+ // Redirect user to checkout
176
+ window.location.href = session.url;
177
+
178
+ // Get transaction history
179
+ const transactions = await payments.getTransactions({
180
+ limit: 20,
181
+ status: 'succeeded',
182
+ });
183
+
184
+ // Get transaction stats
185
+ const stats = await payments.getTransactionStats();
186
+ console.log('Total revenue:', stats.totalRevenue);
187
+ console.log('This month:', stats.thisMonth.revenue);
188
+
189
+ // Create a refund
190
+ await payments.createRefund({
191
+ transactionId: 'transaction-id',
192
+ amount: 999, // Partial refund of $9.99
193
+ reason: 'Customer requested',
194
+ });
195
+
196
+ // Calculate fees
197
+ const fee = payments.calculateFee(1999, 'free'); // 40 cents (2%)
198
+ const net = payments.calculateNetAmount(1999, 'free'); // 1959 cents
199
+ ```
200
+
201
+ ### Stripe Connect Setup
202
+
203
+ ```typescript
204
+ // Get onboarding URL for users to connect their Stripe account
205
+ const onboardingUrl = await payments.getConnectOnboardingUrl(
206
+ 'https://myapp.com/stripe/callback'
207
+ );
208
+
209
+ // Check Connect status
210
+ const status = await payments.getConnectStatus();
211
+ if (status.chargesEnabled && status.payoutsEnabled) {
212
+ // Ready to accept payments
213
+ }
214
+ ```
215
+
216
+ ## React Hooks
217
+
218
+ ```tsx
219
+ import { useCollection, useKV, useAuth } from '@withvlibe/base-sdk/react';
220
+
221
+ function TodoApp() {
222
+ // Collection hook with real-time updates
223
+ const { data: todos, loading, insert, update, remove } = useCollection(db, 'todos', {
224
+ orderBy: 'created_at',
225
+ orderDirection: 'desc',
226
+ realtime: true,
227
+ });
228
+
229
+ // Key-value hook
230
+ const { data: settings, set: setSettings } = useKV(db, 'user-settings');
231
+
232
+ // Auth hook
233
+ const { user, login, logout, hasFeature } = useAuth(auth);
234
+
235
+ if (loading) return <div>Loading...</div>;
236
+
237
+ if (!user) {
238
+ return <button onClick={() => login()}>Login with Vlibe</button>;
239
+ }
240
+
241
+ return (
242
+ <div>
243
+ <h1>Welcome, {user.name}!</h1>
244
+
245
+ {/* Theme toggle */}
246
+ <button onClick={() => setSettings({ ...settings, theme: 'dark' })}>
247
+ Dark Mode
248
+ </button>
249
+
250
+ {/* Todo list */}
251
+ <ul>
252
+ {todos.map((todo) => (
253
+ <li key={todo.id}>
254
+ <input
255
+ type="checkbox"
256
+ checked={todo.completed}
257
+ onChange={() => update(todo.id, { completed: !todo.completed })}
258
+ />
259
+ {todo.title}
260
+ <button onClick={() => remove(todo.id)}>Delete</button>
261
+ </li>
262
+ ))}
263
+ </ul>
264
+
265
+ {/* Add todo */}
266
+ <button onClick={() => insert({ title: 'New Todo', completed: false })}>
267
+ Add Todo
268
+ </button>
269
+
270
+ {/* Premium feature */}
271
+ {hasFeature('analytics') && <Analytics />}
272
+
273
+ <button onClick={() => logout()}>Logout</button>
274
+ </div>
275
+ );
276
+ }
277
+ ```
278
+
279
+ ## Category-Specific Helpers
280
+
281
+ The SDK includes TypeScript types for common patterns:
282
+
283
+ ### Website
284
+
285
+ ```typescript
286
+ import type { Page, Media } from '@withvlibe/base-sdk';
287
+
288
+ const pages = await db.query<Page>('pages', { where: { isPublished: true } });
289
+ const media = await db.query<Media>('media');
290
+ ```
291
+
292
+ ### SaaS
293
+
294
+ ```typescript
295
+ import type { FeatureFlag, UsageMetric } from '@withvlibe/base-sdk';
296
+
297
+ const flags = await db.query<FeatureFlag>('feature_flags');
298
+ const usage = await db.query<UsageMetric>('usage_metrics', {
299
+ where: { userId: user.id },
300
+ });
301
+ ```
302
+
303
+ ### E-commerce
304
+
305
+ ```typescript
306
+ import type { Product, Order, OrderItem } from '@withvlibe/base-sdk';
307
+
308
+ const products = await db.query<Product>('products', { where: { isActive: true } });
309
+ const orders = await db.query<Order>('orders', { where: { userId: user.id } });
310
+ ```
311
+
312
+ ## API Reference
313
+
314
+ ### VlibeBaseDatabase
315
+
316
+ | Method | Description |
317
+ |--------|-------------|
318
+ | `insert(collection, data)` | Insert a document |
319
+ | `query(collection, options?)` | Query documents |
320
+ | `get(collection, id)` | Get a document by ID |
321
+ | `update(collection, id, data)` | Update a document |
322
+ | `delete(collection, id)` | Delete a document |
323
+ | `count(collection, where?)` | Count documents |
324
+ | `setKV(key, value)` | Set a key-value pair |
325
+ | `getKV(key)` | Get a value by key |
326
+ | `deleteKV(key)` | Delete a key-value pair |
327
+ | `subscribe(collection, callback)` | Subscribe to real-time changes |
328
+ | `unsubscribeAll()` | Unsubscribe from all subscriptions |
329
+
330
+ ### VlibeBaseAuth
331
+
332
+ | Method | Description |
333
+ |--------|-------------|
334
+ | `verifySession(token)` | Verify a session token |
335
+ | `getLoginUrl(redirectPath?)` | Get SSO login URL |
336
+ | `getLogoutUrl(redirectPath?)` | Get logout URL |
337
+ | `hasFeature(user, feature)` | Check if user has feature access |
338
+ | `hasSubscription(user)` | Check if user has subscription |
339
+ | `getTier(user)` | Get user's subscription tier |
340
+
341
+ ### VlibeBasePayments
342
+
343
+ | Method | Description |
344
+ |--------|-------------|
345
+ | `createCheckout(options)` | Create a checkout session |
346
+ | `getCheckoutSession(id)` | Get checkout session details |
347
+ | `getTransactions(options?)` | Get transaction history |
348
+ | `getTransaction(id)` | Get a single transaction |
349
+ | `getTransactionStats()` | Get transaction statistics |
350
+ | `createRefund(options)` | Create a refund |
351
+ | `getConnectOnboardingUrl(returnUrl)` | Get Stripe Connect onboarding URL |
352
+ | `getConnectStatus()` | Get Stripe Connect status |
353
+ | `calculateFee(amount, plan)` | Calculate transaction fee |
354
+ | `calculateNetAmount(amount, plan)` | Calculate net amount after fees |
355
+
356
+ ## Comparison with Vlibe Official SDK
357
+
358
+ | Feature | Base SDK | Official SDK |
359
+ |---------|----------|--------------|
360
+ | Auth | ✅ SSO | ✅ SSO |
361
+ | Database | ✅ Managed | ✅ Shared |
362
+ | Payments | ✅ Transaction fees (0.5-2%) | ✅ Revenue split (50/50) |
363
+ | Hosting | Self-hosted | Vlibe-hosted |
364
+ | Revenue | Keep 98-99.5% | Keep 50% |
365
+ | Best for | Independent apps | Vlibe ecosystem apps |
366
+
367
+ ## License
368
+
369
+ MIT © [Vlibe](https://vlibe.app)