@affectively/dash 5.1.1 → 5.2.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.
@@ -7,6 +7,25 @@ export class DashEngine {
7
7
  listeners = new Set();
8
8
  lens = defaultLens;
9
9
  currentSchemaVersion = 1;
10
+ // Cloud sync state
11
+ cloudConfig = null;
12
+ cloudSyncTimer = null;
13
+ isCloudSyncing = false;
14
+ lastCloudSyncTime = 0;
15
+ cloudSyncEnabled = false;
16
+ syncedTables = new Set();
17
+ // Internal tables that should never sync
18
+ INTERNAL_TABLES = new Set([
19
+ 'dash_metadata',
20
+ 'dash_items',
21
+ 'dash_vec_idx',
22
+ 'dash_spatial_idx',
23
+ 'dash_spatial_map',
24
+ 'dash_sync_meta',
25
+ 'dash_sync_queue',
26
+ 'dash_sync_updates',
27
+ 'sqlite_sequence',
28
+ ]);
10
29
  constructor() {
11
30
  // SSR/Build safety: Only initialize in browser environments
12
31
  if (typeof window !== 'undefined') {
@@ -31,12 +50,111 @@ export class DashEngine {
31
50
  // Load Vector Extension (Simulation/Shim for now)
32
51
  await import('./vec_extension.js').then(m => m.loadVectorExtension(this.db));
33
52
  this.initializeSchema();
53
+ // Auto-enable cloud sync if endpoint is available (ON BY DEFAULT)
54
+ this.tryAutoEnableCloudSync();
34
55
  }
35
56
  catch (err) {
36
57
  console.error('Dash: Failed to initialize SQLite WASM', err);
37
58
  throw err;
38
59
  }
39
60
  }
61
+ /**
62
+ * Try to auto-enable cloud sync from environment
63
+ * Cloud sync is ON BY DEFAULT when a sync endpoint is detected
64
+ */
65
+ tryAutoEnableCloudSync() {
66
+ try {
67
+ // Detect sync endpoint from various sources
68
+ const syncUrl = this.detectSyncEndpoint();
69
+ if (!syncUrl) {
70
+ console.log('[Dash] No sync endpoint detected, cloud sync disabled');
71
+ return;
72
+ }
73
+ // Auto-enable with default config
74
+ this.enableCloudSync({
75
+ baseUrl: syncUrl,
76
+ getAuthToken: async () => this.getDefaultAuthToken(),
77
+ syncInterval: 30000,
78
+ onSyncError: (err) => {
79
+ // Graceful degradation - just log, don't crash
80
+ console.warn('[Dash] Cloud sync failed (graceful degradation):', err.message);
81
+ },
82
+ });
83
+ console.log('[Dash] Cloud sync auto-enabled:', syncUrl);
84
+ }
85
+ catch (err) {
86
+ // Graceful degradation - local-first still works
87
+ console.warn('[Dash] Could not auto-enable cloud sync:', err);
88
+ }
89
+ }
90
+ /**
91
+ * Detect sync endpoint from environment variables or same-origin
92
+ */
93
+ detectSyncEndpoint() {
94
+ // Check various env var patterns
95
+ const envVars = [
96
+ 'DASH_SYNC_URL',
97
+ 'NEXT_PUBLIC_DASH_SYNC_URL',
98
+ 'VITE_DASH_SYNC_URL',
99
+ 'DASH_API_URL',
100
+ 'NEXT_PUBLIC_API_URL',
101
+ 'VITE_API_URL',
102
+ ];
103
+ // Try globalThis.process.env (Node/Next.js)
104
+ if (typeof globalThis !== 'undefined' && globalThis.process?.env) {
105
+ const env = globalThis.process.env;
106
+ for (const key of envVars) {
107
+ if (env[key])
108
+ return env[key];
109
+ }
110
+ }
111
+ // Try import.meta.env (Vite)
112
+ if (typeof import.meta !== 'undefined' && import.meta.env) {
113
+ const env = import.meta.env;
114
+ for (const key of envVars) {
115
+ if (env[key])
116
+ return env[key];
117
+ }
118
+ }
119
+ // Try window.__ENV__ (runtime injection)
120
+ if (typeof window !== 'undefined' && window.__ENV__) {
121
+ const env = window.__ENV__;
122
+ for (const key of envVars) {
123
+ if (env[key])
124
+ return env[key];
125
+ }
126
+ }
127
+ // Auto-detect same-origin sync for Cloudflare/edge deployments
128
+ // If running in browser, use same origin as sync endpoint
129
+ if (typeof window !== 'undefined' && window.location?.origin) {
130
+ // Only auto-enable for HTTPS (production) or localhost (dev)
131
+ const origin = window.location.origin;
132
+ if (origin.startsWith('https://') || origin.includes('localhost') || origin.includes('127.0.0.1')) {
133
+ return origin;
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+ /**
139
+ * Get default auth token from common auth patterns
140
+ */
141
+ async getDefaultAuthToken() {
142
+ try {
143
+ // Try localStorage token
144
+ if (typeof localStorage !== 'undefined') {
145
+ const token = localStorage.getItem('auth_token') ||
146
+ localStorage.getItem('access_token') ||
147
+ localStorage.getItem('id_token');
148
+ if (token)
149
+ return token;
150
+ }
151
+ // Try cookie-based auth (will be sent automatically)
152
+ return null;
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
40
158
  initializeSchema() {
41
159
  if (!this.db)
42
160
  return;
@@ -119,6 +237,7 @@ export class DashEngine {
119
237
  // Matches: INSERT INTO table ...
120
238
  // Matches: UPDATE table ...
121
239
  // Matches: DELETE FROM table ...
240
+ // Matches: CREATE TABLE table ...
122
241
  let table = '';
123
242
  if (upper.startsWith('INSERT INTO')) {
124
243
  table = sql.split(/\s+/)[2];
@@ -129,6 +248,22 @@ export class DashEngine {
129
248
  else if (upper.startsWith('DELETE FROM')) {
130
249
  table = sql.split(/\s+/)[2];
131
250
  }
251
+ else if (upper.startsWith('CREATE TABLE')) {
252
+ // Extract table name from CREATE TABLE [IF NOT EXISTS] tablename
253
+ const match = sql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i);
254
+ if (match) {
255
+ table = match[1];
256
+ // Auto-setup cloud sync triggers for new tables
257
+ if (this.cloudSyncEnabled && this.shouldSyncTable(table) && !this.syncedTables.has(table)) {
258
+ // Defer trigger setup to after the table is created
259
+ setTimeout(() => {
260
+ this.setupTableSyncTriggers(table);
261
+ this.syncedTables.add(table);
262
+ console.log('[Dash] Auto-enabled cloud sync for new table:', table);
263
+ }, 0);
264
+ }
265
+ }
266
+ }
132
267
  if (table) {
133
268
  // cleanup quotes etc
134
269
  table = table.replace(/["';]/g, '');
@@ -250,9 +385,408 @@ export class DashEngine {
250
385
  });
251
386
  }
252
387
  close() {
388
+ this.stopCloudSync();
253
389
  this.db?.close();
254
390
  }
255
391
  // ============================================
392
+ // CLOUD SYNC (D1/R2) - AUTOMATIC SYNC
393
+ // ============================================
394
+ /**
395
+ * Enable cloud sync - changes automatically sync to D1/R2
396
+ * Just call this once with your config, and sync happens magically.
397
+ *
398
+ * Cloud sync is ON BY DEFAULT when running in a Cloudflare environment.
399
+ * Call this to customize the config or explicitly enable/disable.
400
+ *
401
+ * @example
402
+ * ```ts
403
+ * await dash.ready();
404
+ * // Option 1: Use auto-detected endpoint (default)
405
+ * // Cloud sync is already enabled if DASH_SYNC_URL env var is set
406
+ *
407
+ * // Option 2: Explicit config
408
+ * dash.enableCloudSync({
409
+ * baseUrl: 'https://api.example.com',
410
+ * getAuthToken: async () => auth.token,
411
+ * });
412
+ *
413
+ * // Option 3: Disable cloud sync
414
+ * dash.enableCloudSync({ disabled: true });
415
+ * ```
416
+ */
417
+ enableCloudSync(config = {}) {
418
+ // Handle explicit disable
419
+ if (config.disabled) {
420
+ this.disableCloudSync();
421
+ return;
422
+ }
423
+ if (!this.db) {
424
+ console.warn('[Dash] Database not ready. Call enableCloudSync after ready()');
425
+ return;
426
+ }
427
+ // Try to get baseUrl from config or auto-detect
428
+ const baseUrl = config.baseUrl || this.detectSyncEndpoint();
429
+ if (!baseUrl) {
430
+ console.warn('[Dash] No sync endpoint available. Cloud sync disabled.');
431
+ return;
432
+ }
433
+ this.cloudConfig = {
434
+ syncInterval: 30000,
435
+ ...config,
436
+ baseUrl,
437
+ getAuthToken: config.getAuthToken || (() => this.getDefaultAuthToken()),
438
+ };
439
+ // Create sync infrastructure tables
440
+ this.initializeCloudSyncSchema();
441
+ // Load last sync time
442
+ const meta = this.execute("SELECT value FROM dash_sync_meta WHERE key = 'lastCloudSyncTime'");
443
+ if (meta.length > 0) {
444
+ this.lastCloudSyncTime = parseInt(meta[0].value, 10) || 0;
445
+ }
446
+ // Set up triggers for all existing user tables
447
+ this.setupAllTableTriggers();
448
+ this.cloudSyncEnabled = true;
449
+ // Start auto-sync
450
+ if (this.cloudConfig.syncInterval && this.cloudConfig.syncInterval > 0) {
451
+ this.startCloudSync();
452
+ }
453
+ console.log('[Dash] Cloud sync enabled');
454
+ }
455
+ /**
456
+ * Initialize cloud sync schema (queue and metadata tables)
457
+ */
458
+ initializeCloudSyncSchema() {
459
+ this.db.exec(`
460
+ CREATE TABLE IF NOT EXISTS dash_sync_meta (
461
+ key TEXT PRIMARY KEY,
462
+ value TEXT
463
+ )
464
+ `);
465
+ this.db.exec(`
466
+ CREATE TABLE IF NOT EXISTS dash_sync_queue (
467
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
468
+ table_name TEXT NOT NULL,
469
+ row_id TEXT NOT NULL,
470
+ operation TEXT NOT NULL CHECK(operation IN ('create', 'update', 'delete')),
471
+ data TEXT,
472
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
473
+ synced INTEGER DEFAULT 0
474
+ )
475
+ `);
476
+ this.db.exec(`
477
+ CREATE INDEX IF NOT EXISTS idx_dash_sync_queue_pending
478
+ ON dash_sync_queue(synced, created_at)
479
+ `);
480
+ }
481
+ /**
482
+ * Set up sync triggers for all user tables
483
+ */
484
+ setupAllTableTriggers() {
485
+ const tables = this.execute(`
486
+ SELECT name FROM sqlite_master
487
+ WHERE type = 'table'
488
+ AND name NOT LIKE 'sqlite_%'
489
+ `);
490
+ for (const t of tables) {
491
+ const tableName = t.name;
492
+ if (!this.shouldSyncTable(tableName))
493
+ continue;
494
+ this.setupTableSyncTriggers(tableName);
495
+ this.syncedTables.add(tableName);
496
+ }
497
+ console.log('[Dash] Sync triggers set up for:', Array.from(this.syncedTables));
498
+ }
499
+ /**
500
+ * Check if a table should be synced
501
+ */
502
+ shouldSyncTable(tableName) {
503
+ // Skip internal tables
504
+ if (this.INTERNAL_TABLES.has(tableName))
505
+ return false;
506
+ // Skip excluded tables
507
+ if (this.cloudConfig?.excludeTables?.includes(tableName))
508
+ return false;
509
+ return true;
510
+ }
511
+ /**
512
+ * Set up sync triggers for a specific table
513
+ */
514
+ setupTableSyncTriggers(tableName) {
515
+ // Check if table has an 'id' column (required for sync)
516
+ const columns = this.execute(`PRAGMA table_info('${tableName.replace(/'/g, "''")}')`);
517
+ const hasId = columns.some((c) => c.name === 'id');
518
+ if (!hasId) {
519
+ console.warn(`[Dash] Table ${tableName} has no 'id' column, skipping sync triggers`);
520
+ return;
521
+ }
522
+ // Drop existing triggers
523
+ try {
524
+ this.db.exec(`DROP TRIGGER IF EXISTS dash_cloud_${tableName}_insert`);
525
+ this.db.exec(`DROP TRIGGER IF EXISTS dash_cloud_${tableName}_update`);
526
+ this.db.exec(`DROP TRIGGER IF EXISTS dash_cloud_${tableName}_delete`);
527
+ }
528
+ catch {
529
+ // Ignore
530
+ }
531
+ // INSERT trigger - capture full row as JSON
532
+ this.db.exec(`
533
+ CREATE TRIGGER dash_cloud_${tableName}_insert
534
+ AFTER INSERT ON "${tableName}"
535
+ WHEN (SELECT value FROM dash_sync_meta WHERE key = 'cloud_enabled') = '1'
536
+ BEGIN
537
+ INSERT INTO dash_sync_queue (table_name, row_id, operation, data)
538
+ SELECT '${tableName}', NEW.id, 'create', json_object(${this.buildJsonObjectArgs(tableName, columns, 'NEW')});
539
+ END
540
+ `);
541
+ // UPDATE trigger
542
+ this.db.exec(`
543
+ CREATE TRIGGER dash_cloud_${tableName}_update
544
+ AFTER UPDATE ON "${tableName}"
545
+ WHEN (SELECT value FROM dash_sync_meta WHERE key = 'cloud_enabled') = '1'
546
+ BEGIN
547
+ INSERT INTO dash_sync_queue (table_name, row_id, operation, data)
548
+ SELECT '${tableName}', NEW.id, 'update', json_object(${this.buildJsonObjectArgs(tableName, columns, 'NEW')});
549
+ END
550
+ `);
551
+ // DELETE trigger
552
+ this.db.exec(`
553
+ CREATE TRIGGER dash_cloud_${tableName}_delete
554
+ AFTER DELETE ON "${tableName}"
555
+ WHEN (SELECT value FROM dash_sync_meta WHERE key = 'cloud_enabled') = '1'
556
+ BEGIN
557
+ INSERT INTO dash_sync_queue (table_name, row_id, operation, data)
558
+ VALUES ('${tableName}', OLD.id, 'delete', NULL);
559
+ END
560
+ `);
561
+ // Enable triggers
562
+ this.execute("INSERT OR REPLACE INTO dash_sync_meta (key, value) VALUES ('cloud_enabled', '1')");
563
+ }
564
+ /**
565
+ * Build json_object() arguments for a table's columns
566
+ */
567
+ buildJsonObjectArgs(tableName, columns, prefix) {
568
+ return columns
569
+ .map((c) => `'${c.name}', ${prefix}."${c.name}"`)
570
+ .join(', ');
571
+ }
572
+ /**
573
+ * Start automatic cloud sync
574
+ */
575
+ startCloudSync() {
576
+ if (this.cloudSyncTimer)
577
+ return;
578
+ this.cloudSyncTimer = setInterval(() => {
579
+ if (typeof navigator !== 'undefined' && !navigator.onLine) {
580
+ return; // Skip sync when offline
581
+ }
582
+ this.syncToCloud().catch(console.error);
583
+ }, this.cloudConfig.syncInterval);
584
+ // Also do an immediate sync
585
+ this.syncToCloud().catch(console.error);
586
+ console.log('[Dash] Cloud auto-sync started, interval:', this.cloudConfig.syncInterval, 'ms');
587
+ }
588
+ /**
589
+ * Stop automatic cloud sync
590
+ */
591
+ stopCloudSync() {
592
+ if (this.cloudSyncTimer) {
593
+ clearInterval(this.cloudSyncTimer);
594
+ this.cloudSyncTimer = null;
595
+ }
596
+ this.cloudSyncEnabled = false;
597
+ console.log('[Dash] Cloud sync stopped');
598
+ }
599
+ /**
600
+ * Perform a sync to cloud (D1/R2)
601
+ */
602
+ async syncToCloud() {
603
+ if (!this.cloudConfig || !this.cloudSyncEnabled) {
604
+ return { pushed: 0, pulled: 0, errors: ['Cloud sync not enabled'], timestamp: Date.now() };
605
+ }
606
+ if (this.isCloudSyncing) {
607
+ return { pushed: 0, pulled: 0, errors: ['Sync already in progress'], timestamp: Date.now() };
608
+ }
609
+ this.isCloudSyncing = true;
610
+ const result = { pushed: 0, pulled: 0, errors: [], timestamp: Date.now() };
611
+ try {
612
+ const token = this.cloudConfig.getAuthToken
613
+ ? await this.cloudConfig.getAuthToken()
614
+ : await this.getDefaultAuthToken();
615
+ // Token is optional - sync can work without auth for public endpoints
616
+ // Get pending changes
617
+ const pending = this.execute(`
618
+ SELECT * FROM dash_sync_queue
619
+ WHERE synced = 0
620
+ ORDER BY created_at ASC
621
+ LIMIT 100
622
+ `);
623
+ // Group by table
624
+ const changesByTable = {};
625
+ for (const entry of pending) {
626
+ const tableName = entry.table_name;
627
+ if (!changesByTable[tableName]) {
628
+ changesByTable[tableName] = { creates: [], updates: [], deletes: [] };
629
+ }
630
+ const data = entry.data ? JSON.parse(entry.data) : null;
631
+ switch (entry.operation) {
632
+ case 'create':
633
+ if (data)
634
+ changesByTable[tableName].creates.push(data);
635
+ break;
636
+ case 'update':
637
+ if (data)
638
+ changesByTable[tableName].updates.push(data);
639
+ break;
640
+ case 'delete':
641
+ changesByTable[tableName].deletes.push(entry.row_id);
642
+ break;
643
+ }
644
+ }
645
+ // Sync each table
646
+ for (const [tableName, changes] of Object.entries(changesByTable)) {
647
+ if (changes.creates.length === 0 && changes.updates.length === 0 && changes.deletes.length === 0) {
648
+ continue;
649
+ }
650
+ try {
651
+ const headers = {
652
+ 'Content-Type': 'application/json',
653
+ };
654
+ if (token) {
655
+ headers['Authorization'] = `Bearer ${token}`;
656
+ }
657
+ const response = await fetch(`${this.cloudConfig.baseUrl}/api/sync`, {
658
+ method: 'POST',
659
+ headers,
660
+ body: JSON.stringify({
661
+ table: tableName,
662
+ creates: changes.creates,
663
+ updates: changes.updates,
664
+ deletes: changes.deletes,
665
+ lastSyncTime: this.lastCloudSyncTime,
666
+ }),
667
+ });
668
+ if (!response.ok) {
669
+ const errorText = await response.text();
670
+ result.errors.push(`${tableName}: ${response.status} ${errorText}`);
671
+ continue;
672
+ }
673
+ const syncResponse = await response.json();
674
+ result.pushed += changes.creates.length + changes.updates.length + changes.deletes.length;
675
+ result.pulled += syncResponse.serverChanges?.length || 0;
676
+ // Apply server changes locally (with triggers disabled)
677
+ if (syncResponse.serverChanges && syncResponse.serverChanges.length > 0) {
678
+ this.execute("UPDATE dash_sync_meta SET value = '0' WHERE key = 'cloud_enabled'");
679
+ try {
680
+ for (const change of syncResponse.serverChanges) {
681
+ this.applyServerChange(tableName, change);
682
+ }
683
+ }
684
+ finally {
685
+ this.execute("UPDATE dash_sync_meta SET value = '1' WHERE key = 'cloud_enabled'");
686
+ }
687
+ }
688
+ // Update sync time
689
+ if (syncResponse.syncTime > this.lastCloudSyncTime) {
690
+ this.lastCloudSyncTime = syncResponse.syncTime;
691
+ this.execute("INSERT OR REPLACE INTO dash_sync_meta (key, value) VALUES ('lastCloudSyncTime', ?)", [String(this.lastCloudSyncTime)]);
692
+ }
693
+ }
694
+ catch (err) {
695
+ result.errors.push(`${tableName}: ${err instanceof Error ? err.message : String(err)}`);
696
+ }
697
+ }
698
+ // Mark as synced
699
+ if (pending.length > 0) {
700
+ const ids = pending.map((e) => e.id).join(',');
701
+ this.execute(`UPDATE dash_sync_queue SET synced = 1 WHERE id IN (${ids})`);
702
+ }
703
+ // Clean up old entries
704
+ this.execute(`
705
+ DELETE FROM dash_sync_queue
706
+ WHERE synced = 1
707
+ AND id NOT IN (
708
+ SELECT id FROM dash_sync_queue
709
+ WHERE synced = 1
710
+ ORDER BY id DESC
711
+ LIMIT 1000
712
+ )
713
+ `);
714
+ this.cloudConfig.onSyncComplete?.(result);
715
+ }
716
+ catch (err) {
717
+ const error = err instanceof Error ? err : new Error(String(err));
718
+ result.errors.push(error.message);
719
+ this.cloudConfig.onSyncError?.(error);
720
+ }
721
+ finally {
722
+ this.isCloudSyncing = false;
723
+ }
724
+ return result;
725
+ }
726
+ /**
727
+ * Apply a single server change locally
728
+ */
729
+ applyServerChange(tableName, change) {
730
+ try {
731
+ if (change.deleted || change._deleted) {
732
+ this.execute(`DELETE FROM "${tableName}" WHERE id = ?`, [change.id]);
733
+ return;
734
+ }
735
+ const columns = Object.keys(change).filter(k => !k.startsWith('_'));
736
+ const placeholders = columns.map(() => '?').join(', ');
737
+ const values = columns.map(k => {
738
+ const v = change[k];
739
+ if (v !== null && typeof v === 'object') {
740
+ return JSON.stringify(v);
741
+ }
742
+ return v;
743
+ });
744
+ const sql = `INSERT OR REPLACE INTO "${tableName}" (${columns.join(', ')}) VALUES (${placeholders})`;
745
+ this.execute(sql, values);
746
+ }
747
+ catch (err) {
748
+ console.error(`[Dash] Failed to apply server change to ${tableName}:`, err);
749
+ }
750
+ }
751
+ /**
752
+ * Force a full cloud sync (reset last sync time)
753
+ */
754
+ async forceCloudSync() {
755
+ this.lastCloudSyncTime = 0;
756
+ this.execute("INSERT OR REPLACE INTO dash_sync_meta (key, value) VALUES ('lastCloudSyncTime', '0')");
757
+ return this.syncToCloud();
758
+ }
759
+ /**
760
+ * Get cloud sync status
761
+ */
762
+ getCloudSyncStatus() {
763
+ let pendingChanges = 0;
764
+ if (this.cloudSyncEnabled && this.db) {
765
+ try {
766
+ const result = this.execute('SELECT COUNT(*) as count FROM dash_sync_queue WHERE synced = 0');
767
+ pendingChanges = result[0]?.count || 0;
768
+ }
769
+ catch {
770
+ // Table might not exist yet
771
+ }
772
+ }
773
+ return {
774
+ enabled: this.cloudSyncEnabled,
775
+ syncing: this.isCloudSyncing,
776
+ lastSyncTime: this.lastCloudSyncTime,
777
+ pendingChanges,
778
+ syncedTables: Array.from(this.syncedTables),
779
+ };
780
+ }
781
+ /**
782
+ * Disable cloud sync
783
+ */
784
+ disableCloudSync() {
785
+ this.stopCloudSync();
786
+ this.execute("UPDATE dash_sync_meta SET value = '0' WHERE key = 'cloud_enabled'");
787
+ console.log('[Dash] Cloud sync disabled');
788
+ }
789
+ // ============================================
256
790
  // INTROSPECTION METHODS FOR DASH-STUDIO
257
791
  // ============================================
258
792
  /**
@@ -1,12 +1,15 @@
1
1
  export { dash } from './engine/sqlite.js';
2
+ export type { CloudConfig, CloudSyncResult } from './engine/sqlite.js';
2
3
  export { liveQuery, signal, effect, computed } from './reactivity/signal.js';
3
4
  export { mcpServer } from './mcp/server.js';
4
5
  export { YjsSqliteProvider } from './sync/provider.js';
5
6
  export { backup, restore, generateKey, exportKey, importKey } from './sync/backup.js';
6
7
  export type { CloudStorageAdapter } from './sync/backup.js';
7
8
  export { HybridProvider } from './sync/hybrid-provider.js';
9
+ export { D1SyncProvider, getD1SyncProvider, resetD1SyncProvider } from './sync/d1-provider.js';
10
+ export type { D1SyncConfig, SyncResult, SyncQueueEntry } from './sync/d1-provider.js';
8
11
  export * as firebase from './api/firebase/index.js';
9
12
  export { collection, doc, query, where, orderBy, limit, limitToLast, startAt, startAfter, endAt, endBefore, offset, Timestamp, GeoPoint, serverTimestamp, deleteField, arrayUnion, arrayRemove, increment, getDoc, getDocs, setDoc, updateDoc, deleteDoc, writeBatch, runTransaction, onSnapshot, } from './api/firebase/index.js';
10
- export { ref, child, set, update, remove, push, get, onDisconnect, onValue, onChildAdded, onChildChanged, onChildRemoved, onChildMoved, off, } from './api/firebase/index.js';
13
+ export { ref, child, set, update, remove, push, get, onDisconnect, onValue, off, } from './api/firebase/index.js';
11
14
  export { createUserWithEmailAndPassword, signInWithEmailAndPassword, signInAnonymously, signOut, getAuth, onAuthStateChanged, updateUserProfile, updateUserEmail, updateUserPassword, deleteUser, sendPasswordResetEmail, sendEmailVerification, GoogleAuthProvider, GithubAuthProvider, FacebookAuthProvider, TwitterAuthProvider, DiscordAuthProvider, TotpMultiFactorGenerator, PhoneMultiFactorGenerator, setPersistence, browserLocalPersistence, browserSessionPersistence, inMemoryPersistence, } from './api/firebase/index.js';
12
- export { ref as storageRef, refFromURL, child as storageChild, uploadBytes, uploadBytesResumable, uploadString, getBytes, getDownloadURL, getMetadata, updateMetadata, deleteObject, list as listFiles, listAll, } from './api/firebase/index.js';
15
+ export { ref as storageRef, refFromURL, child as storageChild, uploadBytes, uploadBytesResumable, uploadString, getBytes, getDownloadURL, getMetadata, updateMetadata, deleteObject, list as listFiles, listAll, } from './api/firebase/storage/index.js';
package/dist/src/index.js CHANGED
@@ -5,13 +5,20 @@ export { mcpServer } from './mcp/server.js';
5
5
  export { YjsSqliteProvider } from './sync/provider.js';
6
6
  export { backup, restore, generateKey, exportKey, importKey } from './sync/backup.js';
7
7
  export { HybridProvider } from './sync/hybrid-provider.js';
8
+ // D1 HTTP Sync (legacy - prefer dash.enableCloudSync())
9
+ export { D1SyncProvider, getD1SyncProvider, resetD1SyncProvider } from './sync/d1-provider.js';
8
10
  // Firebase Compatibility API exports
9
11
  export * as firebase from './api/firebase/index.js';
10
12
  // Firestore
11
13
  export { collection, doc, query, where, orderBy, limit, limitToLast, startAt, startAfter, endAt, endBefore, offset, serverTimestamp, deleteField, arrayUnion, arrayRemove, increment, getDoc, getDocs, setDoc, updateDoc, deleteDoc, writeBatch, runTransaction, onSnapshot, } from './api/firebase/index.js';
12
14
  // Realtime Database
13
- export { ref, child, set, update, remove, push, get, onDisconnect, onValue, onChildAdded, onChildChanged, onChildRemoved, onChildMoved, off, } from './api/firebase/index.js';
15
+ export { ref, child, set, update, remove, push, get, onDisconnect, onValue,
16
+ // onChildAdded,
17
+ // onChildChanged,
18
+ // onChildRemoved,
19
+ // onChildMoved,
20
+ off, } from './api/firebase/index.js';
14
21
  // Authentication
15
22
  export { createUserWithEmailAndPassword, signInWithEmailAndPassword, signInAnonymously, signOut, getAuth, onAuthStateChanged, updateUserProfile, updateUserEmail, updateUserPassword, deleteUser, sendPasswordResetEmail, sendEmailVerification, GoogleAuthProvider, GithubAuthProvider, FacebookAuthProvider, TwitterAuthProvider, DiscordAuthProvider, TotpMultiFactorGenerator, PhoneMultiFactorGenerator, setPersistence, browserLocalPersistence, browserSessionPersistence, inMemoryPersistence, } from './api/firebase/index.js';
16
23
  // Storage
17
- export { ref as storageRef, refFromURL, child as storageChild, uploadBytes, uploadBytesResumable, uploadString, getBytes, getDownloadURL, getMetadata, updateMetadata, deleteObject, list as listFiles, listAll, } from './api/firebase/index.js';
24
+ export { ref as storageRef, refFromURL, child as storageChild, uploadBytes, uploadBytesResumable, uploadString, getBytes, getDownloadURL, getMetadata, updateMetadata, deleteObject, list as listFiles, listAll, } from './api/firebase/storage/index.js';