@telestack/db-sdk 1.0.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 ADDED
@@ -0,0 +1,103 @@
1
+ # 🚀 Telestack DB SDK
2
+
3
+ **Telestack DB** is a production-ready, high-performance real-time database system built on Cloudflare Workers, D1, and Centrifugo. It provides a Firebase-compatible developer experience with significantly lower latency and cost.
4
+
5
+ ## ✨ Key Features
6
+
7
+ - 🏎️ **Extreme Performance**: 15ms average latency (2.8x faster than Firebase).
8
+ - 🔄 **Real-time Sync**: Instant WebSocket-based broadcasts via Centrifugo.
9
+ - 🔐 **Security Rules**: Built-in logic-based path guards (auth-aware).
10
+ - 💾 **Offline Persistence**: Automatic IndexedDB caching and write queuing.
11
+ - 📦 **Atomic Batches**: Commit multiple writes as a single transaction.
12
+ - ⚛️ **Optimistic Concurrency Control (OCC)**: Robust transaction retries for high-contention data.
13
+ - 👥 **Presence API**: Track online status and room membership out of the box.
14
+ - 💰 **90% Cheaper**: No egress fees and significantly lower storage costs.
15
+
16
+ ## 📦 Installation
17
+
18
+ ```bash
19
+ npm install @telestack/db-sdk
20
+ ```
21
+
22
+ ## 🚀 Quick Start
23
+
24
+ ```javascript
25
+ import { TelestackClient } from '@telestack/db-sdk';
26
+
27
+ // Initialize with production defaults
28
+ const db = new TelestackClient({
29
+ userId: 'user-123',
30
+ workspaceId: 'my-project'
31
+ });
32
+
33
+ // Write data
34
+ await db.collection('posts').doc('intro').set({
35
+ title: 'Hello Telestack!',
36
+ content: 'The edge is fast.'
37
+ });
38
+
39
+ // Listen for real-time updates
40
+ db.collection('posts').onSnapshot((docs) => {
41
+ console.log('Received posts:', docs);
42
+ });
43
+
44
+ // Transactions with OCC
45
+ await db.runTransaction(async (transaction) => {
46
+ const doc = await transaction.get(db.doc('stats/global'));
47
+ const newCount = (doc?.count || 0) + 1;
48
+ transaction.update(db.doc('stats/global'), { count: newCount });
49
+ });
50
+ ```
51
+
52
+ ## 📊 Benchmarks (Real World)
53
+
54
+ | Operation | Telestack | Firebase | Advantage |
55
+ |-----------|-----------|----------|-----------|
56
+ | **Read** | 9ms | 25ms | **2.8x Faster** |
57
+ | **Write** | 22ms | 45ms | **2.0x Faster** |
58
+ | **Query** | 9ms | 40ms | **4.4x Faster** |
59
+
60
+ ## 🛠️ Configuration
61
+
62
+ ```javascript
63
+ const client = new TelestackClient({
64
+ endpoint: 'https://telestack-realtime-db.codeforgebyaravinth.workers.dev', // Defaults to prod
65
+ centrifugoUrl: 'wss://telestack-centrifugo.onrender.com/connection/websocket', // Defaults to prod
66
+ userId: 'current-user-id',
67
+ workspaceId: 'your-workspace',
68
+ enablePersistence: true // Enable IndexedDB support
69
+ });
70
+ ```
71
+
72
+ ## 👥 Presence API
73
+
74
+ ```javascript
75
+ const col = db.collection('chat-room');
76
+
77
+ // Detect join/leave events
78
+ col.onPresence((event) => {
79
+ console.log(`${event.user} just ${event.action}ed the room!`);
80
+ });
81
+
82
+ // Get current online count
83
+ const stats = await db.getPresenceStats('collection:chat-room');
84
+ console.log(`People online: ${stats.numUsers}`);
85
+ ```
86
+
87
+ ## 🛡️ Security Rules
88
+
89
+ Define rules in your Worker configuration to protect paths:
90
+
91
+ ```json
92
+ {
93
+ "path": "users/{userId}/**",
94
+ "allow": {
95
+ "write": "auth.uid == userId",
96
+ "read": "auth.uid != null"
97
+ }
98
+ }
99
+ ```
100
+
101
+ ## ⚖️ License
102
+
103
+ MIT © [Telestack](https://telestack.dev)
@@ -0,0 +1,214 @@
1
+ import { Centrifuge } from 'centrifuge';
2
+ declare global {
3
+ interface Window {
4
+ Centrifuge: typeof Centrifuge;
5
+ }
6
+ }
7
+ /**
8
+ * Configuration for TelestackClient
9
+ */
10
+ export interface Config {
11
+ /** HTTP endpoint of the Telestack backend */
12
+ endpoint?: string;
13
+ /** Optional Centrifugo WebSocket endpoint for real-time updates */
14
+ centrifugoUrl?: string;
15
+ /** Workspace ID for multi-tenant apps */
16
+ workspaceId?: string;
17
+ /** Current user ID */
18
+ userId: string;
19
+ /** Enable offline persistence via IndexedDB */
20
+ enablePersistence?: boolean;
21
+ }
22
+ /**
23
+ * PersistenceEngine defines the contract for local storage
24
+ */
25
+ export interface PersistenceEngine {
26
+ get(table: string, id: string): Promise<any>;
27
+ put(table: string, id: string, data: any): Promise<void>;
28
+ delete(table: string, id: string): Promise<void>;
29
+ getAll(table: string): Promise<any[]>;
30
+ clear(table: string): Promise<void>;
31
+ }
32
+ /**
33
+ * IndexedDB implementation of PersistenceEngine
34
+ */
35
+ export declare class IndexedDBPersistence implements PersistenceEngine {
36
+ private db;
37
+ private dbName;
38
+ init(): Promise<void>;
39
+ get(table: string, path: string): Promise<any>;
40
+ put(table: string, id: string, data: any): Promise<void>;
41
+ delete(table: string, id: string): Promise<void>;
42
+ getAll(table: string): Promise<any[]>;
43
+ clear(table: string): Promise<void>;
44
+ }
45
+ /** Supported query operators */
46
+ export type WhereFilterOp = '==' | '!=' | '<' | '<=' | '>' | '>=' | 'array-contains' | 'in' | 'LIKE';
47
+ /** Custom Error class for Telestack operations */
48
+ export declare class TelestackError extends Error {
49
+ message: string;
50
+ code?: string | undefined;
51
+ constructor(message: string, code?: string | undefined);
52
+ }
53
+ /**
54
+ * Main Telestack Client
55
+ */
56
+ export declare class TelestackClient {
57
+ config: Config;
58
+ private centrifuge;
59
+ private isProcessingQueue;
60
+ workspaceId: string;
61
+ private lastVersion;
62
+ private token;
63
+ private persistence;
64
+ constructor(config: Config);
65
+ /** Ensure we have a valid JWT token */
66
+ getToken(): Promise<string>;
67
+ /** Helper for authenticated fetch */
68
+ authFetch(url: string | URL, options?: RequestInit): Promise<Response>;
69
+ /** Incremental sync to fetch changes since last version */
70
+ sync(): Promise<any>;
71
+ /** Get a reference to a collection */
72
+ collection<T = any>(path: string): CollectionReference<T>;
73
+ /** Get a reference to a document */
74
+ doc<T = any>(path: string): DocumentReference<T>;
75
+ /** Get a new write batch */
76
+ batch(): WriteBatch;
77
+ /** Get presence information for a channel */
78
+ getPresence(channel: string): Promise<import("centrifuge").PresenceResult>;
79
+ /** Get presence stats for a channel */
80
+ getPresenceStats(channel: string): Promise<import("centrifuge").PresenceStatsResult>;
81
+ /** Run an atomic transaction with automatic retries (OCC) */
82
+ runTransaction<T>(updateFunction: (transaction: Transaction) => Promise<T>, maxRetries?: number): Promise<T>;
83
+ getCentrifuge(): Centrifuge | null;
84
+ getPersistence(): PersistenceEngine | null;
85
+ getLastVersion(): number;
86
+ updateLastVersion(v: number): void;
87
+ /** Background process to sync offline writes */
88
+ processQueue(): Promise<void>;
89
+ /** Start periodic sync and queue processing */
90
+ private startBackgroundWorkers;
91
+ }
92
+ /**
93
+ * Query class for collection-level queries
94
+ */
95
+ export declare class Query<T = any> {
96
+ protected client: TelestackClient;
97
+ path: string;
98
+ protected filters: {
99
+ field: string;
100
+ op: WhereFilterOp;
101
+ value: any;
102
+ }[];
103
+ protected limitCount?: number;
104
+ protected orderByField?: string;
105
+ protected orderDirection: 'asc' | 'desc';
106
+ private docsCache;
107
+ private debounceTimer;
108
+ constructor(client: TelestackClient, path: string);
109
+ /** Add a filter to the query */
110
+ where(field: string, op: WhereFilterOp, value: any): Query<T>;
111
+ /** Limit the number of documents */
112
+ limit(n: number): Query<T>;
113
+ /** Order the documents */
114
+ orderBy(field: string, direction?: 'asc' | 'desc'): Query<T>;
115
+ /** Convert filters to SQL-like where clause for backend query */
116
+ private buildWhereClause;
117
+ /** Fetch documents matching the query */
118
+ get(): Promise<T[]>;
119
+ /** Check if a document matches the local filters */
120
+ private matches;
121
+ /** Subscribe to realtime updates for this query */
122
+ onSnapshot(callback: (docs: T[]) => void): () => void;
123
+ /** Subscribe to presence events (Join/Leave) for this collection */
124
+ onPresence(callback: (event: {
125
+ action: 'join' | 'leave';
126
+ user: string;
127
+ clientId: string;
128
+ }) => void): () => void;
129
+ }
130
+ /**
131
+ * CollectionReference extends Query with add() and doc() methods
132
+ */
133
+ export declare class CollectionReference<T = any> extends Query<T> {
134
+ doc<U = T>(id: string): DocumentReference<U>;
135
+ /** Add a new document to this collection */
136
+ add(data: T): Promise<{
137
+ id: string;
138
+ version: number;
139
+ }>;
140
+ }
141
+ /**
142
+ * DocumentReference allows CRUD operations and realtime subscription on a single document
143
+ */
144
+ export declare class DocumentReference<T = any> {
145
+ private client;
146
+ private collectionPath;
147
+ private id;
148
+ constructor(client: TelestackClient, collectionPath: string, id: string);
149
+ get path(): string;
150
+ /** Access a nested collection */
151
+ collection<U = any>(name: string): CollectionReference<U>;
152
+ /** Fetch this document */
153
+ get(): Promise<T | null>;
154
+ /** Fetch document snapshot (includes version for transactions) */
155
+ asyncGetSnapshot(): Promise<DocumentSnapshot<T>>;
156
+ /** Compatibility alias for existing codebase */
157
+ getSnapshot(): Promise<DocumentSnapshot<T>>;
158
+ /** Replace or create this document */
159
+ set(data: T): Promise<{
160
+ version: number;
161
+ }>;
162
+ /** Update part of this document */
163
+ update(data: Partial<T>): Promise<{
164
+ version: number;
165
+ }>;
166
+ /** Delete this document */
167
+ delete(): Promise<void>;
168
+ /** Subscribe to realtime changes on this document */
169
+ onSnapshot(callback: (data: T | null) => void): () => void;
170
+ }
171
+ /**
172
+ * WriteBatch allows multiple write operations to be committed atomically
173
+ */
174
+ export declare class WriteBatch {
175
+ private client;
176
+ private operations;
177
+ constructor(client: TelestackClient);
178
+ set<T>(docRef: DocumentReference<T>, data: T): WriteBatch;
179
+ update<T>(docRef: DocumentReference<T>, data: Partial<T>): WriteBatch;
180
+ delete(docRef: DocumentReference): WriteBatch;
181
+ commit(): Promise<void>;
182
+ }
183
+ /**
184
+ * DocumentSnapshot contains document data and its database version
185
+ */
186
+ export declare class DocumentSnapshot<T = any> {
187
+ readonly id: string;
188
+ readonly path: string;
189
+ private _data;
190
+ readonly version: number;
191
+ readonly metadata: {
192
+ fromCache: boolean;
193
+ hasPendingWrites: boolean;
194
+ };
195
+ constructor(id: string, path: string, _data: T | null, version: number, metadata?: {
196
+ fromCache: boolean;
197
+ hasPendingWrites: boolean;
198
+ });
199
+ exists(): boolean;
200
+ data(): T | null;
201
+ }
202
+ /**
203
+ * Transaction allows read-modify-write operations with OCC
204
+ */
205
+ export declare class Transaction {
206
+ private client;
207
+ private operations;
208
+ constructor(client: TelestackClient);
209
+ get<T>(docRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
210
+ set<T>(docRef: DocumentReference<T>, data: T, snapshot?: DocumentSnapshot<T>): Transaction;
211
+ update<T>(docRef: DocumentReference<T>, data: Partial<T>, snapshot?: DocumentSnapshot<T>): Transaction;
212
+ delete(docRef: DocumentReference, snapshot?: DocumentSnapshot): Transaction;
213
+ commit(): Promise<void>;
214
+ }