@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.
@@ -0,0 +1,577 @@
1
+ /**
2
+ * Client-side error handling for Aerostack SDK
3
+ */
4
+ declare enum ClientErrorCode {
5
+ AUTH_INVALID_CREDENTIALS = "AUTH_INVALID_CREDENTIALS",
6
+ AUTH_USER_EXISTS = "AUTH_USER_EXISTS",
7
+ AUTH_EMAIL_NOT_VERIFIED = "AUTH_EMAIL_NOT_VERIFIED",
8
+ AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED",
9
+ AUTH_TOKEN_INVALID = "AUTH_TOKEN_INVALID",
10
+ AUTH_OTP_EXPIRED = "AUTH_OTP_EXPIRED",
11
+ AUTH_OTP_INVALID = "AUTH_OTP_INVALID",
12
+ AUTH_PASSWORD_WEAK = "AUTH_PASSWORD_WEAK",
13
+ AUTH_RESET_TOKEN_INVALID = "AUTH_RESET_TOKEN_INVALID",
14
+ NETWORK_ERROR = "NETWORK_ERROR",
15
+ NETWORK_TIMEOUT = "NETWORK_TIMEOUT",
16
+ VALIDATION_ERROR = "VALIDATION_ERROR",
17
+ REQUEST_FAILED = "REQUEST_FAILED",
18
+ UNKNOWN_ERROR = "UNKNOWN_ERROR"
19
+ }
20
+ interface ClientErrorDetails {
21
+ suggestion?: string;
22
+ field?: string;
23
+ recoveryAction?: string;
24
+ }
25
+ /**
26
+ * Base error class for client-side SDK
27
+ */
28
+ declare class ClientError extends Error {
29
+ code: ClientErrorCode;
30
+ details?: ClientErrorDetails | undefined;
31
+ statusCode?: number | undefined;
32
+ constructor(code: ClientErrorCode, message: string, details?: ClientErrorDetails | undefined, statusCode?: number | undefined);
33
+ /**
34
+ * Check if this is an authentication error
35
+ */
36
+ isAuthError(): boolean;
37
+ /**
38
+ * Check if this is a network error
39
+ */
40
+ isNetworkError(): boolean;
41
+ /**
42
+ * Check if this is a validation error
43
+ */
44
+ isValidationError(): boolean;
45
+ toJSON(): {
46
+ name: string;
47
+ code: ClientErrorCode;
48
+ message: string;
49
+ details: ClientErrorDetails | undefined;
50
+ statusCode: number | undefined;
51
+ };
52
+ }
53
+ /**
54
+ * Authentication-specific errors
55
+ */
56
+ declare class AuthenticationError extends ClientError {
57
+ constructor(code: ClientErrorCode, message: string, details?: ClientErrorDetails, statusCode?: number);
58
+ }
59
+ /**
60
+ * Validation-specific errors
61
+ */
62
+ declare class ValidationError extends ClientError {
63
+ constructor(message: string, field?: string, suggestion?: string);
64
+ }
65
+ /**
66
+ * Network-specific errors
67
+ */
68
+ declare class NetworkError extends ClientError {
69
+ constructor(message: string, suggestion?: string);
70
+ }
71
+
72
+ interface SDKConfig {
73
+ projectSlug: string;
74
+ baseUrl?: string;
75
+ }
76
+ interface AuthResponse {
77
+ success: boolean;
78
+ user?: User;
79
+ token?: string;
80
+ refreshToken?: string;
81
+ expiresAt?: string;
82
+ error?: string;
83
+ requiresVerification?: boolean;
84
+ }
85
+ interface User {
86
+ id: string;
87
+ email: string;
88
+ name?: string;
89
+ emailVerified: boolean;
90
+ createdAt: string;
91
+ customFields?: Record<string, any>;
92
+ }
93
+ interface RegisterData {
94
+ email: string;
95
+ password: string;
96
+ name?: string;
97
+ customFields?: Record<string, any>;
98
+ }
99
+ interface OTPResponse {
100
+ success: boolean;
101
+ message?: string;
102
+ error?: string;
103
+ }
104
+ interface VerifyResponse {
105
+ success: boolean;
106
+ message?: string;
107
+ error?: string;
108
+ }
109
+ interface ResetResponse {
110
+ success: boolean;
111
+ message?: string;
112
+ error?: string;
113
+ }
114
+ interface LogoutResponse {
115
+ success: boolean;
116
+ }
117
+ interface ProfileUpdate {
118
+ name?: string;
119
+ customFields?: Record<string, any>;
120
+ }
121
+ /**
122
+ * Aerostack Client SDK
123
+ *
124
+ * Provides client-side authentication and (future) ecommerce features
125
+ * Focused on:
126
+ * - Complete authentication flows
127
+ * - Password reset
128
+ * - Session management
129
+ * - User profile management
130
+ */
131
+ declare class AerostackClient {
132
+ private projectSlug;
133
+ private baseUrl;
134
+ constructor(config: SDKConfig);
135
+ /**
136
+ * Authentication operations
137
+ */
138
+ get auth(): {
139
+ /**
140
+ * Register a new user
141
+ */
142
+ register: (data: RegisterData) => Promise<AuthResponse>;
143
+ /**
144
+ * Login with email and password
145
+ */
146
+ login: (email: string, password: string) => Promise<AuthResponse>;
147
+ /**
148
+ * Send OTP code to email
149
+ */
150
+ sendOTP: (email: string) => Promise<OTPResponse>;
151
+ /**
152
+ * Verify OTP code and login
153
+ */
154
+ verifyOTP: (email: string, code: string) => Promise<AuthResponse>;
155
+ /**
156
+ * Verify email with token
157
+ */
158
+ verifyEmail: (token: string) => Promise<VerifyResponse>;
159
+ /**
160
+ * Request password reset email
161
+ */
162
+ requestPasswordReset: (email: string) => Promise<ResetResponse>;
163
+ /**
164
+ * Reset password with token
165
+ */
166
+ resetPassword: (token: string, newPassword: string) => Promise<AuthResponse>;
167
+ /**
168
+ * Refresh access token using refresh token
169
+ */
170
+ refreshToken: (refreshToken: string) => Promise<AuthResponse>;
171
+ /**
172
+ * Logout and invalidate tokens
173
+ */
174
+ logout: (token: string) => Promise<LogoutResponse>;
175
+ /**
176
+ * Get current user profile
177
+ */
178
+ getCurrentUser: (token: string) => Promise<User>;
179
+ /**
180
+ * Update user profile
181
+ */
182
+ updateProfile: (token: string, updates: ProfileUpdate) => Promise<User>;
183
+ };
184
+ /**
185
+ * Make HTTP request with comprehensive error handling
186
+ */
187
+ private request;
188
+ /**
189
+ * Map API error codes to client error codes
190
+ */
191
+ private mapErrorCode;
192
+ /**
193
+ * Get helpful suggestion based on error code
194
+ */
195
+ private getSuggestion;
196
+ }
197
+
198
+ /**
199
+ * Type definitions for Aerostack Server SDK
200
+ */
201
+ interface DatabaseResponse<T = any> {
202
+ results: T[];
203
+ success: boolean;
204
+ meta: {
205
+ target: 'd1' | 'postgres';
206
+ rowCount?: number;
207
+ duration?: number;
208
+ };
209
+ }
210
+ interface RoutingRules {
211
+ tables: Record<string, 'd1' | 'postgres'>;
212
+ }
213
+ interface SchemaColumn {
214
+ name: string;
215
+ type: string;
216
+ nullable: boolean;
217
+ defaultValue?: any;
218
+ isPrimaryKey?: boolean;
219
+ }
220
+ interface SchemaTable {
221
+ name: string;
222
+ columns: SchemaColumn[];
223
+ database: 'd1' | 'postgres';
224
+ }
225
+ interface SchemaInfo {
226
+ tables: SchemaTable[];
227
+ database: 'd1' | 'postgres';
228
+ }
229
+ interface Transaction {
230
+ query<T = any>(sql: string, params?: any[]): Promise<DatabaseResponse<T>>;
231
+ commit(): Promise<void>;
232
+ rollback(): Promise<void>;
233
+ }
234
+ interface BatchQuery {
235
+ sql: string;
236
+ params?: any[];
237
+ }
238
+ interface BatchResult {
239
+ results: DatabaseResponse[];
240
+ success: boolean;
241
+ errors?: Array<{
242
+ index: number;
243
+ error: Error;
244
+ }>;
245
+ }
246
+ interface CacheOptions {
247
+ ttl?: number;
248
+ expirationTtl?: number;
249
+ }
250
+ interface CacheGetOptions {
251
+ type?: 'text' | 'json' | 'arrayBuffer' | 'stream';
252
+ }
253
+ interface Job {
254
+ type: string;
255
+ data: any;
256
+ delay?: number;
257
+ retries?: number;
258
+ }
259
+ interface JobResult {
260
+ jobId: string;
261
+ status: 'queued' | 'processing' | 'completed' | 'failed';
262
+ queuedAt: Date;
263
+ }
264
+ interface JobStatus {
265
+ id: string;
266
+ type: string;
267
+ status: 'queued' | 'processing' | 'completed' | 'failed';
268
+ attempts: number;
269
+ createdAt: Date;
270
+ completedAt?: Date;
271
+ error?: string;
272
+ }
273
+ interface UploadOptions {
274
+ contentType?: string;
275
+ metadata?: Record<string, string>;
276
+ cacheControl?: string;
277
+ }
278
+ interface UploadResult {
279
+ key: string;
280
+ url: string;
281
+ size: number;
282
+ contentType: string;
283
+ }
284
+ interface UrlOptions {
285
+ expiresIn?: number;
286
+ download?: boolean;
287
+ }
288
+ interface StorageObject {
289
+ key: string;
290
+ size: number;
291
+ uploaded: Date;
292
+ contentType?: string;
293
+ }
294
+ interface Message {
295
+ role: 'system' | 'user' | 'assistant';
296
+ content: string;
297
+ }
298
+ interface ChatOptions {
299
+ model?: string;
300
+ temperature?: number;
301
+ maxTokens?: number;
302
+ stream?: boolean;
303
+ }
304
+ interface ChatResponse {
305
+ response: string;
306
+ usage?: {
307
+ promptTokens: number;
308
+ completionTokens: number;
309
+ totalTokens: number;
310
+ };
311
+ }
312
+ interface EmbedOptions {
313
+ model?: string;
314
+ }
315
+ interface Embedding {
316
+ embedding: number[];
317
+ model: string;
318
+ }
319
+ interface GenerateOptions {
320
+ model?: string;
321
+ temperature?: number;
322
+ maxTokens?: number;
323
+ }
324
+ interface GenerationResult {
325
+ text: string;
326
+ usage?: {
327
+ promptTokens: number;
328
+ completionTokens: number;
329
+ };
330
+ }
331
+ interface InvokeOptions {
332
+ timeout?: number;
333
+ }
334
+ interface AuthContext {
335
+ user?: any;
336
+ request: Request;
337
+ }
338
+ interface AuthHookResult {
339
+ allow: boolean;
340
+ user?: any;
341
+ error?: string;
342
+ }
343
+ interface AerostackEnv {
344
+ DB?: D1Database;
345
+ CACHE?: KVNamespace;
346
+ QUEUE?: Queue;
347
+ STORAGE?: R2Bucket;
348
+ AI?: Ai;
349
+ DISPATCHER?: DurableObjectNamespace;
350
+ [key: string]: any;
351
+ }
352
+
353
+ /**
354
+ * Server-side error handling for Aerostack SDK
355
+ * Provides structured errors with actionable suggestions
356
+ */
357
+ declare enum ErrorCode {
358
+ DB_CONNECTION_FAILED = "DB_CONNECTION_FAILED",
359
+ DB_QUERY_FAILED = "DB_QUERY_FAILED",
360
+ DB_TABLE_NOT_FOUND = "DB_TABLE_NOT_FOUND",
361
+ DB_COLUMN_NOT_FOUND = "DB_COLUMN_NOT_FOUND",
362
+ DB_AUTH_FAILED = "DB_AUTH_FAILED",
363
+ DB_MIGRATION_FAILED = "DB_MIGRATION_FAILED",
364
+ DB_TRANSACTION_FAILED = "DB_TRANSACTION_FAILED",
365
+ CACHE_GET_FAILED = "CACHE_GET_FAILED",
366
+ CACHE_SET_FAILED = "CACHE_SET_FAILED",
367
+ CACHE_DELETE_FAILED = "CACHE_DELETE_FAILED",
368
+ CACHE_NOT_CONFIGURED = "CACHE_NOT_CONFIGURED",
369
+ QUEUE_ENQUEUE_FAILED = "QUEUE_ENQUEUE_FAILED",
370
+ QUEUE_NOT_CONFIGURED = "QUEUE_NOT_CONFIGURED",
371
+ QUEUE_JOB_NOT_FOUND = "QUEUE_JOB_NOT_FOUND",
372
+ STORAGE_UPLOAD_FAILED = "STORAGE_UPLOAD_FAILED",
373
+ STORAGE_DELETE_FAILED = "STORAGE_DELETE_FAILED",
374
+ STORAGE_NOT_CONFIGURED = "STORAGE_NOT_CONFIGURED",
375
+ STORAGE_FILE_TOO_LARGE = "STORAGE_FILE_TOO_LARGE",
376
+ AI_REQUEST_FAILED = "AI_REQUEST_FAILED",
377
+ AI_NOT_CONFIGURED = "AI_NOT_CONFIGURED",
378
+ AI_RATE_LIMIT = "AI_RATE_LIMIT",
379
+ SERVICE_INVOKE_FAILED = "SERVICE_INVOKE_FAILED",
380
+ SERVICE_NOT_FOUND = "SERVICE_NOT_FOUND",
381
+ CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
382
+ VALIDATION_ERROR = "VALIDATION_ERROR",
383
+ INTERNAL_ERROR = "INTERNAL_ERROR"
384
+ }
385
+ interface ErrorDetails {
386
+ suggestion?: string;
387
+ recoveryAction?: string;
388
+ field?: string;
389
+ cause?: string;
390
+ }
391
+ /**
392
+ * Base error class for all server-side errors
393
+ */
394
+ declare class ServerError extends Error {
395
+ code: ErrorCode;
396
+ details?: ErrorDetails | undefined;
397
+ context?: Record<string, any> | undefined;
398
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails | undefined, context?: Record<string, any> | undefined);
399
+ toJSON(): {
400
+ name: string;
401
+ code: ErrorCode;
402
+ message: string;
403
+ details: ErrorDetails | undefined;
404
+ context: Record<string, any> | undefined;
405
+ };
406
+ }
407
+ /**
408
+ * Database-related errors
409
+ */
410
+ declare class DatabaseError extends ServerError {
411
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
412
+ /**
413
+ * Create error from Postgres error
414
+ */
415
+ static fromPostgresError(err: any, context?: Record<string, any>): DatabaseError;
416
+ /**
417
+ * Create error from D1 error
418
+ */
419
+ static fromD1Error(err: any, context?: Record<string, any>): DatabaseError;
420
+ }
421
+ /**
422
+ * Cache-related errors
423
+ */
424
+ declare class CacheError extends ServerError {
425
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
426
+ }
427
+ /**
428
+ * Queue-related errors
429
+ */
430
+ declare class QueueError extends ServerError {
431
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
432
+ }
433
+ /**
434
+ * Storage-related errors
435
+ */
436
+ declare class StorageError extends ServerError {
437
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
438
+ }
439
+ /**
440
+ * AI-related errors
441
+ */
442
+ declare class AIError extends ServerError {
443
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
444
+ }
445
+ /**
446
+ * Service invocation errors
447
+ */
448
+ declare class ServiceError extends ServerError {
449
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, context?: Record<string, any>);
450
+ }
451
+
452
+ /**
453
+ * AerostackServer provides comprehensive server-side SDK for Cloudflare Workers
454
+ *
455
+ * Features:
456
+ * - Multi-database operations (D1 + Postgres with intelligent routing)
457
+ * - KV cache operations
458
+ * - Queue operations for background jobs
459
+ * - R2 storage operations
460
+ * - AI operations (chat, embeddings, generation)
461
+ * - Service invocation via Workers Dispatch
462
+ */
463
+ declare class AerostackServer {
464
+ private pgPool?;
465
+ private _d1?;
466
+ private _kv?;
467
+ private _queue?;
468
+ private _storage?;
469
+ private _ai?;
470
+ private _dispatcher?;
471
+ private routingRules;
472
+ private env;
473
+ constructor(env: AerostackEnv, options?: {
474
+ routing?: RoutingRules;
475
+ });
476
+ /**
477
+ * Database operations with intelligent routing between D1 and Postgres
478
+ */
479
+ get db(): {
480
+ /**
481
+ * Execute a SQL query with automatic routing
482
+ */
483
+ query: <T = any>(sql: string, params?: any[]) => Promise<DatabaseResponse<T>>;
484
+ /**
485
+ * Get database schema information
486
+ */
487
+ getSchema: (binding?: string) => Promise<SchemaInfo>;
488
+ /**
489
+ * Execute multiple queries in a batch
490
+ */
491
+ batch: (queries: BatchQuery[]) => Promise<BatchResult>;
492
+ };
493
+ /**
494
+ * KV Cache operations
495
+ */
496
+ get cache(): {
497
+ /**
498
+ * Get value from cache
499
+ */
500
+ get: <T = any>(key: string, options?: CacheGetOptions) => Promise<T | null>;
501
+ /**
502
+ * Set value in cache
503
+ */
504
+ set: (key: string, value: any, options?: CacheOptions) => Promise<void>;
505
+ /**
506
+ * Delete value from cache
507
+ */
508
+ delete: (key: string) => Promise<void>;
509
+ /**
510
+ * Check if key exists in cache
511
+ */
512
+ exists: (key: string) => Promise<boolean>;
513
+ };
514
+ /**
515
+ * Queue operations for background jobs
516
+ */
517
+ get queue(): {
518
+ /**
519
+ * Add job to queue
520
+ */
521
+ enqueue: (job: Job) => Promise<JobResult>;
522
+ };
523
+ /**
524
+ * R2 Storage operations
525
+ */
526
+ get storage(): {
527
+ /**
528
+ * Upload file to R2 storage
529
+ */
530
+ upload: (file: ReadableStream | ArrayBuffer | string, key: string, options?: UploadOptions) => Promise<UploadResult>;
531
+ /**
532
+ * Get presigned URL for object
533
+ */
534
+ getUrl: (key: string, options?: UrlOptions) => Promise<string>;
535
+ /**
536
+ * Delete object from storage
537
+ */
538
+ delete: (key: string) => Promise<void>;
539
+ /**
540
+ * List objects in storage
541
+ */
542
+ list: (prefix?: string) => Promise<StorageObject[]>;
543
+ };
544
+ /**
545
+ * AI operations using Cloudflare AI
546
+ */
547
+ get ai(): {
548
+ /**
549
+ * Generate chat completion
550
+ */
551
+ chat: (messages: Message[], options?: ChatOptions) => Promise<ChatResponse>;
552
+ /**
553
+ * Generate text embeddings
554
+ */
555
+ embed: (text: string, options?: EmbedOptions) => Promise<Embedding>;
556
+ /**
557
+ * Generate text from prompt
558
+ */
559
+ generate: (prompt: string, options?: GenerateOptions) => Promise<GenerationResult>;
560
+ };
561
+ /**
562
+ * Service invocation via Workers Dispatch
563
+ */
564
+ get services(): {
565
+ /**
566
+ * Invoke another service via RPC
567
+ */
568
+ invoke: (serviceName: string, data: any, options?: InvokeOptions) => Promise<any>;
569
+ };
570
+ private routeQuery;
571
+ private determineTarget;
572
+ private introspectD1;
573
+ private introspectPostgres;
574
+ private findPostgresConnStr;
575
+ }
576
+
577
+ export { AIError, AerostackClient, type AerostackEnv, AerostackServer, type AuthContext, type AuthHookResult, type AuthResponse, AuthenticationError, type BatchQuery, type BatchResult, CacheError, type CacheGetOptions, type CacheOptions, type ChatOptions, type ChatResponse, ClientError, ClientErrorCode, type ClientErrorDetails, DatabaseError, type DatabaseResponse, type EmbedOptions, type Embedding, ErrorCode, type ErrorDetails, type GenerateOptions, type GenerationResult, type InvokeOptions, type Job, type JobResult, type JobStatus, type LogoutResponse, type Message, NetworkError, type OTPResponse, type ProfileUpdate, QueueError, type RegisterData, type ResetResponse, type RoutingRules, type SDKConfig, type SchemaColumn, type SchemaInfo, type SchemaTable, ServerError, ServiceError, StorageError, type StorageObject, type Transaction, type UploadOptions, type UploadResult, type UrlOptions, type User, ValidationError, type VerifyResponse };