@drakkar.software/starfish-client 1.4.1 → 1.6.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/background-sync.d.ts +16 -0
- package/dist/background-sync.js +29 -0
- package/dist/bindings/suspense.d.ts +25 -0
- package/dist/bindings/suspense.js +49 -0
- package/dist/bindings/zustand.d.ts +36 -0
- package/dist/bindings/zustand.js +35 -15
- package/dist/debounced-sync.d.ts +66 -0
- package/dist/debounced-sync.js +65 -0
- package/dist/dedup.d.ts +6 -0
- package/dist/dedup.js +35 -0
- package/dist/export.d.ts +24 -0
- package/dist/export.js +115 -0
- package/dist/hash.d.ts +10 -0
- package/dist/hash.js +34 -0
- package/dist/identity.d.ts +72 -0
- package/dist/identity.js +161 -0
- package/dist/index.d.ts +18 -3
- package/dist/index.js +10 -2
- package/dist/logger.d.ts +26 -2
- package/dist/logger.js +62 -2
- package/dist/multi-store.d.ts +135 -0
- package/dist/multi-store.js +92 -0
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +62 -0
- package/dist/resolvers.d.ts +19 -0
- package/dist/resolvers.js +57 -0
- package/dist/service-worker.d.ts +18 -0
- package/dist/service-worker.js +55 -0
- package/dist/storage/indexeddb.d.ts +17 -0
- package/dist/storage/indexeddb.js +59 -0
- package/package.json +6 -2
- package/dist/bindings/broadcast.d.ts +0 -19
- package/dist/bindings/broadcast.js +0 -65
- package/dist/bindings/react.d.ts +0 -12
- package/dist/bindings/react.js +0 -25
|
@@ -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;
|
package/dist/platform.js
ADDED
|
@@ -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/resolvers.d.ts
CHANGED
|
@@ -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")
|
|
@@ -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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakkar.software/starfish-client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/Drakkar-Software/starfish.git",
|
|
@@ -37,6 +37,10 @@
|
|
|
37
37
|
"./testing": {
|
|
38
38
|
"types": "./dist/testing.d.ts",
|
|
39
39
|
"import": "./dist/testing.js"
|
|
40
|
+
},
|
|
41
|
+
"./identity": {
|
|
42
|
+
"types": "./dist/identity.d.ts",
|
|
43
|
+
"import": "./dist/identity.js"
|
|
40
44
|
}
|
|
41
45
|
},
|
|
42
46
|
"peerDependencies": {
|
|
@@ -60,7 +64,7 @@
|
|
|
60
64
|
}
|
|
61
65
|
},
|
|
62
66
|
"dependencies": {
|
|
63
|
-
"@drakkar.software/starfish-protocol": "1.
|
|
67
|
+
"@drakkar.software/starfish-protocol": "1.5.0"
|
|
64
68
|
},
|
|
65
69
|
"devDependencies": {
|
|
66
70
|
"@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;
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Syncs a Zustand Starfish store across browser tabs using BroadcastChannel.
|
|
3
|
-
* Returns a cleanup function that closes the channel.
|
|
4
|
-
*/
|
|
5
|
-
export function setupBroadcastSync(store, name) {
|
|
6
|
-
const channel = new BroadcastChannel(`starfish-${name}`);
|
|
7
|
-
let lastReceivedData = null;
|
|
8
|
-
channel.onmessage = (event) => {
|
|
9
|
-
lastReceivedData = event.data.data;
|
|
10
|
-
store.setState({ data: event.data.data, dirty: event.data.dirty });
|
|
11
|
-
};
|
|
12
|
-
const unsub = store.subscribe((state, prev) => {
|
|
13
|
-
if (state.data === lastReceivedData)
|
|
14
|
-
return;
|
|
15
|
-
if (state.data !== prev.data || state.dirty !== prev.dirty) {
|
|
16
|
-
channel.postMessage({ data: state.data, dirty: state.dirty });
|
|
17
|
-
}
|
|
18
|
-
});
|
|
19
|
-
return () => {
|
|
20
|
-
unsub();
|
|
21
|
-
channel.close();
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Syncs a Zustand Starfish store across browser tabs using storage events.
|
|
26
|
-
* Fallback for environments without BroadcastChannel.
|
|
27
|
-
* Returns a cleanup function.
|
|
28
|
-
*/
|
|
29
|
-
export function setupStorageFallback(store, name) {
|
|
30
|
-
const storageKey = `starfish-broadcast-${name}`;
|
|
31
|
-
let lastReceivedData = null;
|
|
32
|
-
const onStorage = (e) => {
|
|
33
|
-
if (e.key !== storageKey || !e.newValue)
|
|
34
|
-
return;
|
|
35
|
-
const payload = JSON.parse(e.newValue);
|
|
36
|
-
lastReceivedData = payload.data;
|
|
37
|
-
store.setState({ data: payload.data, dirty: payload.dirty });
|
|
38
|
-
};
|
|
39
|
-
globalThis.addEventListener("storage", onStorage);
|
|
40
|
-
const unsub = store.subscribe((state, prev) => {
|
|
41
|
-
if (state.data === lastReceivedData)
|
|
42
|
-
return;
|
|
43
|
-
if (state.data !== prev.data || state.dirty !== prev.dirty) {
|
|
44
|
-
localStorage.setItem(storageKey, JSON.stringify({ data: state.data, dirty: state.dirty }));
|
|
45
|
-
}
|
|
46
|
-
});
|
|
47
|
-
return () => {
|
|
48
|
-
unsub();
|
|
49
|
-
globalThis.removeEventListener("storage", onStorage);
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Auto-detects the best cross-tab sync mechanism and sets it up.
|
|
54
|
-
* Uses BroadcastChannel when available, falls back to storage events.
|
|
55
|
-
* Returns a cleanup function.
|
|
56
|
-
*/
|
|
57
|
-
export function setupCrossTabSync(store, name) {
|
|
58
|
-
if (typeof BroadcastChannel !== "undefined") {
|
|
59
|
-
return setupBroadcastSync(store, name);
|
|
60
|
-
}
|
|
61
|
-
if (typeof globalThis.addEventListener === "function" && typeof localStorage !== "undefined") {
|
|
62
|
-
return setupStorageFallback(store, name);
|
|
63
|
-
}
|
|
64
|
-
return () => { };
|
|
65
|
-
}
|
package/dist/bindings/react.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { StoreApi } from "zustand/vanilla";
|
|
2
|
-
import type { StarfishStore, StarfishState } from "./zustand.js";
|
|
3
|
-
/** Derived sync status for UI display. */
|
|
4
|
-
export type SyncStatus = "synced" | "syncing" | "pending" | "error" | "offline";
|
|
5
|
-
/** Derive a single sync status from store state. */
|
|
6
|
-
export declare function deriveSyncStatus(state: StarfishState): SyncStatus;
|
|
7
|
-
/** Use the full Starfish store state and actions. */
|
|
8
|
-
export declare function useStarfish(store: StoreApi<StarfishStore>): StarfishStore;
|
|
9
|
-
/** Use only the synced data, with an optional selector for fine-grained subscriptions. */
|
|
10
|
-
export declare function useStarfishData<T = Record<string, unknown>>(store: StoreApi<StarfishStore>, selector?: (data: Record<string, unknown>) => T): T;
|
|
11
|
-
/** Use the derived sync status (synced | syncing | pending | error | offline). */
|
|
12
|
-
export declare function useSyncStatus(store: StoreApi<StarfishStore>): SyncStatus;
|
package/dist/bindings/react.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { useStore } from "zustand";
|
|
2
|
-
/** Derive a single sync status from store state. */
|
|
3
|
-
export function deriveSyncStatus(state) {
|
|
4
|
-
if (!state.online)
|
|
5
|
-
return "offline";
|
|
6
|
-
if (state.error)
|
|
7
|
-
return "error";
|
|
8
|
-
if (state.syncing)
|
|
9
|
-
return "syncing";
|
|
10
|
-
if (state.dirty)
|
|
11
|
-
return "pending";
|
|
12
|
-
return "synced";
|
|
13
|
-
}
|
|
14
|
-
/** Use the full Starfish store state and actions. */
|
|
15
|
-
export function useStarfish(store) {
|
|
16
|
-
return useStore(store);
|
|
17
|
-
}
|
|
18
|
-
/** Use only the synced data, with an optional selector for fine-grained subscriptions. */
|
|
19
|
-
export function useStarfishData(store, selector) {
|
|
20
|
-
return useStore(store, (state) => selector ? selector(state.data) : state.data);
|
|
21
|
-
}
|
|
22
|
-
/** Use the derived sync status (synced | syncing | pending | error | offline). */
|
|
23
|
-
export function useSyncStatus(store) {
|
|
24
|
-
return useStore(store, deriveSyncStatus);
|
|
25
|
-
}
|