@drakkar.software/starfish-client 3.0.0-alpha.10 → 3.0.0-alpha.11
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/bindings/zustand.js +22 -6
- package/dist/bindings/zustand.js.map +2 -2
- package/dist/client.d.ts +30 -13
- package/dist/index.js +22 -6
- package/dist/index.js.map +2 -2
- package/package.json +2 -2
package/dist/bindings/zustand.js
CHANGED
|
@@ -436,12 +436,16 @@ var StarfishClient = class {
|
|
|
436
436
|
return result;
|
|
437
437
|
}
|
|
438
438
|
/**
|
|
439
|
-
* Pull several
|
|
440
|
-
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
439
|
+
* Pull several documents in one round-trip via `/batch/pull`. `collections` is
|
|
440
|
+
* the list of distinct collection names; `opts.params` supplies, per collection,
|
|
441
|
+
* an ARRAY of path-param sets — one per document to read — so the SAME collection
|
|
442
|
+
* can fan in many documents (e.g. many users' `profile`) in a single request.
|
|
443
|
+
* The server auto-fills the `{identity}` param from the authenticated caller for
|
|
444
|
+
* any set that omits it, so a self-doc collection needs no params. Returns a map
|
|
445
|
+
* of collection name → an ARRAY of pulled documents (or per-document `{ error }`),
|
|
446
|
+
* in request order. Honors the configured namespace.
|
|
447
|
+
*
|
|
448
|
+
* For the common "many docs of one collection" case prefer {@link batchPullMany}.
|
|
445
449
|
*
|
|
446
450
|
* Note: not append/checkpoint-aware — for incremental append-only reads use
|
|
447
451
|
* `pull(path, { since })` (or `AppendLogCursor`) per collection.
|
|
@@ -464,6 +468,18 @@ var StarfishClient = class {
|
|
|
464
468
|
}
|
|
465
469
|
return await res.json();
|
|
466
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* Convenience over {@link batchPull} for reading MANY documents of ONE
|
|
473
|
+
* collection in a single round-trip: pass the per-document param-sets and get
|
|
474
|
+
* back the {@link BatchPullEntry} array aligned to `paramsList` by index (each
|
|
475
|
+
* entry is `{ data, hash, timestamp }` or `{ error }`). An empty `paramsList`
|
|
476
|
+
* issues no request and returns `[]`.
|
|
477
|
+
*/
|
|
478
|
+
async batchPullMany(collection, paramsList) {
|
|
479
|
+
if (paramsList.length === 0) return [];
|
|
480
|
+
const res = await this.batchPull([collection], { params: { [collection]: paramsList } });
|
|
481
|
+
return res.collections[collection] ?? [];
|
|
482
|
+
}
|
|
467
483
|
/**
|
|
468
484
|
* Push synced data to the server.
|
|
469
485
|
* @param path - The push endpoint path (e.g. "/push/users/abc/settings")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/bindings/zustand.ts", "../../../../../node_modules/.pnpm/zustand@5.0.11_@types+react@19.2.14_immer@11.1.4_react@19.2.4_use-sync-external-store@1.6.0_react@19.2.4_/node_modules/zustand/esm/middleware.mjs", "../../src/client.ts", "../../src/types.ts", "../../src/sync.ts", "../../src/validate.ts", "../../src/broadcast.ts"],
|
|
4
|
-
"sourcesContent": ["import { createStore, type StoreApi } from \"zustand/vanilla\"\nimport { useStore } from \"zustand\"\nimport {\n persist,\n subscribeWithSelector,\n createJSONStorage,\n type StateStorage,\n} from \"zustand/middleware\"\nimport type { DevtoolsOptions } from \"zustand/middleware\"\nimport { useEffect, useRef, useState, useCallback } from \"react\"\nimport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nimport { StarfishClient } from \"../client.js\"\nimport { SyncManager } from \"../sync.js\"\nimport { AppendLogCursor, type AppendElement } from \"../append-log.js\"\nimport { setupCrossTabSync, type BroadcastableStore } from \"../broadcast.js\"\nimport type { StarfishCapProvider, ConflictResolver } from \"../types.js\"\nimport type { SyncLogger } from \"../logger.js\"\nimport type { Validator } from \"../validate.js\"\n\nexport interface StarfishState {\n data: Record<string, unknown>\n syncing: boolean\n online: boolean\n dirty: boolean\n error: string | null\n /** Last-known server hash, persisted alongside `data`/`dirty`. Restored into the bound SyncManager on hydration. */\n hash: string | null\n}\n\nexport interface StarfishActions {\n pull: () => Promise<void>\n set: (modifier: (current: Record<string, unknown>) => Record<string, unknown>) => void\n /** Update data without marking dirty or triggering flush. Use for restoring pulled data into the store. */\n restore: (data: Record<string, unknown>) => void\n flush: () => Promise<void>\n setOnline: (online: boolean) => void\n}\n\nexport type StarfishStore = StarfishState & StarfishActions\n\nexport interface CreateStarfishStoreOptions {\n /** Unique name used as the persistence key (prefixed with `starfish-`) */\n name: string\n syncManager: SyncManager\n /** Pass `false` to disable persistence. Defaults to `localStorage` in browsers. */\n storage?: StateStorage | false\n /**\n * Wrap the store with Redux DevTools. Import `devtools` from `'zustand/middleware'`\n * and pass it directly \u2014 this keeps the import in your code, preventing\n * `import.meta.env` from being bundled in Metro/Hermes environments.\n *\n * @example\n * import { devtools } from 'zustand/middleware'\n * createStarfishStore({ devtools: (fn) => devtools(fn, { name: 'my-app' }) })\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n devtools?: (storeCreator: any) => any\n /** Pass `produce` from `immer` to enable draft-based mutations in `set()`. */\n produce?: <T>(base: T, recipe: (draft: T) => T | void) => T\n /**\n * Called when remote data arrives via `pull()` \u2014 **not** called for local `set()` writes.\n *\n * Use this to restore domain stores after a pull without worrying about feedback loops.\n * The callback fires **after** the Starfish store state is updated, so the store already\n * reflects the new data when this runs.\n *\n * Replaces the manual `isRestoring` flag pattern:\n * ```ts\n * createStarfishStore({\n * name: \"app\",\n * syncManager,\n * onRemoteUpdate: (data) => {\n * taskStore.setState({ tasks: data.tasks as Task[] })\n * settingsStore.setState({ settings: data.settings as Settings })\n * },\n * })\n * ```\n */\n onRemoteUpdate?: (data: Record<string, unknown>) => void\n}\n\n// Re-export DevtoolsOptions for convenience\nexport type { DevtoolsOptions }\n\nexport function createStarfishStore(\n options: CreateStarfishStoreOptions,\n): StoreApi<StarfishStore> {\n const { name, syncManager, storage } = options\n\n type NamedSet = (partial: Partial<StarfishStore>, replace?: boolean, action?: string) => void\n\n const storeCreator = (\n rawSet: StoreApi<StarfishStore>[\"setState\"],\n get: StoreApi<StarfishStore>[\"getState\"],\n ): StarfishStore => {\n const set = rawSet as NamedSet\n return {\n data: {},\n syncing: false,\n online: true,\n dirty: false,\n error: null,\n hash: null,\n\n pull: async () => {\n set({ syncing: true, error: null }, false, \"pull/start\")\n try {\n await syncManager.pull()\n const newData = syncManager.getData()\n set({ data: newData, syncing: false, hash: syncManager.getHash() }, false, \"pull/success\")\n // Fire after state update so domain stores can read the updated Starfish state if needed.\n // Calling set() inside onRemoteUpdate does NOT re-enter pull(), so no feedback loop.\n options.onRemoteUpdate?.(newData)\n } catch (err) {\n set({ syncing: false, error: err instanceof Error ? err.message : String(err) }, false, \"pull/error\")\n }\n },\n\n set: (modifier) => {\n try {\n const next = options.produce\n ? options.produce(get().data, modifier as (draft: Record<string, unknown>) => Record<string, unknown> | void)\n : modifier(get().data)\n set({ data: next, dirty: true, error: null }, false, \"set\")\n if (get().online) get().flush().catch(() => {})\n } catch (err) {\n set({ error: err instanceof Error ? err.message : String(err) }, false, \"set/error\")\n }\n },\n\n restore: (data) => {\n set({ data }, false, \"restore\")\n },\n\n flush: async () => {\n if (get().syncing || !get().dirty) return\n set({ syncing: true, error: null }, false, \"flush/start\")\n try {\n await syncManager.push(get().data)\n set({ data: syncManager.getData(), syncing: false, dirty: false, hash: syncManager.getHash() }, false, \"flush/success\")\n } catch (err) {\n set({ syncing: false, error: err instanceof Error ? err.message : String(err) }, false, \"flush/error\")\n }\n },\n\n setOnline: (online) => {\n set({ online }, false, \"setOnline\")\n if (online && get().dirty) get().flush().catch(() => {})\n },\n }}\n\n const withPersist = storage === false\n ? storeCreator\n : persist(storeCreator, {\n name: `starfish-${name}`,\n storage: storage ? createJSONStorage(() => storage) : undefined,\n partialize: (state) => ({\n data: state.data,\n dirty: state.dirty,\n hash: state.hash,\n }),\n onRehydrateStorage: () => (state) => {\n // Only restore if the manager hasn't already received a hash from a live pull/push.\n // With async storage, pull() may resolve before hydration completes \u2014 the server's\n // hash always wins over the persisted one.\n if (state?.hash && syncManager.getHash() === null) syncManager.setHash(state.hash)\n },\n })\n\n const withSelector = subscribeWithSelector(withPersist)\n\n return createStore<StarfishStore>()(\n options.devtools ? options.devtools(withSelector) : withSelector,\n )\n}\n\n// \u2500\u2500 React hooks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Derived sync status for UI display. */\nexport type SyncStatus = \"synced\" | \"syncing\" | \"pending\" | \"error\" | \"offline\"\n\n/** Derive a single sync status from store state. */\nexport function deriveSyncStatus(state: StarfishState): SyncStatus {\n if (!state.online) return \"offline\"\n if (state.error) return \"error\"\n if (state.syncing) return \"syncing\"\n if (state.dirty) return \"pending\"\n return \"synced\"\n}\n\n/**\n * Aggregate multiple sync statuses into a single worst-case status.\n * Priority (worst first): error > syncing > pending > offline > synced.\n */\nexport function aggregateSyncStatus(statuses: SyncStatus[]): SyncStatus {\n if (statuses.includes(\"error\")) return \"error\"\n if (statuses.includes(\"syncing\")) return \"syncing\"\n if (statuses.includes(\"pending\")) return \"pending\"\n if (statuses.includes(\"offline\")) return \"offline\"\n return \"synced\"\n}\n\n/** Use the full Starfish store state and actions. */\nexport function useStarfish(store: StoreApi<StarfishStore>): StarfishStore {\n return useStore(store)\n}\n\n/** Use only the synced data, with an optional selector for fine-grained subscriptions. */\nexport function useStarfishData<T = Record<string, unknown>>(\n store: StoreApi<StarfishStore>,\n selector?: (data: Record<string, unknown>) => T,\n): T {\n return useStore(store, (state) =>\n selector ? selector(state.data) : (state.data as unknown as T),\n )\n}\n\n/** Use the derived sync status (synced | syncing | pending | error | offline). */\nexport function useSyncStatus(store: StoreApi<StarfishStore>): SyncStatus {\n return useStore(store, deriveSyncStatus)\n}\n\n/**\n * Subscribe to sync status changes outside of React.\n *\n * Framework-agnostic \u2014 works in React Native, Node.js, or anywhere hooks are unavailable.\n * The callback is invoked immediately with the current status and then on every change.\n *\n * ```ts\n * const unsub = subscribeSyncStatus(store, (status) => {\n * updateStatusBar(status)\n * })\n *\n * // Later, to stop listening:\n * unsub()\n * ```\n */\nexport function subscribeSyncStatus(\n store: StoreApi<StarfishStore>,\n callback: (status: SyncStatus) => void,\n): () => void {\n let prev = deriveSyncStatus(store.getState())\n callback(prev)\n return store.subscribe((state) => {\n const next = deriveSyncStatus(state)\n if (next !== prev) {\n prev = next\n callback(next)\n }\n })\n}\n\n/** Sets up cross-tab sync for a Starfish store. Cleans up on unmount. */\nexport function useCrossTabSync(\n store: StoreApi<StarfishStore>,\n name: string,\n): void {\n useEffect(() => {\n return setupCrossTabSync(store as unknown as BroadcastableStore, name)\n }, [store, name])\n}\n\n/** Binds browser online/offline events to the store's setOnline action. Cleans up on unmount. */\nexport function useConnectivity(store: StoreApi<StarfishStore>): void {\n useEffect(() => {\n const handleOnline = () => store.getState().setOnline(true)\n const handleOffline = () => store.getState().setOnline(false)\n\n window.addEventListener(\"online\", handleOnline)\n window.addEventListener(\"offline\", handleOffline)\n\n return () => {\n window.removeEventListener(\"online\", handleOnline)\n window.removeEventListener(\"offline\", handleOffline)\n }\n }, [store])\n}\n\n/** Returns a human-readable \"last synced\" label that updates every 5 seconds. */\nexport function useLastSynced(store: StoreApi<StarfishStore>): string {\n const lastSyncedAt = useRef<number | null>(null)\n const [label, setLabel] = useState(\"Never synced\")\n\n const computeLabel = useCallback(() => {\n if (lastSyncedAt.current === null) return \"Never synced\"\n const seconds = Math.floor((Date.now() - lastSyncedAt.current) / 1000)\n if (seconds < 10) return \"Just now\"\n if (seconds < 60) return `${seconds}s ago`\n return `${Math.floor(seconds / 60)}m ago`\n }, [])\n\n // Track sync completion\n useEffect(() => {\n let prevSyncing = store.getState().syncing\n const unsub = store.subscribe((state) => {\n if (prevSyncing && !state.syncing && !state.error) {\n lastSyncedAt.current = Date.now()\n setLabel(computeLabel())\n }\n prevSyncing = state.syncing\n })\n return unsub\n }, [store, computeLabel])\n\n // Update label periodically\n useEffect(() => {\n const timer = setInterval(() => {\n setLabel(computeLabel())\n }, 5000)\n return () => clearInterval(timer)\n }, [computeLabel])\n\n return label\n}\n\n// \u2500\u2500 SyncInitializer hook \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SyncInitConfig {\n serverUrl: string\n /**\n * Optional server namespace, forwarded to the underlying {@link StarfishClient}\n * so `pullPath`/`pushPath` are rewritten to `/v1/<namespace>/\u2026` (signed AND sent).\n * Leave unset for a root-mounted server. Pass the bare name (e.g. `\"octochat\"`),\n * not `/v1/octochat` \u2014 the `/v1/` is added by the client.\n */\n namespace?: string\n capProvider?: StarfishCapProvider\n pullPath: string\n pushPath: string\n /** Pre-built encryptor for E2E collections (build via `createKeyringEncryptor`). */\n encryptor?: Encryptor\n onConflict?: ConflictResolver\n /** Called when pulled data arrives. Use to restore domain stores. */\n onData?: (data: Record<string, unknown>) => void\n storeName?: string\n storage?: StateStorage | false\n fetch?: typeof globalThis.fetch\n logger?: SyncLogger\n validate?: Validator\n}\n\n/**\n * React hook that manages the full Starfish sync lifecycle.\n *\n * Creates StarfishClient \u2192 SyncManager \u2192 Zustand store, pulls on mount,\n * calls `onData` when remote data arrives, and tears down on unmount or\n * config change.\n *\n * Pass `null` to disable sync (returns `null`).\n */\nexport function useSyncInit(config: SyncInitConfig | null): StoreApi<StarfishStore> | null {\n const [store, setStore] = useState<StoreApi<StarfishStore> | null>(null)\n const onDataRef = useRef(config?.onData)\n onDataRef.current = config?.onData\n\n useEffect(() => {\n if (!config) {\n setStore(null)\n return\n }\n\n const client = new StarfishClient({\n baseUrl: config.serverUrl,\n namespace: config.namespace,\n capProvider: config.capProvider,\n fetch: config.fetch,\n })\n\n const syncManager = new SyncManager({\n client,\n pullPath: config.pullPath,\n pushPath: config.pushPath,\n encryptor: config.encryptor,\n onConflict: config.onConflict,\n logger: config.logger,\n validate: config.validate,\n })\n\n const newStore = createStarfishStore({\n name: config.storeName ?? \"sync\",\n syncManager,\n storage: config.storage,\n // onRemoteUpdate fires only for pull() results, never for local set() writes \u2014\n // so no isRestoring flag is needed.\n onRemoteUpdate: (data) => {\n try {\n onDataRef.current?.(data)\n } catch (err) {\n newStore.setState({\n error: `onData failed: ${err instanceof Error ? err.message : String(err)}`,\n })\n }\n },\n })\n\n setStore(newStore)\n\n // Initial pull \u2014 errors are stored in state.error by the pull() action\n newStore.getState().pull().catch(() => {})\n\n return () => {\n setStore(null)\n }\n // Intentionally depend on serializable config values, not the object reference\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n config?.serverUrl,\n config?.pullPath,\n config?.pushPath,\n config?.encryptor,\n config?.storeName,\n ])\n\n return store\n}\n\n// \u2500\u2500 Append-only log binding \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// The reactive counterpart for an append-only collection, backed by an\n// `AppendLogCursor` instead of a `SyncManager`. A log only grows, so the\n// store is read-only \u2014 there is no `set`/`flush`/`dirty`/conflict surface,\n// and no `persist` middleware: the cursor owns the items + checkpoint, so\n// persist by reading `getItems()` and rehydrate by constructing the cursor\n// with `initialItems` (see `AppendLogCursor`).\n//\n// The store assumes it is the SOLE driver of its cursor: it seeds `items` from\n// `cursor.getItems()` at construction and updates only via its own `pull()`.\n// Don't also call `cursor.pull()` directly on the same cursor, or the store's\n// `items`/`checkpoint` will go stale.\n\nexport interface StarfishLogState {\n /** The full accumulated log, newest appended last. */\n items: AppendElement[]\n /** A `pull()` is in flight. */\n loading: boolean\n online: boolean\n error: string | null\n /** The cursor's checkpoint (max `ts` held). */\n checkpoint: number\n}\n\nexport interface StarfishLogActions {\n /** Pull elements newer than the checkpoint, append them, and return the new\n * batch. Errors are captured into `error` (mirroring the SyncManager store). */\n pull: () => Promise<AppendElement[]>\n setOnline: (online: boolean) => void\n}\n\nexport type StarfishLogStore = StarfishLogState & StarfishLogActions\n\nexport interface CreateStarfishLogOptions {\n cursor: AppendLogCursor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n devtools?: (storeCreator: any) => any\n}\n\nexport function createStarfishLog(\n options: CreateStarfishLogOptions,\n): StoreApi<StarfishLogStore> {\n const { cursor } = options\n\n type NamedSet = (partial: Partial<StarfishLogStore>, replace?: boolean, action?: string) => void\n\n const storeCreator = (\n rawSet: StoreApi<StarfishLogStore>[\"setState\"],\n get: StoreApi<StarfishLogStore>[\"getState\"],\n ): StarfishLogStore => {\n const set = rawSet as NamedSet\n return {\n // Seed from the cursor so a warm-started cursor's items show immediately.\n items: cursor.getItems(),\n loading: false,\n online: true,\n error: null,\n checkpoint: cursor.getCheckpoint(),\n\n pull: async () => {\n if (get().loading) return []\n set({ loading: true, error: null }, false, \"log/pull/start\")\n try {\n const batch = await cursor.pull()\n set(\n { items: cursor.getItems(), checkpoint: cursor.getCheckpoint(), loading: false },\n false,\n \"log/pull/success\",\n )\n return batch\n } catch (err) {\n set({ loading: false, error: err instanceof Error ? err.message : String(err) }, false, \"log/pull/error\")\n return []\n }\n },\n\n setOnline: (online) => {\n set({ online }, false, \"log/setOnline\")\n },\n }\n }\n\n const withSelector = subscribeWithSelector(storeCreator)\n return createStore<StarfishLogStore>()(\n options.devtools ? options.devtools(withSelector) : withSelector,\n )\n}\n\n/** Derived status for an append-log store. */\nexport type LogStatus = \"idle\" | \"loading\" | \"error\" | \"offline\"\n\n/** Derive a single status from log store state. */\nexport function deriveLogStatus(state: StarfishLogState): LogStatus {\n if (!state.online) return \"offline\"\n if (state.error) return \"error\"\n if (state.loading) return \"loading\"\n return \"idle\"\n}\n\n/** Use the full append-log store state and actions. */\nexport function useStarfishLog(store: StoreApi<StarfishLogStore>): StarfishLogStore {\n return useStore(store)\n}\n\n/** Use only the accumulated items, with an optional selector for fine-grained subscriptions. */\nexport function useStarfishLogItems<T = AppendElement[]>(\n store: StoreApi<StarfishLogStore>,\n selector?: (items: AppendElement[]) => T,\n): T {\n return useStore(store, (state) =>\n selector ? selector(state.items) : (state.items as unknown as T),\n )\n}\n\n/** Use the derived log status (idle | loading | error | offline). */\nexport function useLogStatus(store: StoreApi<StarfishLogStore>): LogStatus {\n return useStore(store, deriveLogStatus)\n}\n\n/** Subscribe to log status changes outside of React. Invoked immediately with the\n * current status, then on every change. Returns an unsubscribe function. */\nexport function subscribeLogStatus(\n store: StoreApi<StarfishLogStore>,\n callback: (status: LogStatus) => void,\n): () => void {\n let prev = deriveLogStatus(store.getState())\n callback(prev)\n return store.subscribe((state) => {\n const next = deriveLogStatus(state)\n if (next !== prev) {\n prev = next\n callback(next)\n }\n })\n}\n\n/** Binds browser online/offline events to the log store's setOnline action. Cleans up on unmount. */\nexport function useLogConnectivity(store: StoreApi<StarfishLogStore>): void {\n useEffect(() => {\n const handleOnline = () => store.getState().setOnline(true)\n const handleOffline = () => store.getState().setOnline(false)\n window.addEventListener(\"online\", handleOnline)\n window.addEventListener(\"offline\", handleOffline)\n return () => {\n window.removeEventListener(\"online\", handleOnline)\n window.removeEventListener(\"offline\", handleOffline)\n }\n }, [store])\n}\n", "const reduxImpl = (reducer, initial) => (set, _get, api) => {\n api.dispatch = (action) => {\n set((state) => reducer(state, action), false, action);\n return action;\n };\n api.dispatchFromDevtools = true;\n return { dispatch: (...args) => api.dispatch(...args), ...initial };\n};\nconst redux = reduxImpl;\n\nconst shouldDispatchFromDevtools = (api) => !!api.dispatchFromDevtools && typeof api.dispatch === \"function\";\nconst trackedConnections = /* @__PURE__ */ new Map();\nconst getTrackedConnectionState = (name) => {\n const api = trackedConnections.get(name);\n if (!api) return {};\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])\n );\n};\nconst extractConnectionInformation = (store, extensionConnector, options) => {\n if (store === void 0) {\n return {\n type: \"untracked\",\n connection: extensionConnector.connect(options)\n };\n }\n const existingConnection = trackedConnections.get(options.name);\n if (existingConnection) {\n return { type: \"tracked\", store, ...existingConnection };\n }\n const newConnection = {\n connection: extensionConnector.connect(options),\n stores: {}\n };\n trackedConnections.set(options.name, newConnection);\n return { type: \"tracked\", store, ...newConnection };\n};\nconst removeStoreFromTrackedConnections = (name, store) => {\n if (store === void 0) return;\n const connectionInfo = trackedConnections.get(name);\n if (!connectionInfo) return;\n delete connectionInfo.stores[store];\n if (Object.keys(connectionInfo.stores).length === 0) {\n trackedConnections.delete(name);\n }\n};\nconst findCallerName = (stack) => {\n var _a, _b;\n if (!stack) return void 0;\n const traceLines = stack.split(\"\\n\");\n const apiSetStateLineIndex = traceLines.findIndex(\n (traceLine) => traceLine.includes(\"api.setState\")\n );\n if (apiSetStateLineIndex < 0) return void 0;\n const callerLine = ((_a = traceLines[apiSetStateLineIndex + 1]) == null ? void 0 : _a.trim()) || \"\";\n return (_b = /.+ (.+) .+/.exec(callerLine)) == null ? void 0 : _b[1];\n};\nconst devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;\n let extensionConnector;\n try {\n extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") && window.__REDUX_DEVTOOLS_EXTENSION__;\n } catch (e) {\n }\n if (!extensionConnector) {\n return fn(set, get, api);\n }\n const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);\n let isRecording = true;\n api.setState = ((state, replace, nameOrAction) => {\n const r = set(state, replace);\n if (!isRecording) return r;\n const action = nameOrAction === void 0 ? {\n type: anonymousActionType || findCallerName(new Error().stack) || \"anonymous\"\n } : typeof nameOrAction === \"string\" ? { type: nameOrAction } : nameOrAction;\n if (store === void 0) {\n connection == null ? void 0 : connection.send(action, get());\n return r;\n }\n connection == null ? void 0 : connection.send(\n {\n ...action,\n type: `${store}/${action.type}`\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState()\n }\n );\n return r;\n });\n api.devtools = {\n cleanup: () => {\n if (connection && typeof connection.unsubscribe === \"function\") {\n connection.unsubscribe();\n }\n removeStoreFromTrackedConnections(options.name, store);\n }\n };\n const setStateFromDevtools = (...a) => {\n const originalIsRecording = isRecording;\n isRecording = false;\n set(...a);\n isRecording = originalIsRecording;\n };\n const initialState = fn(api.setState, get, api);\n if (connectionInformation.type === \"untracked\") {\n connection == null ? void 0 : connection.init(initialState);\n } else {\n connectionInformation.stores[connectionInformation.store] = api;\n connection == null ? void 0 : connection.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store2]) => [\n key,\n key === connectionInformation.store ? initialState : store2.getState()\n ])\n )\n );\n }\n if (shouldDispatchFromDevtools(api)) {\n let didWarnAboutReservedActionType = false;\n const originalDispatch = api.dispatch;\n api.dispatch = (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && args[0].type === \"__setState\" && !didWarnAboutReservedActionType) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved to set state from the devtools. Avoid using it.'\n );\n didWarnAboutReservedActionType = true;\n }\n originalDispatch(...args);\n };\n }\n connection.subscribe((message) => {\n var _a;\n switch (message.type) {\n case \"ACTION\":\n if (typeof message.payload !== \"string\") {\n console.error(\n \"[zustand devtools middleware] Unsupported action format\"\n );\n return;\n }\n return parseJsonThen(\n message.payload,\n (action) => {\n if (action.type === \"__setState\") {\n if (store === void 0) {\n setStateFromDevtools(action.state);\n return;\n }\n if (Object.keys(action.state).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format.\n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `\n );\n }\n const stateFromDevtools = action.state[store];\n if (stateFromDevtools === void 0 || stateFromDevtools === null) {\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {\n setStateFromDevtools(stateFromDevtools);\n }\n return;\n }\n if (shouldDispatchFromDevtools(api)) {\n api.dispatch(action);\n }\n }\n );\n case \"DISPATCH\":\n switch (message.payload.type) {\n case \"RESET\":\n setStateFromDevtools(initialState);\n if (store === void 0) {\n return connection == null ? void 0 : connection.init(api.getState());\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"COMMIT\":\n if (store === void 0) {\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"ROLLBACK\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n setStateFromDevtools(state[store]);\n connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n });\n case \"JUMP_TO_STATE\":\n case \"JUMP_TO_ACTION\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {\n setStateFromDevtools(state[store]);\n }\n });\n case \"IMPORT_STATE\": {\n const { nextLiftedState } = message.payload;\n const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;\n if (!lastComputedState) return;\n if (store === void 0) {\n setStateFromDevtools(lastComputedState);\n } else {\n setStateFromDevtools(lastComputedState[store]);\n }\n connection == null ? void 0 : connection.send(\n null,\n // FIXME no-any\n nextLiftedState\n );\n return;\n }\n case \"PAUSE_RECORDING\":\n return isRecording = !isRecording;\n }\n return;\n }\n });\n return initialState;\n};\nconst devtools = devtoolsImpl;\nconst parseJsonThen = (stringified, fn) => {\n let parsed;\n try {\n parsed = JSON.parse(stringified);\n } catch (e) {\n console.error(\n \"[zustand devtools middleware] Could not parse the received json\",\n e\n );\n }\n if (parsed !== void 0) fn(parsed);\n};\n\nconst subscribeWithSelectorImpl = (fn) => (set, get, api) => {\n const origSubscribe = api.subscribe;\n api.subscribe = ((selector, optListener, options) => {\n let listener = selector;\n if (optListener) {\n const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;\n let currentSlice = selector(api.getState());\n listener = (state) => {\n const nextSlice = selector(state);\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice;\n optListener(currentSlice = nextSlice, previousSlice);\n }\n };\n if (options == null ? void 0 : options.fireImmediately) {\n optListener(currentSlice, currentSlice);\n }\n }\n return origSubscribe(listener);\n });\n const initialState = fn(set, get, api);\n return initialState;\n};\nconst subscribeWithSelector = subscribeWithSelectorImpl;\n\nfunction combine(initialState, create) {\n return (...args) => Object.assign({}, initialState, create(...args));\n}\n\nfunction createJSONStorage(getStorage, options) {\n let storage;\n try {\n storage = getStorage();\n } catch (e) {\n return;\n }\n const persistStorage = {\n getItem: (name) => {\n var _a;\n const parse = (str2) => {\n if (str2 === null) {\n return null;\n }\n return JSON.parse(str2, options == null ? void 0 : options.reviver);\n };\n const str = (_a = storage.getItem(name)) != null ? _a : null;\n if (str instanceof Promise) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer)),\n removeItem: (name) => storage.removeItem(name)\n };\n return persistStorage;\n}\nconst toThenable = (fn) => (input) => {\n try {\n const result = fn(input);\n if (result instanceof Promise) {\n return result;\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result);\n },\n catch(_onRejected) {\n return this;\n }\n };\n } catch (e) {\n return {\n then(_onFulfilled) {\n return this;\n },\n catch(onRejected) {\n return toThenable(onRejected)(e);\n }\n };\n }\n};\nconst persistImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n storage: createJSONStorage(() => window.localStorage),\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n let hydrationVersion = 0;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage = options.storage;\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const setItem = () => {\n const state = options.partialize({ ...get() });\n return storage.setItem(options.name, {\n state,\n version: options.version\n });\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n return setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n return setItem();\n },\n get,\n api\n );\n api.getInitialState = () => configResult;\n let stateFromStorage;\n const hydrate = () => {\n var _a, _b;\n if (!storage) return;\n const currentVersion = ++hydrationVersion;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => {\n var _a2;\n return cb((_a2 = get()) != null ? _a2 : configResult);\n });\n const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n const migration = options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n if (migration instanceof Promise) {\n return migration.then((result) => [true, result]);\n }\n return [true, migration];\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return [false, deserializedStorageValue.state];\n }\n }\n return [false, void 0];\n }).then((migrationResult) => {\n var _a2;\n if (currentVersion !== hydrationVersion) {\n return;\n }\n const [migrated, migratedState] = migrationResult;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n if (migrated) {\n return setItem();\n }\n }).then(() => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);\n stateFromStorage = get();\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.storage) {\n storage = newOptions.storage;\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n if (!options.skipHydration) {\n hydrate();\n }\n return stateFromStorage || configResult;\n};\nconst persist = persistImpl;\n\nfunction ssrSafe(config, isSSR = typeof window === \"undefined\") {\n return (set, get, api) => {\n if (!isSSR) {\n return config(set, get, api);\n }\n const ssrSet = () => {\n throw new Error(\"Cannot set state of Zustand store in SSR\");\n };\n api.setState = ssrSet;\n return config(ssrSet, get, api);\n };\n}\n\nexport { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector, ssrSafe as unstable_ssrSafe };\n", "import type { PullResult, PushSuccess } from \"@drakkar.software/starfish-protocol\"\nimport {\n AUTHOR_PUBKEY_FIELD,\n AUTHOR_SIGNATURE_FIELD,\n DATA_FIELD,\n TS_FIELD,\n BASE_HASH_FIELD,\n PUSH_PATH_PREFIX,\n HEADER_AUTHORIZATION,\n HEADER_SIG,\n HEADER_TS,\n HEADER_NONCE,\n HEADER_ALG,\n HEADER_PUB,\n HEADER_CONTENT_TYPE,\n HEADER_ACCEPT,\n DEFAULT_ALG,\n signAppendAuthor,\n signRequest,\n stableStringify,\n type AppendAuthor,\n type SignableMethod,\n type SignableRequest,\n} from \"@drakkar.software/starfish-protocol\"\nimport type {\n StarfishClientOptions,\n StarfishCapProvider,\n} from \"./types.js\"\nimport { ConflictError, StarfishHttpError } from \"./types.js\"\n\nconst APPEND_DEFAULT_FIELD = \"items\"\n\n/** The storage `documentKey` for a push `path`: the path with the `/push/`\n * action prefix stripped (the namespace lives only in the URL). The author\n * signature binds to this key. */\nexport function stripPushPrefix(path: string): string {\n return path.startsWith(PUSH_PATH_PREFIX) ? path.slice(PUSH_PATH_PREFIX.length) : path\n}\n\n/** Result of pulling a binary blob from the server. */\nexport interface BlobPullResult {\n data: ArrayBuffer\n /** Content hash from the ETag header. Null if the server didn't include an ETag. */\n hash: string | null\n contentType: string\n}\n\n/** Result of pushing a binary blob to the server. */\nexport interface BlobPushResult {\n hash: string\n}\n\n/** Options for append-only pull \u2014 extracts a single array field from the response. */\nexport interface AppendPullOptions {\n /** Array field name in `data`. Defaults to `\"items\"`. */\n appendField?: string\n /** Only return items appended after this timestamp (ms). Sent as `?checkpoint=`. */\n since?: number\n /** Return only the last K items (applied after `since` filter). Sent as `?last=`. */\n last?: number\n}\n\n/**\n * Options for a structured (non-append) pull.\n *\n * `withKeyring: true` appends `?withKeyring=1` so the server includes the\n * collection's sibling `<collection>/_keyring` document in the response,\n * saving a cold-start round-trip. The cap-cert scope MUST cover BOTH the\n * data path and `<collection>/_keyring` \u2014 `scopes.writer(collection)` denies\n * the keyring path and will produce a 403; use `scopes.readWrite()` or grant\n * the keyring path explicitly when opting in.\n */\nexport interface PullOptions {\n /** Server timestamp of the last successful pull (ms). Sent as `?checkpoint=`. */\n checkpoint?: number\n /** Include the sibling `_keyring` document in the response. Defaults to false. */\n withKeyring?: boolean\n}\n\n/** Per-collection result in a {@link BatchPullResult}: either the pulled\n * document (`data`/`hash`/`timestamp`) or a per-collection `error` string. */\nexport interface BatchPullEntry {\n data?: unknown\n hash?: string\n timestamp?: number\n error?: string\n}\n\n/** Response of {@link StarfishClient.batchPull}: a map of requested collection\n * name \u2192 its {@link BatchPullEntry}. */\nexport interface BatchPullResult {\n collections: Record<string, BatchPullEntry>\n}\n\n/** Options for {@link StarfishClient.batchPull}. */\nexport interface BatchPullOptions {\n /** Per-collection path params, e.g. `{ notes: { teamId: \"42\" } }`. Serialized\n * to a URL-encoded JSON `params` query parameter. The `{identity}` param is\n * auto-filled by the server from the authenticated caller, so it need not be\n * supplied (and a supplied identity that isn't the caller's is rejected). */\n params?: Record<string, Record<string, string>>\n}\n\n/**\n * Base64-encode the canonical stable-stringification of a cap-cert.\n *\n * Used as the value of the `Authorization: Cap <\u2026>` header in v3.0. We rely\n * on the host's `btoa` for browsers and fall back to `Buffer` in Node so the\n * client stays free of native dependencies.\n */\nfunction encodeCapAuth(cap: unknown): string {\n const json = stableStringify(cap as Record<string, unknown>)\n if (typeof btoa === \"function\") {\n return btoa(json)\n }\n const bufCtor = (globalThis as { Buffer?: { from: (s: string, enc: string) => { toString: (enc: string) => string } } }).Buffer\n if (bufCtor) return bufCtor.from(json, \"utf-8\").toString(\"base64\")\n throw new Error(\"No base64 encoder available\")\n}\n\n/**\n * Low-level HTTP client for the Starfish sync protocol.\n * Handles auth headers and response parsing.\n */\nexport class StarfishClient {\n private readonly baseUrl: string\n private readonly namespace?: string\n private readonly capProvider?: StarfishCapProvider\n private readonly fetch: typeof globalThis.fetch\n /**\n * Installed client-side plugins. Currently stored as inert data; no\n * hooks fire yet. Extensions can inspect this list if needed.\n */\n public readonly plugins: ReadonlyArray<import(\"./types.js\").ClientPlugin>\n\n constructor(options: StarfishClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/$/, \"\")\n // Empty string \u21D2 no namespace (treat like unset), so a falsy env value\n // doesn't produce a malformed `/v1//\u2026` path.\n this.namespace = options.namespace || undefined\n this.capProvider = options.capProvider\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis)\n this.plugins = options.plugins ? [...options.plugins] : []\n }\n\n /**\n * Resolve the host portion of the URL the client will send to. The host\n * is folded into the signed canonical input as the `h` field so the\n * server can refuse a signature that was minted against a different\n * Starfish host (replay-across-servers defence).\n *\n * When `baseUrl` is relative \u2014 e.g. the consumer passed a custom `fetch`\n * that resolves relative URLs in its own context \u2014 there is no parseable\n * host; we return `\"\"` so signing still proceeds. The server-side\n * verifier will also reconstruct host from its inbound URL, so the\n * empty-host case still verifies symmetrically when both sides agree.\n */\n private signingHost(): string {\n try {\n return new URL(this.baseUrl).host\n } catch {\n return \"\"\n }\n }\n\n /**\n * Rewrite a request path for the configured namespace. A no-op when no\n * namespace is set; otherwise `/{action}/\u2026` becomes `/v1/{namespace}/{action}/\u2026`\n * (the `/v1` protocol-version segment is part of the namespaced route, matching\n * the Python client and the server's namespace mount).\n *\n * Applied to the path used for BOTH the signature and the URL so the canonical\n * path the client signs equals the path the server reconstructs from the URL.\n * Covers SDK-helper-built paths too \u2014 that's the point: a namespace-unaware\n * helper passing `/push/spaces/x/_keyring` reaches `/v1/{ns}/push/spaces/x/_keyring`.\n */\n private applyNamespace(path: string): string {\n return this.namespace ? `/v1/${this.namespace}${path}` : path\n }\n\n /**\n * Build auth headers for a request. When a `capProvider` is set, signs the\n * request with the device's Ed25519 private key and returns the v3 header\n * set (`Authorization: Cap \u2026`, `X-Starfish-Sig`, `X-Starfish-Ts`,\n * `X-Starfish-Nonce`). Empty when no provider is configured (public reads).\n *\n * Body bytes signed MUST equal the bytes sent on the wire \u2014 callers pass\n * the already-serialized body string here so signing and transmission agree.\n * The host bound into the signature is derived from `baseUrl` once per call.\n */\n private async buildAuthHeaders(\n method: SignableMethod,\n pathAndQuery: string,\n body: string | undefined,\n ): Promise<Record<string, string>> {\n if (!this.capProvider) return {}\n const capCtx = await this.capProvider.getCap()\n return this.capRequestHeaders(capCtx, method, pathAndQuery, body)\n }\n\n /**\n * Build the request-signing headers from an ALREADY-fetched cap context. Split\n * out of {@link buildAuthHeaders} so {@link append} can fetch the cap once and\n * reuse it for BOTH the author signature (over the element data) and the\n * request signature (over the body), without redeeming the cap twice \u2014 a\n * second `getCap()` could rotate keys and break the `authorPubkey ===\n * presenter` bind the server checks.\n */\n private async capRequestHeaders(\n capCtx: Awaited<ReturnType<StarfishCapProvider[\"getCap\"]>>,\n method: SignableMethod,\n pathAndQuery: string,\n body: string | undefined,\n ): Promise<Record<string, string>> {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = capCtx\n const req: SignableRequest = {\n method,\n pathAndQuery,\n body,\n host: this.signingHost(),\n }\n // The signing suite is the suite of whoever holds `devEdPrivHex`:\n // - device/member: the subject signs, so use the cert's subject suite.\n // Tolerant-reader rule (matches the server resolver): an absent\n // `subAlg` means \"same suite as the issuer\", so fall back to\n // `cap.issAlg`, not the global default.\n // - audience (public-link): the presenter is an arbitrary redeemer\n // signing with their own key, unrelated to the cert's suites, so use\n // `presenterAlg` (defaulting to ed25519). The server reads it back from\n // `X-Starfish-Alg` for audience caps.\n const signAlg =\n cap.kind === \"audience\" ? (presenterAlg ?? DEFAULT_ALG) : (cap.subAlg ?? cap.issAlg)\n const { alg, sig, ts, nonce } = await signRequest(req, devEdPrivHex, {\n alg: signAlg,\n })\n const headers: Record<string, string> = {\n [HEADER_AUTHORIZATION]: `Cap ${encodeCapAuth(cap)}`,\n [HEADER_SIG]: sig,\n [HEADER_TS]: String(ts),\n [HEADER_NONCE]: nonce,\n [HEADER_ALG]: alg,\n }\n // Audience (public-link) caps bind no single subject, so the server needs\n // the presenter's pubkey to verify the signature and check the allow-list.\n if (pubHex !== undefined) headers[HEADER_PUB] = pubHex\n return headers\n }\n\n /**\n * Resolve the author public key to attach to a signed append: the redeemer's\n * `pubHex` for an audience cap, else the cert subject `cap.sub` for a\n * device/member cap. This is the SAME key that signs the request, so a server\n * enforcing author proof can bind the stored element to its writer. Returns\n * undefined only for a (malformed) cap with neither \u2014 the append then goes\n * unsigned and a server requiring signatures rejects it.\n */\n private appendAuthorKey(\n capCtx: Awaited<ReturnType<StarfishCapProvider[\"getCap\"]>>,\n ): { authorPubHex: string; signAlg: typeof DEFAULT_ALG } | null {\n const { cap, pubHex, presenterAlg } = capCtx\n const authorPubHex = pubHex ?? cap.sub\n if (authorPubHex === undefined) return null\n const signAlg =\n cap.kind === \"audience\" ? (presenterAlg ?? DEFAULT_ALG) : (cap.subAlg ?? cap.issAlg)\n return { authorPubHex, signAlg }\n }\n\n /** Pull synced data from the server. Returns the raw `PullResult`. */\n async pull(path: string, checkpoint?: number): Promise<PullResult>\n /** Pull synced data with structured options (e.g. `{withKeyring: true}`). */\n async pull(path: string, options: PullOptions): Promise<PullResult>\n /** Pull an append-only collection. Extracts and returns `data[appendField]` as `T[]`. */\n async pull<T = unknown>(path: string, options: AppendPullOptions): Promise<T[]>\n async pull<T = unknown>(\n path: string,\n checkpointOrOptions?: number | AppendPullOptions | PullOptions,\n ): Promise<PullResult | T[]> {\n let pathAndQuery = this.applyNamespace(path)\n let appendField: string | undefined\n\n if (typeof checkpointOrOptions === \"number\") {\n if (checkpointOrOptions) pathAndQuery += `?checkpoint=${checkpointOrOptions}`\n } else if (checkpointOrOptions != null) {\n // Disambiguate AppendPullOptions vs PullOptions.\n //\n // PullOptions are identified by the presence of `withKeyring` or\n // `checkpoint` keys (which AppendPullOptions does not have \u2014 append\n // uses `since`, not `checkpoint`). Anything else, including an empty\n // `{}` object, retains the historical behavior of AppendPullOptions\n // (extracts `data.items` with `?` query).\n const opts = checkpointOrOptions as AppendPullOptions & PullOptions\n const isPullOptions =\n opts.withKeyring !== undefined || opts.checkpoint !== undefined\n const params = new URLSearchParams()\n\n if (isPullOptions) {\n if (opts.checkpoint != null && opts.checkpoint > 0) {\n params.set(\"checkpoint\", String(opts.checkpoint))\n }\n if (opts.withKeyring) {\n params.set(\"withKeyring\", \"1\")\n }\n } else {\n appendField = opts.appendField ?? APPEND_DEFAULT_FIELD\n if (opts.since != null) {\n if (opts.since < 0) throw new Error(\"since must be non-negative\")\n params.set(\"checkpoint\", String(opts.since))\n }\n if (opts.last != null) {\n if (opts.last < 0) throw new Error(\"last must be non-negative\")\n params.set(\"last\", String(opts.last))\n }\n }\n if (params.size > 0) pathAndQuery += `?${params.toString()}`\n }\n\n const url = `${this.baseUrl}${pathAndQuery}`\n const authHeaders = await this.buildAuthHeaders(\"GET\", pathAndQuery, undefined)\n\n const res = await this.fetch(url, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"application/json\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n\n const result = await res.json() as PullResult\n if (appendField !== undefined) {\n const list = (result.data as Record<string, unknown> | null)?.[appendField]\n return (Array.isArray(list) ? list : []) as T[]\n }\n return result\n }\n\n /**\n * Pull several collections in one round-trip via `/batch/pull`. `collections`\n * is the list of collection names; `opts.params` supplies path params per\n * collection (serialized to a URL-encoded JSON `params` query). The server\n * auto-fills the `{identity}` param from the authenticated caller, so per-user\n * collections need no params. Returns a map of collection name \u2192 its pulled\n * document or a per-collection `{ error }`. Honors the configured namespace.\n *\n * Note: not append/checkpoint-aware \u2014 for incremental append-only reads use\n * `pull(path, { since })` (or `AppendLogCursor`) per collection.\n */\n async batchPull(\n collections: string[],\n opts: BatchPullOptions = {},\n ): Promise<BatchPullResult> {\n const search = new URLSearchParams()\n search.set(\"collections\", collections.join(\",\"))\n if (opts.params && Object.keys(opts.params).length > 0) {\n search.set(\"params\", JSON.stringify(opts.params))\n }\n const pathAndQuery = `${this.applyNamespace(\"/batch/pull\")}?${search.toString()}`\n const url = `${this.baseUrl}${pathAndQuery}`\n const authHeaders = await this.buildAuthHeaders(\"GET\", pathAndQuery, undefined)\n\n const res = await this.fetch(url, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"application/json\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return await res.json() as BatchPullResult\n }\n\n /**\n * Push synced data to the server.\n * @param path - The push endpoint path (e.g. \"/push/users/abc/settings\")\n * @param data - The full document data to push\n * @param baseHash - Hash of the document this push is based on (null for first push)\n *\n * v3 author proof (`authorPubkey` + `authorSignature`) is passed via `author`\n * (produced by `SyncManager` when a `signer` is configured) and sent as\n * top-level body siblings of `data`, where the server verifies it.\n * @throws {ConflictError} if the server detects a hash mismatch (409)\n */\n async push(\n path: string,\n data: Record<string, unknown>,\n baseHash: string | null,\n author?: AppendAuthor,\n ): Promise<PushSuccess> {\n const body = JSON.stringify({\n [DATA_FIELD]: data,\n [BASE_HASH_FIELD]: baseHash,\n ...(author && {\n [AUTHOR_PUBKEY_FIELD]: author.authorPubkey,\n [AUTHOR_SIGNATURE_FIELD]: author.authorSignature,\n }),\n })\n\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"POST\", sendPath, body)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: \"application/json\",\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body,\n })\n\n if (res.status === 409) {\n throw new ConflictError()\n }\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<PushSuccess>\n }\n\n /**\n * Append an element to an appendOnly (`by_timestamp`) collection.\n *\n * Unlike {@link push}, appendOnly writes carry no hash/conflict check \u2014 an\n * authorized append is always accepted. Each element is stored server-side as\n * `{ts, data}` and pulls can filter by `ts` via `since`/`checkpoint`.\n *\n * @param path - the push endpoint (e.g. \"/push/events\")\n * @param data - the element payload. For a `delegated` collection, encrypt it\n * first (e.g. `createKeyringEncryptor(keyring, kem).encrypt(data)`); the\n * server stores it opaquely and never reads it.\n * @param opts.ts - optional client-supplied element timestamp (ms). Must be a\n * non-negative integer strictly greater than the latest stored element's ts\n * (else the server responds 409). Omit to let the server assign one.\n * @throws {StarfishHttpError} on a non-2xx response \u2014 e.g. 409\n * `{ error: \"non_monotonic_timestamp\" }` for a non-monotonic timestamp, or\n * `{ error: \"append_limit_exceeded\", limit }` if the collection's `maxItems`\n * cap is reached (partition by a path parameter for higher volume).\n */\n async append(\n path: string,\n data: Record<string, unknown>,\n opts: { ts?: number } = {},\n ): Promise<PushSuccess> {\n const sendPath = this.applyNamespace(path)\n const bodyObj: Record<string, unknown> = { [DATA_FIELD]: data }\n if (opts.ts !== undefined) bodyObj[TS_FIELD] = opts.ts\n\n // Author proof. Fetch the cap ONCE and reuse it for both the author\n // signature (over the element `data`) and the request signature (over the\n // final body) \u2014 see {@link capRequestHeaders}. The author fields are signed\n // with the same key that authenticates the request, so a collection with\n // `requireAuthorSignature` (the default) binds the stored element to its\n // writer. Without a cap provider the append is sent unsigned and such a\n // collection rejects it.\n const capCtx = this.capProvider ? await this.capProvider.getCap() : null\n if (capCtx) {\n const authorKey = this.appendAuthorKey(capCtx)\n if (authorKey) {\n // The signature binds the author to BOTH the element data AND the\n // document it is written to (the storage path = `path` minus the\n // `/push/` action prefix; the namespace lives only in the URL).\n const documentKey = stripPushPrefix(path)\n const { authorPubkey, authorSignature } = signAppendAuthor(\n documentKey,\n data,\n authorKey.authorPubHex,\n capCtx.devEdPrivHex,\n authorKey.signAlg,\n )\n bodyObj[AUTHOR_PUBKEY_FIELD] = authorPubkey\n bodyObj[AUTHOR_SIGNATURE_FIELD] = authorSignature\n }\n }\n\n const body = JSON.stringify(bodyObj)\n const authHeaders = capCtx\n ? await this.capRequestHeaders(capCtx, \"POST\", sendPath, body)\n : {}\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: \"application/json\",\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body,\n })\n\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<PushSuccess>\n }\n\n /**\n * Pull binary data from a blob collection.\n * Returns raw bytes with the content hash from the ETag header.\n */\n async pullBlob(path: string): Promise<BlobPullResult> {\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"GET\", sendPath, undefined)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"*/*\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n\n const etag = res.headers.get(\"ETag\")?.replace(/\"/g, \"\") ?? null\n const contentType = res.headers.get(HEADER_CONTENT_TYPE) ?? \"application/octet-stream\"\n const data = await res.arrayBuffer()\n\n return { data, hash: etag, contentType }\n }\n\n /**\n * Push binary data to a blob collection.\n * Binary collections use last-write-wins (no conflict detection).\n */\n async pushBlob(\n path: string,\n data: ArrayBuffer | Uint8Array | Blob,\n contentType: string,\n ): Promise<BlobPushResult> {\n // Blobs are not JSON; we leave body undefined when signing \u2014 server-side\n // verification is expected to use a separate path for blob uploads.\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"POST\", sendPath, undefined)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body: data as BodyInit,\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<BlobPushResult>\n }\n}\n", "import type { Alg, CapCert } from \"@drakkar.software/starfish-protocol\"\n\n/** Push conflict error (HTTP 409). */\nexport class ConflictError extends Error {\n constructor() {\n super(\"hash_mismatch\")\n this.name = \"ConflictError\"\n }\n}\n\n/** HTTP error from the Starfish server. */\nexport class StarfishHttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string\n ) {\n super(`HTTP ${status}: ${body}`)\n this.name = \"StarfishHttpError\"\n }\n}\n\n/**\n * v3.0 cap-cert provider for `StarfishClient`. Returns the device's cap-cert and\n * the matching Ed25519 private key (hex). The client calls `getCap()` once per\n * outgoing request; implementations are expected to cache so this is cheap.\n *\n * When set, the client signs every outgoing request: each call carries\n * `Authorization: Cap <base64(stableStringify(cap))>` plus `X-Starfish-Sig`,\n * `X-Starfish-Ts`, `X-Starfish-Nonce`.\n */\nexport interface StarfishCapProvider {\n /**\n * Returns the device's cap-cert and its Ed25519 private key (hex).\n * Implementations are expected to cache; the client may call this once per\n * authenticated request.\n *\n * For an `audience` (public-link) cap, which binds no single subject, also\n * return `pubHex` \u2014 the redeemer's own Ed25519 pubkey matching `devEdPrivHex`.\n * The client then sends it as `X-Starfish-Pub` so the server can verify the\n * request signature against it and check the cap's `aud` allow-list. Omit\n * `pubHex` for device/member caps (the server uses `cap.sub`).\n *\n * `presenterAlg` is the crypto suite of `devEdPrivHex` (the key that signs\n * the request). It matters only for `audience` caps, where the presenter is\n * an arbitrary redeemer whose suite is unrelated to the cap's `issAlg`; the\n * client sends it as `X-Starfish-Alg`. For device/member caps the subject's\n * suite is taken authoritatively from the verified cert, so this is ignored.\n * Defaults to `\"ed25519\"` when omitted.\n */\n getCap(): Promise<{\n cap: CapCert\n devEdPrivHex: string\n pubHex?: string\n presenterAlg?: Alg\n }>\n}\n\n/** Options for creating a StarfishClient. */\nexport interface StarfishClientOptions {\n /** Base URL of the Starfish server (e.g. \"https://api.example.com/v1\"). */\n baseUrl: string\n /**\n * Optional namespace for a namespace-mounted server. When set, every request\n * path `/{action}/\u2026` is rewritten to `/v1/{namespace}/{action}/\u2026` for BOTH the\n * URL the client hits AND the canonical path it signs, so the signature the\n * server reconstructs from the namespaced URL verifies (no rewrite layer\n * needed). Mirrors the Python client's `namespace` parameter.\n *\n * Crucially this also rewrites the paths that namespace-unaware SDK helpers\n * build internally (e.g. `starfish-keyring`'s `addCollectionRecipient`, blob\n * uploads), so consumers no longer hand-prefix paths or wrap the client to\n * reach a namespaced deployment. Leave unset (default) for a root-mounted\n * server \u2014 paths pass through unchanged, byte-identical to before.\n *\n * Pass the bare namespace name (e.g. `\"octochat\"`); `baseUrl` then carries only\n * the origin (and any reverse-proxy mount the proxy strips), not the `/v1`\n * version segment. Must match `[A-Za-z0-9_-]+` and not be a reserved route name\n * (`pull`, `push`, `health`, `batch`).\n */\n namespace?: string\n /**\n * Cap-cert provider. When set, requests are signed with Ed25519 and carry\n * `Authorization: Cap <\u2026>`. Omit for unauthenticated public-read collections.\n */\n capProvider?: StarfishCapProvider\n /** Optional fetch implementation (defaults to global fetch). */\n fetch?: typeof fetch\n /**\n * Optional list of client-side plugins. The list is stored on the client\n * instance but does not fire any hooks yet \u2014 the contract is plumbed so\n * extension packages (`starfish-identities`, `starfish-keyring`,\n * `starfish-sharing`, \u2026) can register against it later without a breaking\n * API change.\n *\n * The current set of hooks is purposely empty; extensions that need to\n * react to mint events or transport actions today can wrap the client\n * directly. Future hook additions will be additive.\n */\n plugins?: ClientPlugin[]\n}\n\n/**\n * Client-side plugin contract.\n *\n * A placeholder shape: the interface intentionally has no required hooks\n * yet; extensions declare a plugin object with `name` and opt into\n * specific lifecycle hooks once those exist. Apps wire plugins via\n * `new StarfishClient({ plugins: [...] })`.\n */\nexport interface ClientPlugin {\n /** Human-readable name. Used in error messages and audit output. */\n name: string\n /**\n * Reserved for future hook fields. Plugins typically declare only\n * `name`. Hook additions are additive \u2014 extensions implementing a\n * future hook will populate the relevant optional property without\n * affecting existing zero-hook plugins.\n */\n}\n\n/** Conflict resolver: given local and remote data, return merged result. */\nexport type ConflictResolver = (\n local: Record<string, unknown>,\n remote: Record<string, unknown>\n) => Record<string, unknown>\n", "import type { PullResult } from \"@drakkar.software/starfish-protocol\"\nimport {\n AUTHOR_PUBKEY_FIELD,\n AUTHOR_SIGNATURE_FIELD,\n PUSH_PATH_PREFIX,\n deepMerge,\n docAuthorCanonicalInput,\n getBase64,\n type AppendAuthor,\n} from \"@drakkar.software/starfish-protocol\"\nimport type { ConflictResolver } from \"./types.js\"\nimport { ConflictError } from \"./types.js\"\nimport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nimport { StarfishClient, stripPushPrefix } from \"./client.js\"\nimport type { SyncLogger } from \"./logger.js\"\nimport type { Validator } from \"./validate.js\"\nimport { ValidationError } from \"./validate.js\"\n\nexport class AbortError extends Error {\n constructor() {\n super(\"SyncManager was aborted\")\n this.name = \"AbortError\"\n }\n}\n\n/**\n * v3.0 author-signature plumbing for `SyncManager`.\n *\n * Returns the device's Ed25519 public key (hex) and a function that signs\n * arbitrary payload bytes. `SyncManager` calls `getSigner()` once per push\n * and uses the returned `sign` to produce a base64-encoded signature over\n * the canonical stringification of the encrypted payload (sans author fields).\n *\n * Implementations typically wrap the same Ed25519 private key used by\n * `StarfishCapProvider` so that `cap.sub === devEdPubHex`.\n */\nexport interface SyncSigner {\n /**\n * Returns the device's `cap.sub` (Ed25519 pubkey, hex) and a payload signer.\n * The `sign` function receives the canonical signing input bytes and must\n * return the raw 64-byte Ed25519 signature.\n */\n getSigner(): Promise<{ devEdPubHex: string; sign(payload: Uint8Array): Promise<Uint8Array> }>\n}\n\n\nexport interface SyncManagerOptions {\n client: StarfishClient\n pullPath: string\n pushPath: string\n /** Custom conflict resolver. Defaults to remote-wins deep merge. Arrays are atomic. */\n onConflict?: ConflictResolver\n /** Max conflict retry attempts (default: 3). */\n maxRetries?: number\n /**\n * Encryptor for client-side E2E encryption. For v3 `delegated` collections,\n * build it via `createKeyringEncryptor(keyring, deviceKemKeys)`.\n */\n encryptor?: Encryptor\n /**\n * v3 author-signature plumbing. When set, every push attaches\n * `authorPubkey` (= `cap.sub`) and `authorSignature` (= base64 Ed25519 over\n * stable-stringify of the encrypted payload minus author fields).\n */\n signer?: SyncSigner\n /** Structured logger for sync events. */\n logger?: SyncLogger\n /** Name passed to logger methods (default: derived from pullPath). */\n loggerName?: string\n /** Validate data before push. Throws ValidationError on failure. */\n validate?: Validator\n}\n\nexport class SyncManager {\n private readonly client: StarfishClient\n private readonly pullPath: string\n private readonly pushPath: string\n private readonly onConflict: ConflictResolver\n private readonly maxRetries: number\n private readonly encryptor: Encryptor | null\n private readonly signer?: SyncSigner\n private readonly logger?: SyncLogger\n private readonly loggerName: string\n private readonly validate?: Validator\n\n private lastHash: string | null = null\n private lastCheckpoint: number = 0\n private localData: Record<string, unknown> = {}\n private aborted: boolean = false\n\n constructor(options: SyncManagerOptions) {\n this.client = options.client\n this.pullPath = options.pullPath\n this.pushPath = options.pushPath\n this.onConflict = options.onConflict ?? deepMerge\n this.maxRetries = options.maxRetries ?? 3\n this.signer = options.signer\n this.logger = options.logger\n this.loggerName = options.loggerName ?? options.pullPath.split(\"/\").filter(Boolean).pop() ?? options.pullPath\n this.validate = options.validate\n this.encryptor = options.encryptor ?? null\n }\n\n abort(): void {\n this.aborted = true\n }\n\n get isAborted(): boolean {\n return this.aborted\n }\n\n getData(): Record<string, unknown> {\n return { ...this.localData }\n }\n\n getHash(): string | null {\n return this.lastHash\n }\n\n /** Set the last-known server hash. Used by persistence layers to restore state across restarts. */\n setHash(hash: string | null): void {\n this.lastHash = hash\n }\n\n getCheckpoint(): number {\n return this.lastCheckpoint\n }\n\n async pull(): Promise<PullResult> {\n if (this.aborted) throw new AbortError()\n this.logger?.pullStart(this.loggerName)\n const start = performance.now()\n try {\n // NOTE: `SyncManager.pull` does NOT auto-enable `withKeyring`. Clients\n // that drive the keyring helpers from `recipients.ts` and want to save\n // the cold-start round-trip should call `client.pull(path, {withKeyring: true})`\n // directly. We keep `SyncManager` keyring-agnostic so it stays usable\n // for collections that don't use delegated encryption.\n const result = await this.client.pull(this.pullPath, this.lastCheckpoint)\n if (this.aborted) throw new AbortError()\n\n if (this.encryptor) {\n const decrypted = await this.encryptor.decrypt(result.data)\n if (this.aborted) throw new AbortError()\n this.localData = decrypted\n result.data = decrypted\n } else if (this.lastCheckpoint > 0) {\n this.localData = deepMerge(this.localData, result.data)\n result.data = this.localData\n } else {\n this.localData = result.data\n }\n\n this.lastHash = result.hash\n this.lastCheckpoint = result.timestamp\n this.logger?.pullSuccess(this.loggerName, Math.round(performance.now() - start))\n return result\n } catch (err) {\n this.logger?.pullError(this.loggerName, err instanceof Error ? err.message : String(err))\n throw err\n }\n }\n\n async push(data: Record<string, unknown>): Promise<{ hash: string; timestamp: number }> {\n if (this.aborted) throw new AbortError()\n if (this.validate) {\n const result = this.validate(data)\n if (result !== true) throw new ValidationError(result)\n }\n this.logger?.pushStart(this.loggerName)\n const start = performance.now()\n let attempt = 0\n let pendingData = data\n\n while (attempt <= this.maxRetries) {\n try {\n const sealed = this.encryptor\n ? await this.encryptor.encrypt(pendingData)\n : pendingData\n if (this.aborted) throw new AbortError()\n\n // v3.0 signer path: sign the document author proof over the doc-author\n // canonical input (domain-tagged, bound to documentKey) and pass it as\n // top-level body siblings of `data` (NOT inside `data`), where the server\n // verifies it and stores the raw author pubkey.\n let author: AppendAuthor | undefined\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const documentKey = stripPushPrefix(this.pushPath)\n const canonical = docAuthorCanonicalInput(documentKey, sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n author = {\n [AUTHOR_PUBKEY_FIELD]: devEdPubHex,\n [AUTHOR_SIGNATURE_FIELD]: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n sealed as Record<string, unknown>,\n this.lastHash,\n author,\n )\n if (this.aborted) throw new AbortError()\n this.lastHash = result.hash\n this.lastCheckpoint = result.timestamp\n this.localData = pendingData\n this.logger?.pushSuccess(this.loggerName, Math.round(performance.now() - start))\n return result\n } catch (err) {\n if (err instanceof AbortError) throw err\n if (!(err instanceof ConflictError) || attempt >= this.maxRetries) {\n this.logger?.pushError(this.loggerName, err instanceof Error ? err.message : String(err))\n throw err\n }\n this.logger?.conflict(this.loggerName, attempt + 1)\n try {\n const remote = await this.client.pull(this.pullPath)\n if (this.aborted) throw new AbortError()\n const remoteData = this.encryptor\n ? await this.encryptor.decrypt(remote.data)\n : remote.data\n if (this.aborted) throw new AbortError()\n this.lastHash = remote.hash\n this.lastCheckpoint = remote.timestamp\n pendingData = this.onConflict(pendingData, remoteData)\n } catch (resolveErr) {\n if (resolveErr instanceof AbortError) throw resolveErr\n const msg = resolveErr instanceof Error ? resolveErr.message : String(resolveErr)\n this.logger?.pushError(this.loggerName, `Conflict resolution failed (attempt ${attempt + 1}): ${msg}`)\n throw resolveErr\n }\n await new Promise<void>(resolve => setTimeout(resolve, Math.min(100 * Math.pow(2, attempt), 2000) + Math.random() * 100))\n attempt++\n }\n }\n throw new ConflictError()\n }\n\n async update(\n modifier: (current: Record<string, unknown>) => Record<string, unknown>\n ): Promise<{ hash: string; timestamp: number }> {\n await this.pull()\n const updated = modifier(this.localData)\n return this.push(updated)\n }\n}\n", "/** Validation result: true if valid, or an array of error messages. */\nexport type ValidationResult = true | string[]\n\n/** A function that validates data before push. */\nexport type Validator = (data: Record<string, unknown>) => ValidationResult\n\n/** Error thrown when pre-push validation fails. */\nexport class ValidationError extends Error {\n constructor(public readonly errors: string[]) {\n super(`Validation failed: ${errors.join(\"; \")}`)\n this.name = \"ValidationError\"\n }\n}\n\n/**\n * Creates a validator from a JSON Schema object.\n * Requires an Ajv-compatible validate function.\n *\n * @example\n * ```ts\n * import Ajv from \"ajv\"\n * const ajv = new Ajv()\n * const validator = createSchemaValidator(ajv, mySchema)\n * ```\n */\nexport function createSchemaValidator(\n ajv: { compile: (schema: object) => { (data: unknown): boolean; errors?: unknown }; errorsText: (errors?: unknown) => string },\n schema: object,\n): Validator {\n const validate = ajv.compile(schema)\n return (data) => {\n if (validate(data)) return true\n return [ajv.errorsText(validate.errors)]\n }\n}\n", "/** Minimal store interface for cross-tab sync. Works with both Zustand and Legend bindings. */\nexport interface BroadcastableStore {\n getState(): { data: Record<string, unknown>; dirty: boolean }\n setState(partial: { data: Record<string, unknown>; dirty: boolean }): void\n subscribe(listener: (state: { data: Record<string, unknown>; dirty: boolean }, prev: { data: Record<string, unknown>; dirty: boolean }) => void): () => void\n}\n\ninterface BroadcastPayload {\n data: Record<string, unknown>\n dirty: boolean\n}\n\n/**\n * Syncs a Starfish store across browser tabs using BroadcastChannel.\n * Works with any store that has getState/setState/subscribe (Zustand, Legend adapters, etc.).\n * Returns a cleanup function that closes the channel.\n */\nexport function setupBroadcastSync(\n store: BroadcastableStore,\n name: string,\n): () => void {\n const channel = new BroadcastChannel(`starfish-${name}`)\n let lastReceivedData: Record<string, unknown> | null = null\n\n channel.onmessage = (event: MessageEvent<unknown>) => {\n const payload = event.data as BroadcastPayload | undefined\n if (!payload || typeof payload !== \"object\" || !payload.data || typeof payload.data !== \"object\") return\n lastReceivedData = payload.data\n store.setState({ data: payload.data, dirty: !!payload.dirty })\n }\n\n const unsub = store.subscribe((state, prev) => {\n if (state.data === lastReceivedData) return\n if (state.data !== prev.data || state.dirty !== prev.dirty) {\n try {\n channel.postMessage({ data: state.data, dirty: state.dirty } satisfies BroadcastPayload)\n } catch { /* non-serializable data \u2014 skip broadcast */ }\n }\n })\n\n return () => {\n unsub()\n channel.close()\n }\n}\n\n/**\n * Syncs a Starfish store across browser tabs using storage events.\n * Fallback for environments without BroadcastChannel.\n * Returns a cleanup function.\n */\nexport function setupStorageFallback(\n store: BroadcastableStore,\n name: string,\n): () => void {\n const storageKey = `starfish-broadcast-${name}`\n let lastReceivedData: Record<string, unknown> | null = null\n\n const onStorage = (e: StorageEvent) => {\n if (e.key !== storageKey || !e.newValue) return\n let payload: BroadcastPayload\n try {\n payload = JSON.parse(e.newValue)\n } catch {\n return\n }\n if (!payload || typeof payload !== \"object\" || !payload.data || typeof payload.data !== \"object\") return\n lastReceivedData = payload.data\n store.setState({ data: payload.data, dirty: !!payload.dirty })\n }\n\n globalThis.addEventListener(\"storage\", onStorage)\n\n const unsub = store.subscribe((state, prev) => {\n if (state.data === lastReceivedData) return\n if (state.data !== prev.data || state.dirty !== prev.dirty) {\n try {\n localStorage.setItem(\n storageKey,\n JSON.stringify({ data: state.data, dirty: state.dirty } satisfies BroadcastPayload),\n )\n } catch { /* quota exceeded or non-serializable \u2014 skip */ }\n }\n })\n\n return () => {\n unsub()\n globalThis.removeEventListener(\"storage\", onStorage)\n }\n}\n\n/**\n * Auto-detects the best cross-tab sync mechanism and sets it up.\n * Uses BroadcastChannel when available, falls back to storage events.\n * Returns a cleanup function.\n */\nexport function setupCrossTabSync(\n store: BroadcastableStore,\n name: string,\n): () => void {\n if (typeof BroadcastChannel !== \"undefined\") {\n return setupBroadcastSync(store, name)\n }\n if (typeof globalThis.addEventListener === \"function\" && typeof localStorage !== \"undefined\") {\n return setupStorageFallback(store, name)\n }\n return () => {}\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,mBAAkC;AAC3C,SAAS,gBAAgB;;;ACqPzB,IAAM,4BAA4B,CAAC,OAAO,CAAC,KAAK,KAAK,QAAQ;AAC3D,QAAM,gBAAgB,IAAI;AAC1B,MAAI,aAAa,CAAC,UAAU,aAAa,YAAY;AACnD,QAAI,WAAW;AACf,QAAI,aAAa;AACf,YAAM,cAAc,WAAW,OAAO,SAAS,QAAQ,eAAe,OAAO;AAC7E,UAAI,eAAe,SAAS,IAAI,SAAS,CAAC;AAC1C,iBAAW,CAAC,UAAU;AACpB,cAAM,YAAY,SAAS,KAAK;AAChC,YAAI,CAAC,WAAW,cAAc,SAAS,GAAG;AACxC,gBAAM,gBAAgB;AACtB,sBAAY,eAAe,WAAW,aAAa;AAAA,QACrD;AAAA,MACF;AACA,UAAI,WAAW,OAAO,SAAS,QAAQ,iBAAiB;AACtD,oBAAY,cAAc,YAAY;AAAA,MACxC;AAAA,IACF;AACA,WAAO,cAAc,QAAQ;AAAA,EAC/B;AACA,QAAM,eAAe,GAAG,KAAK,KAAK,GAAG;AACrC,SAAO;AACT;AACA,IAAM,wBAAwB;AAM9B,SAAS,k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WAAW,QAAQ,SAAS,YAAY,IAAI;AAAA,EACtD;AACF;AAMO,SAAS,gBAAgB,OAAoC;AAClE,MAAI,CAAC,MAAM,OAAQ,QAAO;AAC1B,MAAI,MAAM,MAAO,QAAO;AACxB,MAAI,MAAM,QAAS,QAAO;AAC1B,SAAO;AACT;AAGO,SAAS,eAAe,OAAqD;AAClF,SAAO,SAAS,KAAK;AACvB;AAGO,SAAS,oBACd,OACA,UACG;AACH,SAAO;AAAA,IAAS;AAAA,IAAO,CAAC,UACtB,WAAW,SAAS,MAAM,KAAK,IAAK,MAAM;AAAA,EAC5C;AACF;AAGO,SAAS,aAAa,OAA8C;AACzE,SAAO,SAAS,OAAO,eAAe;AACxC;AAIO,SAAS,mBACd,OACA,UACY;AACZ,MAAI,OAAO,gBAAgB,MAAM,SAAS,CAAC;AAC3C,WAAS,IAAI;AACb,SAAO,MAAM,UAAU,CAAC,UAAU;AAChC,UAAM,OAAO,gBAAgB,KAAK;AAClC,QAAI,SAAS,MAAM;AACjB,aAAO;AACP,eAAS,IAAI;AAAA,IACf;AAAA,EACF,CAAC;AACH;AAGO,SAAS,mBAAmB,OAAyC;AAC1E,YAAU,MAAM;AACd,UAAM,eAAe,MAAM,MAAM,SAAS,EAAE,UAAU,IAAI;AAC1D,UAAM,gBAAgB,MAAM,MAAM,SAAS,EAAE,UAAU,KAAK;AAC5D,WAAO,iBAAiB,UAAU,YAAY;AAC9C,WAAO,iBAAiB,WAAW,aAAa;AAChD,WAAO,MAAM;AACX,aAAO,oBAAoB,UAAU,YAAY;AACjD,aAAO,oBAAoB,WAAW,aAAa;AAAA,IACrD;AAAA,EACF,GAAG,CAAC,KAAK,CAAC;AACZ;",
|
|
4
|
+
"sourcesContent": ["import { createStore, type StoreApi } from \"zustand/vanilla\"\nimport { useStore } from \"zustand\"\nimport {\n persist,\n subscribeWithSelector,\n createJSONStorage,\n type StateStorage,\n} from \"zustand/middleware\"\nimport type { DevtoolsOptions } from \"zustand/middleware\"\nimport { useEffect, useRef, useState, useCallback } from \"react\"\nimport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nimport { StarfishClient } from \"../client.js\"\nimport { SyncManager } from \"../sync.js\"\nimport { AppendLogCursor, type AppendElement } from \"../append-log.js\"\nimport { setupCrossTabSync, type BroadcastableStore } from \"../broadcast.js\"\nimport type { StarfishCapProvider, ConflictResolver } from \"../types.js\"\nimport type { SyncLogger } from \"../logger.js\"\nimport type { Validator } from \"../validate.js\"\n\nexport interface StarfishState {\n data: Record<string, unknown>\n syncing: boolean\n online: boolean\n dirty: boolean\n error: string | null\n /** Last-known server hash, persisted alongside `data`/`dirty`. Restored into the bound SyncManager on hydration. */\n hash: string | null\n}\n\nexport interface StarfishActions {\n pull: () => Promise<void>\n set: (modifier: (current: Record<string, unknown>) => Record<string, unknown>) => void\n /** Update data without marking dirty or triggering flush. Use for restoring pulled data into the store. */\n restore: (data: Record<string, unknown>) => void\n flush: () => Promise<void>\n setOnline: (online: boolean) => void\n}\n\nexport type StarfishStore = StarfishState & StarfishActions\n\nexport interface CreateStarfishStoreOptions {\n /** Unique name used as the persistence key (prefixed with `starfish-`) */\n name: string\n syncManager: SyncManager\n /** Pass `false` to disable persistence. Defaults to `localStorage` in browsers. */\n storage?: StateStorage | false\n /**\n * Wrap the store with Redux DevTools. Import `devtools` from `'zustand/middleware'`\n * and pass it directly \u2014 this keeps the import in your code, preventing\n * `import.meta.env` from being bundled in Metro/Hermes environments.\n *\n * @example\n * import { devtools } from 'zustand/middleware'\n * createStarfishStore({ devtools: (fn) => devtools(fn, { name: 'my-app' }) })\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n devtools?: (storeCreator: any) => any\n /** Pass `produce` from `immer` to enable draft-based mutations in `set()`. */\n produce?: <T>(base: T, recipe: (draft: T) => T | void) => T\n /**\n * Called when remote data arrives via `pull()` \u2014 **not** called for local `set()` writes.\n *\n * Use this to restore domain stores after a pull without worrying about feedback loops.\n * The callback fires **after** the Starfish store state is updated, so the store already\n * reflects the new data when this runs.\n *\n * Replaces the manual `isRestoring` flag pattern:\n * ```ts\n * createStarfishStore({\n * name: \"app\",\n * syncManager,\n * onRemoteUpdate: (data) => {\n * taskStore.setState({ tasks: data.tasks as Task[] })\n * settingsStore.setState({ settings: data.settings as Settings })\n * },\n * })\n * ```\n */\n onRemoteUpdate?: (data: Record<string, unknown>) => void\n}\n\n// Re-export DevtoolsOptions for convenience\nexport type { DevtoolsOptions }\n\nexport function createStarfishStore(\n options: CreateStarfishStoreOptions,\n): StoreApi<StarfishStore> {\n const { name, syncManager, storage } = options\n\n type NamedSet = (partial: Partial<StarfishStore>, replace?: boolean, action?: string) => void\n\n const storeCreator = (\n rawSet: StoreApi<StarfishStore>[\"setState\"],\n get: StoreApi<StarfishStore>[\"getState\"],\n ): StarfishStore => {\n const set = rawSet as NamedSet\n return {\n data: {},\n syncing: false,\n online: true,\n dirty: false,\n error: null,\n hash: null,\n\n pull: async () => {\n set({ syncing: true, error: null }, false, \"pull/start\")\n try {\n await syncManager.pull()\n const newData = syncManager.getData()\n set({ data: newData, syncing: false, hash: syncManager.getHash() }, false, \"pull/success\")\n // Fire after state update so domain stores can read the updated Starfish state if needed.\n // Calling set() inside onRemoteUpdate does NOT re-enter pull(), so no feedback loop.\n options.onRemoteUpdate?.(newData)\n } catch (err) {\n set({ syncing: false, error: err instanceof Error ? err.message : String(err) }, false, \"pull/error\")\n }\n },\n\n set: (modifier) => {\n try {\n const next = options.produce\n ? options.produce(get().data, modifier as (draft: Record<string, unknown>) => Record<string, unknown> | void)\n : modifier(get().data)\n set({ data: next, dirty: true, error: null }, false, \"set\")\n if (get().online) get().flush().catch(() => {})\n } catch (err) {\n set({ error: err instanceof Error ? err.message : String(err) }, false, \"set/error\")\n }\n },\n\n restore: (data) => {\n set({ data }, false, \"restore\")\n },\n\n flush: async () => {\n if (get().syncing || !get().dirty) return\n set({ syncing: true, error: null }, false, \"flush/start\")\n try {\n await syncManager.push(get().data)\n set({ data: syncManager.getData(), syncing: false, dirty: false, hash: syncManager.getHash() }, false, \"flush/success\")\n } catch (err) {\n set({ syncing: false, error: err instanceof Error ? err.message : String(err) }, false, \"flush/error\")\n }\n },\n\n setOnline: (online) => {\n set({ online }, false, \"setOnline\")\n if (online && get().dirty) get().flush().catch(() => {})\n },\n }}\n\n const withPersist = storage === false\n ? storeCreator\n : persist(storeCreator, {\n name: `starfish-${name}`,\n storage: storage ? createJSONStorage(() => storage) : undefined,\n partialize: (state) => ({\n data: state.data,\n dirty: state.dirty,\n hash: state.hash,\n }),\n onRehydrateStorage: () => (state) => {\n // Only restore if the manager hasn't already received a hash from a live pull/push.\n // With async storage, pull() may resolve before hydration completes \u2014 the server's\n // hash always wins over the persisted one.\n if (state?.hash && syncManager.getHash() === null) syncManager.setHash(state.hash)\n },\n })\n\n const withSelector = subscribeWithSelector(withPersist)\n\n return createStore<StarfishStore>()(\n options.devtools ? options.devtools(withSelector) : withSelector,\n )\n}\n\n// \u2500\u2500 React hooks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Derived sync status for UI display. */\nexport type SyncStatus = \"synced\" | \"syncing\" | \"pending\" | \"error\" | \"offline\"\n\n/** Derive a single sync status from store state. */\nexport function deriveSyncStatus(state: StarfishState): SyncStatus {\n if (!state.online) return \"offline\"\n if (state.error) return \"error\"\n if (state.syncing) return \"syncing\"\n if (state.dirty) return \"pending\"\n return \"synced\"\n}\n\n/**\n * Aggregate multiple sync statuses into a single worst-case status.\n * Priority (worst first): error > syncing > pending > offline > synced.\n */\nexport function aggregateSyncStatus(statuses: SyncStatus[]): SyncStatus {\n if (statuses.includes(\"error\")) return \"error\"\n if (statuses.includes(\"syncing\")) return \"syncing\"\n if (statuses.includes(\"pending\")) return \"pending\"\n if (statuses.includes(\"offline\")) return \"offline\"\n return \"synced\"\n}\n\n/** Use the full Starfish store state and actions. */\nexport function useStarfish(store: StoreApi<StarfishStore>): StarfishStore {\n return useStore(store)\n}\n\n/** Use only the synced data, with an optional selector for fine-grained subscriptions. */\nexport function useStarfishData<T = Record<string, unknown>>(\n store: StoreApi<StarfishStore>,\n selector?: (data: Record<string, unknown>) => T,\n): T {\n return useStore(store, (state) =>\n selector ? selector(state.data) : (state.data as unknown as T),\n )\n}\n\n/** Use the derived sync status (synced | syncing | pending | error | offline). */\nexport function useSyncStatus(store: StoreApi<StarfishStore>): SyncStatus {\n return useStore(store, deriveSyncStatus)\n}\n\n/**\n * Subscribe to sync status changes outside of React.\n *\n * Framework-agnostic \u2014 works in React Native, Node.js, or anywhere hooks are unavailable.\n * The callback is invoked immediately with the current status and then on every change.\n *\n * ```ts\n * const unsub = subscribeSyncStatus(store, (status) => {\n * updateStatusBar(status)\n * })\n *\n * // Later, to stop listening:\n * unsub()\n * ```\n */\nexport function subscribeSyncStatus(\n store: StoreApi<StarfishStore>,\n callback: (status: SyncStatus) => void,\n): () => void {\n let prev = deriveSyncStatus(store.getState())\n callback(prev)\n return store.subscribe((state) => {\n const next = deriveSyncStatus(state)\n if (next !== prev) {\n prev = next\n callback(next)\n }\n })\n}\n\n/** Sets up cross-tab sync for a Starfish store. Cleans up on unmount. */\nexport function useCrossTabSync(\n store: StoreApi<StarfishStore>,\n name: string,\n): void {\n useEffect(() => {\n return setupCrossTabSync(store as unknown as BroadcastableStore, name)\n }, [store, name])\n}\n\n/** Binds browser online/offline events to the store's setOnline action. Cleans up on unmount. */\nexport function useConnectivity(store: StoreApi<StarfishStore>): void {\n useEffect(() => {\n const handleOnline = () => store.getState().setOnline(true)\n const handleOffline = () => store.getState().setOnline(false)\n\n window.addEventListener(\"online\", handleOnline)\n window.addEventListener(\"offline\", handleOffline)\n\n return () => {\n window.removeEventListener(\"online\", handleOnline)\n window.removeEventListener(\"offline\", handleOffline)\n }\n }, [store])\n}\n\n/** Returns a human-readable \"last synced\" label that updates every 5 seconds. */\nexport function useLastSynced(store: StoreApi<StarfishStore>): string {\n const lastSyncedAt = useRef<number | null>(null)\n const [label, setLabel] = useState(\"Never synced\")\n\n const computeLabel = useCallback(() => {\n if (lastSyncedAt.current === null) return \"Never synced\"\n const seconds = Math.floor((Date.now() - lastSyncedAt.current) / 1000)\n if (seconds < 10) return \"Just now\"\n if (seconds < 60) return `${seconds}s ago`\n return `${Math.floor(seconds / 60)}m ago`\n }, [])\n\n // Track sync completion\n useEffect(() => {\n let prevSyncing = store.getState().syncing\n const unsub = store.subscribe((state) => {\n if (prevSyncing && !state.syncing && !state.error) {\n lastSyncedAt.current = Date.now()\n setLabel(computeLabel())\n }\n prevSyncing = state.syncing\n })\n return unsub\n }, [store, computeLabel])\n\n // Update label periodically\n useEffect(() => {\n const timer = setInterval(() => {\n setLabel(computeLabel())\n }, 5000)\n return () => clearInterval(timer)\n }, [computeLabel])\n\n return label\n}\n\n// \u2500\u2500 SyncInitializer hook \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SyncInitConfig {\n serverUrl: string\n /**\n * Optional server namespace, forwarded to the underlying {@link StarfishClient}\n * so `pullPath`/`pushPath` are rewritten to `/v1/<namespace>/\u2026` (signed AND sent).\n * Leave unset for a root-mounted server. Pass the bare name (e.g. `\"octochat\"`),\n * not `/v1/octochat` \u2014 the `/v1/` is added by the client.\n */\n namespace?: string\n capProvider?: StarfishCapProvider\n pullPath: string\n pushPath: string\n /** Pre-built encryptor for E2E collections (build via `createKeyringEncryptor`). */\n encryptor?: Encryptor\n onConflict?: ConflictResolver\n /** Called when pulled data arrives. Use to restore domain stores. */\n onData?: (data: Record<string, unknown>) => void\n storeName?: string\n storage?: StateStorage | false\n fetch?: typeof globalThis.fetch\n logger?: SyncLogger\n validate?: Validator\n}\n\n/**\n * React hook that manages the full Starfish sync lifecycle.\n *\n * Creates StarfishClient \u2192 SyncManager \u2192 Zustand store, pulls on mount,\n * calls `onData` when remote data arrives, and tears down on unmount or\n * config change.\n *\n * Pass `null` to disable sync (returns `null`).\n */\nexport function useSyncInit(config: SyncInitConfig | null): StoreApi<StarfishStore> | null {\n const [store, setStore] = useState<StoreApi<StarfishStore> | null>(null)\n const onDataRef = useRef(config?.onData)\n onDataRef.current = config?.onData\n\n useEffect(() => {\n if (!config) {\n setStore(null)\n return\n }\n\n const client = new StarfishClient({\n baseUrl: config.serverUrl,\n namespace: config.namespace,\n capProvider: config.capProvider,\n fetch: config.fetch,\n })\n\n const syncManager = new SyncManager({\n client,\n pullPath: config.pullPath,\n pushPath: config.pushPath,\n encryptor: config.encryptor,\n onConflict: config.onConflict,\n logger: config.logger,\n validate: config.validate,\n })\n\n const newStore = createStarfishStore({\n name: config.storeName ?? \"sync\",\n syncManager,\n storage: config.storage,\n // onRemoteUpdate fires only for pull() results, never for local set() writes \u2014\n // so no isRestoring flag is needed.\n onRemoteUpdate: (data) => {\n try {\n onDataRef.current?.(data)\n } catch (err) {\n newStore.setState({\n error: `onData failed: ${err instanceof Error ? err.message : String(err)}`,\n })\n }\n },\n })\n\n setStore(newStore)\n\n // Initial pull \u2014 errors are stored in state.error by the pull() action\n newStore.getState().pull().catch(() => {})\n\n return () => {\n setStore(null)\n }\n // Intentionally depend on serializable config values, not the object reference\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n config?.serverUrl,\n config?.pullPath,\n config?.pushPath,\n config?.encryptor,\n config?.storeName,\n ])\n\n return store\n}\n\n// \u2500\u2500 Append-only log binding \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// The reactive counterpart for an append-only collection, backed by an\n// `AppendLogCursor` instead of a `SyncManager`. A log only grows, so the\n// store is read-only \u2014 there is no `set`/`flush`/`dirty`/conflict surface,\n// and no `persist` middleware: the cursor owns the items + checkpoint, so\n// persist by reading `getItems()` and rehydrate by constructing the cursor\n// with `initialItems` (see `AppendLogCursor`).\n//\n// The store assumes it is the SOLE driver of its cursor: it seeds `items` from\n// `cursor.getItems()` at construction and updates only via its own `pull()`.\n// Don't also call `cursor.pull()` directly on the same cursor, or the store's\n// `items`/`checkpoint` will go stale.\n\nexport interface StarfishLogState {\n /** The full accumulated log, newest appended last. */\n items: AppendElement[]\n /** A `pull()` is in flight. */\n loading: boolean\n online: boolean\n error: string | null\n /** The cursor's checkpoint (max `ts` held). */\n checkpoint: number\n}\n\nexport interface StarfishLogActions {\n /** Pull elements newer than the checkpoint, append them, and return the new\n * batch. Errors are captured into `error` (mirroring the SyncManager store). */\n pull: () => Promise<AppendElement[]>\n setOnline: (online: boolean) => void\n}\n\nexport type StarfishLogStore = StarfishLogState & StarfishLogActions\n\nexport interface CreateStarfishLogOptions {\n cursor: AppendLogCursor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n devtools?: (storeCreator: any) => any\n}\n\nexport function createStarfishLog(\n options: CreateStarfishLogOptions,\n): StoreApi<StarfishLogStore> {\n const { cursor } = options\n\n type NamedSet = (partial: Partial<StarfishLogStore>, replace?: boolean, action?: string) => void\n\n const storeCreator = (\n rawSet: StoreApi<StarfishLogStore>[\"setState\"],\n get: StoreApi<StarfishLogStore>[\"getState\"],\n ): StarfishLogStore => {\n const set = rawSet as NamedSet\n return {\n // Seed from the cursor so a warm-started cursor's items show immediately.\n items: cursor.getItems(),\n loading: false,\n online: true,\n error: null,\n checkpoint: cursor.getCheckpoint(),\n\n pull: async () => {\n if (get().loading) return []\n set({ loading: true, error: null }, false, \"log/pull/start\")\n try {\n const batch = await cursor.pull()\n set(\n { items: cursor.getItems(), checkpoint: cursor.getCheckpoint(), loading: false },\n false,\n \"log/pull/success\",\n )\n return batch\n } catch (err) {\n set({ loading: false, error: err instanceof Error ? err.message : String(err) }, false, \"log/pull/error\")\n return []\n }\n },\n\n setOnline: (online) => {\n set({ online }, false, \"log/setOnline\")\n },\n }\n }\n\n const withSelector = subscribeWithSelector(storeCreator)\n return createStore<StarfishLogStore>()(\n options.devtools ? options.devtools(withSelector) : withSelector,\n )\n}\n\n/** Derived status for an append-log store. */\nexport type LogStatus = \"idle\" | \"loading\" | \"error\" | \"offline\"\n\n/** Derive a single status from log store state. */\nexport function deriveLogStatus(state: StarfishLogState): LogStatus {\n if (!state.online) return \"offline\"\n if (state.error) return \"error\"\n if (state.loading) return \"loading\"\n return \"idle\"\n}\n\n/** Use the full append-log store state and actions. */\nexport function useStarfishLog(store: StoreApi<StarfishLogStore>): StarfishLogStore {\n return useStore(store)\n}\n\n/** Use only the accumulated items, with an optional selector for fine-grained subscriptions. */\nexport function useStarfishLogItems<T = AppendElement[]>(\n store: StoreApi<StarfishLogStore>,\n selector?: (items: AppendElement[]) => T,\n): T {\n return useStore(store, (state) =>\n selector ? selector(state.items) : (state.items as unknown as T),\n )\n}\n\n/** Use the derived log status (idle | loading | error | offline). */\nexport function useLogStatus(store: StoreApi<StarfishLogStore>): LogStatus {\n return useStore(store, deriveLogStatus)\n}\n\n/** Subscribe to log status changes outside of React. Invoked immediately with the\n * current status, then on every change. Returns an unsubscribe function. */\nexport function subscribeLogStatus(\n store: StoreApi<StarfishLogStore>,\n callback: (status: LogStatus) => void,\n): () => void {\n let prev = deriveLogStatus(store.getState())\n callback(prev)\n return store.subscribe((state) => {\n const next = deriveLogStatus(state)\n if (next !== prev) {\n prev = next\n callback(next)\n }\n })\n}\n\n/** Binds browser online/offline events to the log store's setOnline action. Cleans up on unmount. */\nexport function useLogConnectivity(store: StoreApi<StarfishLogStore>): void {\n useEffect(() => {\n const handleOnline = () => store.getState().setOnline(true)\n const handleOffline = () => store.getState().setOnline(false)\n window.addEventListener(\"online\", handleOnline)\n window.addEventListener(\"offline\", handleOffline)\n return () => {\n window.removeEventListener(\"online\", handleOnline)\n window.removeEventListener(\"offline\", handleOffline)\n }\n }, [store])\n}\n", "const reduxImpl = (reducer, initial) => (set, _get, api) => {\n api.dispatch = (action) => {\n set((state) => reducer(state, action), false, action);\n return action;\n };\n api.dispatchFromDevtools = true;\n return { dispatch: (...args) => api.dispatch(...args), ...initial };\n};\nconst redux = reduxImpl;\n\nconst shouldDispatchFromDevtools = (api) => !!api.dispatchFromDevtools && typeof api.dispatch === \"function\";\nconst trackedConnections = /* @__PURE__ */ new Map();\nconst getTrackedConnectionState = (name) => {\n const api = trackedConnections.get(name);\n if (!api) return {};\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])\n );\n};\nconst extractConnectionInformation = (store, extensionConnector, options) => {\n if (store === void 0) {\n return {\n type: \"untracked\",\n connection: extensionConnector.connect(options)\n };\n }\n const existingConnection = trackedConnections.get(options.name);\n if (existingConnection) {\n return { type: \"tracked\", store, ...existingConnection };\n }\n const newConnection = {\n connection: extensionConnector.connect(options),\n stores: {}\n };\n trackedConnections.set(options.name, newConnection);\n return { type: \"tracked\", store, ...newConnection };\n};\nconst removeStoreFromTrackedConnections = (name, store) => {\n if (store === void 0) return;\n const connectionInfo = trackedConnections.get(name);\n if (!connectionInfo) return;\n delete connectionInfo.stores[store];\n if (Object.keys(connectionInfo.stores).length === 0) {\n trackedConnections.delete(name);\n }\n};\nconst findCallerName = (stack) => {\n var _a, _b;\n if (!stack) return void 0;\n const traceLines = stack.split(\"\\n\");\n const apiSetStateLineIndex = traceLines.findIndex(\n (traceLine) => traceLine.includes(\"api.setState\")\n );\n if (apiSetStateLineIndex < 0) return void 0;\n const callerLine = ((_a = traceLines[apiSetStateLineIndex + 1]) == null ? void 0 : _a.trim()) || \"\";\n return (_b = /.+ (.+) .+/.exec(callerLine)) == null ? void 0 : _b[1];\n};\nconst devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;\n let extensionConnector;\n try {\n extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") && window.__REDUX_DEVTOOLS_EXTENSION__;\n } catch (e) {\n }\n if (!extensionConnector) {\n return fn(set, get, api);\n }\n const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);\n let isRecording = true;\n api.setState = ((state, replace, nameOrAction) => {\n const r = set(state, replace);\n if (!isRecording) return r;\n const action = nameOrAction === void 0 ? {\n type: anonymousActionType || findCallerName(new Error().stack) || \"anonymous\"\n } : typeof nameOrAction === \"string\" ? { type: nameOrAction } : nameOrAction;\n if (store === void 0) {\n connection == null ? void 0 : connection.send(action, get());\n return r;\n }\n connection == null ? void 0 : connection.send(\n {\n ...action,\n type: `${store}/${action.type}`\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState()\n }\n );\n return r;\n });\n api.devtools = {\n cleanup: () => {\n if (connection && typeof connection.unsubscribe === \"function\") {\n connection.unsubscribe();\n }\n removeStoreFromTrackedConnections(options.name, store);\n }\n };\n const setStateFromDevtools = (...a) => {\n const originalIsRecording = isRecording;\n isRecording = false;\n set(...a);\n isRecording = originalIsRecording;\n };\n const initialState = fn(api.setState, get, api);\n if (connectionInformation.type === \"untracked\") {\n connection == null ? void 0 : connection.init(initialState);\n } else {\n connectionInformation.stores[connectionInformation.store] = api;\n connection == null ? void 0 : connection.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store2]) => [\n key,\n key === connectionInformation.store ? initialState : store2.getState()\n ])\n )\n );\n }\n if (shouldDispatchFromDevtools(api)) {\n let didWarnAboutReservedActionType = false;\n const originalDispatch = api.dispatch;\n api.dispatch = (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && args[0].type === \"__setState\" && !didWarnAboutReservedActionType) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved to set state from the devtools. Avoid using it.'\n );\n didWarnAboutReservedActionType = true;\n }\n originalDispatch(...args);\n };\n }\n connection.subscribe((message) => {\n var _a;\n switch (message.type) {\n case \"ACTION\":\n if (typeof message.payload !== \"string\") {\n console.error(\n \"[zustand devtools middleware] Unsupported action format\"\n );\n return;\n }\n return parseJsonThen(\n message.payload,\n (action) => {\n if (action.type === \"__setState\") {\n if (store === void 0) {\n setStateFromDevtools(action.state);\n return;\n }\n if (Object.keys(action.state).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format.\n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `\n );\n }\n const stateFromDevtools = action.state[store];\n if (stateFromDevtools === void 0 || stateFromDevtools === null) {\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {\n setStateFromDevtools(stateFromDevtools);\n }\n return;\n }\n if (shouldDispatchFromDevtools(api)) {\n api.dispatch(action);\n }\n }\n );\n case \"DISPATCH\":\n switch (message.payload.type) {\n case \"RESET\":\n setStateFromDevtools(initialState);\n if (store === void 0) {\n return connection == null ? void 0 : connection.init(api.getState());\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"COMMIT\":\n if (store === void 0) {\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"ROLLBACK\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n setStateFromDevtools(state[store]);\n connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n });\n case \"JUMP_TO_STATE\":\n case \"JUMP_TO_ACTION\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {\n setStateFromDevtools(state[store]);\n }\n });\n case \"IMPORT_STATE\": {\n const { nextLiftedState } = message.payload;\n const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;\n if (!lastComputedState) return;\n if (store === void 0) {\n setStateFromDevtools(lastComputedState);\n } else {\n setStateFromDevtools(lastComputedState[store]);\n }\n connection == null ? void 0 : connection.send(\n null,\n // FIXME no-any\n nextLiftedState\n );\n return;\n }\n case \"PAUSE_RECORDING\":\n return isRecording = !isRecording;\n }\n return;\n }\n });\n return initialState;\n};\nconst devtools = devtoolsImpl;\nconst parseJsonThen = (stringified, fn) => {\n let parsed;\n try {\n parsed = JSON.parse(stringified);\n } catch (e) {\n console.error(\n \"[zustand devtools middleware] Could not parse the received json\",\n e\n );\n }\n if (parsed !== void 0) fn(parsed);\n};\n\nconst subscribeWithSelectorImpl = (fn) => (set, get, api) => {\n const origSubscribe = api.subscribe;\n api.subscribe = ((selector, optListener, options) => {\n let listener = selector;\n if (optListener) {\n const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;\n let currentSlice = selector(api.getState());\n listener = (state) => {\n const nextSlice = selector(state);\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice;\n optListener(currentSlice = nextSlice, previousSlice);\n }\n };\n if (options == null ? void 0 : options.fireImmediately) {\n optListener(currentSlice, currentSlice);\n }\n }\n return origSubscribe(listener);\n });\n const initialState = fn(set, get, api);\n return initialState;\n};\nconst subscribeWithSelector = subscribeWithSelectorImpl;\n\nfunction combine(initialState, create) {\n return (...args) => Object.assign({}, initialState, create(...args));\n}\n\nfunction createJSONStorage(getStorage, options) {\n let storage;\n try {\n storage = getStorage();\n } catch (e) {\n return;\n }\n const persistStorage = {\n getItem: (name) => {\n var _a;\n const parse = (str2) => {\n if (str2 === null) {\n return null;\n }\n return JSON.parse(str2, options == null ? void 0 : options.reviver);\n };\n const str = (_a = storage.getItem(name)) != null ? _a : null;\n if (str instanceof Promise) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer)),\n removeItem: (name) => storage.removeItem(name)\n };\n return persistStorage;\n}\nconst toThenable = (fn) => (input) => {\n try {\n const result = fn(input);\n if (result instanceof Promise) {\n return result;\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result);\n },\n catch(_onRejected) {\n return this;\n }\n };\n } catch (e) {\n return {\n then(_onFulfilled) {\n return this;\n },\n catch(onRejected) {\n return toThenable(onRejected)(e);\n }\n };\n }\n};\nconst persistImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n storage: createJSONStorage(() => window.localStorage),\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n let hydrationVersion = 0;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage = options.storage;\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const setItem = () => {\n const state = options.partialize({ ...get() });\n return storage.setItem(options.name, {\n state,\n version: options.version\n });\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n return setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n return setItem();\n },\n get,\n api\n );\n api.getInitialState = () => configResult;\n let stateFromStorage;\n const hydrate = () => {\n var _a, _b;\n if (!storage) return;\n const currentVersion = ++hydrationVersion;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => {\n var _a2;\n return cb((_a2 = get()) != null ? _a2 : configResult);\n });\n const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n const migration = options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n if (migration instanceof Promise) {\n return migration.then((result) => [true, result]);\n }\n return [true, migration];\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return [false, deserializedStorageValue.state];\n }\n }\n return [false, void 0];\n }).then((migrationResult) => {\n var _a2;\n if (currentVersion !== hydrationVersion) {\n return;\n }\n const [migrated, migratedState] = migrationResult;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n if (migrated) {\n return setItem();\n }\n }).then(() => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);\n stateFromStorage = get();\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.storage) {\n storage = newOptions.storage;\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n if (!options.skipHydration) {\n hydrate();\n }\n return stateFromStorage || configResult;\n};\nconst persist = persistImpl;\n\nfunction ssrSafe(config, isSSR = typeof window === \"undefined\") {\n return (set, get, api) => {\n if (!isSSR) {\n return config(set, get, api);\n }\n const ssrSet = () => {\n throw new Error(\"Cannot set state of Zustand store in SSR\");\n };\n api.setState = ssrSet;\n return config(ssrSet, get, api);\n };\n}\n\nexport { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector, ssrSafe as unstable_ssrSafe };\n", "import type { PullResult, PushSuccess } from \"@drakkar.software/starfish-protocol\"\nimport {\n AUTHOR_PUBKEY_FIELD,\n AUTHOR_SIGNATURE_FIELD,\n DATA_FIELD,\n TS_FIELD,\n BASE_HASH_FIELD,\n PUSH_PATH_PREFIX,\n HEADER_AUTHORIZATION,\n HEADER_SIG,\n HEADER_TS,\n HEADER_NONCE,\n HEADER_ALG,\n HEADER_PUB,\n HEADER_CONTENT_TYPE,\n HEADER_ACCEPT,\n DEFAULT_ALG,\n signAppendAuthor,\n signRequest,\n stableStringify,\n type AppendAuthor,\n type SignableMethod,\n type SignableRequest,\n} from \"@drakkar.software/starfish-protocol\"\nimport type {\n StarfishClientOptions,\n StarfishCapProvider,\n} from \"./types.js\"\nimport { ConflictError, StarfishHttpError } from \"./types.js\"\n\nconst APPEND_DEFAULT_FIELD = \"items\"\n\n/** The storage `documentKey` for a push `path`: the path with the `/push/`\n * action prefix stripped (the namespace lives only in the URL). The author\n * signature binds to this key. */\nexport function stripPushPrefix(path: string): string {\n return path.startsWith(PUSH_PATH_PREFIX) ? path.slice(PUSH_PATH_PREFIX.length) : path\n}\n\n/** Result of pulling a binary blob from the server. */\nexport interface BlobPullResult {\n data: ArrayBuffer\n /** Content hash from the ETag header. Null if the server didn't include an ETag. */\n hash: string | null\n contentType: string\n}\n\n/** Result of pushing a binary blob to the server. */\nexport interface BlobPushResult {\n hash: string\n}\n\n/** Options for append-only pull \u2014 extracts a single array field from the response. */\nexport interface AppendPullOptions {\n /** Array field name in `data`. Defaults to `\"items\"`. */\n appendField?: string\n /** Only return items appended after this timestamp (ms). Sent as `?checkpoint=`. */\n since?: number\n /** Return only the last K items (applied after `since` filter). Sent as `?last=`. */\n last?: number\n}\n\n/**\n * Options for a structured (non-append) pull.\n *\n * `withKeyring: true` appends `?withKeyring=1` so the server includes the\n * collection's sibling `<collection>/_keyring` document in the response,\n * saving a cold-start round-trip. The cap-cert scope MUST cover BOTH the\n * data path and `<collection>/_keyring` \u2014 `scopes.writer(collection)` denies\n * the keyring path and will produce a 403; use `scopes.readWrite()` or grant\n * the keyring path explicitly when opting in.\n */\nexport interface PullOptions {\n /** Server timestamp of the last successful pull (ms). Sent as `?checkpoint=`. */\n checkpoint?: number\n /** Include the sibling `_keyring` document in the response. Defaults to false. */\n withKeyring?: boolean\n}\n\n/** Per-collection result in a {@link BatchPullResult}: either the pulled\n * document (`data`/`hash`/`timestamp`) or a per-collection `error` string. */\nexport interface BatchPullEntry {\n data?: unknown\n hash?: string\n timestamp?: number\n error?: string\n}\n\n/** Response of {@link StarfishClient.batchPull}: a map of requested collection\n * name \u2192 an ARRAY of {@link BatchPullEntry}, one per requested param-set, in\n * request order. A collection read with no params yields a one-element array. */\nexport interface BatchPullResult {\n collections: Record<string, BatchPullEntry[]>\n}\n\n/** Options for {@link StarfishClient.batchPull}. */\nexport interface BatchPullOptions {\n /** Per-collection path params: collection name \u2192 an ARRAY of param-sets, one\n * per document to read from that collection, e.g.\n * `{ profile: [{ identity: \"a\" }, { identity: \"b\" }] }` reads two profiles in\n * one round-trip. Serialized to a URL-encoded JSON `params` query. The\n * `{identity}` param is auto-filled by the server from the authenticated\n * caller when a set omits it, so a single self-doc read can pass `[{}]` \u2014 or\n * omit the collection from `params` entirely (an unlisted collection reads one\n * auto-filled doc). Results come back under the same name in request order. */\n params?: Record<string, Record<string, string>[]>\n}\n\n/**\n * Base64-encode the canonical stable-stringification of a cap-cert.\n *\n * Used as the value of the `Authorization: Cap <\u2026>` header in v3.0. We rely\n * on the host's `btoa` for browsers and fall back to `Buffer` in Node so the\n * client stays free of native dependencies.\n */\nfunction encodeCapAuth(cap: unknown): string {\n const json = stableStringify(cap as Record<string, unknown>)\n if (typeof btoa === \"function\") {\n return btoa(json)\n }\n const bufCtor = (globalThis as { Buffer?: { from: (s: string, enc: string) => { toString: (enc: string) => string } } }).Buffer\n if (bufCtor) return bufCtor.from(json, \"utf-8\").toString(\"base64\")\n throw new Error(\"No base64 encoder available\")\n}\n\n/**\n * Low-level HTTP client for the Starfish sync protocol.\n * Handles auth headers and response parsing.\n */\nexport class StarfishClient {\n private readonly baseUrl: string\n private readonly namespace?: string\n private readonly capProvider?: StarfishCapProvider\n private readonly fetch: typeof globalThis.fetch\n /**\n * Installed client-side plugins. Currently stored as inert data; no\n * hooks fire yet. Extensions can inspect this list if needed.\n */\n public readonly plugins: ReadonlyArray<import(\"./types.js\").ClientPlugin>\n\n constructor(options: StarfishClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/$/, \"\")\n // Empty string \u21D2 no namespace (treat like unset), so a falsy env value\n // doesn't produce a malformed `/v1//\u2026` path.\n this.namespace = options.namespace || undefined\n this.capProvider = options.capProvider\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis)\n this.plugins = options.plugins ? [...options.plugins] : []\n }\n\n /**\n * Resolve the host portion of the URL the client will send to. The host\n * is folded into the signed canonical input as the `h` field so the\n * server can refuse a signature that was minted against a different\n * Starfish host (replay-across-servers defence).\n *\n * When `baseUrl` is relative \u2014 e.g. the consumer passed a custom `fetch`\n * that resolves relative URLs in its own context \u2014 there is no parseable\n * host; we return `\"\"` so signing still proceeds. The server-side\n * verifier will also reconstruct host from its inbound URL, so the\n * empty-host case still verifies symmetrically when both sides agree.\n */\n private signingHost(): string {\n try {\n return new URL(this.baseUrl).host\n } catch {\n return \"\"\n }\n }\n\n /**\n * Rewrite a request path for the configured namespace. A no-op when no\n * namespace is set; otherwise `/{action}/\u2026` becomes `/v1/{namespace}/{action}/\u2026`\n * (the `/v1` protocol-version segment is part of the namespaced route, matching\n * the Python client and the server's namespace mount).\n *\n * Applied to the path used for BOTH the signature and the URL so the canonical\n * path the client signs equals the path the server reconstructs from the URL.\n * Covers SDK-helper-built paths too \u2014 that's the point: a namespace-unaware\n * helper passing `/push/spaces/x/_keyring` reaches `/v1/{ns}/push/spaces/x/_keyring`.\n */\n private applyNamespace(path: string): string {\n return this.namespace ? `/v1/${this.namespace}${path}` : path\n }\n\n /**\n * Build auth headers for a request. When a `capProvider` is set, signs the\n * request with the device's Ed25519 private key and returns the v3 header\n * set (`Authorization: Cap \u2026`, `X-Starfish-Sig`, `X-Starfish-Ts`,\n * `X-Starfish-Nonce`). Empty when no provider is configured (public reads).\n *\n * Body bytes signed MUST equal the bytes sent on the wire \u2014 callers pass\n * the already-serialized body string here so signing and transmission agree.\n * The host bound into the signature is derived from `baseUrl` once per call.\n */\n private async buildAuthHeaders(\n method: SignableMethod,\n pathAndQuery: string,\n body: string | undefined,\n ): Promise<Record<string, string>> {\n if (!this.capProvider) return {}\n const capCtx = await this.capProvider.getCap()\n return this.capRequestHeaders(capCtx, method, pathAndQuery, body)\n }\n\n /**\n * Build the request-signing headers from an ALREADY-fetched cap context. Split\n * out of {@link buildAuthHeaders} so {@link append} can fetch the cap once and\n * reuse it for BOTH the author signature (over the element data) and the\n * request signature (over the body), without redeeming the cap twice \u2014 a\n * second `getCap()` could rotate keys and break the `authorPubkey ===\n * presenter` bind the server checks.\n */\n private async capRequestHeaders(\n capCtx: Awaited<ReturnType<StarfishCapProvider[\"getCap\"]>>,\n method: SignableMethod,\n pathAndQuery: string,\n body: string | undefined,\n ): Promise<Record<string, string>> {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = capCtx\n const req: SignableRequest = {\n method,\n pathAndQuery,\n body,\n host: this.signingHost(),\n }\n // The signing suite is the suite of whoever holds `devEdPrivHex`:\n // - device/member: the subject signs, so use the cert's subject suite.\n // Tolerant-reader rule (matches the server resolver): an absent\n // `subAlg` means \"same suite as the issuer\", so fall back to\n // `cap.issAlg`, not the global default.\n // - audience (public-link): the presenter is an arbitrary redeemer\n // signing with their own key, unrelated to the cert's suites, so use\n // `presenterAlg` (defaulting to ed25519). The server reads it back from\n // `X-Starfish-Alg` for audience caps.\n const signAlg =\n cap.kind === \"audience\" ? (presenterAlg ?? DEFAULT_ALG) : (cap.subAlg ?? cap.issAlg)\n const { alg, sig, ts, nonce } = await signRequest(req, devEdPrivHex, {\n alg: signAlg,\n })\n const headers: Record<string, string> = {\n [HEADER_AUTHORIZATION]: `Cap ${encodeCapAuth(cap)}`,\n [HEADER_SIG]: sig,\n [HEADER_TS]: String(ts),\n [HEADER_NONCE]: nonce,\n [HEADER_ALG]: alg,\n }\n // Audience (public-link) caps bind no single subject, so the server needs\n // the presenter's pubkey to verify the signature and check the allow-list.\n if (pubHex !== undefined) headers[HEADER_PUB] = pubHex\n return headers\n }\n\n /**\n * Resolve the author public key to attach to a signed append: the redeemer's\n * `pubHex` for an audience cap, else the cert subject `cap.sub` for a\n * device/member cap. This is the SAME key that signs the request, so a server\n * enforcing author proof can bind the stored element to its writer. Returns\n * undefined only for a (malformed) cap with neither \u2014 the append then goes\n * unsigned and a server requiring signatures rejects it.\n */\n private appendAuthorKey(\n capCtx: Awaited<ReturnType<StarfishCapProvider[\"getCap\"]>>,\n ): { authorPubHex: string; signAlg: typeof DEFAULT_ALG } | null {\n const { cap, pubHex, presenterAlg } = capCtx\n const authorPubHex = pubHex ?? cap.sub\n if (authorPubHex === undefined) return null\n const signAlg =\n cap.kind === \"audience\" ? (presenterAlg ?? DEFAULT_ALG) : (cap.subAlg ?? cap.issAlg)\n return { authorPubHex, signAlg }\n }\n\n /** Pull synced data from the server. Returns the raw `PullResult`. */\n async pull(path: string, checkpoint?: number): Promise<PullResult>\n /** Pull synced data with structured options (e.g. `{withKeyring: true}`). */\n async pull(path: string, options: PullOptions): Promise<PullResult>\n /** Pull an append-only collection. Extracts and returns `data[appendField]` as `T[]`. */\n async pull<T = unknown>(path: string, options: AppendPullOptions): Promise<T[]>\n async pull<T = unknown>(\n path: string,\n checkpointOrOptions?: number | AppendPullOptions | PullOptions,\n ): Promise<PullResult | T[]> {\n let pathAndQuery = this.applyNamespace(path)\n let appendField: string | undefined\n\n if (typeof checkpointOrOptions === \"number\") {\n if (checkpointOrOptions) pathAndQuery += `?checkpoint=${checkpointOrOptions}`\n } else if (checkpointOrOptions != null) {\n // Disambiguate AppendPullOptions vs PullOptions.\n //\n // PullOptions are identified by the presence of `withKeyring` or\n // `checkpoint` keys (which AppendPullOptions does not have \u2014 append\n // uses `since`, not `checkpoint`). Anything else, including an empty\n // `{}` object, retains the historical behavior of AppendPullOptions\n // (extracts `data.items` with `?` query).\n const opts = checkpointOrOptions as AppendPullOptions & PullOptions\n const isPullOptions =\n opts.withKeyring !== undefined || opts.checkpoint !== undefined\n const params = new URLSearchParams()\n\n if (isPullOptions) {\n if (opts.checkpoint != null && opts.checkpoint > 0) {\n params.set(\"checkpoint\", String(opts.checkpoint))\n }\n if (opts.withKeyring) {\n params.set(\"withKeyring\", \"1\")\n }\n } else {\n appendField = opts.appendField ?? APPEND_DEFAULT_FIELD\n if (opts.since != null) {\n if (opts.since < 0) throw new Error(\"since must be non-negative\")\n params.set(\"checkpoint\", String(opts.since))\n }\n if (opts.last != null) {\n if (opts.last < 0) throw new Error(\"last must be non-negative\")\n params.set(\"last\", String(opts.last))\n }\n }\n if (params.size > 0) pathAndQuery += `?${params.toString()}`\n }\n\n const url = `${this.baseUrl}${pathAndQuery}`\n const authHeaders = await this.buildAuthHeaders(\"GET\", pathAndQuery, undefined)\n\n const res = await this.fetch(url, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"application/json\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n\n const result = await res.json() as PullResult\n if (appendField !== undefined) {\n const list = (result.data as Record<string, unknown> | null)?.[appendField]\n return (Array.isArray(list) ? list : []) as T[]\n }\n return result\n }\n\n /**\n * Pull several documents in one round-trip via `/batch/pull`. `collections` is\n * the list of distinct collection names; `opts.params` supplies, per collection,\n * an ARRAY of path-param sets \u2014 one per document to read \u2014 so the SAME collection\n * can fan in many documents (e.g. many users' `profile`) in a single request.\n * The server auto-fills the `{identity}` param from the authenticated caller for\n * any set that omits it, so a self-doc collection needs no params. Returns a map\n * of collection name \u2192 an ARRAY of pulled documents (or per-document `{ error }`),\n * in request order. Honors the configured namespace.\n *\n * For the common \"many docs of one collection\" case prefer {@link batchPullMany}.\n *\n * Note: not append/checkpoint-aware \u2014 for incremental append-only reads use\n * `pull(path, { since })` (or `AppendLogCursor`) per collection.\n */\n async batchPull(\n collections: string[],\n opts: BatchPullOptions = {},\n ): Promise<BatchPullResult> {\n const search = new URLSearchParams()\n search.set(\"collections\", collections.join(\",\"))\n if (opts.params && Object.keys(opts.params).length > 0) {\n search.set(\"params\", JSON.stringify(opts.params))\n }\n const pathAndQuery = `${this.applyNamespace(\"/batch/pull\")}?${search.toString()}`\n const url = `${this.baseUrl}${pathAndQuery}`\n const authHeaders = await this.buildAuthHeaders(\"GET\", pathAndQuery, undefined)\n\n const res = await this.fetch(url, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"application/json\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return await res.json() as BatchPullResult\n }\n\n /**\n * Convenience over {@link batchPull} for reading MANY documents of ONE\n * collection in a single round-trip: pass the per-document param-sets and get\n * back the {@link BatchPullEntry} array aligned to `paramsList` by index (each\n * entry is `{ data, hash, timestamp }` or `{ error }`). An empty `paramsList`\n * issues no request and returns `[]`.\n */\n async batchPullMany(\n collection: string,\n paramsList: Record<string, string>[],\n ): Promise<BatchPullEntry[]> {\n if (paramsList.length === 0) return []\n const res = await this.batchPull([collection], { params: { [collection]: paramsList } })\n return res.collections[collection] ?? []\n }\n\n /**\n * Push synced data to the server.\n * @param path - The push endpoint path (e.g. \"/push/users/abc/settings\")\n * @param data - The full document data to push\n * @param baseHash - Hash of the document this push is based on (null for first push)\n *\n * v3 author proof (`authorPubkey` + `authorSignature`) is passed via `author`\n * (produced by `SyncManager` when a `signer` is configured) and sent as\n * top-level body siblings of `data`, where the server verifies it.\n * @throws {ConflictError} if the server detects a hash mismatch (409)\n */\n async push(\n path: string,\n data: Record<string, unknown>,\n baseHash: string | null,\n author?: AppendAuthor,\n ): Promise<PushSuccess> {\n const body = JSON.stringify({\n [DATA_FIELD]: data,\n [BASE_HASH_FIELD]: baseHash,\n ...(author && {\n [AUTHOR_PUBKEY_FIELD]: author.authorPubkey,\n [AUTHOR_SIGNATURE_FIELD]: author.authorSignature,\n }),\n })\n\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"POST\", sendPath, body)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: \"application/json\",\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body,\n })\n\n if (res.status === 409) {\n throw new ConflictError()\n }\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<PushSuccess>\n }\n\n /**\n * Append an element to an appendOnly (`by_timestamp`) collection.\n *\n * Unlike {@link push}, appendOnly writes carry no hash/conflict check \u2014 an\n * authorized append is always accepted. Each element is stored server-side as\n * `{ts, data}` and pulls can filter by `ts` via `since`/`checkpoint`.\n *\n * @param path - the push endpoint (e.g. \"/push/events\")\n * @param data - the element payload. For a `delegated` collection, encrypt it\n * first (e.g. `createKeyringEncryptor(keyring, kem).encrypt(data)`); the\n * server stores it opaquely and never reads it.\n * @param opts.ts - optional client-supplied element timestamp (ms). Must be a\n * non-negative integer strictly greater than the latest stored element's ts\n * (else the server responds 409). Omit to let the server assign one.\n * @throws {StarfishHttpError} on a non-2xx response \u2014 e.g. 409\n * `{ error: \"non_monotonic_timestamp\" }` for a non-monotonic timestamp, or\n * `{ error: \"append_limit_exceeded\", limit }` if the collection's `maxItems`\n * cap is reached (partition by a path parameter for higher volume).\n */\n async append(\n path: string,\n data: Record<string, unknown>,\n opts: { ts?: number } = {},\n ): Promise<PushSuccess> {\n const sendPath = this.applyNamespace(path)\n const bodyObj: Record<string, unknown> = { [DATA_FIELD]: data }\n if (opts.ts !== undefined) bodyObj[TS_FIELD] = opts.ts\n\n // Author proof. Fetch the cap ONCE and reuse it for both the author\n // signature (over the element `data`) and the request signature (over the\n // final body) \u2014 see {@link capRequestHeaders}. The author fields are signed\n // with the same key that authenticates the request, so a collection with\n // `requireAuthorSignature` (the default) binds the stored element to its\n // writer. Without a cap provider the append is sent unsigned and such a\n // collection rejects it.\n const capCtx = this.capProvider ? await this.capProvider.getCap() : null\n if (capCtx) {\n const authorKey = this.appendAuthorKey(capCtx)\n if (authorKey) {\n // The signature binds the author to BOTH the element data AND the\n // document it is written to (the storage path = `path` minus the\n // `/push/` action prefix; the namespace lives only in the URL).\n const documentKey = stripPushPrefix(path)\n const { authorPubkey, authorSignature } = signAppendAuthor(\n documentKey,\n data,\n authorKey.authorPubHex,\n capCtx.devEdPrivHex,\n authorKey.signAlg,\n )\n bodyObj[AUTHOR_PUBKEY_FIELD] = authorPubkey\n bodyObj[AUTHOR_SIGNATURE_FIELD] = authorSignature\n }\n }\n\n const body = JSON.stringify(bodyObj)\n const authHeaders = capCtx\n ? await this.capRequestHeaders(capCtx, \"POST\", sendPath, body)\n : {}\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: \"application/json\",\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body,\n })\n\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<PushSuccess>\n }\n\n /**\n * Pull binary data from a blob collection.\n * Returns raw bytes with the content hash from the ETag header.\n */\n async pullBlob(path: string): Promise<BlobPullResult> {\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"GET\", sendPath, undefined)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"GET\",\n headers: { [HEADER_ACCEPT]: \"*/*\", ...authHeaders },\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n\n const etag = res.headers.get(\"ETag\")?.replace(/\"/g, \"\") ?? null\n const contentType = res.headers.get(HEADER_CONTENT_TYPE) ?? \"application/octet-stream\"\n const data = await res.arrayBuffer()\n\n return { data, hash: etag, contentType }\n }\n\n /**\n * Push binary data to a blob collection.\n * Binary collections use last-write-wins (no conflict detection).\n */\n async pushBlob(\n path: string,\n data: ArrayBuffer | Uint8Array | Blob,\n contentType: string,\n ): Promise<BlobPushResult> {\n // Blobs are not JSON; we leave body undefined when signing \u2014 server-side\n // verification is expected to use a separate path for blob uploads.\n const sendPath = this.applyNamespace(path)\n const authHeaders = await this.buildAuthHeaders(\"POST\", sendPath, undefined)\n\n const res = await this.fetch(`${this.baseUrl}${sendPath}`, {\n method: \"POST\",\n headers: {\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_ACCEPT]: \"application/json\",\n ...authHeaders,\n },\n body: data as BodyInit,\n })\n if (!res.ok) {\n throw new StarfishHttpError(res.status, await res.text())\n }\n return res.json() as Promise<BlobPushResult>\n }\n}\n", "import type { Alg, CapCert } from \"@drakkar.software/starfish-protocol\"\n\n/** Push conflict error (HTTP 409). */\nexport class ConflictError extends Error {\n constructor() {\n super(\"hash_mismatch\")\n this.name = \"ConflictError\"\n }\n}\n\n/** HTTP error from the Starfish server. */\nexport class StarfishHttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string\n ) {\n super(`HTTP ${status}: ${body}`)\n this.name = \"StarfishHttpError\"\n }\n}\n\n/**\n * v3.0 cap-cert provider for `StarfishClient`. Returns the device's cap-cert and\n * the matching Ed25519 private key (hex). The client calls `getCap()` once per\n * outgoing request; implementations are expected to cache so this is cheap.\n *\n * When set, the client signs every outgoing request: each call carries\n * `Authorization: Cap <base64(stableStringify(cap))>` plus `X-Starfish-Sig`,\n * `X-Starfish-Ts`, `X-Starfish-Nonce`.\n */\nexport interface StarfishCapProvider {\n /**\n * Returns the device's cap-cert and its Ed25519 private key (hex).\n * Implementations are expected to cache; the client may call this once per\n * authenticated request.\n *\n * For an `audience` (public-link) cap, which binds no single subject, also\n * return `pubHex` \u2014 the redeemer's own Ed25519 pubkey matching `devEdPrivHex`.\n * The client then sends it as `X-Starfish-Pub` so the server can verify the\n * request signature against it and check the cap's `aud` allow-list. Omit\n * `pubHex` for device/member caps (the server uses `cap.sub`).\n *\n * `presenterAlg` is the crypto suite of `devEdPrivHex` (the key that signs\n * the request). It matters only for `audience` caps, where the presenter is\n * an arbitrary redeemer whose suite is unrelated to the cap's `issAlg`; the\n * client sends it as `X-Starfish-Alg`. For device/member caps the subject's\n * suite is taken authoritatively from the verified cert, so this is ignored.\n * Defaults to `\"ed25519\"` when omitted.\n */\n getCap(): Promise<{\n cap: CapCert\n devEdPrivHex: string\n pubHex?: string\n presenterAlg?: Alg\n }>\n}\n\n/** Options for creating a StarfishClient. */\nexport interface StarfishClientOptions {\n /** Base URL of the Starfish server (e.g. \"https://api.example.com/v1\"). */\n baseUrl: string\n /**\n * Optional namespace for a namespace-mounted server. When set, every request\n * path `/{action}/\u2026` is rewritten to `/v1/{namespace}/{action}/\u2026` for BOTH the\n * URL the client hits AND the canonical path it signs, so the signature the\n * server reconstructs from the namespaced URL verifies (no rewrite layer\n * needed). Mirrors the Python client's `namespace` parameter.\n *\n * Crucially this also rewrites the paths that namespace-unaware SDK helpers\n * build internally (e.g. `starfish-keyring`'s `addCollectionRecipient`, blob\n * uploads), so consumers no longer hand-prefix paths or wrap the client to\n * reach a namespaced deployment. Leave unset (default) for a root-mounted\n * server \u2014 paths pass through unchanged, byte-identical to before.\n *\n * Pass the bare namespace name (e.g. `\"octochat\"`); `baseUrl` then carries only\n * the origin (and any reverse-proxy mount the proxy strips), not the `/v1`\n * version segment. Must match `[A-Za-z0-9_-]+` and not be a reserved route name\n * (`pull`, `push`, `health`, `batch`).\n */\n namespace?: string\n /**\n * Cap-cert provider. When set, requests are signed with Ed25519 and carry\n * `Authorization: Cap <\u2026>`. Omit for unauthenticated public-read collections.\n */\n capProvider?: StarfishCapProvider\n /** Optional fetch implementation (defaults to global fetch). */\n fetch?: typeof fetch\n /**\n * Optional list of client-side plugins. The list is stored on the client\n * instance but does not fire any hooks yet \u2014 the contract is plumbed so\n * extension packages (`starfish-identities`, `starfish-keyring`,\n * `starfish-sharing`, \u2026) can register against it later without a breaking\n * API change.\n *\n * The current set of hooks is purposely empty; extensions that need to\n * react to mint events or transport actions today can wrap the client\n * directly. Future hook additions will be additive.\n */\n plugins?: ClientPlugin[]\n}\n\n/**\n * Client-side plugin contract.\n *\n * A placeholder shape: the interface intentionally has no required hooks\n * yet; extensions declare a plugin object with `name` and opt into\n * specific lifecycle hooks once those exist. Apps wire plugins via\n * `new StarfishClient({ plugins: [...] })`.\n */\nexport interface ClientPlugin {\n /** Human-readable name. Used in error messages and audit output. */\n name: string\n /**\n * Reserved for future hook fields. Plugins typically declare only\n * `name`. Hook additions are additive \u2014 extensions implementing a\n * future hook will populate the relevant optional property without\n * affecting existing zero-hook plugins.\n */\n}\n\n/** Conflict resolver: given local and remote data, return merged result. */\nexport type ConflictResolver = (\n local: Record<string, unknown>,\n remote: Record<string, unknown>\n) => Record<string, unknown>\n", "import type { PullResult } from \"@drakkar.software/starfish-protocol\"\nimport {\n AUTHOR_PUBKEY_FIELD,\n AUTHOR_SIGNATURE_FIELD,\n PUSH_PATH_PREFIX,\n deepMerge,\n docAuthorCanonicalInput,\n getBase64,\n type AppendAuthor,\n} from \"@drakkar.software/starfish-protocol\"\nimport type { ConflictResolver } from \"./types.js\"\nimport { ConflictError } from \"./types.js\"\nimport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nimport { StarfishClient, stripPushPrefix } from \"./client.js\"\nimport type { SyncLogger } from \"./logger.js\"\nimport type { Validator } from \"./validate.js\"\nimport { ValidationError } from \"./validate.js\"\n\nexport class AbortError extends Error {\n constructor() {\n super(\"SyncManager was aborted\")\n this.name = \"AbortError\"\n }\n}\n\n/**\n * v3.0 author-signature plumbing for `SyncManager`.\n *\n * Returns the device's Ed25519 public key (hex) and a function that signs\n * arbitrary payload bytes. `SyncManager` calls `getSigner()` once per push\n * and uses the returned `sign` to produce a base64-encoded signature over\n * the canonical stringification of the encrypted payload (sans author fields).\n *\n * Implementations typically wrap the same Ed25519 private key used by\n * `StarfishCapProvider` so that `cap.sub === devEdPubHex`.\n */\nexport interface SyncSigner {\n /**\n * Returns the device's `cap.sub` (Ed25519 pubkey, hex) and a payload signer.\n * The `sign` function receives the canonical signing input bytes and must\n * return the raw 64-byte Ed25519 signature.\n */\n getSigner(): Promise<{ devEdPubHex: string; sign(payload: Uint8Array): Promise<Uint8Array> }>\n}\n\n\nexport interface SyncManagerOptions {\n client: StarfishClient\n pullPath: string\n pushPath: string\n /** Custom conflict resolver. Defaults to remote-wins deep merge. Arrays are atomic. */\n onConflict?: ConflictResolver\n /** Max conflict retry attempts (default: 3). */\n maxRetries?: number\n /**\n * Encryptor for client-side E2E encryption. For v3 `delegated` collections,\n * build it via `createKeyringEncryptor(keyring, deviceKemKeys)`.\n */\n encryptor?: Encryptor\n /**\n * v3 author-signature plumbing. When set, every push attaches\n * `authorPubkey` (= `cap.sub`) and `authorSignature` (= base64 Ed25519 over\n * stable-stringify of the encrypted payload minus author fields).\n */\n signer?: SyncSigner\n /** Structured logger for sync events. */\n logger?: SyncLogger\n /** Name passed to logger methods (default: derived from pullPath). */\n loggerName?: string\n /** Validate data before push. Throws ValidationError on failure. */\n validate?: Validator\n}\n\nexport class SyncManager {\n private readonly client: StarfishClient\n private readonly pullPath: string\n private readonly pushPath: string\n private readonly onConflict: ConflictResolver\n private readonly maxRetries: number\n private readonly encryptor: Encryptor | null\n private readonly signer?: SyncSigner\n private readonly logger?: SyncLogger\n private readonly loggerName: string\n private readonly validate?: Validator\n\n private lastHash: string | null = null\n private lastCheckpoint: number = 0\n private localData: Record<string, unknown> = {}\n private aborted: boolean = false\n\n constructor(options: SyncManagerOptions) {\n this.client = options.client\n this.pullPath = options.pullPath\n this.pushPath = options.pushPath\n this.onConflict = options.onConflict ?? deepMerge\n this.maxRetries = options.maxRetries ?? 3\n this.signer = options.signer\n this.logger = options.logger\n this.loggerName = options.loggerName ?? options.pullPath.split(\"/\").filter(Boolean).pop() ?? options.pullPath\n this.validate = options.validate\n this.encryptor = options.encryptor ?? null\n }\n\n abort(): void {\n this.aborted = true\n }\n\n get isAborted(): boolean {\n return this.aborted\n }\n\n getData(): Record<string, unknown> {\n return { ...this.localData }\n }\n\n getHash(): string | null {\n return this.lastHash\n }\n\n /** Set the last-known server hash. Used by persistence layers to restore state across restarts. */\n setHash(hash: string | null): void {\n this.lastHash = hash\n }\n\n getCheckpoint(): number {\n return this.lastCheckpoint\n }\n\n async pull(): Promise<PullResult> {\n if (this.aborted) throw new AbortError()\n this.logger?.pullStart(this.loggerName)\n const start = performance.now()\n try {\n // NOTE: `SyncManager.pull` does NOT auto-enable `withKeyring`. Clients\n // that drive the keyring helpers from `recipients.ts` and want to save\n // the cold-start round-trip should call `client.pull(path, {withKeyring: true})`\n // directly. We keep `SyncManager` keyring-agnostic so it stays usable\n // for collections that don't use delegated encryption.\n const result = await this.client.pull(this.pullPath, this.lastCheckpoint)\n if (this.aborted) throw new AbortError()\n\n if (this.encryptor) {\n const decrypted = await this.encryptor.decrypt(result.data)\n if (this.aborted) throw new AbortError()\n this.localData = decrypted\n result.data = decrypted\n } else if (this.lastCheckpoint > 0) {\n this.localData = deepMerge(this.localData, result.data)\n result.data = this.localData\n } else {\n this.localData = result.data\n }\n\n this.lastHash = result.hash\n this.lastCheckpoint = result.timestamp\n this.logger?.pullSuccess(this.loggerName, Math.round(performance.now() - start))\n return result\n } catch (err) {\n this.logger?.pullError(this.loggerName, err instanceof Error ? err.message : String(err))\n throw err\n }\n }\n\n async push(data: Record<string, unknown>): Promise<{ hash: string; timestamp: number }> {\n if (this.aborted) throw new AbortError()\n if (this.validate) {\n const result = this.validate(data)\n if (result !== true) throw new ValidationError(result)\n }\n this.logger?.pushStart(this.loggerName)\n const start = performance.now()\n let attempt = 0\n let pendingData = data\n\n while (attempt <= this.maxRetries) {\n try {\n const sealed = this.encryptor\n ? await this.encryptor.encrypt(pendingData)\n : pendingData\n if (this.aborted) throw new AbortError()\n\n // v3.0 signer path: sign the document author proof over the doc-author\n // canonical input (domain-tagged, bound to documentKey) and pass it as\n // top-level body siblings of `data` (NOT inside `data`), where the server\n // verifies it and stores the raw author pubkey.\n let author: AppendAuthor | undefined\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const documentKey = stripPushPrefix(this.pushPath)\n const canonical = docAuthorCanonicalInput(documentKey, sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n author = {\n [AUTHOR_PUBKEY_FIELD]: devEdPubHex,\n [AUTHOR_SIGNATURE_FIELD]: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n sealed as Record<string, unknown>,\n this.lastHash,\n author,\n )\n if (this.aborted) throw new AbortError()\n this.lastHash = result.hash\n this.lastCheckpoint = result.timestamp\n this.localData = pendingData\n this.logger?.pushSuccess(this.loggerName, Math.round(performance.now() - start))\n return result\n } catch (err) {\n if (err instanceof AbortError) throw err\n if (!(err instanceof ConflictError) || attempt >= this.maxRetries) {\n this.logger?.pushError(this.loggerName, err instanceof Error ? err.message : String(err))\n throw err\n }\n this.logger?.conflict(this.loggerName, attempt + 1)\n try {\n const remote = await this.client.pull(this.pullPath)\n if (this.aborted) throw new AbortError()\n const remoteData = this.encryptor\n ? await this.encryptor.decrypt(remote.data)\n : remote.data\n if (this.aborted) throw new AbortError()\n this.lastHash = remote.hash\n this.lastCheckpoint = remote.timestamp\n pendingData = this.onConflict(pendingData, remoteData)\n } catch (resolveErr) {\n if (resolveErr instanceof AbortError) throw resolveErr\n const msg = resolveErr instanceof Error ? resolveErr.message : String(resolveErr)\n this.logger?.pushError(this.loggerName, `Conflict resolution failed (attempt ${attempt + 1}): ${msg}`)\n throw resolveErr\n }\n await new Promise<void>(resolve => setTimeout(resolve, Math.min(100 * Math.pow(2, attempt), 2000) + Math.random() * 100))\n attempt++\n }\n }\n throw new ConflictError()\n }\n\n async update(\n modifier: (current: Record<string, unknown>) => Record<string, unknown>\n ): Promise<{ hash: string; timestamp: number }> {\n await this.pull()\n const updated = modifier(this.localData)\n return this.push(updated)\n }\n}\n", "/** Validation result: true if valid, or an array of error messages. */\nexport type ValidationResult = true | string[]\n\n/** A function that validates data before push. */\nexport type Validator = (data: Record<string, unknown>) => ValidationResult\n\n/** Error thrown when pre-push validation fails. */\nexport class ValidationError extends Error {\n constructor(public readonly errors: string[]) {\n super(`Validation failed: ${errors.join(\"; \")}`)\n this.name = \"ValidationError\"\n }\n}\n\n/**\n * Creates a validator from a JSON Schema object.\n * Requires an Ajv-compatible validate function.\n *\n * @example\n * ```ts\n * import Ajv from \"ajv\"\n * const ajv = new Ajv()\n * const validator = createSchemaValidator(ajv, mySchema)\n * ```\n */\nexport function createSchemaValidator(\n ajv: { compile: (schema: object) => { (data: unknown): boolean; errors?: unknown }; errorsText: (errors?: unknown) => string },\n schema: object,\n): Validator {\n const validate = ajv.compile(schema)\n return (data) => {\n if (validate(data)) return true\n return [ajv.errorsText(validate.errors)]\n }\n}\n", "/** Minimal store interface for cross-tab sync. Works with both Zustand and Legend bindings. */\nexport interface BroadcastableStore {\n getState(): { data: Record<string, unknown>; dirty: boolean }\n setState(partial: { data: Record<string, unknown>; dirty: boolean }): void\n subscribe(listener: (state: { data: Record<string, unknown>; dirty: boolean }, prev: { data: Record<string, unknown>; dirty: boolean }) => void): () => void\n}\n\ninterface BroadcastPayload {\n data: Record<string, unknown>\n dirty: boolean\n}\n\n/**\n * Syncs a Starfish store across browser tabs using BroadcastChannel.\n * Works with any store that has getState/setState/subscribe (Zustand, Legend adapters, etc.).\n * Returns a cleanup function that closes the channel.\n */\nexport function setupBroadcastSync(\n store: BroadcastableStore,\n name: string,\n): () => void {\n const channel = new BroadcastChannel(`starfish-${name}`)\n let lastReceivedData: Record<string, unknown> | null = null\n\n channel.onmessage = (event: MessageEvent<unknown>) => {\n const payload = event.data as BroadcastPayload | undefined\n if (!payload || typeof payload !== \"object\" || !payload.data || typeof payload.data !== \"object\") return\n lastReceivedData = payload.data\n store.setState({ data: payload.data, dirty: !!payload.dirty })\n }\n\n const unsub = store.subscribe((state, prev) => {\n if (state.data === lastReceivedData) return\n if (state.data !== prev.data || state.dirty !== prev.dirty) {\n try {\n channel.postMessage({ data: state.data, dirty: state.dirty } satisfies BroadcastPayload)\n } catch { /* non-serializable data \u2014 skip broadcast */ }\n }\n })\n\n return () => {\n unsub()\n channel.close()\n }\n}\n\n/**\n * Syncs a Starfish store across browser tabs using storage events.\n * Fallback for environments without BroadcastChannel.\n * Returns a cleanup function.\n */\nexport function setupStorageFallback(\n store: BroadcastableStore,\n name: string,\n): () => void {\n const storageKey = `starfish-broadcast-${name}`\n let lastReceivedData: Record<string, unknown> | null = null\n\n const onStorage = (e: StorageEvent) => {\n if (e.key !== storageKey || !e.newValue) return\n let payload: BroadcastPayload\n try {\n payload = JSON.parse(e.newValue)\n } catch {\n return\n }\n if (!payload || typeof payload !== \"object\" || !payload.data || typeof payload.data !== \"object\") return\n lastReceivedData = payload.data\n store.setState({ data: payload.data, dirty: !!payload.dirty })\n }\n\n globalThis.addEventListener(\"storage\", onStorage)\n\n const unsub = store.subscribe((state, prev) => {\n if (state.data === lastReceivedData) return\n if (state.data !== prev.data || state.dirty !== prev.dirty) {\n try {\n localStorage.setItem(\n storageKey,\n JSON.stringify({ data: state.data, dirty: state.dirty } satisfies BroadcastPayload),\n )\n } catch { /* quota exceeded or non-serializable \u2014 skip */ }\n }\n })\n\n return () => {\n unsub()\n globalThis.removeEventListener(\"storage\", onStorage)\n }\n}\n\n/**\n * Auto-detects the best cross-tab sync mechanism and sets it up.\n * Uses BroadcastChannel when available, falls back to storage events.\n * Returns a cleanup function.\n */\nexport function setupCrossTabSync(\n store: BroadcastableStore,\n name: string,\n): () => void {\n if (typeof BroadcastChannel !== \"undefined\") {\n return setupBroadcastSync(store, name)\n }\n if (typeof globalThis.addEventListener === \"function\" && typeof localStorage !== \"undefined\") {\n return setupStorageFallback(store, name)\n }\n return () => {}\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,mBAAkC;AAC3C,SAAS,gBAAgB;;;ACqPzB,IAAM,4BAA4B,CAAC,OAAO,CAAC,KAAK,KAAK,QAAQ;AAC3D,QAAM,gBAAgB,IAAI;AAC1B,MAAI,aAAa,CAAC,UAAU,aAAa,YAAY;AACnD,QAAI,WAAW;AACf,QAAI,aAAa;AACf,YAAM,cAAc,WAAW,OAAO,SAAS,QAAQ,eAAe,OAAO;AAC7E,UAAI,eAAe,SAAS,IAAI,SAAS,CAAC;AAC1C,iBAAW,CAAC,UAAU;AACpB,cAAM,YAAY,SAAS,KAAK;AAChC,YAAI,CAAC,WAAW,cAAc,SAAS,GAAG;AACxC,gBAAM,gBAAgB;AACtB,sBAAY,eAAe,WAAW,aAAa;AAAA,QACrD;AAAA,MACF;AACA,UAAI,WAAW,OAAO,SAAS,QAAQ,iBAAiB;AACtD,oBAAY,cAAc,YAAY;AAAA,MACxC;AAAA,IACF;AACA,WAAO,cAAc,QAAQ;AAAA,EAC/B;AACA,QAAM,eAAe,GAAG,KAAK,KAAK,GAAG;AACrC,SAAO;AACT;AACA,IAAM,wBAAwB;AAM9B,SAAS,kBAAkB,YAAY,SAAS;AAC9C,MAAI;AACJ,MAAI;AACF,cAAU,WAAW;AAAA,EACvB,SAAS,GAAG;AACV;AAAA,EACF;AACA,QAAM,iBAAiB;AAAA,IACrB,SAAS,CAAC,SAAS;AACjB,UAAI;AACJ,YAAM,QAAQ,CAA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