@aerostack/sdk 0.1.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,327 @@
1
+ # @aerostack/sdk
2
+
3
+ The official Aerostack SDK for building serverless applications with comprehensive backend features and authentication.
4
+
5
+ ## Features
6
+
7
+ ### 🔧 **Server SDK** - Full Backend Platform
8
+ Comprehensive server-side SDK for Cloudflare Workers with:
9
+ - **Multi-Database Operations**: D1 + Postgres with intelligent query routing
10
+ - **KV Cache**: High-performance edge caching
11
+ - **Queue**: Background job processing
12
+ - **R2 Storage**: File upload and management
13
+ - **AI Operations**: Chat completions, embeddings, text generation
14
+ - **Service Invocation**: Cross-service RPC via Workers Dispatch
15
+ - **Production-Ready Error Handling**: Structured errors with actionable suggestions
16
+
17
+ ### 🔐 **Client SDK** - Authentication Excellence
18
+ Client-focused SDK with complete auth features:
19
+ - User registration and login
20
+ - OTP authentication
21
+ - Email verification
22
+ - Password reset flows
23
+ - Session management (refresh tokens)
24
+ - User profile management
25
+ - Comprehensive error handling
26
+
27
+ > **Note**: MFA and Social Auth coming in future releases
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ npm install @aerostack/sdk
33
+ # or
34
+ pnpm add @aerostack/sdk
35
+ # or
36
+ yarn add @aerostack/sdk
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ### Server SDK (Cloudflare Workers)
42
+
43
+ ```typescript
44
+ import { AerostackServer } from '@aerostack/sdk';
45
+
46
+ export default {
47
+ async fetch(request: Request, env: Env) {
48
+ const aerostack = new AerostackServer(env);
49
+
50
+ // Database query with intelligent routing
51
+ const users = await aerostack.db.query('SELECT * FROM users WHERE active = ?', [true]);
52
+
53
+ // Cache operations
54
+ await aerostack.cache.set('user:123', { name: 'John' }, { ttl: 3600 });
55
+ const user = await aerostack.cache.get('user:123');
56
+
57
+ // Queue background job
58
+ await aerostack.queue.enqueue({
59
+ type: 'send-email',
60
+ data: { to: 'user@example.com', subject: 'Welcome!' }
61
+ });
62
+
63
+ // AI chat completion
64
+ const response = await aerostack.ai.chat([
65
+ { role: 'user', content: 'Hello!' }
66
+ ]);
67
+
68
+ return new Response(JSON.stringify(users));
69
+ }
70
+ };
71
+ ```
72
+
73
+ ### Client SDK (Frontend)
74
+
75
+ ```typescript
76
+ import { AerostackClient } from '@aerostack/sdk';
77
+
78
+ const client = new AerostackClient({
79
+ projectSlug: 'my-project',
80
+ baseUrl: 'https://api.aerostack.app' // optional
81
+ });
82
+
83
+ // Register user
84
+ try {
85
+ const { user, token } = await client.auth.register({
86
+ email: 'user@example.com',
87
+ password: 'secure-password',
88
+ name: 'John Doe'
89
+ });
90
+ console.log('Registered:', user);
91
+ } catch (error) {
92
+ if (error.code === 'AUTH_USER_EXISTS') {
93
+ console.log(error.details.suggestion); // "Try logging in instead"
94
+ }
95
+ }
96
+
97
+ // Login
98
+ const { user, token } = await client.auth.login('user@example.com', 'password');
99
+
100
+ // OTP authentication
101
+ await client.auth.sendOTP('user@example.com');
102
+ const auth = await client.auth.verifyOTP('user@example.com', '123456');
103
+
104
+ // Password reset
105
+ await client.auth.requestPasswordReset('user@example.com');
106
+ await client.auth.resetPassword('reset-token', 'new-password');
107
+
108
+ // Session management
109
+ const newToken = await client.auth.refreshToken(refreshToken);
110
+ await client.auth.logout(token);
111
+
112
+ // User profile
113
+ const currentUser = await client.auth.getCurrentUser(token);
114
+ const updated = await client.auth.updateProfile(token, { name: 'Jane Doe' });
115
+ ```
116
+
117
+ ## Server SDK API
118
+
119
+ ### Database Operations
120
+
121
+ ```typescript
122
+ // Query with intelligent routing (D1 or Postgres)
123
+ const result = await aerostack.db.query<User>('SELECT * FROM users WHERE id = ?', [123]);
124
+
125
+ // Get schema information
126
+ const schema = await aerostack.db.getSchema();
127
+
128
+ // Batch queries
129
+ const results = await aerostack.db.batch([
130
+ { sql: 'INSERT INTO users ...', params: [...] },
131
+ { sql: 'UPDATE posts ...', params: [...] }
132
+ ]);
133
+ ```
134
+
135
+ ### Cache Operations
136
+
137
+ ```typescript
138
+ // Set with TTL
139
+ await aerostack.cache.set('key', { data: 'value' }, { ttl: 3600 });
140
+
141
+ // Get
142
+ const value = await aerostack.cache.get('key');
143
+
144
+ // Delete
145
+ await aerostack.cache.delete('key');
146
+
147
+ // Check existence
148
+ const exists = await aerostack.cache.exists('key');
149
+ ```
150
+
151
+ ### Queue Operations
152
+
153
+ ```typescript
154
+ // Enqueue job
155
+ const job = await aerostack.queue.enqueue({
156
+ type: 'send-email',
157
+ data: { to: 'user@example.com' },
158
+ delay: 60 // seconds
159
+ });
160
+
161
+ console.log(job.jobId); // 'job_...'
162
+ ```
163
+
164
+ ### Storage Operations
165
+
166
+ ```typescript
167
+ // Upload file
168
+ const result = await aerostack.storage.upload(
169
+ fileBuffer,
170
+ 'uploads/avatar.jpg',
171
+ { contentType: 'image/jpeg' }
172
+ );
173
+
174
+ // Get URL
175
+ const url = await aerostack.storage.getUrl('uploads/avatar.jpg');
176
+
177
+ // Delete
178
+ await aerostack.storage.delete('uploads/avatar.jpg');
179
+
180
+ // List files
181
+ const files = await aerostack.storage.list('uploads/');
182
+ ```
183
+
184
+ ### AI Operations
185
+
186
+ ```typescript
187
+ // Chat completion
188
+ const chat = await aerostack.ai.chat([
189
+ { role: 'system', content: 'You are a helpful assistant' },
190
+ { role: 'user', content: 'Hello!' }
191
+ ], { temperature: 0.7 });
192
+
193
+ // Text embeddings
194
+ const embedding = await aerostack.ai.embed('Text to embed');
195
+
196
+ // Text generation
197
+ const generated = await aerostack.ai.generate('Write a story about...');
198
+ ```
199
+
200
+ ### Service Invocation
201
+
202
+ ```typescript
203
+ // Invoke another service
204
+ const result = await aerostack.services.invoke('billing-service', {
205
+ action: 'process-payment',
206
+ amount: 1000
207
+ });
208
+ ```
209
+
210
+ ## Error Handling
211
+
212
+ Both SDKs provide structured error handling with actionable suggestions:
213
+
214
+ ### Server SDK Errors
215
+
216
+ ```typescript
217
+ import { DatabaseError, CacheError, AIError } from '@aerostack/sdk';
218
+
219
+ try {
220
+ await aerostack.db.query('SELECT * FROM users');
221
+ } catch (error) {
222
+ if (error instanceof DatabaseError) {
223
+ console.log(error.code); // 'DB_TABLE_NOT_FOUND'
224
+ console.log(error.message); // 'Table does not exist: users'
225
+ console.log(error.details.suggestion); // 'Run migrations first'
226
+ console.log(error.details.recoveryAction); // 'CREATE_TABLE'
227
+ }
228
+ }
229
+ ```
230
+
231
+ ### Client SDK Errors
232
+
233
+ ```typescript
234
+ import { ClientError, AuthenticationError, ValidationError } from '@aerostack/sdk';
235
+
236
+ try {
237
+ await client.auth.login('user@example.com', 'wrong-password');
238
+ } catch (error) {
239
+ if (error instanceof ClientError) {
240
+ console.log(error.code); // 'AUTH_INVALID_CREDENTIALS'
241
+ console.log(error.message); // 'Invalid credentials'
242
+ console.log(error.details.suggestion); // 'Double-check your email and password'
243
+ console.log(error.statusCode); // 401
244
+
245
+ // Helper methods
246
+ if (error.isAuthError()) {
247
+ // Handle auth errors
248
+ }
249
+ }
250
+ }
251
+ ```
252
+
253
+ ## Configuration
254
+
255
+ ### Server SDK Environment
256
+
257
+ The Server SDK automatically detects the following from your environment:
258
+
259
+ ```toml
260
+ # aerostack.toml
261
+ [[d1_databases]]
262
+ binding = "DB"
263
+ database_name = "my-database"
264
+
265
+ [[postgres_databases]]
266
+ binding = "POSTGRES"
267
+ connection_string = "$NEON_DATABASE_URL"
268
+
269
+ [[kv_namespaces]]
270
+ binding = "CACHE"
271
+ id = "..."
272
+
273
+ [[queues]]
274
+ binding = "QUEUE"
275
+ queue_name = "background-jobs"
276
+
277
+ [[r2_buckets]]
278
+ binding = "STORAGE"
279
+ bucket_name = "my-bucket"
280
+ ```
281
+
282
+ ### Client SDK Configuration
283
+
284
+ ```typescript
285
+ const client = new AerostackClient({
286
+ projectSlug: 'my-project', // Required
287
+ baseUrl: 'https://api.aerostack.app' // Optional, defaults to production
288
+ });
289
+ ```
290
+
291
+ ## TypeScript Support
292
+
293
+ Both SDKs are written in TypeScript with full type definitions:
294
+
295
+ ```typescript
296
+ import type {
297
+ DatabaseResponse,
298
+ SchemaInfo,
299
+ User,
300
+ AuthResponse,
301
+ ChatResponse,
302
+ UploadResult
303
+ } from '@aerostack/sdk';
304
+
305
+ // Type-safe database queries
306
+ const users = await aerostack.db.query<User>('SELECT * FROM users');
307
+ users.results[0].email; // ✅ TypeScript knows this is a User[]
308
+
309
+ // Type-safe auth responses
310
+ const auth = await client.auth.login('...', '...');
311
+ auth.user.emailVerified; // ✅ TypeScript knows the shape
312
+ ```
313
+
314
+ ## Examples
315
+
316
+ See the [examples directory](./examples) for complete working examples:
317
+ - [Server SDK - Full Feature Demo](./examples/server-sdk-demo.ts)
318
+ - [Client SDK - Auth Flows](./examples/client-sdk-demo.ts)
319
+ - [Error Handling Patterns](./examples/error-handling.ts)
320
+
321
+ ## Contributing
322
+
323
+ Contributions are welcome! Please read our [Contributing Guide](../../CONTRIBUTING.md) for details.
324
+
325
+ ## License
326
+
327
+ MIT © Aerostack Team