@drakkar.software/starfish-client 3.0.0-alpha.2 → 3.0.0-alpha.21

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/logger.d.ts CHANGED
@@ -5,6 +5,9 @@ export interface SyncMetrics {
5
5
  conflictCount?: number;
6
6
  retryCount?: number;
7
7
  cacheHit?: boolean;
8
+ /** Elements an append-log pull dropped under `onElementError: "skip"`
9
+ * (failed verification/decryption). Omitted when none were skipped. */
10
+ skippedCount?: number;
8
11
  }
9
12
  /** Structured logger for sync operations. */
10
13
  export interface SyncLogger {
@@ -1,5 +1,5 @@
1
1
  import type { StoreApi } from "zustand/vanilla";
2
- import type { StarfishStore } from "./bindings/zustand.js";
2
+ import type { StarfishStore, StarfishLogStore } from "./bindings/zustand.js";
3
3
  /**
4
4
  * Minimal interface matching React Native's `AppState` module.
5
5
  * Pass `AppState` from `react-native` directly.
@@ -69,3 +69,30 @@ export interface MobileLifecycleOptions {
69
69
  * @returns A cleanup function that removes all event listeners.
70
70
  */
71
71
  export declare function createMobileLifecycle(store: StoreApi<StarfishStore>, deps: MobileLifecycleDeps, options?: MobileLifecycleOptions): () => void;
72
+ export interface AppendLogLifecycleOptions {
73
+ /**
74
+ * Pull new elements when the app returns to the foreground.
75
+ * Only pulls if the store is online and not already loading.
76
+ * Default: `true`.
77
+ */
78
+ pullOnForeground?: boolean;
79
+ }
80
+ /**
81
+ * Wires React Native app lifecycle events to an append-log store
82
+ * (`createStarfishLog`). A log is read-only, so this only pulls on foreground
83
+ * (there is nothing to flush on background). NetInfo connectivity changes are
84
+ * forwarded to `store.getState().setOnline()`.
85
+ *
86
+ * ```ts
87
+ * import { AppState } from "react-native"
88
+ * import NetInfo from "@react-native-community/netinfo"
89
+ * import { createStarfishLog, createAppendLogMobileLifecycle } from "@drakkar.software/starfish-client"
90
+ *
91
+ * const store = createStarfishLog({ cursor })
92
+ * const cleanup = createAppendLogMobileLifecycle(store, { appState: AppState, netInfo: NetInfo })
93
+ * useEffect(() => cleanup, [])
94
+ * ```
95
+ *
96
+ * @returns A cleanup function that removes all event listeners.
97
+ */
98
+ export declare function createAppendLogMobileLifecycle(store: StoreApi<StarfishLogStore>, deps: MobileLifecycleDeps, options?: AppendLogLifecycleOptions): () => void;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Read-modify-write a document with hash-CAS conflict retry.
3
+ *
4
+ * The everyday way to atomically edit a synced document: pull the current
5
+ * version, apply a pure `mutator` to its data, push the result with the read
6
+ * hash, and retry on a {@link ConflictError} (a concurrent writer moved the hash)
7
+ * by re-reading FRESH server state and re-applying the mutator. A missing
8
+ * document (404) is surfaced to the mutator as `{ data: null, hash: null }` so it
9
+ * can create the doc on first write.
10
+ *
11
+ * This replaces the ad-hoc `for (attempt…) { pull; mutate; try push catch
12
+ * ConflictError }` loop that applications otherwise hand-roll around every
13
+ * editable doc. The `mutator` MUST be idempotent — it re-runs on each retry — and
14
+ * returns `null` to signal a no-op (nothing changed; skip the write).
15
+ */
16
+ import { StarfishClient } from "./client.js";
17
+ /** The current state handed to a {@link DocMutator}: the document data (or `null`
18
+ * when the doc does not exist yet) and the hash to base the next push on. */
19
+ export interface DocState<T> {
20
+ data: T | null;
21
+ hash: string | null;
22
+ }
23
+ /**
24
+ * Pure transform from the current document to the next. Return the full next
25
+ * document body to write, or `null` for a no-op (the write is skipped). Runs once
26
+ * per attempt on freshly-pulled state, so it must be idempotent.
27
+ */
28
+ export type DocMutator<T> = (cur: DocState<T>) => T | null;
29
+ export interface MutateDocOptions {
30
+ /** Max push attempts before a persistent conflict propagates. Default 3. */
31
+ maxAttempts?: number;
32
+ }
33
+ /**
34
+ * Atomically read-modify-write the document at `path`. Returns the document that
35
+ * was written, or `null` if the mutator signalled a no-op. Throws the underlying
36
+ * error on a non-conflict failure, or a {@link ConflictError} if every attempt
37
+ * raced and lost.
38
+ */
39
+ export declare function mutateDoc<T extends Record<string, unknown> = Record<string, unknown>>(client: StarfishClient, path: string, mutator: DocMutator<T>, options?: MutateDocOptions): Promise<T | null>;
package/dist/sync.d.ts CHANGED
@@ -70,13 +70,41 @@ export declare class SyncManager {
70
70
  private lastCheckpoint;
71
71
  private localData;
72
72
  private aborted;
73
+ private lastFromCache;
73
74
  constructor(options: SyncManagerOptions);
74
75
  abort(): void;
75
76
  get isAborted(): boolean;
76
77
  getData(): Record<string, unknown>;
78
+ /**
79
+ * Merge a remote snapshot with local (optimistic) data using this manager's
80
+ * conflict resolver — the same resolver the push-conflict path uses. A plain
81
+ * {@link pull} overwrites the store's data with the server snapshot, which
82
+ * would drop un-pushed local writes (they live only in the store, never in
83
+ * `localData` until a push succeeds). The zustand binding calls this on pull
84
+ * while the store is dirty so those writes survive. `local` wins by the same
85
+ * rules as a push conflict.
86
+ */
87
+ resolve(local: Record<string, unknown>, remote: Record<string, unknown>): Record<string, unknown>;
77
88
  getHash(): string | null;
78
89
  /** Set the last-known server hash. Used by persistence layers to restore state across restarts. */
79
90
  setHash(hash: string | null): void;
91
+ /**
92
+ * Whether the most recent {@link pull} (or {@link seedFromCache}) was served
93
+ * from the client's offline read-through cache rather than a live server
94
+ * response. The binding surfaces this as a `stale` flag so the UI can show an
95
+ * offline indicator without treating a cache hit as "reachable". Reset to
96
+ * false by the next successful network pull.
97
+ */
98
+ getLastPullFromCache(): boolean;
99
+ /**
100
+ * Cache-first paint: seed `localData` from the client's read-through cache
101
+ * WITHOUT touching the network, decrypting in memory for E2E collections.
102
+ * Returns whether anything was seeded (false on a miss, an expired entry, or
103
+ * a decrypt failure — e.g. keyring skew). Call once on store creation before
104
+ * the initial live {@link pull}, which then supersedes the seeded snapshot.
105
+ * Requires the client to have been built with a `cache`.
106
+ */
107
+ seedFromCache(): Promise<boolean>;
80
108
  getCheckpoint(): number;
81
109
  pull(): Promise<PullResult>;
82
110
  push(data: Record<string, unknown>): Promise<{
package/dist/types.d.ts CHANGED
@@ -36,10 +36,49 @@ export interface StarfishCapProvider {
36
36
  pubHex?: string;
37
37
  }>;
38
38
  }
39
+ /**
40
+ * A minimal async key-value store the client uses as a read-through cache for
41
+ * {@link StarfishClient.pull} (offline-first reads). Host-provided so the SDK
42
+ * stays storage-agnostic — back it by `localStorage`, `AsyncStorage`, a file,
43
+ * etc. Shaped like a subset of zustand's `StateStorage` so an existing adapter
44
+ * fits.
45
+ *
46
+ * IMPORTANT — what gets stored: the client caches the RAW server response only
47
+ * (`data`/`hash`/`timestamp`). For E2E (`delegated`) collections that payload is
48
+ * the SEALED ciphertext the server holds — never the decrypted form — so this
49
+ * cache is ciphertext-at-rest by construction. Decryption always happens in
50
+ * memory on read (see {@link SyncManager}). Public/plaintext collections cache
51
+ * their plaintext, exactly as the server stores it.
52
+ */
53
+ export interface PullCache {
54
+ /** Return the previously-stored string for `key`, or null if absent. Must not throw. */
55
+ get(key: string): Promise<string | null>;
56
+ /** Store `value` under `key`. Must not throw (failures are swallowed by the client). */
57
+ set(key: string, value: string): Promise<void>;
58
+ }
39
59
  /** Options for creating a StarfishClient. */
40
60
  export interface StarfishClientOptions {
41
61
  /** Base URL of the Starfish server (e.g. "https://api.example.com/v1"). */
42
62
  baseUrl: string;
63
+ /**
64
+ * Optional namespace for a namespace-mounted server. When set, every request
65
+ * path `/{action}/…` is rewritten to `/v1/{namespace}/{action}/…` for BOTH the
66
+ * URL the client hits AND the canonical path it signs, so the signature the
67
+ * server reconstructs from the namespaced URL verifies (no rewrite layer
68
+ * needed). Mirrors the Python client's `namespace` parameter.
69
+ *
70
+ * Crucially this also rewrites the paths that namespace-unaware SDK helpers
71
+ * build internally (e.g. `starfish-keyring`'s `addCollectionRecipient`, blob
72
+ * uploads), so consumers no longer hand-prefix paths or wrap the client to
73
+ * reach a namespaced deployment. Leave unset (default) for a root-mounted
74
+ * server — paths pass through unchanged, byte-identical to before.
75
+ *
76
+ * Pass the bare namespace name (e.g. `"octochat"`); `baseUrl` then carries only
77
+ * the origin (and any reverse-proxy mount the proxy strips), not the `/v1`
78
+ * version segment. Must match `[A-Za-z0-9_-]+` and not be a reserved route name
79
+ * (`pull`, `push`, `health`, `batch`).
80
+ */
81
+ namespace?: string;
43
82
  /**
44
83
  * Cap-cert provider. When set, requests are signed with Ed25519 and carry
45
84
  * `Authorization: Cap <…>`. Omit for unauthenticated public-read collections.
@@ -47,6 +86,29 @@ export interface StarfishClientOptions {
47
86
  capProvider?: StarfishCapProvider;
48
87
  /** Optional fetch implementation (defaults to global fetch). */
49
88
  fetch?: typeof fetch;
89
+ /**
90
+ * Optional read-through cache for {@link StarfishClient.pull} — the basis for
91
+ * offline-first reads. When set, every successful non-append pull is written
92
+ * through to the cache (keyed by document path), and a pull that fails because
93
+ * the TRANSPORT is unreachable (offline / DNS / timeout — `fetch` rejects)
94
+ * falls back to the cached response, tagged so callers can tell it's stale.
95
+ *
96
+ * A real HTTP error (404/403/5xx) is a genuine server answer and always
97
+ * propagates — the cache is NOT consulted — so "no document yet" and
98
+ * "access denied" keep their meaning. Caches ciphertext for E2E collections
99
+ * (the server only ever holds sealed payloads); never decrypted data.
100
+ */
101
+ cache?: PullCache;
102
+ /**
103
+ * Optional max age (ms) for {@link cache} entries. An entry older than this is
104
+ * treated as a cache MISS on every read — both cache-first paint and the
105
+ * offline fallback — so a stale-beyond-policy snapshot is never served (the
106
+ * pull then goes to the network, or rethrows the transport error offline).
107
+ * Each cached snapshot records its write time; expiry is `now - cachedAt >
108
+ * cacheMaxAgeMs`. Omit (default) for entries that never expire — recommended
109
+ * for an offline-first app where any last-synced data beats none.
110
+ */
111
+ cacheMaxAgeMs?: number;
50
112
  /**
51
113
  * Optional list of client-side plugins. The list is stored on the client
52
114
  * instance but does not fire any hooks yet — the contract is plumbed so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakkar.software/starfish-client",
3
- "version": "3.0.0-alpha.2",
3
+ "version": "3.0.0-alpha.21",
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": "3.0.0-alpha.2"
63
+ "@drakkar.software/starfish-protocol": "3.0.0-alpha.21"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@legendapp/state": "^2.0.0",