@drakkar.software/starfish-client 1.4.0 → 1.5.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/dist/index.js CHANGED
@@ -4,10 +4,16 @@ export { StarfishClient } from "./client.js";
4
4
  export { SyncManager } from "./sync.js";
5
5
  export { createEncryptor, ENCRYPTED_KEY } from "./crypto.js";
6
6
  export { ConflictError, StarfishHttpError, } from "./types.js";
7
- export { consoleSyncLogger, noopSyncLogger } from "./logger.js";
7
+ export { consoleSyncLogger, noopSyncLogger, createMetricsCollector } from "./logger.js";
8
8
  export { createMigrator } from "./migrate.js";
9
9
  export { ValidationError, createSchemaValidator } from "./validate.js";
10
10
  export { classifyError } from "./fetch.js";
11
- export { createUnionMerge, createSoftDeleteResolver, timestampWinner, pruneTombstones, } from "./resolvers.js";
11
+ export { createUnionMerge, createSoftDeleteResolver, timestampWinner, pruneTombstones, withConflictMeta, } from "./resolvers.js";
12
12
  export { SnapshotHistory } from "./history.js";
13
13
  export { startPolling, startAdaptivePolling } from "./polling.js";
14
+ export { createDedupFetch } from "./dedup.js";
15
+ export { createIndexedDBStorage } from "./storage/indexeddb.js";
16
+ export { exportData, importData, exportToBlob } from "./export.js";
17
+ export { isBackgroundSyncSupported, registerBackgroundSync } from "./background-sync.js";
18
+ export { isServiceWorkerSupported, registerServiceWorker, unregisterServiceWorkers } from "./service-worker.js";
19
+ export { createSuspenseResource } from "./bindings/suspense.js";
package/dist/logger.d.ts CHANGED
@@ -1,10 +1,18 @@
1
+ /** Extended metrics for sync operations. */
2
+ export interface SyncMetrics {
3
+ bytesTransferred?: number;
4
+ compressedSize?: number;
5
+ conflictCount?: number;
6
+ retryCount?: number;
7
+ cacheHit?: boolean;
8
+ }
1
9
  /** Structured logger for sync operations. */
2
10
  export interface SyncLogger {
3
11
  pullStart(store: string): void;
4
- pullSuccess(store: string, durationMs: number): void;
12
+ pullSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void;
5
13
  pullError(store: string, error: string): void;
6
14
  pushStart(store: string): void;
7
- pushSuccess(store: string, durationMs: number): void;
15
+ pushSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void;
8
16
  pushError(store: string, error: string): void;
9
17
  conflict(store: string, attempt: number): void;
10
18
  }
@@ -12,3 +20,19 @@ export interface SyncLogger {
12
20
  export declare const consoleSyncLogger: SyncLogger;
13
21
  /** Silent sync logger (no output). */
14
22
  export declare const noopSyncLogger: SyncLogger;
23
+ /** Collects sync metrics over time. */
24
+ export interface MetricsCollector {
25
+ recordPull(name: string, durationMs: number, metrics?: SyncMetrics): void;
26
+ recordPush(name: string, durationMs: number, metrics?: SyncMetrics): void;
27
+ recordConflict(name: string): void;
28
+ getSummary(): Record<string, {
29
+ totalPulls: number;
30
+ totalPushes: number;
31
+ avgDurationMs: number;
32
+ totalBytes: number;
33
+ totalConflicts: number;
34
+ }>;
35
+ reset(): void;
36
+ }
37
+ /** Create a metrics collector that accumulates sync statistics. */
38
+ export declare function createMetricsCollector(): MetricsCollector;
package/dist/logger.js CHANGED
@@ -1,10 +1,22 @@
1
1
  /** Console-based sync logger with structured output. */
2
2
  export const consoleSyncLogger = {
3
3
  pullStart: (s) => console.log(`[starfish:${s}] pull started`),
4
- pullSuccess: (s, ms) => console.log(`[starfish:${s}] pull OK (${ms}ms)`),
4
+ pullSuccess: (s, ms, m) => {
5
+ let msg = `[starfish:${s}] pull OK (${ms}ms)`;
6
+ if (m?.bytesTransferred)
7
+ msg += ` ${m.bytesTransferred}B`;
8
+ if (m?.cacheHit)
9
+ msg += ` (cache hit)`;
10
+ console.log(msg);
11
+ },
5
12
  pullError: (s, err) => console.error(`[starfish:${s}] pull failed: ${err}`),
6
13
  pushStart: (s) => console.log(`[starfish:${s}] push started`),
7
- pushSuccess: (s, ms) => console.log(`[starfish:${s}] push OK (${ms}ms)`),
14
+ pushSuccess: (s, ms, m) => {
15
+ let msg = `[starfish:${s}] push OK (${ms}ms)`;
16
+ if (m?.bytesTransferred)
17
+ msg += ` ${m.bytesTransferred}B`;
18
+ console.log(msg);
19
+ },
8
20
  pushError: (s, err) => console.error(`[starfish:${s}] push failed: ${err}`),
9
21
  conflict: (s, n) => console.warn(`[starfish:${s}] conflict (attempt ${n})`),
10
22
  };
@@ -18,3 +30,51 @@ export const noopSyncLogger = {
18
30
  pushError: () => { },
19
31
  conflict: () => { },
20
32
  };
33
+ /** Create a metrics collector that accumulates sync statistics. */
34
+ export function createMetricsCollector() {
35
+ const stores = new Map();
36
+ function ensureStore(name) {
37
+ let s = stores.get(name);
38
+ if (!s) {
39
+ s = { totalPulls: 0, totalPushes: 0, totalDurationMs: 0, totalBytes: 0, totalConflicts: 0 };
40
+ stores.set(name, s);
41
+ }
42
+ return s;
43
+ }
44
+ return {
45
+ recordPull(name, durationMs, metrics) {
46
+ const s = ensureStore(name);
47
+ s.totalPulls++;
48
+ s.totalDurationMs += durationMs;
49
+ if (metrics?.bytesTransferred)
50
+ s.totalBytes += metrics.bytesTransferred;
51
+ },
52
+ recordPush(name, durationMs, metrics) {
53
+ const s = ensureStore(name);
54
+ s.totalPushes++;
55
+ s.totalDurationMs += durationMs;
56
+ if (metrics?.bytesTransferred)
57
+ s.totalBytes += metrics.bytesTransferred;
58
+ },
59
+ recordConflict(name) {
60
+ ensureStore(name).totalConflicts++;
61
+ },
62
+ getSummary() {
63
+ const result = {};
64
+ for (const [name, s] of stores) {
65
+ const totalOps = s.totalPulls + s.totalPushes;
66
+ result[name] = {
67
+ totalPulls: s.totalPulls,
68
+ totalPushes: s.totalPushes,
69
+ avgDurationMs: totalOps > 0 ? Math.round(s.totalDurationMs / totalOps) : 0,
70
+ totalBytes: s.totalBytes,
71
+ totalConflicts: s.totalConflicts,
72
+ };
73
+ }
74
+ return result;
75
+ },
76
+ reset() {
77
+ stores.clear();
78
+ },
79
+ };
80
+ }
package/dist/migrate.js CHANGED
@@ -25,7 +25,12 @@ export function createMigrator(config) {
25
25
  if (!fn) {
26
26
  throw new Error(`Missing migration for version ${v} -> ${v + 1}`);
27
27
  }
28
- result = fn(result);
28
+ try {
29
+ result = fn(result);
30
+ }
31
+ catch (err) {
32
+ throw new Error(`Migration from version ${v} to ${v + 1} failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
33
+ }
29
34
  }
30
35
  result._schemaVersion = config.currentVersion;
31
36
  return result;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Platform abstraction for crypto and base64 operations.
3
+ *
4
+ * Browser and Node.js >= 15 work with zero configuration (globalThis.crypto).
5
+ * React Native users must call configurePlatform() before using the SDK.
6
+ */
7
+ /** Minimal crypto interface required by the SDK (subset of Web Crypto API). */
8
+ export interface CryptoProvider {
9
+ subtle: {
10
+ digest(algorithm: string, data: BufferSource): Promise<ArrayBuffer>;
11
+ importKey(format: "raw", keyData: BufferSource, algorithm: string | Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
12
+ deriveKey(algorithm: HkdfParams, baseKey: CryptoKey, derivedKeyType: AesKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
13
+ encrypt(algorithm: AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
14
+ decrypt(algorithm: AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
15
+ };
16
+ getRandomValues<T extends ArrayBufferView>(array: T): T;
17
+ }
18
+ /** Base64 encode/decode for Uint8Array <-> string. */
19
+ export interface Base64Provider {
20
+ encode(data: Uint8Array): string;
21
+ decode(encoded: string): Uint8Array;
22
+ }
23
+ export interface PlatformConfig {
24
+ crypto?: CryptoProvider;
25
+ base64?: Base64Provider;
26
+ }
27
+ /**
28
+ * Configure platform-specific providers for environments
29
+ * that lack the Web Crypto API (e.g., React Native).
30
+ *
31
+ * Call once at app startup, before using any SDK functions.
32
+ * Not needed for browser or Node.js >= 15.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { configurePlatform } from "@satellite/client"
37
+ * import QuickCrypto from "react-native-quick-crypto"
38
+ *
39
+ * configurePlatform({
40
+ * crypto: QuickCrypto,
41
+ * base64: {
42
+ * encode: (data) => Buffer.from(data).toString("base64"),
43
+ * decode: (str) => new Uint8Array(Buffer.from(str, "base64")),
44
+ * },
45
+ * })
46
+ * ```
47
+ */
48
+ export declare function configurePlatform(config: PlatformConfig): void;
49
+ /** Resolve the active crypto provider. */
50
+ export declare function getCrypto(): CryptoProvider;
51
+ /** Resolve the active base64 provider. */
52
+ export declare function getBase64(): Base64Provider;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Platform abstraction for crypto and base64 operations.
3
+ *
4
+ * Browser and Node.js >= 15 work with zero configuration (globalThis.crypto).
5
+ * React Native users must call configurePlatform() before using the SDK.
6
+ */
7
+ let _crypto;
8
+ let _base64;
9
+ /**
10
+ * Configure platform-specific providers for environments
11
+ * that lack the Web Crypto API (e.g., React Native).
12
+ *
13
+ * Call once at app startup, before using any SDK functions.
14
+ * Not needed for browser or Node.js >= 15.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { configurePlatform } from "@satellite/client"
19
+ * import QuickCrypto from "react-native-quick-crypto"
20
+ *
21
+ * configurePlatform({
22
+ * crypto: QuickCrypto,
23
+ * base64: {
24
+ * encode: (data) => Buffer.from(data).toString("base64"),
25
+ * decode: (str) => new Uint8Array(Buffer.from(str, "base64")),
26
+ * },
27
+ * })
28
+ * ```
29
+ */
30
+ export function configurePlatform(config) {
31
+ if (config.crypto)
32
+ _crypto = config.crypto;
33
+ if (config.base64)
34
+ _base64 = config.base64;
35
+ }
36
+ /** Resolve the active crypto provider. */
37
+ export function getCrypto() {
38
+ if (_crypto)
39
+ return _crypto;
40
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle) {
41
+ return globalThis.crypto;
42
+ }
43
+ throw new Error("@satellite/client: No crypto provider available. " +
44
+ "In React Native, call configurePlatform({ crypto: ... }) before using the SDK.");
45
+ }
46
+ /** Resolve the active base64 provider. */
47
+ export function getBase64() {
48
+ if (_base64)
49
+ return _base64;
50
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
51
+ return {
52
+ encode(data) {
53
+ return btoa(String.fromCharCode(...data));
54
+ },
55
+ decode(encoded) {
56
+ return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
57
+ },
58
+ };
59
+ }
60
+ throw new Error("@satellite/client: No base64 provider available. " +
61
+ "In React Native, call configurePlatform({ base64: ... }) before using the SDK.");
62
+ }
package/dist/polling.js CHANGED
@@ -14,7 +14,7 @@ export function startPolling(pullFn, getState, intervalMs = 30_000) {
14
14
  const timer = setInterval(() => {
15
15
  const { online, syncing } = getState();
16
16
  if (online && !syncing)
17
- pullFn();
17
+ pullFn().catch(() => { });
18
18
  }, intervalMs);
19
19
  return () => clearInterval(timer);
20
20
  }
@@ -42,7 +42,7 @@ export function startAdaptivePolling(pullFn, getState, options) {
42
42
  return;
43
43
  const { online, syncing } = getState();
44
44
  if (online && !syncing)
45
- pullFn();
45
+ pullFn().catch(() => { });
46
46
  }, intervalMs);
47
47
  return {
48
48
  pause: () => { paused = true; },
@@ -1,4 +1,23 @@
1
1
  import type { ConflictResolver } from "./types.js";
2
+ /** Metadata about which fields were affected during conflict resolution. */
3
+ export interface ConflictMeta {
4
+ /** Field names that differed between local and remote. */
5
+ conflictedFields: string[];
6
+ /** How the conflict was resolved. */
7
+ resolvedBy: "local" | "remote" | "merged";
8
+ /** Timestamp of resolution. */
9
+ timestamp: number;
10
+ }
11
+ /** Conflict resolver that also returns metadata about the resolution. */
12
+ export type ConflictResolverWithMeta = (local: Record<string, unknown>, remote: Record<string, unknown>) => {
13
+ data: Record<string, unknown>;
14
+ meta: ConflictMeta;
15
+ };
16
+ /**
17
+ * Wrap a standard ConflictResolver to also return metadata about which fields conflicted.
18
+ * Compares local and remote keys to detect differing fields.
19
+ */
20
+ export declare function withConflictMeta(resolver: ConflictResolver): ConflictResolverWithMeta;
2
21
  /**
3
22
  * Creates a conflict resolver that merges arrays by ID with per-item
4
23
  * timestamp comparison, and uses document-level timestamp for scalars.
package/dist/resolvers.js CHANGED
@@ -1,3 +1,60 @@
1
+ /** Shallow structural comparison of two values. Handles objects, arrays, and primitives. */
2
+ function shallowEqual(a, b) {
3
+ if (a === b)
4
+ return true;
5
+ if (a == null || b == null)
6
+ return a === b;
7
+ if (typeof a !== typeof b)
8
+ return false;
9
+ if (typeof a !== "object")
10
+ return false;
11
+ if (Array.isArray(a) !== Array.isArray(b))
12
+ return false;
13
+ if (Array.isArray(a) && Array.isArray(b)) {
14
+ if (a.length !== b.length)
15
+ return false;
16
+ return a.every((v, i) => shallowEqual(v, b[i]));
17
+ }
18
+ const aObj = a;
19
+ const bObj = b;
20
+ const aKeys = Object.keys(aObj);
21
+ const bKeys = Object.keys(bObj);
22
+ if (aKeys.length !== bKeys.length)
23
+ return false;
24
+ return aKeys.every((k) => shallowEqual(aObj[k], bObj[k]));
25
+ }
26
+ /**
27
+ * Wrap a standard ConflictResolver to also return metadata about which fields conflicted.
28
+ * Compares local and remote keys to detect differing fields.
29
+ */
30
+ export function withConflictMeta(resolver) {
31
+ return (local, remote) => {
32
+ const conflictedFields = [];
33
+ const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)]);
34
+ for (const key of allKeys) {
35
+ const lv = local[key];
36
+ const rv = remote[key];
37
+ if (!shallowEqual(lv, rv)) {
38
+ conflictedFields.push(key);
39
+ }
40
+ }
41
+ const data = resolver(local, remote);
42
+ // Determine how it was resolved using structural comparison
43
+ let resolvedBy = "merged";
44
+ if (shallowEqual(data, local))
45
+ resolvedBy = "local";
46
+ else if (shallowEqual(data, remote))
47
+ resolvedBy = "remote";
48
+ return {
49
+ data,
50
+ meta: {
51
+ conflictedFields,
52
+ resolvedBy,
53
+ timestamp: Date.now(),
54
+ },
55
+ };
56
+ };
57
+ }
1
58
  /** Compare two timestamp values. Handles both numeric (epoch) and string (ISO-8601) timestamps. */
2
59
  function compareTimestamps(a, b) {
3
60
  if (typeof a === "number" && typeof b === "number")
@@ -99,9 +156,9 @@ export function createSoftDeleteResolver(options) {
99
156
  const rec = item;
100
157
  const id = rec[idKey];
101
158
  const deletedAt = rec[deletedAtKey];
102
- if (typeof deletedAt === "number") {
103
- const existing = tombstones.get(id) ?? 0;
104
- if (deletedAt > existing)
159
+ if (typeof deletedAt === "number" || typeof deletedAt === "string") {
160
+ const existing = tombstones.get(id);
161
+ if (existing == null || compareTimestamps(deletedAt, existing))
105
162
  tombstones.set(id, deletedAt);
106
163
  }
107
164
  }
@@ -157,6 +214,10 @@ export function pruneTombstones(items, ttlMs = 30 * 24 * 60 * 60 * 1000, deleted
157
214
  const deletedAt = item[deletedAtKey];
158
215
  if (deletedAt == null)
159
216
  return true;
160
- return typeof deletedAt === "number" && deletedAt > cutoff;
217
+ if (typeof deletedAt === "number")
218
+ return deletedAt > cutoff;
219
+ if (typeof deletedAt === "string")
220
+ return new Date(deletedAt).getTime() > cutoff;
221
+ return false;
161
222
  });
162
223
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Service Worker utilities for offline support and PWA functionality.
3
+ */
4
+ export interface ServiceWorkerOptions {
5
+ /** Scope for the service worker registration. */
6
+ scope?: string;
7
+ /** Called when an updated service worker is available. */
8
+ onUpdate?: (registration: ServiceWorkerRegistration) => void;
9
+ }
10
+ /** Check if service workers are supported in the current environment. */
11
+ export declare function isServiceWorkerSupported(): boolean;
12
+ /**
13
+ * Register a service worker for offline support.
14
+ * Returns the registration, or null if not supported.
15
+ */
16
+ export declare function registerServiceWorker(scriptUrl: string, opts?: ServiceWorkerOptions): Promise<ServiceWorkerRegistration | null>;
17
+ /** Unregister all service worker registrations. Returns true if any were unregistered. */
18
+ export declare function unregisterServiceWorkers(): Promise<boolean>;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Service Worker utilities for offline support and PWA functionality.
3
+ */
4
+ /** Check if service workers are supported in the current environment. */
5
+ export function isServiceWorkerSupported() {
6
+ return typeof navigator !== "undefined" && "serviceWorker" in navigator;
7
+ }
8
+ /**
9
+ * Register a service worker for offline support.
10
+ * Returns the registration, or null if not supported.
11
+ */
12
+ export async function registerServiceWorker(scriptUrl, opts) {
13
+ if (!isServiceWorkerSupported())
14
+ return null;
15
+ try {
16
+ const registration = await navigator.serviceWorker.register(scriptUrl, {
17
+ scope: opts?.scope,
18
+ });
19
+ if (opts?.onUpdate) {
20
+ registration.onupdatefound = () => {
21
+ const installingWorker = registration.installing;
22
+ if (installingWorker) {
23
+ installingWorker.onstatechange = () => {
24
+ if (installingWorker.state === "installed" &&
25
+ navigator.serviceWorker.controller) {
26
+ opts.onUpdate(registration);
27
+ }
28
+ };
29
+ }
30
+ };
31
+ }
32
+ return registration;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ /** Unregister all service worker registrations. Returns true if any were unregistered. */
39
+ export async function unregisterServiceWorkers() {
40
+ if (!isServiceWorkerSupported())
41
+ return false;
42
+ try {
43
+ const registrations = await navigator.serviceWorker.getRegistrations();
44
+ let unregistered = false;
45
+ for (const registration of registrations) {
46
+ const result = await registration.unregister();
47
+ if (result)
48
+ unregistered = true;
49
+ }
50
+ return unregistered;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * IndexedDB-based storage adapter for Zustand persistence.
3
+ * Implements the same interface as Zustand's StateStorage (getItem/setItem/removeItem).
4
+ * Supports larger data than localStorage (typically 50MB+).
5
+ */
6
+ export interface IndexedDBStorageOptions {
7
+ /** Database name. Default: "starfish" */
8
+ dbName?: string;
9
+ /** Object store name. Default: "state" */
10
+ storeName?: string;
11
+ }
12
+ export interface AsyncStateStorage {
13
+ getItem: (name: string) => Promise<string | null>;
14
+ setItem: (name: string, value: string) => Promise<void>;
15
+ removeItem: (name: string) => Promise<void>;
16
+ }
17
+ export declare function createIndexedDBStorage(opts?: IndexedDBStorageOptions): AsyncStateStorage;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * IndexedDB-based storage adapter for Zustand persistence.
3
+ * Implements the same interface as Zustand's StateStorage (getItem/setItem/removeItem).
4
+ * Supports larger data than localStorage (typically 50MB+).
5
+ */
6
+ function openDB(dbName, storeName) {
7
+ return new Promise((resolve, reject) => {
8
+ const request = indexedDB.open(dbName, 1);
9
+ request.onupgradeneeded = () => {
10
+ const db = request.result;
11
+ if (!db.objectStoreNames.contains(storeName)) {
12
+ db.createObjectStore(storeName);
13
+ }
14
+ };
15
+ request.onsuccess = () => resolve(request.result);
16
+ request.onerror = () => reject(request.error);
17
+ });
18
+ }
19
+ function idbRequest(request) {
20
+ return new Promise((resolve, reject) => {
21
+ request.onsuccess = () => resolve(request.result);
22
+ request.onerror = () => reject(request.error);
23
+ });
24
+ }
25
+ export function createIndexedDBStorage(opts) {
26
+ const dbName = opts?.dbName ?? "starfish";
27
+ const storeName = opts?.storeName ?? "state";
28
+ let dbPromise = null;
29
+ function getDB() {
30
+ if (!dbPromise) {
31
+ dbPromise = openDB(dbName, storeName).catch((err) => {
32
+ dbPromise = null; // Reset so next call retries
33
+ throw err;
34
+ });
35
+ }
36
+ return dbPromise;
37
+ }
38
+ return {
39
+ async getItem(name) {
40
+ const db = await getDB();
41
+ const tx = db.transaction(storeName, "readonly");
42
+ const store = tx.objectStore(storeName);
43
+ const result = await idbRequest(store.get(name));
44
+ return result ?? null;
45
+ },
46
+ async setItem(name, value) {
47
+ const db = await getDB();
48
+ const tx = db.transaction(storeName, "readwrite");
49
+ const store = tx.objectStore(storeName);
50
+ await idbRequest(store.put(value, name));
51
+ },
52
+ async removeItem(name) {
53
+ const db = await getDB();
54
+ const tx = db.transaction(storeName, "readwrite");
55
+ const store = tx.objectStore(storeName);
56
+ await idbRequest(store.delete(name));
57
+ },
58
+ };
59
+ }
package/dist/sync.js CHANGED
@@ -52,6 +52,7 @@ export class SyncManager {
52
52
  }
53
53
  else if (this.lastCheckpoint > 0) {
54
54
  this.localData = deepMerge(this.localData, result.data);
55
+ result.data = this.localData;
55
56
  }
56
57
  else {
57
58
  this.localData = result.data;
@@ -62,7 +63,7 @@ export class SyncManager {
62
63
  return result;
63
64
  }
64
65
  catch (err) {
65
- this.logger?.pullError(this.loggerName, err.message);
66
+ this.logger?.pullError(this.loggerName, err instanceof Error ? err.message : String(err));
66
67
  throw err;
67
68
  }
68
69
  }
@@ -93,17 +94,24 @@ export class SyncManager {
93
94
  }
94
95
  catch (err) {
95
96
  if (!(err instanceof ConflictError) || attempt >= this.maxRetries) {
96
- this.logger?.pushError(this.loggerName, err.message);
97
+ this.logger?.pushError(this.loggerName, err instanceof Error ? err.message : String(err));
97
98
  throw err;
98
99
  }
99
100
  this.logger?.conflict(this.loggerName, attempt + 1);
100
- const remote = await this.client.pull(this.pullPath);
101
- this.lastHash = remote.hash;
102
- this.lastCheckpoint = remote.timestamp;
103
- const remoteData = this.encryptor
104
- ? await this.encryptor.decrypt(remote.data)
105
- : remote.data;
106
- pendingData = this.onConflict(pendingData, remoteData);
101
+ try {
102
+ const remote = await this.client.pull(this.pullPath);
103
+ const remoteData = this.encryptor
104
+ ? await this.encryptor.decrypt(remote.data)
105
+ : remote.data;
106
+ this.lastHash = remote.hash;
107
+ this.lastCheckpoint = remote.timestamp;
108
+ pendingData = this.onConflict(pendingData, remoteData);
109
+ }
110
+ catch (resolveErr) {
111
+ const msg = resolveErr instanceof Error ? resolveErr.message : String(resolveErr);
112
+ this.logger?.pushError(this.loggerName, `Conflict resolution failed (attempt ${attempt + 1}): ${msg}`);
113
+ throw resolveErr;
114
+ }
107
115
  await new Promise(resolve => setTimeout(resolve, Math.min(100 * Math.pow(2, attempt), 2000) + Math.random() * 100));
108
116
  attempt++;
109
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakkar.software/starfish-client",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/Drakkar-Software/starfish.git",
@@ -60,7 +60,7 @@
60
60
  }
61
61
  },
62
62
  "dependencies": {
63
- "@drakkar.software/starfish-protocol": "1.4.0"
63
+ "@drakkar.software/starfish-protocol": "1.5.0"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@legendapp/state": "^2.0.0",
@@ -1,19 +0,0 @@
1
- import type { StoreApi } from "zustand/vanilla";
2
- import type { StarfishStore } from "./zustand.js";
3
- /**
4
- * Syncs a Zustand Starfish store across browser tabs using BroadcastChannel.
5
- * Returns a cleanup function that closes the channel.
6
- */
7
- export declare function setupBroadcastSync(store: StoreApi<StarfishStore>, name: string): () => void;
8
- /**
9
- * Syncs a Zustand Starfish store across browser tabs using storage events.
10
- * Fallback for environments without BroadcastChannel.
11
- * Returns a cleanup function.
12
- */
13
- export declare function setupStorageFallback(store: StoreApi<StarfishStore>, name: string): () => void;
14
- /**
15
- * Auto-detects the best cross-tab sync mechanism and sets it up.
16
- * Uses BroadcastChannel when available, falls back to storage events.
17
- * Returns a cleanup function.
18
- */
19
- export declare function setupCrossTabSync(store: StoreApi<StarfishStore>, name: string): () => void;