@drakkar.software/starfish-client 3.0.0-alpha.5 → 3.0.0-alpha.7
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.d.ts +7 -0
- package/dist/bindings/zustand.js +5 -2
- package/dist/bindings/zustand.js.map +2 -2
- package/dist/client.d.ts +4 -2
- package/dist/index.js +4 -2
- package/dist/index.js.map +2 -2
- package/package.json +2 -2
|
@@ -104,6 +104,13 @@ export declare function useConnectivity(store: StoreApi<StarfishStore>): void;
|
|
|
104
104
|
export declare function useLastSynced(store: StoreApi<StarfishStore>): string;
|
|
105
105
|
export interface SyncInitConfig {
|
|
106
106
|
serverUrl: string;
|
|
107
|
+
/**
|
|
108
|
+
* Optional server namespace, forwarded to the underlying {@link StarfishClient}
|
|
109
|
+
* so `pullPath`/`pushPath` are rewritten to `/v1/<namespace>/…` (signed AND sent).
|
|
110
|
+
* Leave unset for a root-mounted server. Pass the bare name (e.g. `"octochat"`),
|
|
111
|
+
* not `/v1/octochat` — the `/v1/` is added by the client.
|
|
112
|
+
*/
|
|
113
|
+
namespace?: string;
|
|
107
114
|
capProvider?: StarfishCapProvider;
|
|
108
115
|
pullPath: string;
|
|
109
116
|
pushPath: string;
|
package/dist/bindings/zustand.js
CHANGED
|
@@ -440,8 +440,10 @@ var StarfishClient = class {
|
|
|
440
440
|
* @param opts.ts - optional client-supplied element timestamp (ms). Must be a
|
|
441
441
|
* non-negative integer strictly greater than the latest stored element's ts
|
|
442
442
|
* (else the server responds 409). Omit to let the server assign one.
|
|
443
|
-
* @throws {StarfishHttpError} on a non-2xx response
|
|
444
|
-
* non-monotonic timestamp
|
|
443
|
+
* @throws {StarfishHttpError} on a non-2xx response — e.g. 409
|
|
444
|
+
* `{ error: "non_monotonic_timestamp" }` for a non-monotonic timestamp, or
|
|
445
|
+
* `{ error: "append_limit_exceeded", limit }` if the collection's `maxItems`
|
|
446
|
+
* cap is reached (partition by a path parameter for higher volume).
|
|
445
447
|
*/
|
|
446
448
|
async append(path, data, opts = {}) {
|
|
447
449
|
const bodyObj = { data };
|
|
@@ -901,6 +903,7 @@ function useSyncInit(config) {
|
|
|
901
903
|
}
|
|
902
904
|
const client = new StarfishClient({
|
|
903
905
|
baseUrl: config.serverUrl,
|
|
906
|
+
namespace: config.namespace,
|
|
904
907
|
capProvider: config.capProvider,
|
|
905
908
|
fetch: config.fetch
|
|
906
909
|
});
|
|
@@ -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 { 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 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 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", "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 DEFAULT_ALG,\n signRequest,\n stableStringify,\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/** 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/**\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) {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = await this.capProvider.getCap()\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 Authorization: `Cap ${encodeCapAuth(cap)}`,\n \"X-Starfish-Sig\": sig,\n \"X-Starfish-Ts\": String(ts),\n \"X-Starfish-Nonce\": nonce,\n \"X-Starfish-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[\"X-Starfish-Pub\"] = pubHex\n return headers\n }\n return {}\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: { 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 * 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 fields (`authorPubkey` + `authorSignature`) live inside `data`\n * and are produced by `SyncManager` when a `signer` is configured.\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 ): Promise<PushSuccess> {\n const body = JSON.stringify({\n data,\n baseHash,\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 \"Content-Type\": \"application/json\",\n 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 (e.g. 409 for a\n * non-monotonic timestamp).\n */\n async append(\n path: string,\n data: Record<string, unknown>,\n opts: { ts?: number } = {},\n ): Promise<PushSuccess> {\n const bodyObj: Record<string, unknown> = { data }\n if (opts.ts !== undefined) bodyObj[\"ts\"] = opts.ts\n const body = JSON.stringify(bodyObj)\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 \"Content-Type\": \"application/json\",\n 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: { 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(\"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 \"Content-Type\": contentType,\n 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 { deepMerge, getBase64, stableStringify } 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 } 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 over stableStringify(payload-without-author-fields)\n // and attach `authorPubkey` + `authorSignature` to the sealed payload.\n // The author fields live INSIDE `data` so the server stores them with\n // the encrypted document.\n let payload: Record<string, unknown> = sealed\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const canonical = stableStringify(sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n payload = {\n ...sealed,\n authorPubkey: devEdPubHex,\n authorSignature: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n payload,\n this.lastHash,\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,C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,UAAU,QAAQ;AAE5B,YAAU,MAAM;AACd,QAAI,CAAC,QAAQ;AACX,eAAS,IAAI;AACb;AAAA,IACF;AAEA,UAAM,SAAS,IAAI,eAAe;AAAA,MAChC,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,MACpB,OAAO,OAAO;AAAA,IAChB,CAAC;AAED,UAAM,cAAc,IAAI,YAAY;AAAA,MAClC;AAAA,MACA,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,WAAW,OAAO;AAAA,MAClB,YAAY,OAAO;AAAA,MACnB,QAAQ,OAAO;AAAA,MACf,UAAU,OAAO;AAAA,IACnB,CAAC;AAED,UAAM,WAAW,oBAAoB;AAAA,MACnC,MAAM,OAAO,aAAa;AAAA,MAC1B;AAAA,MACA,SAAS,OAAO;AAAA;AAAA;AAAA,MAGhB,gBAAgB,CAAC,SAAS;AACxB,YAAI;AACF,oBAAU,UAAU,IAAI;AAAA,QAC1B,SAAS,KAAK;AACZ,mBAAS,SAAS;AAAA,YAChB,OAAO,kBAAkB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,UAC3E,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF,CAAC;AAED,aAAS,QAAQ;AAGjB,aAAS,SAAS,EAAE,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAEzC,WAAO,MAAM;AACX,eAAS,IAAI;AAAA,IACf;AAAA,EAGF,GAAG;AAAA,IACD,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO;AACT;",
|
|
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 { 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", "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 DEFAULT_ALG,\n signRequest,\n stableStringify,\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/** 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/**\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) {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = await this.capProvider.getCap()\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 Authorization: `Cap ${encodeCapAuth(cap)}`,\n \"X-Starfish-Sig\": sig,\n \"X-Starfish-Ts\": String(ts),\n \"X-Starfish-Nonce\": nonce,\n \"X-Starfish-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[\"X-Starfish-Pub\"] = pubHex\n return headers\n }\n return {}\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: { 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 * 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 fields (`authorPubkey` + `authorSignature`) live inside `data`\n * and are produced by `SyncManager` when a `signer` is configured.\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 ): Promise<PushSuccess> {\n const body = JSON.stringify({\n data,\n baseHash,\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 \"Content-Type\": \"application/json\",\n 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 bodyObj: Record<string, unknown> = { data }\n if (opts.ts !== undefined) bodyObj[\"ts\"] = opts.ts\n const body = JSON.stringify(bodyObj)\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 \"Content-Type\": \"application/json\",\n 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: { 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(\"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 \"Content-Type\": contentType,\n 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 { deepMerge, getBase64, stableStringify } 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 } 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 over stableStringify(payload-without-author-fields)\n // and attach `authorPubkey` + `authorSignature` to the sealed payload.\n // The author fields live INSIDE `data` so the server stores them with\n // the encrypted document.\n let payload: Record<string, unknown> = sealed\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const canonical = stableStringify(sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n payload = {\n ...sealed,\n authorPubkey: devEdPubHex,\n authorSignature: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n payload,\n this.lastHash,\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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,UAAM,WAAW,oBAAoB;AAAA,MACnC,MAAM,OAAO,aAAa;AAAA,MAC1B;AAAA,MACA,SAAS,OAAO;AAAA;AAAA;AAAA,MAGhB,gBAAgB,CAAC,SAAS;AACxB,YAAI;AACF,oBAAU,UAAU,IAAI;AAAA,QAC1B,SAAS,KAAK;AACZ,mBAAS,SAAS;AAAA,YAChB,OAAO,kBAAkB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,UAC3E,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF,CAAC;AAED,aAAS,QAAQ;AAGjB,aAAS,SAAS,EAAE,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAEzC,WAAO,MAAM;AACX,eAAS,IAAI;AAAA,IACf;AAAA,EAGF,GAAG;AAAA,IACD,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO;AACT;",
|
|
6
6
|
"names": ["stableStringify", "stableStringify"]
|
|
7
7
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -118,8 +118,10 @@ export declare class StarfishClient {
|
|
|
118
118
|
* @param opts.ts - optional client-supplied element timestamp (ms). Must be a
|
|
119
119
|
* non-negative integer strictly greater than the latest stored element's ts
|
|
120
120
|
* (else the server responds 409). Omit to let the server assign one.
|
|
121
|
-
* @throws {StarfishHttpError} on a non-2xx response
|
|
122
|
-
* non-monotonic timestamp
|
|
121
|
+
* @throws {StarfishHttpError} on a non-2xx response — e.g. 409
|
|
122
|
+
* `{ error: "non_monotonic_timestamp" }` for a non-monotonic timestamp, or
|
|
123
|
+
* `{ error: "append_limit_exceeded", limit }` if the collection's `maxItems`
|
|
124
|
+
* cap is reached (partition by a path parameter for higher volume).
|
|
123
125
|
*/
|
|
124
126
|
append(path: string, data: Record<string, unknown>, opts?: {
|
|
125
127
|
ts?: number;
|
package/dist/index.js
CHANGED
|
@@ -215,8 +215,10 @@ var StarfishClient = class {
|
|
|
215
215
|
* @param opts.ts - optional client-supplied element timestamp (ms). Must be a
|
|
216
216
|
* non-negative integer strictly greater than the latest stored element's ts
|
|
217
217
|
* (else the server responds 409). Omit to let the server assign one.
|
|
218
|
-
* @throws {StarfishHttpError} on a non-2xx response
|
|
219
|
-
* non-monotonic timestamp
|
|
218
|
+
* @throws {StarfishHttpError} on a non-2xx response — e.g. 409
|
|
219
|
+
* `{ error: "non_monotonic_timestamp" }` for a non-monotonic timestamp, or
|
|
220
|
+
* `{ error: "append_limit_exceeded", limit }` if the collection's `maxItems`
|
|
221
|
+
* cap is reached (partition by a path parameter for higher volume).
|
|
220
222
|
*/
|
|
221
223
|
async append(path, data, opts = {}) {
|
|
222
224
|
const bodyObj = { data };
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../src/client.ts", "../src/types.ts", "../src/sync.ts", "../src/validate.ts", "../src/logger.ts", "../src/migrate.ts", "../src/fetch.ts", "../src/resolvers.ts", "../src/history.ts", "../src/polling.ts", "../src/dedup.ts", "../src/config.ts", "../src/storage/indexeddb.ts", "../src/export.ts", "../src/background-sync.ts", "../src/service-worker.ts", "../src/bindings/suspense.ts", "../src/debounced-sync.ts", "../src/mobile-lifecycle.ts", "../src/multi-store.ts"],
|
|
4
|
-
"sourcesContent": ["export { configurePlatform } from \"@drakkar.software/starfish-protocol\"\nexport type { CryptoProvider, Base64Provider, PlatformConfig } from \"@drakkar.software/starfish-protocol\"\nexport { stableStringify, computeHash } from \"@drakkar.software/starfish-protocol\"\nexport { buildRevocationList, revocationListCanonicalSigningInput } from \"@drakkar.software/starfish-protocol\"\nexport type {\n RevocationList,\n RevocationEntry,\n RevokedSubject,\n BuildRevocationListOpts,\n} from \"@drakkar.software/starfish-protocol\"\nexport type { PullResult, PushSuccess, PullKeyringProjection } from \"@drakkar.software/starfish-protocol\"\n\nexport { StarfishClient } from \"./client.js\"\nexport type { BlobPullResult, BlobPushResult, AppendPullOptions, PullOptions } from \"./client.js\"\nexport { SyncManager, AbortError } from \"./sync.js\"\nexport type { SyncManagerOptions, SyncSigner } from \"./sync.js\"\nexport { ENCRYPTED_KEY } from \"@drakkar.software/starfish-protocol\"\nexport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nexport {\n ConflictError,\n StarfishHttpError,\n} from \"./types.js\"\nexport type {\n StarfishClientOptions,\n StarfishCapProvider,\n ConflictResolver,\n ClientPlugin,\n} from \"./types.js\"\nexport { consoleSyncLogger, noopSyncLogger, createMetricsCollector } from \"./logger.js\"\nexport type { SyncLogger, SyncMetrics, MetricsCollector } from \"./logger.js\"\nexport { createMigrator } from \"./migrate.js\"\nexport type { MigrationFn, MigrationConfig } from \"./migrate.js\"\nexport { ValidationError, createSchemaValidator } from \"./validate.js\"\nexport type { Validator, ValidationResult } from \"./validate.js\"\nexport { classifyError } from \"./fetch.js\"\nexport type { ErrorCategory } from \"./fetch.js\"\nexport {\n createUnionMerge,\n createSoftDeleteResolver,\n timestampWinner,\n pruneTombstones,\n withConflictMeta,\n} from \"./resolvers.js\"\nexport type { ConflictMeta, ConflictResolverWithMeta } from \"./resolvers.js\"\nexport { SnapshotHistory } from \"./history.js\"\nexport type { Snapshot, SnapshotHistoryOptions } from \"./history.js\"\nexport { startPolling, startAdaptivePolling } from \"./polling.js\"\nexport type { PollableState, AdaptivePollingOptions, AdaptivePollingControls } from \"./polling.js\"\nexport { createDedupFetch } from \"./dedup.js\"\nexport { fetchServerConfig } from \"./config.js\"\nexport type { EncryptionMode, CollectionClientInfo, ConfigResponse } from \"./config.js\"\nexport { createIndexedDBStorage } from \"./storage/indexeddb.js\"\nexport type { IndexedDBStorageOptions, AsyncStateStorage } from \"./storage/indexeddb.js\"\nexport { exportData, importData, exportToBlob } from \"./export.js\"\nexport type { ExportOptions } from \"./export.js\"\nexport { isBackgroundSyncSupported, registerBackgroundSync } from \"./background-sync.js\"\nexport type { BackgroundSyncOptions } from \"./background-sync.js\"\nexport { isServiceWorkerSupported, registerServiceWorker, unregisterServiceWorkers } from \"./service-worker.js\"\nexport type { ServiceWorkerOptions } from \"./service-worker.js\"\nexport { createSuspenseResource } from \"./bindings/suspense.js\"\nexport { createDebouncedSync, createDebouncedPush } from \"./debounced-sync.js\"\nexport type { DebouncedSyncOptions, DebouncedSync, DebouncedPushOptions, DebouncedPush } from \"./debounced-sync.js\"\nexport { createMobileLifecycle } from \"./mobile-lifecycle.js\"\nexport type { AppStateModule, NetInfoModule, MobileLifecycleDeps, MobileLifecycleOptions } from \"./mobile-lifecycle.js\"\nexport { createMultiStoreSync } from \"./multi-store.js\"\nexport type {\n StoreSlice,\n BackupDocument,\n MultiStoreMigrationFn,\n MultiStoreSyncOptions,\n MultiStoreSync,\n} from \"./multi-store.js\"\nexport type { AppendOnlyClientInfo } from \"./config.js\"\n", "import type { PullResult, PushSuccess } from \"@drakkar.software/starfish-protocol\"\nimport {\n DEFAULT_ALG,\n signRequest,\n stableStringify,\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/** 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/**\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) {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = await this.capProvider.getCap()\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 Authorization: `Cap ${encodeCapAuth(cap)}`,\n \"X-Starfish-Sig\": sig,\n \"X-Starfish-Ts\": String(ts),\n \"X-Starfish-Nonce\": nonce,\n \"X-Starfish-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[\"X-Starfish-Pub\"] = pubHex\n return headers\n }\n return {}\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: { 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 * 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 fields (`authorPubkey` + `authorSignature`) live inside `data`\n * and are produced by `SyncManager` when a `signer` is configured.\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 ): Promise<PushSuccess> {\n const body = JSON.stringify({\n data,\n baseHash,\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 \"Content-Type\": \"application/json\",\n 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 (e.g. 409 for a\n * non-monotonic timestamp).\n */\n async append(\n path: string,\n data: Record<string, unknown>,\n opts: { ts?: number } = {},\n ): Promise<PushSuccess> {\n const bodyObj: Record<string, unknown> = { data }\n if (opts.ts !== undefined) bodyObj[\"ts\"] = opts.ts\n const body = JSON.stringify(bodyObj)\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 \"Content-Type\": \"application/json\",\n 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: { 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(\"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 \"Content-Type\": contentType,\n 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 { deepMerge, getBase64, stableStringify } 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 } 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 over stableStringify(payload-without-author-fields)\n // and attach `authorPubkey` + `authorSignature` to the sealed payload.\n // The author fields live INSIDE `data` so the server stores them with\n // the encrypted document.\n let payload: Record<string, unknown> = sealed\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const canonical = stableStringify(sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n payload = {\n ...sealed,\n authorPubkey: devEdPubHex,\n authorSignature: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n payload,\n this.lastHash,\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", "/** Extended metrics for sync operations. */\nexport interface SyncMetrics {\n bytesTransferred?: number\n compressedSize?: number\n conflictCount?: number\n retryCount?: number\n cacheHit?: boolean\n}\n\n/** Structured logger for sync operations. */\nexport interface SyncLogger {\n pullStart(store: string): void\n pullSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void\n pullError(store: string, error: string): void\n pushStart(store: string): void\n pushSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void\n pushError(store: string, error: string): void\n conflict(store: string, attempt: number): void\n}\n\n/** Console-based sync logger with structured output. */\nexport const consoleSyncLogger: SyncLogger = {\n pullStart: (s) => console.log(`[starfish:${s}] pull started`),\n pullSuccess: (s, ms, m) => {\n let msg = `[starfish:${s}] pull OK (${ms}ms)`\n if (m?.bytesTransferred) msg += ` ${m.bytesTransferred}B`\n if (m?.cacheHit) msg += ` (cache hit)`\n console.log(msg)\n },\n pullError: (s, err) => console.error(`[starfish:${s}] pull failed: ${err}`),\n pushStart: (s) => console.log(`[starfish:${s}] push started`),\n pushSuccess: (s, ms, m) => {\n let msg = `[starfish:${s}] push OK (${ms}ms)`\n if (m?.bytesTransferred) msg += ` ${m.bytesTransferred}B`\n console.log(msg)\n },\n pushError: (s, err) => console.error(`[starfish:${s}] push failed: ${err}`),\n conflict: (s, n) => console.warn(`[starfish:${s}] conflict (attempt ${n})`),\n}\n\n/** Silent sync logger (no output). */\nexport const noopSyncLogger: SyncLogger = {\n pullStart: () => {},\n pullSuccess: () => {},\n pullError: () => {},\n pushStart: () => {},\n pushSuccess: () => {},\n pushError: () => {},\n conflict: () => {},\n}\n\n/** Accumulated metrics for a single store. */\ninterface StoreSummary {\n totalPulls: number\n totalPushes: number\n totalDurationMs: number\n totalBytes: number\n totalConflicts: number\n}\n\n/** Collects sync metrics over time. */\nexport interface MetricsCollector {\n recordPull(name: string, durationMs: number, metrics?: SyncMetrics): void\n recordPush(name: string, durationMs: number, metrics?: SyncMetrics): void\n recordConflict(name: string): void\n getSummary(): Record<string, { totalPulls: number; totalPushes: number; avgDurationMs: number; totalBytes: number; totalConflicts: number }>\n reset(): void\n}\n\n/** Create a metrics collector that accumulates sync statistics. */\nexport function createMetricsCollector(): MetricsCollector {\n const stores = new Map<string, StoreSummary>()\n\n function ensureStore(name: string): StoreSummary {\n let s = stores.get(name)\n if (!s) {\n s = { totalPulls: 0, totalPushes: 0, totalDurationMs: 0, totalBytes: 0, totalConflicts: 0 }\n stores.set(name, s)\n }\n return s\n }\n\n return {\n recordPull(name, durationMs, metrics) {\n const s = ensureStore(name)\n s.totalPulls++\n s.totalDurationMs += durationMs\n if (metrics?.bytesTransferred) s.totalBytes += metrics.bytesTransferred\n },\n recordPush(name, durationMs, metrics) {\n const s = ensureStore(name)\n s.totalPushes++\n s.totalDurationMs += durationMs\n if (metrics?.bytesTransferred) s.totalBytes += metrics.bytesTransferred\n },\n recordConflict(name) {\n ensureStore(name).totalConflicts++\n },\n getSummary() {\n const result: Record<string, { totalPulls: number; totalPushes: number; avgDurationMs: number; totalBytes: number; totalConflicts: number }> = {}\n for (const [name, s] of stores) {\n const totalOps = s.totalPulls + s.totalPushes\n result[name] = {\n totalPulls: s.totalPulls,\n totalPushes: s.totalPushes,\n avgDurationMs: totalOps > 0 ? Math.round(s.totalDurationMs / totalOps) : 0,\n totalBytes: s.totalBytes,\n totalConflicts: s.totalConflicts,\n }\n }\n return result\n },\n reset() {\n stores.clear()\n },\n }\n}\n", "/** A function that migrates data from one schema version to the next. */\nexport type MigrationFn = (data: Record<string, unknown>) => Record<string, unknown>\n\nexport interface MigrationConfig {\n /** The current schema version of the application. */\n currentVersion: number\n /** Map of version number to the migration that upgrades FROM that version. */\n migrations: Record<number, MigrationFn>\n}\n\n/**\n * Creates a migration runner that upgrades documents to the current schema version.\n *\n * Given a document with `_schemaVersion`, applies each migration in sequence\n * until the document reaches `currentVersion`. Throws if the document version\n * is ahead of the app (forward compatibility guard).\n */\nexport function createMigrator(\n config: MigrationConfig,\n): (data: Record<string, unknown>) => Record<string, unknown> {\n // Eagerly validate the migration chain\n for (let v = 1; v < config.currentVersion; v++) {\n if (!config.migrations[v]) {\n throw new Error(`Missing migration for version ${v} -> ${v + 1}`)\n }\n }\n\n return (data) => {\n const version = typeof data._schemaVersion === \"number\" ? data._schemaVersion : 1\n\n if (version > config.currentVersion) {\n throw new Error(\n `Document schema version ${version} is newer than app version ${config.currentVersion}. Update the app.`,\n )\n }\n\n if (version === config.currentVersion) return data\n\n let result = { ...data }\n for (let v = version; v < config.currentVersion; v++) {\n const fn = config.migrations[v]\n if (!fn) {\n throw new Error(`Missing migration for version ${v} -> ${v + 1}`)\n }\n try {\n result = fn(result)\n } catch (err) {\n throw new Error(\n `Migration from version ${v} to ${v + 1} failed: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n )\n }\n }\n result._schemaVersion = config.currentVersion\n return result\n }\n}\n", "/** Error category returned by classifyError. */\nexport type ErrorCategory =\n | \"network\"\n | \"auth\"\n | \"conflict\"\n | \"rate-limited\"\n | \"server\"\n | \"client\"\n | \"unknown\"\n\n/** Classify an error from a fetch response or network failure. */\nexport function classifyError(err: unknown): ErrorCategory {\n if (err instanceof Response || (err && typeof err === \"object\" && \"status\" in err)) {\n const status = (err as { status: unknown }).status\n if (typeof status !== \"number\" || isNaN(status)) return \"unknown\"\n if (status === 0) return \"network\"\n if (status === 401 || status === 403) return \"auth\"\n if (status === 409) return \"conflict\"\n if (status === 429) return \"rate-limited\"\n if (status >= 500) return \"server\"\n if (status >= 400) return \"client\"\n }\n if (err instanceof Error && /failed to fetch|fetch failed|network|load failed|ECONNREFUSED|ENOTFOUND/i.test(err.message)) return \"network\"\n return \"unknown\"\n}\n\nexport interface RetryOptions {\n /** Max number of retries (default: 3). */\n maxRetries?: number\n /** Initial delay in ms before first retry (default: 500). */\n initialDelayMs?: number\n /** Maximum delay in ms (default: 10000). */\n maxDelayMs?: number\n}\n\n/**\n * Wraps a fetch function with automatic retry for retriable errors\n * (network failures, 429, 5xx). Respects Retry-After headers.\n */\nexport function createRetryFetch(options?: RetryOptions): typeof globalThis.fetch {\n const maxRetries = Math.max(0, options?.maxRetries ?? 3)\n const initialDelay = options?.initialDelayMs ?? 500\n const maxDelay = options?.maxDelayMs ?? 10_000\n\n return async (input, init?) => {\n let attempt = 0\n while (true) {\n try {\n const res = await globalThis.fetch(input, init)\n if (res.ok || attempt >= maxRetries) return res\n\n const category = classifyError(res)\n if (category !== \"rate-limited\" && category !== \"server\") return res\n\n const retryAfter = res.headers.get(\"Retry-After\")?.trim()\n let delay: number\n if (retryAfter) {\n const seconds = Number(retryAfter)\n if (retryAfter !== \"\" && !isNaN(seconds)) {\n delay = Math.min(seconds * 1000, maxDelay)\n } else {\n const date = Date.parse(retryAfter)\n delay = isNaN(date) ? initialDelay : Math.min(Math.max(date - Date.now(), 0), maxDelay)\n }\n } else {\n delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay)\n }\n\n await new Promise<void>((r) => setTimeout(r, delay))\n attempt++\n } catch (err) {\n if (attempt >= maxRetries) throw err\n const category = classifyError(err)\n if (category !== \"network\") throw err\n\n const delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay)\n await new Promise<void>((r) => setTimeout(r, delay))\n attempt++\n }\n }\n }\n}\n\ntype BreakerState = \"closed\" | \"open\" | \"half-open\"\n\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures to open the circuit (default: 5). */\n threshold?: number\n /** Cooldown in ms before transitioning from open to half-open (default: 30000). */\n cooldownMs?: number\n}\n\n/** Circuit breaker that prevents requests when the backend is unavailable. */\nexport class CircuitBreaker {\n private state: BreakerState = \"closed\"\n private failures = 0\n private openedAt = 0\n private readonly threshold: number\n private readonly cooldownMs: number\n\n constructor(options?: CircuitBreakerOptions) {\n this.threshold = options?.threshold ?? 5\n this.cooldownMs = options?.cooldownMs ?? 30_000\n }\n\n getState(): BreakerState {\n this.maybeTransition()\n return this.state\n }\n\n isOpen(): boolean {\n return this.getState() === \"open\"\n }\n\n recordSuccess(): void {\n this.failures = 0\n this.state = \"closed\"\n }\n\n recordFailure(): void {\n this.failures++\n if (this.state === \"half-open\" || this.failures >= this.threshold) {\n this.state = \"open\"\n this.openedAt = Date.now()\n }\n }\n\n private maybeTransition(): void {\n if (this.state === \"open\" && Date.now() - this.openedAt >= this.cooldownMs) {\n this.state = \"half-open\"\n }\n }\n}\n\n/**\n * Wraps fetch to gzip-compress string request bodies using the CompressionStream API.\n * Adds Content-Encoding: gzip header. Non-string bodies (ArrayBuffer, Blob, etc.)\n * are passed through uncompressed. Requires CompressionStream (browsers, Node.js 18+, Deno).\n */\nexport function createCompressedFetch(inner?: typeof globalThis.fetch): typeof globalThis.fetch {\n const baseFetch = inner ?? globalThis.fetch.bind(globalThis)\n return async (input, init?) => {\n if (!init?.body || typeof CompressionStream === \"undefined\") {\n return baseFetch(input, init)\n }\n\n const bodyText = typeof init.body === \"string\" ? init.body : null\n if (!bodyText) return baseFetch(input, init)\n\n try {\n const stream = new Blob([bodyText]).stream().pipeThrough(new CompressionStream(\"gzip\"))\n const compressed = await new Response(stream).arrayBuffer()\n\n const normalized = Object.fromEntries(new Headers(init.headers as HeadersInit).entries())\n normalized[\"content-encoding\"] = \"gzip\"\n\n return baseFetch(input, {\n ...init,\n body: compressed,\n headers: normalized,\n })\n } catch {\n return baseFetch(input, init)\n }\n }\n}\n\n/**\n * Combines retry and circuit breaker into a single resilient fetch wrapper.\n * Rejects immediately when the circuit is open.\n */\nexport function createResilientFetch(\n retryOptions?: RetryOptions,\n breakerOptions?: CircuitBreakerOptions,\n): { fetch: typeof globalThis.fetch; breaker: CircuitBreaker } {\n const breaker = new CircuitBreaker(breakerOptions)\n const retryFetch = createRetryFetch(retryOptions)\n\n const resilientFetch: typeof globalThis.fetch = async (input, init?) => {\n if (breaker.isOpen()) {\n const cooldown = Math.ceil((breakerOptions?.cooldownMs ?? 30_000) / 1000)\n throw new Error(`Request blocked: too many consecutive failures. Retry in ${cooldown}s.`)\n }\n\n try {\n const res = await retryFetch(input, init)\n if (res.status >= 500) {\n breaker.recordFailure()\n } else {\n breaker.recordSuccess()\n }\n return res\n } catch (err) {\n breaker.recordFailure()\n throw err\n }\n }\n\n return { fetch: resilientFetch, breaker }\n}\n", "import type { ConflictResolver } from \"./types.js\"\n\n/** Metadata about which fields were affected during conflict resolution. */\nexport interface ConflictMeta {\n /** Field names that differed between local and remote. */\n conflictedFields: string[]\n /** How the conflict was resolved. */\n resolvedBy: \"local\" | \"remote\" | \"merged\"\n /** Timestamp of resolution. */\n timestamp: number\n}\n\n/** Conflict resolver that also returns metadata about the resolution. */\nexport type ConflictResolverWithMeta = (\n local: Record<string, unknown>,\n remote: Record<string, unknown>,\n) => { data: Record<string, unknown>; meta: ConflictMeta }\n\n/** Shallow structural comparison of two values. Handles objects, arrays, and primitives. */\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a == null || b == null) return a === b\n if (typeof a !== typeof b) return false\n if (typeof a !== \"object\") return false\n\n if (Array.isArray(a) !== Array.isArray(b)) return false\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((v, i) => shallowEqual(v, b[i]))\n }\n\n const aObj = a as Record<string, unknown>\n const bObj = b as Record<string, unknown>\n const aKeys = Object.keys(aObj)\n const bKeys = Object.keys(bObj)\n if (aKeys.length !== bKeys.length) return false\n return aKeys.every((k) => shallowEqual(aObj[k], bObj[k]))\n}\n\n/**\n * Wrap a standard ConflictResolver to also return metadata about which fields conflicted.\n * Compares local and remote keys to detect differing fields.\n */\nexport function withConflictMeta(resolver: ConflictResolver): ConflictResolverWithMeta {\n return (local, remote) => {\n const conflictedFields: string[] = []\n const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)])\n for (const key of allKeys) {\n const lv = local[key]\n const rv = remote[key]\n if (!shallowEqual(lv, rv)) {\n conflictedFields.push(key)\n }\n }\n\n const data = resolver(local, remote)\n\n // Determine how it was resolved using structural comparison\n let resolvedBy: \"local\" | \"remote\" | \"merged\" = \"merged\"\n if (shallowEqual(data, local)) resolvedBy = \"local\"\n else if (shallowEqual(data, remote)) resolvedBy = \"remote\"\n\n return {\n data,\n meta: {\n conflictedFields,\n resolvedBy,\n timestamp: Date.now(),\n },\n }\n }\n}\n\n/** Compare two timestamp values. Handles both numeric (epoch) and string (ISO-8601) timestamps. */\nfunction compareTimestamps(a: unknown, b: unknown): boolean {\n if (typeof a === \"number\" && typeof b === \"number\") return a >= b\n return String(a ?? \"\") >= String(b ?? \"\")\n}\n\n/**\n * Creates a conflict resolver that merges arrays by ID with per-item\n * timestamp comparison, and uses document-level timestamp for scalars.\n *\n * For arrays: builds a union of both sets keyed by `idKey`. When both\n * sides have the same item, the one with the newer `timestampKey` wins.\n * For scalars: the document with the newer `documentTimestampKey` wins.\n *\n * @example\n * ```ts\n * const merge = createUnionMerge()\n * const sync = new SyncManager({ ..., onConflict: merge })\n * ```\n */\nexport function createUnionMerge(options?: {\n /** Key used to identify items in arrays (default: \"id\"). */\n idKey?: string\n /** Key used for per-item timestamp comparison (default: \"updatedAt\"). */\n timestampKey?: string\n /** Key used for document-level timestamp comparison (default: \"timestamp\"). */\n documentTimestampKey?: string\n}): ConflictResolver {\n const idKey = options?.idKey ?? \"id\"\n const tsKey = options?.timestampKey ?? \"updatedAt\"\n const docTsKey = options?.documentTimestampKey ?? \"timestamp\"\n\n return (local, remote) => {\n const result: Record<string, unknown> = {}\n const localNewer = compareTimestamps(local[docTsKey], remote[docTsKey])\n const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)])\n\n for (const key of allKeys) {\n const lv = local[key]\n const rv = remote[key]\n\n // Both sides have arrays \u2014 attempt ID-based union\n if (Array.isArray(lv) && Array.isArray(rv)) {\n const map = new Map<unknown, Record<string, unknown>>()\n\n // Seed with remote items\n for (const item of rv) {\n if (item && typeof item === \"object\" && idKey in item) {\n map.set((item as Record<string, unknown>)[idKey], item as Record<string, unknown>)\n } else {\n map.set(Symbol(), item as Record<string, unknown>)\n }\n }\n\n // Overlay local items (per-item timestamp wins)\n for (const item of lv) {\n if (item && typeof item === \"object\" && idKey in item) {\n const localItem = item as Record<string, unknown>\n const id = localItem[idKey]\n const remoteItem = map.get(id)\n if (!remoteItem) {\n map.set(id, localItem)\n } else {\n if (compareTimestamps(localItem[tsKey], remoteItem[tsKey])) {\n map.set(id, localItem)\n }\n }\n } else {\n map.set(Symbol(), item as Record<string, unknown>)\n }\n }\n\n result[key] = [...map.values()]\n } else if (lv !== undefined && rv !== undefined) {\n // Scalar: document-level timestamp wins\n result[key] = localNewer ? lv : rv\n } else {\n // Only one side has the key\n result[key] = lv ?? rv\n }\n }\n\n return result\n }\n}\n\n/**\n * Creates a conflict resolver that handles soft-deleted items (tombstones).\n * Extends union merge with tombstone awareness: if an item exists on one side\n * with a `deletedAtKey` set, that deletion is respected even if the other side\n * still has the item alive \u2014 as long as the deletion timestamp is newer.\n */\nexport function createSoftDeleteResolver(options?: {\n idKey?: string\n timestampKey?: string\n documentTimestampKey?: string\n /** Key marking an item as deleted (default: \"_deletedAt\"). */\n deletedAtKey?: string\n}): ConflictResolver {\n const idKey = options?.idKey ?? \"id\"\n const tsKey = options?.timestampKey ?? \"updatedAt\"\n const deletedAtKey = options?.deletedAtKey ?? \"_deletedAt\"\n const baseMerge = createUnionMerge(options)\n\n return (local, remote) => {\n const merged = baseMerge(local, remote)\n\n // Build a tombstone map from both sides: id \u2192 deletedAt timestamp\n const tombstones = new Map<unknown, unknown>()\n for (const source of [local, remote]) {\n for (const key of Object.keys(source)) {\n const arr = source[key]\n if (!Array.isArray(arr)) continue\n for (const item of arr) {\n if (item && typeof item === \"object\" && idKey in item && deletedAtKey in item) {\n const rec = item as Record<string, unknown>\n const id = rec[idKey]\n const deletedAt = rec[deletedAtKey]\n if (typeof deletedAt === \"number\" || typeof deletedAt === \"string\") {\n const existing = tombstones.get(id)\n if (existing == null || compareTimestamps(deletedAt, existing)) tombstones.set(id, deletedAt)\n }\n }\n }\n }\n }\n\n // For merged arrays, ensure tombstoned items stay deleted\n // (don't resurrect an item if its tombstone is newer than its updatedAt)\n for (const key of Object.keys(merged)) {\n const value = merged[key]\n if (!Array.isArray(value)) continue\n\n merged[key] = value.filter((item) => {\n if (!item || typeof item !== \"object\" || !(idKey in item)) return true\n const rec = item as Record<string, unknown>\n const id = rec[idKey]\n const deletedAt = tombstones.get(id)\n if (deletedAt == null) return true\n // Keep the item if it has a deletedAt (it's the tombstone itself)\n if (rec[deletedAtKey] != null) return true\n // Filter out alive items that have a newer tombstone\n return compareTimestamps(rec[tsKey], deletedAt) && rec[tsKey] !== deletedAt\n })\n }\n\n return merged\n }\n}\n\n/**\n * Simple resolver: the document with the newer timestamp wins entirely.\n * No per-field or per-item merging.\n */\nexport function timestampWinner(\n timestampKey = \"timestamp\",\n): ConflictResolver {\n return (local, remote) => {\n return compareTimestamps(local[timestampKey], remote[timestampKey])\n ? local\n : remote\n }\n}\n\n/**\n * Remove expired tombstones from an array of items.\n * Items with a `deletedAtKey` older than `ttlMs` are pruned.\n *\n * @param items - Array of items, some with a deletedAt timestamp\n * @param ttlMs - Time-to-live in ms for tombstones (default: 30 days)\n * @param deletedAtKey - Key marking deletion timestamp (default: \"_deletedAt\")\n */\nexport function pruneTombstones<T extends Record<string, unknown>>(\n items: T[],\n ttlMs = 30 * 24 * 60 * 60 * 1000,\n deletedAtKey = \"_deletedAt\",\n): T[] {\n const cutoff = Date.now() - ttlMs\n return items.filter((item) => {\n const deletedAt = item[deletedAtKey]\n if (deletedAt == null) return true\n if (typeof deletedAt === \"number\") return deletedAt > cutoff\n if (typeof deletedAt === \"string\") return new Date(deletedAt).getTime() > cutoff\n return false\n })\n}\n", "export interface Snapshot {\n timestamp: number\n label: string\n data: string\n}\n\nexport interface SnapshotHistoryOptions {\n /** Maximum number of snapshots to retain. Oldest are trimmed first. Default: 20. */\n maxSnapshots?: number\n /** localStorage key for persistence. Pass to enable auto-save/load. */\n storageKey?: string\n}\n\nexport class SnapshotHistory {\n private snapshots: Snapshot[] = []\n private readonly maxSnapshots: number\n private readonly storageKey: string | undefined\n\n constructor(options?: SnapshotHistoryOptions) {\n this.maxSnapshots = options?.maxSnapshots ?? 20\n this.storageKey = options?.storageKey\n\n if (this.storageKey) {\n try {\n const raw = localStorage.getItem(this.storageKey)\n if (raw) {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) this.snapshots = parsed\n }\n } catch { /* corrupted or unavailable \u2014 start fresh */ }\n }\n }\n\n /** Take a labeled snapshot of the given data. */\n take(label: string, data: Record<string, unknown>): void {\n this.snapshots.push({\n timestamp: Date.now(),\n label,\n data: JSON.stringify(data),\n })\n if (this.snapshots.length > this.maxSnapshots) {\n this.snapshots = this.snapshots.slice(-this.maxSnapshots)\n }\n this.persist()\n }\n\n /** Restore data from a snapshot at the given index. Returns undefined if index is invalid or data is corrupt. */\n restore(index: number): Record<string, unknown> | undefined {\n const snapshot = this.snapshots[index]\n if (!snapshot) return undefined\n try {\n return JSON.parse(snapshot.data)\n } catch {\n return undefined\n }\n }\n\n /** List available snapshots (metadata only, no data payload). */\n list(): Array<{ timestamp: number; label: string }> {\n return this.snapshots.map(({ timestamp, label }) => ({ timestamp, label }))\n }\n\n /** Clear all snapshots. */\n clear(): void {\n this.snapshots = []\n this.persist()\n }\n\n private persist(): void {\n if (!this.storageKey) return\n try {\n localStorage.setItem(this.storageKey, JSON.stringify(this.snapshots))\n } catch { /* quota exceeded \u2014 skip silently */ }\n }\n}\n", "/** Minimal state needed by polling utilities. */\nexport interface PollableState {\n online: boolean\n syncing: boolean\n}\n\nconst DEFAULT_INTERVALS: Record<string, number> = {\n \"slow-2g\": 120_000,\n \"2g\": 60_000,\n \"3g\": 30_000,\n \"4g\": 10_000,\n}\n\nconst DEFAULT_FALLBACK_MS = 15_000\n\n/**\n * Start periodic pulling at a fixed interval.\n * Skips pulls when offline or already syncing.\n * Returns a cleanup function that stops polling.\n */\nexport function startPolling(\n pullFn: () => Promise<void>,\n getState: () => PollableState,\n intervalMs = 30_000,\n): () => void {\n const timer = setInterval(() => {\n const { online, syncing } = getState()\n if (online && !syncing) pullFn().catch((err) => { console.error(\"[Starfish] poll failed:\", err) })\n }, intervalMs)\n\n return () => clearInterval(timer)\n}\n\nexport interface AdaptivePollingOptions {\n /** Override the base interval in ms. If set, skips network quality detection. */\n intervalMs?: number\n /** Custom mapping from effectiveType to interval in ms. */\n intervals?: Record<string, number>\n}\n\nexport interface AdaptivePollingControls {\n pause: () => void\n resume: () => void\n stop: () => void\n}\n\n/**\n * Start polling with adaptive intervals based on network quality.\n * Uses the Network Information API (`navigator.connection.effectiveType`) when available.\n * Returns controls to pause, resume, or stop polling.\n */\nexport function startAdaptivePolling(\n pullFn: () => Promise<void>,\n getState: () => PollableState,\n options?: AdaptivePollingOptions,\n): AdaptivePollingControls {\n let intervalMs: number\n\n if (options?.intervalMs != null) {\n intervalMs = options.intervalMs\n } else {\n const intervals = options?.intervals ?? DEFAULT_INTERVALS\n let effectiveType: string | undefined\n if (typeof navigator !== \"undefined\" && \"connection\" in navigator) {\n effectiveType = (navigator as unknown as { connection: { effectiveType?: string } }).connection.effectiveType\n }\n intervalMs = (effectiveType != null ? intervals[effectiveType] : undefined) ?? DEFAULT_FALLBACK_MS\n }\n\n let paused = false\n\n const timer = setInterval(() => {\n if (paused) return\n const { online, syncing } = getState()\n if (online && !syncing) pullFn().catch((err) => { console.error(\"[Starfish] adaptive poll failed:\", err) })\n }, intervalMs)\n\n return {\n pause: () => { paused = true },\n resume: () => { paused = false },\n stop: () => clearInterval(timer),\n }\n}\n", "/**\n * Request deduplication: prevents multiple concurrent identical GET requests.\n * If a GET request is in-flight for a URL, subsequent identical GET requests\n * return the same Promise. POST/PUT/DELETE/PATCH are never deduped.\n */\nexport function createDedupFetch(\n baseFetch: typeof globalThis.fetch = globalThis.fetch.bind(globalThis),\n): typeof globalThis.fetch {\n const inflightGets = new Map<string, Promise<Response>>()\n\n return (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const method = (init?.method ?? \"GET\").toUpperCase()\n\n // Only dedup GET requests\n if (method !== \"GET\") {\n return baseFetch(input, init)\n }\n\n const url = typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url\n\n const existing = inflightGets.get(url)\n if (existing) {\n // Return a clone \u2014 the original is reserved for cloning only\n return existing.then((res) => res.clone())\n }\n\n // Store a promise that resolves to a response we keep solely for cloning.\n // The first caller also gets a clone, ensuring the \"master\" body is never consumed.\n const promise = baseFetch(input, init)\n .then((res) => res)\n .finally(() => {\n inflightGets.delete(url)\n })\n\n inflightGets.set(url, promise)\n\n // First caller also gets a clone so the cached response body stays unconsumed\n return promise.then((res) => res.clone())\n }) as typeof globalThis.fetch\n}\n", "/** Encryption modes supported by the Starfish server. */\nexport type EncryptionMode = \"none\" | \"delegated\"\n\n/** Append-only configuration exposed via GET /config. */\nexport interface AppendOnlyClientInfo {\n /** Append-only strategy. Only `\"by_timestamp\"` is currently supported. */\n type: \"by_timestamp\"\n /** Array field name in the stored document. Defaults to \"items\". */\n field?: string\n /** false = no storage write (replaces queueOnly). true/absent = append to array. */\n persist?: boolean\n}\n\n/** Per-collection metadata returned by GET /config. */\nexport interface CollectionClientInfo {\n name: string\n maxBodyBytes: number\n encryption: EncryptionMode\n allowedMimeTypes: string[]\n pullOnly?: boolean\n pushOnly?: boolean\n appendOnly?: AppendOnlyClientInfo\n ttlMs?: number\n forceFullFetch?: boolean\n}\n\n/** Response shape of GET /config. */\nexport interface ConfigResponse {\n collections: CollectionClientInfo[]\n namespaces?: Record<string, { collections: CollectionClientInfo[] }>\n}\n\n/**\n * Fetch the server's collection manifest from GET /config.\n *\n * @param baseUrl - Base URL of the Starfish server (e.g. `\"https://api.example.com/v1\"`).\n * @param options.headers - Optional request headers (e.g. `Authorization`).\n * @throws {Error} if the server returns a non-2xx response.\n */\nexport async function fetchServerConfig(\n baseUrl: string,\n options?: { headers?: Record<string, string> },\n): Promise<ConfigResponse> {\n const url = `${baseUrl.replace(/\\/$/, \"\")}/config`\n const res = await fetch(url, {\n method: \"GET\",\n headers: options?.headers,\n })\n if (!res.ok) {\n throw new Error(`fetchServerConfig: ${res.status} ${res.statusText}`)\n }\n return res.json() as Promise<ConfigResponse>\n}\n", "/**\n * IndexedDB-based storage adapter for Zustand persistence.\n * Implements the same interface as Zustand's StateStorage (getItem/setItem/removeItem).\n * Supports larger data than localStorage (typically 50MB+).\n */\n\nexport interface IndexedDBStorageOptions {\n /** Database name. Default: \"starfish\" */\n dbName?: string\n /** Object store name. Default: \"state\" */\n storeName?: string\n}\n\nexport interface AsyncStateStorage {\n getItem: (name: string) => Promise<string | null>\n setItem: (name: string, value: string) => Promise<void>\n removeItem: (name: string) => Promise<void>\n}\n\nfunction openDB(dbName: string, storeName: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(dbName, 1)\n request.onupgradeneeded = () => {\n const db = request.result\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName)\n }\n }\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n}\n\nfunction idbRequest<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n}\n\nexport function createIndexedDBStorage(\n opts?: IndexedDBStorageOptions,\n): AsyncStateStorage {\n const dbName = opts?.dbName ?? \"starfish\"\n const storeName = opts?.storeName ?? \"state\"\n let dbPromise: Promise<IDBDatabase> | null = null\n\n function getDB(): Promise<IDBDatabase> {\n if (!dbPromise) {\n dbPromise = openDB(dbName, storeName).catch((err) => {\n dbPromise = null // Reset so next call retries\n throw err\n })\n }\n return dbPromise\n }\n\n return {\n async getItem(name: string): Promise<string | null> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readonly\")\n const store = tx.objectStore(storeName)\n const result = await idbRequest(store.get(name))\n return result ?? null\n },\n\n async setItem(name: string, value: string): Promise<void> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readwrite\")\n const store = tx.objectStore(storeName)\n await idbRequest(store.put(value, name))\n },\n\n async removeItem(name: string): Promise<void> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readwrite\")\n const store = tx.objectStore(storeName)\n await idbRequest(store.delete(name))\n },\n }\n}\n", "/**\n * Data export/import helpers for Starfish sync data.\n * Supports JSON and CSV formats.\n */\n\nexport interface ExportOptions {\n /** Output format. Default: \"json\" */\n format?: \"json\" | \"csv\"\n /** Pretty-print JSON output. Default: false */\n pretty?: boolean\n}\n\n/**\n * Export data to a string representation.\n * JSON: serializes the full object.\n * CSV: flattens top-level keys into columns. Array values are JSON-encoded.\n */\nexport function exportData(\n data: Record<string, unknown>,\n opts?: ExportOptions,\n): string {\n const format = opts?.format ?? \"json\"\n\n if (format === \"json\") {\n return opts?.pretty\n ? JSON.stringify(data, null, 2)\n : JSON.stringify(data)\n }\n\n // CSV export: each top-level key becomes a column\n return toCsv(data)\n}\n\n/**\n * Import data from a string representation.\n */\nexport function importData(\n raw: string,\n format: \"json\" | \"csv\" = \"json\",\n): Record<string, unknown> {\n if (format === \"json\") {\n const parsed = JSON.parse(raw)\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"Expected a JSON object\")\n }\n return parsed as Record<string, unknown>\n }\n\n return fromCsv(raw)\n}\n\n/**\n * Export data to a Blob suitable for download.\n */\nexport function exportToBlob(\n data: Record<string, unknown>,\n opts?: ExportOptions,\n): Blob {\n const format = opts?.format ?? \"json\"\n const content = exportData(data, opts)\n const mimeType = format === \"csv\" ? \"text/csv;charset=utf-8\" : \"application/json;charset=utf-8\"\n return new Blob([content], { type: mimeType })\n}\n\nfunction toCsv(data: Record<string, unknown>): string {\n const keys = Object.keys(data)\n const header = keys.map(escapeCsvField).join(\",\")\n\n const values = keys.map((k) => {\n const v = data[k]\n if (v === null || v === undefined) return \"\"\n if (typeof v === \"object\") return escapeCsvField(JSON.stringify(v))\n return escapeCsvField(String(v))\n })\n\n return `${header}\\n${values.join(\",\")}`\n}\n\nfunction fromCsv(raw: string): Record<string, unknown> {\n const lines = raw.trim().split(\"\\n\")\n if (lines.length < 2) {\n throw new Error(\"CSV must have at least a header row and a data row\")\n }\n\n const headers = parseCsvLine(lines[0]!)\n const values = parseCsvLine(lines[1]!)\n\n const result: Record<string, unknown> = {}\n for (let i = 0; i < headers.length; i++) {\n const key = headers[i]!\n const val = values[i] ?? \"\"\n // Try to parse JSON values\n try {\n result[key] = JSON.parse(val)\n } catch {\n result[key] = val\n }\n }\n return result\n}\n\nfunction escapeCsvField(field: string): string {\n if (field.includes(\",\") || field.includes('\"') || field.includes(\"\\n\")) {\n return `\"${field.replace(/\"/g, '\"\"')}\"`\n }\n return field\n}\n\nfunction parseCsvLine(line: string): string[] {\n const result: string[] = []\n let current = \"\"\n let inQuotes = false\n\n for (let i = 0; i < line.length; i++) {\n const ch = line[i]!\n if (inQuotes) {\n if (ch === '\"' && line[i + 1] === '\"') {\n current += '\"'\n i++\n } else if (ch === '\"') {\n inQuotes = false\n } else {\n current += ch\n }\n } else {\n if (ch === '\"') {\n inQuotes = true\n } else if (ch === \",\") {\n result.push(current)\n current = \"\"\n } else {\n current += ch\n }\n }\n }\n result.push(current)\n return result\n}\n", "/**\n * Background Sync API integration for pending changes.\n * Uses the Web Background Sync API to retry failed sync operations\n * when connectivity is restored, even if the app is closed.\n */\n\nexport interface BackgroundSyncOptions {\n /** Sync event tag. Default: \"starfish-sync\" */\n tag?: string\n}\n\n/** Check if the Background Sync API is supported in the current environment. */\nexport function isBackgroundSyncSupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n \"serviceWorker\" in navigator &&\n \"SyncManager\" in globalThis\n )\n}\n\n/**\n * Register a background sync event with the active service worker.\n * Returns true if registration succeeded, false if not supported or no active SW.\n */\nexport async function registerBackgroundSync(\n opts?: BackgroundSyncOptions,\n): Promise<boolean> {\n if (!isBackgroundSyncSupported()) return false\n\n const tag = opts?.tag ?? \"starfish-sync\"\n\n try {\n const registration = await navigator.serviceWorker.ready\n // @ts-expect-error - SyncManager types may not be available\n await registration.sync.register(tag)\n return true\n } catch {\n return false\n }\n}\n", "/**\n * Service Worker utilities for offline support and PWA functionality.\n */\n\nexport interface ServiceWorkerOptions {\n /** Scope for the service worker registration. */\n scope?: string\n /** Called when an updated service worker is available. */\n onUpdate?: (registration: ServiceWorkerRegistration) => void\n}\n\n/** Check if service workers are supported in the current environment. */\nexport function isServiceWorkerSupported(): boolean {\n return typeof navigator !== \"undefined\" && \"serviceWorker\" in navigator\n}\n\n/**\n * Register a service worker for offline support.\n * Returns the registration, or null if not supported.\n */\nexport async function registerServiceWorker(\n scriptUrl: string,\n opts?: ServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (!isServiceWorkerSupported()) return null\n\n try {\n const registration = await navigator.serviceWorker.register(scriptUrl, {\n scope: opts?.scope,\n })\n\n if (opts?.onUpdate) {\n registration.onupdatefound = () => {\n const installingWorker = registration.installing\n if (installingWorker) {\n installingWorker.onstatechange = () => {\n if (\n installingWorker.state === \"installed\" &&\n navigator.serviceWorker.controller\n ) {\n opts.onUpdate!(registration)\n }\n }\n }\n }\n }\n\n return registration\n } catch {\n return null\n }\n}\n\n/** Unregister all service worker registrations. Returns true if any were unregistered. */\nexport async function unregisterServiceWorkers(): Promise<boolean> {\n if (!isServiceWorkerSupported()) return false\n\n try {\n const registrations = await navigator.serviceWorker.getRegistrations()\n let unregistered = false\n for (const registration of registrations) {\n const result = await registration.unregister()\n if (result) unregistered = true\n }\n return unregistered\n } catch {\n return false\n }\n}\n", "/**\n * React Suspense integration for Starfish sync data.\n * Creates resources that throw Promises while loading (Suspense protocol).\n */\n\ntype SuspenseStatus = \"pending\" | \"resolved\" | \"rejected\"\n\ninterface SuspenseResource<T> {\n /** Read the resource value. Throws a Promise while pending (Suspense protocol). */\n read(): T\n}\n\n/**\n * Create a Suspense-compatible resource from an async fetcher.\n * The first call to `read()` triggers the fetch. While loading, `read()` throws\n * a Promise (which React Suspense catches to show a fallback). Once resolved,\n * `read()` returns the value synchronously.\n *\n * @example\n * ```tsx\n * const resource = createSuspenseResource(() => syncManager.pull())\n * function MyComponent() {\n * const data = resource.read() // throws while loading, returns data when ready\n * return <div>{JSON.stringify(data)}</div>\n * }\n * ```\n */\nexport function createSuspenseResource<T>(\n fetcher: () => Promise<T>,\n): SuspenseResource<T> {\n let status: SuspenseStatus = \"pending\"\n let result: T\n let error: unknown\n let promise: Promise<void> | null = null\n\n function init(): Promise<void> {\n if (promise) return promise\n promise = fetcher().then(\n (value) => {\n status = \"resolved\"\n result = value\n },\n (err) => {\n status = \"rejected\"\n error = err\n },\n )\n return promise\n }\n\n return {\n read(): T {\n switch (status) {\n case \"pending\":\n throw init()\n case \"resolved\":\n return result\n case \"rejected\":\n throw error\n }\n },\n }\n}\n", "import type { StoreApi } from \"zustand/vanilla\"\nimport type { StarfishStore } from \"./bindings/zustand.js\"\nimport type { SyncManager } from \"./sync.js\"\n\n// \u2500\u2500 Shared types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DebouncedSyncOptions {\n /**\n * How long to wait after the last `notify()` call before pushing (default: 2000 ms).\n * Shorter values reduce latency; longer values batch more edits into a single push.\n */\n delayMs?: number\n /**\n * Emit a warning when the estimated encrypted payload exceeds this byte count (default: 900 KB).\n * The estimate multiplies the JSON size by 1.34 (base64 overhead for encrypted blobs).\n * Set to `Infinity` to disable.\n */\n warnBytes?: number\n /**\n * Block the push when the estimated encrypted payload exceeds this byte count (default: 1 MB).\n * Prevents cryptic 413 errors from the server. Set to `Infinity` to disable.\n */\n maxBytes?: number\n /**\n * Serialize store data to a sync document before pushing.\n * Called inside the debounce timer, so it always captures the latest state.\n * If omitted, `store.getState().data` is used as-is.\n */\n serialize?: (currentData: Record<string, unknown>) => Record<string, unknown>\n /**\n * Called when the estimated payload size exceeds `warnBytes` but is still below `maxBytes`.\n * Use to show a warning in the UI.\n */\n onSizeWarning?: (estimatedBytes: number) => void\n /**\n * Called when the estimated payload size exceeds `maxBytes`.\n * The push is blocked. Use to alert the user that data needs to be pruned.\n * If omitted, a console error is printed.\n */\n onSizeExceeded?: (estimatedBytes: number) => void\n}\n\nexport interface DebouncedSync {\n /**\n * Schedule a push. If called again within `delayMs`, the timer resets.\n * Safe to call on every domain store mutation.\n */\n notify: () => void\n /** Cancel any pending debounced push. Does not affect an already-in-flight push. */\n cancel: () => void\n}\n\nexport interface DebouncedPushOptions {\n /**\n * How long to wait after the last `notify()` call before pushing (default: 2000 ms).\n */\n delayMs?: number\n /**\n * Required: provides the document to push when the debounce timer fires.\n * Called inside the timer so it always captures the latest state.\n */\n serialize: () => Record<string, unknown>\n /**\n * Emit a warning when the estimated encrypted payload exceeds this byte count (default: 900 KB).\n * Set to `Infinity` to disable.\n */\n warnBytes?: number\n /**\n * Block the push when the estimated encrypted payload exceeds this byte count (default: 1 MB).\n * Set to `Infinity` to disable.\n */\n maxBytes?: number\n /**\n * Called when the estimated payload size exceeds `warnBytes` but is below `maxBytes`.\n */\n onSizeWarning?: (estimatedBytes: number) => void\n /**\n * Called when the estimated payload size exceeds `maxBytes`. The push is blocked.\n * If omitted, a console error is printed.\n */\n onSizeExceeded?: (estimatedBytes: number) => void\n /**\n * Called when `syncManager.push()` throws. Default: `console.warn`.\n */\n onError?: (err: unknown) => void\n}\n\nexport interface DebouncedPush {\n /**\n * Schedule a push. If called again within `delayMs`, the timer resets.\n */\n notify: () => void\n /** Cancel any pending debounced push. Does not affect an already-in-flight push. */\n cancel: () => void\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst DEFAULT_DELAY_MS = 2000\nconst DEFAULT_WARN_BYTES = 900 * 1024 // 900 KB\nconst DEFAULT_MAX_BYTES = 1024 * 1024 // 1 MB\n\ninterface SizeGuardOptions {\n warnBytes: number\n maxBytes: number\n onSizeWarning?: (bytes: number) => void\n onSizeExceeded?: (bytes: number) => void\n}\n\n/** Returns true if the push should be blocked. */\nfunction checkPayloadSize(doc: Record<string, unknown>, opts: SizeGuardOptions): boolean {\n // Estimate encrypted payload size. AES-GCM output is similar to input size;\n // base64 encoding adds ~33% overhead, plus a small IV/tag overhead.\n const estimatedBytes = Math.ceil(JSON.stringify(doc).length * 1.34)\n\n if (estimatedBytes > opts.maxBytes) {\n if (opts.onSizeExceeded) {\n opts.onSizeExceeded(estimatedBytes)\n } else {\n console.error(\n `[starfish] Push blocked: estimated payload ${(estimatedBytes / 1024).toFixed(0)} KB ` +\n `exceeds limit of ${(opts.maxBytes / 1024).toFixed(0)} KB. Prune your data before syncing.`,\n )\n }\n return true\n }\n\n if (estimatedBytes > opts.warnBytes) {\n if (opts.onSizeWarning) {\n opts.onSizeWarning(estimatedBytes)\n } else {\n console.warn(\n `[starfish] Payload approaching limit: estimated ${(estimatedBytes / 1024).toFixed(0)} KB ` +\n `(warn threshold: ${(opts.warnBytes / 1024).toFixed(0)} KB).`,\n )\n }\n }\n\n return false\n}\n\n/**\n * Creates a debounced push helper that coalesces rapid mutations into a single sync.\n *\n * Designed to be called on every domain store mutation (e.g., every keystroke).\n * The push is delayed by `delayMs` after the **last** call, so typing quickly\n * results in one push, not one per character.\n *\n * Also estimates the encrypted payload size before pushing and warns / blocks\n * if it approaches the server's body size limit.\n *\n * ```ts\n * const { notify } = createDebouncedSync(starfishStore, {\n * serialize: () => ({ tasks: taskStore.getState().tasks }),\n * })\n *\n * // Call on every domain store mutation:\n * taskStore.subscribe(() => notify())\n * ```\n */\nexport function createDebouncedSync(\n store: StoreApi<StarfishStore>,\n options: DebouncedSyncOptions = {},\n): DebouncedSync {\n const {\n delayMs = DEFAULT_DELAY_MS,\n warnBytes = DEFAULT_WARN_BYTES,\n maxBytes = DEFAULT_MAX_BYTES,\n serialize,\n onSizeWarning,\n onSizeExceeded,\n } = options\n\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n function notify(): void {\n cancel()\n timer = setTimeout(() => {\n timer = null\n const current = store.getState().data\n const doc = serialize ? serialize(current) : current\n\n if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded })) return\n\n store.getState().set(() => doc)\n }, delayMs)\n }\n\n return { notify, cancel }\n}\n\n/**\n * Creates a debounced push helper that calls `syncManager.push()` directly,\n * without requiring a Zustand store.\n *\n * Use this for one-way publishing workflows: public pages, derived snapshots,\n * or any case where you want to push data without a full `createStarfishStore` setup.\n *\n * ```ts\n * const syncManager = new SyncManager({ client, pullPath, pushPath })\n *\n * const { notify, cancel } = createDebouncedPush(syncManager, {\n * serialize: () => buildPublicPageDocument(),\n * })\n *\n * // Push after every relevant store mutation:\n * planningStore.subscribe(() => notify())\n *\n * // Clean up on teardown:\n * cancel()\n * ```\n */\nexport function createDebouncedPush(\n syncManager: SyncManager,\n options: DebouncedPushOptions,\n): DebouncedPush {\n const {\n delayMs = DEFAULT_DELAY_MS,\n warnBytes = DEFAULT_WARN_BYTES,\n maxBytes = DEFAULT_MAX_BYTES,\n serialize,\n onSizeWarning,\n onSizeExceeded,\n onError,\n } = options\n\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n function notify(): void {\n cancel()\n timer = setTimeout(() => {\n timer = null\n const doc = serialize()\n\n if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded })) return\n\n syncManager.push(doc).catch((err: unknown) => {\n if (onError) {\n onError(err)\n } else {\n console.warn(\"[starfish] Push failed:\", err)\n }\n })\n }, delayMs)\n }\n\n return { notify, cancel }\n}\n", "import type { StoreApi } from \"zustand/vanilla\"\nimport type { StarfishStore } from \"./bindings/zustand.js\"\n\n// \u2500\u2500 Types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Minimal interface matching React Native's `AppState` module.\n * Pass `AppState` from `react-native` directly.\n */\nexport interface AppStateModule {\n addEventListener: (\n type: \"change\",\n listener: (state: string) => void,\n ) => { remove: () => void }\n}\n\n/**\n * Minimal interface matching `@react-native-community/netinfo`'s default export.\n * Pass `NetInfo` from `@react-native-community/netinfo` directly.\n */\nexport interface NetInfoModule {\n addEventListener: (\n listener: (state: { isConnected: boolean | null }) => void,\n ) => () => void\n}\n\nexport interface MobileLifecycleDeps {\n /** React Native `AppState` module. */\n appState: AppStateModule\n /**\n * Optional: NetInfo module from `@react-native-community/netinfo`.\n * When provided, connectivity changes are forwarded to `store.getState().setOnline()`.\n */\n netInfo?: NetInfoModule\n}\n\nexport interface MobileLifecycleOptions {\n /**\n * Pull remote changes when the app returns to the foreground.\n * Only pulls if the store is online and not already syncing.\n * Default: `true`.\n */\n pullOnForeground?: boolean\n /**\n * Flush dirty data when the app transitions to the background.\n * Only flushes if the store has unsaved changes.\n * Default: `true`.\n */\n flushOnBackground?: boolean\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Wires React Native app lifecycle events to a Starfish store.\n *\n * - **Background**: flushes pending changes before the OS suspends the app.\n * - **Foreground**: pulls remote changes when the user returns to the app.\n * - **NetInfo**: forwards connectivity changes to `store.getState().setOnline()`.\n *\n * Uses dependency injection so no `react-native` or `netinfo` imports are needed\n * in this package. Pass the modules directly:\n *\n * ```ts\n * import { AppState } from \"react-native\"\n * import NetInfo from \"@react-native-community/netinfo\"\n * import { createMobileLifecycle } from \"@drakkar.software/starfish-client\"\n *\n * // Call once, after the store is created:\n * const cleanup = createMobileLifecycle(\n * store,\n * { appState: AppState, netInfo: NetInfo },\n * )\n *\n * // In a React component (e.g. root layout):\n * useEffect(() => cleanup, [])\n * ```\n *\n * @returns A cleanup function that removes all event listeners.\n */\nexport function createMobileLifecycle(\n store: StoreApi<StarfishStore>,\n deps: MobileLifecycleDeps,\n options: MobileLifecycleOptions = {},\n): () => void {\n const { pullOnForeground = true, flushOnBackground = true } = options\n\n const appSub = deps.appState.addEventListener(\"change\", (appState) => {\n if (appState === \"background\" && flushOnBackground) {\n if (store.getState().dirty) {\n store.getState().flush().catch((err) => { console.error(\"[Starfish] background flush failed:\", err) })\n }\n } else if (appState === \"active\" && pullOnForeground) {\n const { online, syncing } = store.getState()\n if (online && !syncing) {\n store.getState().pull().catch((err) => { console.error(\"[Starfish] foreground pull failed:\", err) })\n }\n }\n // \"inactive\" (iOS transition) and other states are intentionally ignored\n })\n\n let netUnsub: (() => void) | null = null\n if (deps.netInfo) {\n netUnsub = deps.netInfo.addEventListener(({ isConnected }) => {\n store.getState().setOnline(!!isConnected)\n })\n }\n\n return () => {\n appSub.remove()\n netUnsub?.()\n }\n}\n", "// \u2500\u2500 Types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Serializer/deserializer pair for one slice of application state.\n *\n * `serialize` snapshots the current state into a plain object.\n * `restore` applies a snapshot (potentially from a different app version after migration).\n */\nexport interface StoreSlice<T = unknown> {\n /**\n * Snapshot the current state of this slice into a serializable value.\n * Called during `serialize()`.\n */\n serialize: () => T\n /**\n * Apply a snapshot to this slice.\n * Called during `restore()` \u2014 data may be from an older schema version after migration.\n */\n restore: (data: T) => void\n}\n\n/**\n * A versioned backup document produced by `MultiStoreSync.serialize()`.\n * Safe to pass to `store.set()` as the Starfish sync document.\n */\nexport interface BackupDocument<T = Record<string, unknown>> {\n /** Schema version declared in `createMultiStoreSync`. */\n version: number\n /** Unix timestamp (ms) when this backup was created. */\n timestamp: number\n /** Serialized slice data, keyed by slice name. */\n data: T\n}\n\n/**\n * A migration function that transforms data from one version to the next.\n * Receives the full `data` object and must return an updated `data` object.\n * Only the `data` field is passed; `version` and `timestamp` are managed automatically.\n */\nexport type MultiStoreMigrationFn = (data: Record<string, unknown>) => Record<string, unknown>\n\nexport interface MultiStoreSyncOptions<T extends Record<string, unknown>> {\n /**\n * Named slices to include in the backup document.\n * Each slice provides `serialize()` and `restore()` methods.\n *\n * @example\n * ```ts\n * slices: {\n * tasks: {\n * serialize: () => taskStore.getState().tasks,\n * restore: (data) => taskStore.setState({ tasks: data }),\n * },\n * settings: {\n * serialize: () => settingsStore.getState().settings,\n * restore: (data) => settingsStore.setState({ settings: data }),\n * },\n * }\n * ```\n */\n slices: { [K in keyof T]: StoreSlice<T[K]> }\n /**\n * Current schema version. Increment when slices are added, renamed, or their shape changes.\n * Used to detect forward-incompatible documents from future app versions.\n */\n version: number\n /**\n * Optional migration chain. Key is the version number that produced the data;\n * value is a function that upgrades it to the next version.\n *\n * Migrations run sequentially from the document version up to the current version.\n *\n * @example\n * ```ts\n * migrations: {\n * 1: (data) => ({ ...data, settings: { ...data.settings, theme: \"light\" } }),\n * 2: (data) => ({ ...data, tasks: data.todos, todos: undefined }),\n * }\n * ```\n */\n migrations?: Record<number, MultiStoreMigrationFn>\n}\n\n/**\n * Returned by `createMultiStoreSync`. Serialize and restore coordinated multi-store state.\n */\nexport interface MultiStoreSync<T extends Record<string, unknown>> {\n /**\n * Snapshot all slices into a `BackupDocument`.\n * Pass the result to `starfishStore.getState().set(() => multiSync.serialize())`.\n */\n serialize: () => BackupDocument<T>\n /**\n * Apply a `BackupDocument` to all slices, running migrations as needed.\n *\n * Throws if the document version is newer than the current version (forward-incompatible).\n * Silently migrates older documents.\n */\n restore: (doc: BackupDocument) => void\n /** Current schema version as declared in options. */\n readonly version: number\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates a multi-store sync coordinator.\n *\n * Collects multiple application stores into a single Starfish sync document,\n * with versioned schema migrations for backward compatibility.\n *\n * ```ts\n * const multiSync = createMultiStoreSync({\n * slices: {\n * tasks: {\n * serialize: () => taskStore.getState().tasks,\n * restore: (tasks) => taskStore.setState({ tasks }),\n * },\n * settings: {\n * serialize: () => settingsStore.getState().settings,\n * restore: (settings) => settingsStore.setState({ settings }),\n * },\n * },\n * version: 2,\n * migrations: {\n * // data from version 1 \u2192 upgrade to version 2\n * 1: (data) => ({ ...data, settings: { ...(data.settings as object), darkMode: false } }),\n * },\n * })\n *\n * // Push:\n * starfishStore.getState().set(() => multiSync.serialize())\n *\n * // Restore on pull (pass as onRemoteUpdate to createStarfishStore):\n * createStarfishStore({\n * name: \"app\",\n * syncManager,\n * onRemoteUpdate: (doc) => multiSync.restore(doc as BackupDocument),\n * })\n * ```\n */\nexport function createMultiStoreSync<T extends Record<string, unknown>>(\n options: MultiStoreSyncOptions<T>,\n): MultiStoreSync<T> {\n const { slices, version, migrations = {} } = options\n\n // Validate migration chain at construction time (fail fast)\n for (const fromVersion of Object.keys(migrations)) {\n const v = Number(fromVersion)\n if (isNaN(v) || v < 1) {\n throw new Error(`Migration key must be a positive integer, got: \"${fromVersion}\"`)\n }\n }\n\n function serialize(): BackupDocument<T> {\n const data = {} as T\n for (const key of Object.keys(slices) as Array<keyof T>) {\n data[key] = slices[key].serialize() as T[typeof key]\n }\n return { version, timestamp: Date.now(), data }\n }\n\n function restore(doc: BackupDocument): void {\n if (typeof doc !== \"object\" || doc === null) {\n throw new Error(\"restore: expected a BackupDocument object\")\n }\n\n const docVersion = doc.version ?? 1\n\n if (typeof docVersion !== \"number\" || !Number.isInteger(docVersion) || docVersion < 1) {\n throw new Error(`restore: invalid document version: ${String(doc.version)}`)\n }\n\n if (docVersion > version) {\n throw new Error(\n `restore: document version ${docVersion} is newer than current version ${version}. ` +\n `Update the app to restore this backup.`,\n )\n }\n\n // Run migrations sequentially from docVersion up to current version\n let data: Record<string, unknown> =\n typeof doc.data === \"object\" && doc.data !== null\n ? { ...(doc.data as Record<string, unknown>) }\n : {}\n\n for (let v = docVersion; v < version; v++) {\n const migration = migrations[v]\n if (!migration) continue\n try {\n data = migration(data)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(`restore: migration from version ${v} to ${v + 1} failed: ${msg}`)\n }\n }\n\n // Restore each slice\n for (const key of Object.keys(slices) as Array<keyof T>) {\n const sliceData = data[key as string]\n if (sliceData !== undefined) {\n slices[key].restore(sliceData as T[typeof key])\n }\n }\n }\n\n return { serialize, restore, version }\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,yBAAyB;AAElC,SAAS,mBAAAA,kBAAiB,mBAAmB;AAC7C,SAAS,qBAAqB,2CAA2C;;;ACFzE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACJA,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,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AACpC,UAAI,cAAc,QAAW;AAC3B,eAAO,GAAG,EAAE,QAAQ,SAA0B;AAAA,MAChD;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,SAAS,QAAQ;AACvC;",
|
|
4
|
+
"sourcesContent": ["export { configurePlatform } from \"@drakkar.software/starfish-protocol\"\nexport type { CryptoProvider, Base64Provider, PlatformConfig } from \"@drakkar.software/starfish-protocol\"\nexport { stableStringify, computeHash } from \"@drakkar.software/starfish-protocol\"\nexport { buildRevocationList, revocationListCanonicalSigningInput } from \"@drakkar.software/starfish-protocol\"\nexport type {\n RevocationList,\n RevocationEntry,\n RevokedSubject,\n BuildRevocationListOpts,\n} from \"@drakkar.software/starfish-protocol\"\nexport type { PullResult, PushSuccess, PullKeyringProjection } from \"@drakkar.software/starfish-protocol\"\n\nexport { StarfishClient } from \"./client.js\"\nexport type { BlobPullResult, BlobPushResult, AppendPullOptions, PullOptions } from \"./client.js\"\nexport { SyncManager, AbortError } from \"./sync.js\"\nexport type { SyncManagerOptions, SyncSigner } from \"./sync.js\"\nexport { ENCRYPTED_KEY } from \"@drakkar.software/starfish-protocol\"\nexport type { Encryptor } from \"@drakkar.software/starfish-protocol\"\nexport {\n ConflictError,\n StarfishHttpError,\n} from \"./types.js\"\nexport type {\n StarfishClientOptions,\n StarfishCapProvider,\n ConflictResolver,\n ClientPlugin,\n} from \"./types.js\"\nexport { consoleSyncLogger, noopSyncLogger, createMetricsCollector } from \"./logger.js\"\nexport type { SyncLogger, SyncMetrics, MetricsCollector } from \"./logger.js\"\nexport { createMigrator } from \"./migrate.js\"\nexport type { MigrationFn, MigrationConfig } from \"./migrate.js\"\nexport { ValidationError, createSchemaValidator } from \"./validate.js\"\nexport type { Validator, ValidationResult } from \"./validate.js\"\nexport { classifyError } from \"./fetch.js\"\nexport type { ErrorCategory } from \"./fetch.js\"\nexport {\n createUnionMerge,\n createSoftDeleteResolver,\n timestampWinner,\n pruneTombstones,\n withConflictMeta,\n} from \"./resolvers.js\"\nexport type { ConflictMeta, ConflictResolverWithMeta } from \"./resolvers.js\"\nexport { SnapshotHistory } from \"./history.js\"\nexport type { Snapshot, SnapshotHistoryOptions } from \"./history.js\"\nexport { startPolling, startAdaptivePolling } from \"./polling.js\"\nexport type { PollableState, AdaptivePollingOptions, AdaptivePollingControls } from \"./polling.js\"\nexport { createDedupFetch } from \"./dedup.js\"\nexport { fetchServerConfig } from \"./config.js\"\nexport type { EncryptionMode, CollectionClientInfo, ConfigResponse } from \"./config.js\"\nexport { createIndexedDBStorage } from \"./storage/indexeddb.js\"\nexport type { IndexedDBStorageOptions, AsyncStateStorage } from \"./storage/indexeddb.js\"\nexport { exportData, importData, exportToBlob } from \"./export.js\"\nexport type { ExportOptions } from \"./export.js\"\nexport { isBackgroundSyncSupported, registerBackgroundSync } from \"./background-sync.js\"\nexport type { BackgroundSyncOptions } from \"./background-sync.js\"\nexport { isServiceWorkerSupported, registerServiceWorker, unregisterServiceWorkers } from \"./service-worker.js\"\nexport type { ServiceWorkerOptions } from \"./service-worker.js\"\nexport { createSuspenseResource } from \"./bindings/suspense.js\"\nexport { createDebouncedSync, createDebouncedPush } from \"./debounced-sync.js\"\nexport type { DebouncedSyncOptions, DebouncedSync, DebouncedPushOptions, DebouncedPush } from \"./debounced-sync.js\"\nexport { createMobileLifecycle } from \"./mobile-lifecycle.js\"\nexport type { AppStateModule, NetInfoModule, MobileLifecycleDeps, MobileLifecycleOptions } from \"./mobile-lifecycle.js\"\nexport { createMultiStoreSync } from \"./multi-store.js\"\nexport type {\n StoreSlice,\n BackupDocument,\n MultiStoreMigrationFn,\n MultiStoreSyncOptions,\n MultiStoreSync,\n} from \"./multi-store.js\"\nexport type { AppendOnlyClientInfo } from \"./config.js\"\n", "import type { PullResult, PushSuccess } from \"@drakkar.software/starfish-protocol\"\nimport {\n DEFAULT_ALG,\n signRequest,\n stableStringify,\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/** 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/**\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) {\n const { cap, devEdPrivHex, pubHex, presenterAlg } = await this.capProvider.getCap()\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 Authorization: `Cap ${encodeCapAuth(cap)}`,\n \"X-Starfish-Sig\": sig,\n \"X-Starfish-Ts\": String(ts),\n \"X-Starfish-Nonce\": nonce,\n \"X-Starfish-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[\"X-Starfish-Pub\"] = pubHex\n return headers\n }\n return {}\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: { 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 * 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 fields (`authorPubkey` + `authorSignature`) live inside `data`\n * and are produced by `SyncManager` when a `signer` is configured.\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 ): Promise<PushSuccess> {\n const body = JSON.stringify({\n data,\n baseHash,\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 \"Content-Type\": \"application/json\",\n 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 bodyObj: Record<string, unknown> = { data }\n if (opts.ts !== undefined) bodyObj[\"ts\"] = opts.ts\n const body = JSON.stringify(bodyObj)\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 \"Content-Type\": \"application/json\",\n 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: { 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(\"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 \"Content-Type\": contentType,\n 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 { deepMerge, getBase64, stableStringify } 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 } 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 over stableStringify(payload-without-author-fields)\n // and attach `authorPubkey` + `authorSignature` to the sealed payload.\n // The author fields live INSIDE `data` so the server stores them with\n // the encrypted document.\n let payload: Record<string, unknown> = sealed\n if (this.signer) {\n const { devEdPubHex, sign } = await this.signer.getSigner()\n if (this.aborted) throw new AbortError()\n const canonical = stableStringify(sealed as Record<string, unknown>)\n const sigBytes = await sign(new TextEncoder().encode(canonical))\n if (this.aborted) throw new AbortError()\n payload = {\n ...sealed,\n authorPubkey: devEdPubHex,\n authorSignature: getBase64().encode(sigBytes),\n }\n }\n\n const result = await this.client.push(\n this.pushPath,\n payload,\n this.lastHash,\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", "/** Extended metrics for sync operations. */\nexport interface SyncMetrics {\n bytesTransferred?: number\n compressedSize?: number\n conflictCount?: number\n retryCount?: number\n cacheHit?: boolean\n}\n\n/** Structured logger for sync operations. */\nexport interface SyncLogger {\n pullStart(store: string): void\n pullSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void\n pullError(store: string, error: string): void\n pushStart(store: string): void\n pushSuccess(store: string, durationMs: number, metrics?: SyncMetrics): void\n pushError(store: string, error: string): void\n conflict(store: string, attempt: number): void\n}\n\n/** Console-based sync logger with structured output. */\nexport const consoleSyncLogger: SyncLogger = {\n pullStart: (s) => console.log(`[starfish:${s}] pull started`),\n pullSuccess: (s, ms, m) => {\n let msg = `[starfish:${s}] pull OK (${ms}ms)`\n if (m?.bytesTransferred) msg += ` ${m.bytesTransferred}B`\n if (m?.cacheHit) msg += ` (cache hit)`\n console.log(msg)\n },\n pullError: (s, err) => console.error(`[starfish:${s}] pull failed: ${err}`),\n pushStart: (s) => console.log(`[starfish:${s}] push started`),\n pushSuccess: (s, ms, m) => {\n let msg = `[starfish:${s}] push OK (${ms}ms)`\n if (m?.bytesTransferred) msg += ` ${m.bytesTransferred}B`\n console.log(msg)\n },\n pushError: (s, err) => console.error(`[starfish:${s}] push failed: ${err}`),\n conflict: (s, n) => console.warn(`[starfish:${s}] conflict (attempt ${n})`),\n}\n\n/** Silent sync logger (no output). */\nexport const noopSyncLogger: SyncLogger = {\n pullStart: () => {},\n pullSuccess: () => {},\n pullError: () => {},\n pushStart: () => {},\n pushSuccess: () => {},\n pushError: () => {},\n conflict: () => {},\n}\n\n/** Accumulated metrics for a single store. */\ninterface StoreSummary {\n totalPulls: number\n totalPushes: number\n totalDurationMs: number\n totalBytes: number\n totalConflicts: number\n}\n\n/** Collects sync metrics over time. */\nexport interface MetricsCollector {\n recordPull(name: string, durationMs: number, metrics?: SyncMetrics): void\n recordPush(name: string, durationMs: number, metrics?: SyncMetrics): void\n recordConflict(name: string): void\n getSummary(): Record<string, { totalPulls: number; totalPushes: number; avgDurationMs: number; totalBytes: number; totalConflicts: number }>\n reset(): void\n}\n\n/** Create a metrics collector that accumulates sync statistics. */\nexport function createMetricsCollector(): MetricsCollector {\n const stores = new Map<string, StoreSummary>()\n\n function ensureStore(name: string): StoreSummary {\n let s = stores.get(name)\n if (!s) {\n s = { totalPulls: 0, totalPushes: 0, totalDurationMs: 0, totalBytes: 0, totalConflicts: 0 }\n stores.set(name, s)\n }\n return s\n }\n\n return {\n recordPull(name, durationMs, metrics) {\n const s = ensureStore(name)\n s.totalPulls++\n s.totalDurationMs += durationMs\n if (metrics?.bytesTransferred) s.totalBytes += metrics.bytesTransferred\n },\n recordPush(name, durationMs, metrics) {\n const s = ensureStore(name)\n s.totalPushes++\n s.totalDurationMs += durationMs\n if (metrics?.bytesTransferred) s.totalBytes += metrics.bytesTransferred\n },\n recordConflict(name) {\n ensureStore(name).totalConflicts++\n },\n getSummary() {\n const result: Record<string, { totalPulls: number; totalPushes: number; avgDurationMs: number; totalBytes: number; totalConflicts: number }> = {}\n for (const [name, s] of stores) {\n const totalOps = s.totalPulls + s.totalPushes\n result[name] = {\n totalPulls: s.totalPulls,\n totalPushes: s.totalPushes,\n avgDurationMs: totalOps > 0 ? Math.round(s.totalDurationMs / totalOps) : 0,\n totalBytes: s.totalBytes,\n totalConflicts: s.totalConflicts,\n }\n }\n return result\n },\n reset() {\n stores.clear()\n },\n }\n}\n", "/** A function that migrates data from one schema version to the next. */\nexport type MigrationFn = (data: Record<string, unknown>) => Record<string, unknown>\n\nexport interface MigrationConfig {\n /** The current schema version of the application. */\n currentVersion: number\n /** Map of version number to the migration that upgrades FROM that version. */\n migrations: Record<number, MigrationFn>\n}\n\n/**\n * Creates a migration runner that upgrades documents to the current schema version.\n *\n * Given a document with `_schemaVersion`, applies each migration in sequence\n * until the document reaches `currentVersion`. Throws if the document version\n * is ahead of the app (forward compatibility guard).\n */\nexport function createMigrator(\n config: MigrationConfig,\n): (data: Record<string, unknown>) => Record<string, unknown> {\n // Eagerly validate the migration chain\n for (let v = 1; v < config.currentVersion; v++) {\n if (!config.migrations[v]) {\n throw new Error(`Missing migration for version ${v} -> ${v + 1}`)\n }\n }\n\n return (data) => {\n const version = typeof data._schemaVersion === \"number\" ? data._schemaVersion : 1\n\n if (version > config.currentVersion) {\n throw new Error(\n `Document schema version ${version} is newer than app version ${config.currentVersion}. Update the app.`,\n )\n }\n\n if (version === config.currentVersion) return data\n\n let result = { ...data }\n for (let v = version; v < config.currentVersion; v++) {\n const fn = config.migrations[v]\n if (!fn) {\n throw new Error(`Missing migration for version ${v} -> ${v + 1}`)\n }\n try {\n result = fn(result)\n } catch (err) {\n throw new Error(\n `Migration from version ${v} to ${v + 1} failed: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n )\n }\n }\n result._schemaVersion = config.currentVersion\n return result\n }\n}\n", "/** Error category returned by classifyError. */\nexport type ErrorCategory =\n | \"network\"\n | \"auth\"\n | \"conflict\"\n | \"rate-limited\"\n | \"server\"\n | \"client\"\n | \"unknown\"\n\n/** Classify an error from a fetch response or network failure. */\nexport function classifyError(err: unknown): ErrorCategory {\n if (err instanceof Response || (err && typeof err === \"object\" && \"status\" in err)) {\n const status = (err as { status: unknown }).status\n if (typeof status !== \"number\" || isNaN(status)) return \"unknown\"\n if (status === 0) return \"network\"\n if (status === 401 || status === 403) return \"auth\"\n if (status === 409) return \"conflict\"\n if (status === 429) return \"rate-limited\"\n if (status >= 500) return \"server\"\n if (status >= 400) return \"client\"\n }\n if (err instanceof Error && /failed to fetch|fetch failed|network|load failed|ECONNREFUSED|ENOTFOUND/i.test(err.message)) return \"network\"\n return \"unknown\"\n}\n\nexport interface RetryOptions {\n /** Max number of retries (default: 3). */\n maxRetries?: number\n /** Initial delay in ms before first retry (default: 500). */\n initialDelayMs?: number\n /** Maximum delay in ms (default: 10000). */\n maxDelayMs?: number\n}\n\n/**\n * Wraps a fetch function with automatic retry for retriable errors\n * (network failures, 429, 5xx). Respects Retry-After headers.\n */\nexport function createRetryFetch(options?: RetryOptions): typeof globalThis.fetch {\n const maxRetries = Math.max(0, options?.maxRetries ?? 3)\n const initialDelay = options?.initialDelayMs ?? 500\n const maxDelay = options?.maxDelayMs ?? 10_000\n\n return async (input, init?) => {\n let attempt = 0\n while (true) {\n try {\n const res = await globalThis.fetch(input, init)\n if (res.ok || attempt >= maxRetries) return res\n\n const category = classifyError(res)\n if (category !== \"rate-limited\" && category !== \"server\") return res\n\n const retryAfter = res.headers.get(\"Retry-After\")?.trim()\n let delay: number\n if (retryAfter) {\n const seconds = Number(retryAfter)\n if (retryAfter !== \"\" && !isNaN(seconds)) {\n delay = Math.min(seconds * 1000, maxDelay)\n } else {\n const date = Date.parse(retryAfter)\n delay = isNaN(date) ? initialDelay : Math.min(Math.max(date - Date.now(), 0), maxDelay)\n }\n } else {\n delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay)\n }\n\n await new Promise<void>((r) => setTimeout(r, delay))\n attempt++\n } catch (err) {\n if (attempt >= maxRetries) throw err\n const category = classifyError(err)\n if (category !== \"network\") throw err\n\n const delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay)\n await new Promise<void>((r) => setTimeout(r, delay))\n attempt++\n }\n }\n }\n}\n\ntype BreakerState = \"closed\" | \"open\" | \"half-open\"\n\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures to open the circuit (default: 5). */\n threshold?: number\n /** Cooldown in ms before transitioning from open to half-open (default: 30000). */\n cooldownMs?: number\n}\n\n/** Circuit breaker that prevents requests when the backend is unavailable. */\nexport class CircuitBreaker {\n private state: BreakerState = \"closed\"\n private failures = 0\n private openedAt = 0\n private readonly threshold: number\n private readonly cooldownMs: number\n\n constructor(options?: CircuitBreakerOptions) {\n this.threshold = options?.threshold ?? 5\n this.cooldownMs = options?.cooldownMs ?? 30_000\n }\n\n getState(): BreakerState {\n this.maybeTransition()\n return this.state\n }\n\n isOpen(): boolean {\n return this.getState() === \"open\"\n }\n\n recordSuccess(): void {\n this.failures = 0\n this.state = \"closed\"\n }\n\n recordFailure(): void {\n this.failures++\n if (this.state === \"half-open\" || this.failures >= this.threshold) {\n this.state = \"open\"\n this.openedAt = Date.now()\n }\n }\n\n private maybeTransition(): void {\n if (this.state === \"open\" && Date.now() - this.openedAt >= this.cooldownMs) {\n this.state = \"half-open\"\n }\n }\n}\n\n/**\n * Wraps fetch to gzip-compress string request bodies using the CompressionStream API.\n * Adds Content-Encoding: gzip header. Non-string bodies (ArrayBuffer, Blob, etc.)\n * are passed through uncompressed. Requires CompressionStream (browsers, Node.js 18+, Deno).\n */\nexport function createCompressedFetch(inner?: typeof globalThis.fetch): typeof globalThis.fetch {\n const baseFetch = inner ?? globalThis.fetch.bind(globalThis)\n return async (input, init?) => {\n if (!init?.body || typeof CompressionStream === \"undefined\") {\n return baseFetch(input, init)\n }\n\n const bodyText = typeof init.body === \"string\" ? init.body : null\n if (!bodyText) return baseFetch(input, init)\n\n try {\n const stream = new Blob([bodyText]).stream().pipeThrough(new CompressionStream(\"gzip\"))\n const compressed = await new Response(stream).arrayBuffer()\n\n const normalized = Object.fromEntries(new Headers(init.headers as HeadersInit).entries())\n normalized[\"content-encoding\"] = \"gzip\"\n\n return baseFetch(input, {\n ...init,\n body: compressed,\n headers: normalized,\n })\n } catch {\n return baseFetch(input, init)\n }\n }\n}\n\n/**\n * Combines retry and circuit breaker into a single resilient fetch wrapper.\n * Rejects immediately when the circuit is open.\n */\nexport function createResilientFetch(\n retryOptions?: RetryOptions,\n breakerOptions?: CircuitBreakerOptions,\n): { fetch: typeof globalThis.fetch; breaker: CircuitBreaker } {\n const breaker = new CircuitBreaker(breakerOptions)\n const retryFetch = createRetryFetch(retryOptions)\n\n const resilientFetch: typeof globalThis.fetch = async (input, init?) => {\n if (breaker.isOpen()) {\n const cooldown = Math.ceil((breakerOptions?.cooldownMs ?? 30_000) / 1000)\n throw new Error(`Request blocked: too many consecutive failures. Retry in ${cooldown}s.`)\n }\n\n try {\n const res = await retryFetch(input, init)\n if (res.status >= 500) {\n breaker.recordFailure()\n } else {\n breaker.recordSuccess()\n }\n return res\n } catch (err) {\n breaker.recordFailure()\n throw err\n }\n }\n\n return { fetch: resilientFetch, breaker }\n}\n", "import type { ConflictResolver } from \"./types.js\"\n\n/** Metadata about which fields were affected during conflict resolution. */\nexport interface ConflictMeta {\n /** Field names that differed between local and remote. */\n conflictedFields: string[]\n /** How the conflict was resolved. */\n resolvedBy: \"local\" | \"remote\" | \"merged\"\n /** Timestamp of resolution. */\n timestamp: number\n}\n\n/** Conflict resolver that also returns metadata about the resolution. */\nexport type ConflictResolverWithMeta = (\n local: Record<string, unknown>,\n remote: Record<string, unknown>,\n) => { data: Record<string, unknown>; meta: ConflictMeta }\n\n/** Shallow structural comparison of two values. Handles objects, arrays, and primitives. */\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a == null || b == null) return a === b\n if (typeof a !== typeof b) return false\n if (typeof a !== \"object\") return false\n\n if (Array.isArray(a) !== Array.isArray(b)) return false\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((v, i) => shallowEqual(v, b[i]))\n }\n\n const aObj = a as Record<string, unknown>\n const bObj = b as Record<string, unknown>\n const aKeys = Object.keys(aObj)\n const bKeys = Object.keys(bObj)\n if (aKeys.length !== bKeys.length) return false\n return aKeys.every((k) => shallowEqual(aObj[k], bObj[k]))\n}\n\n/**\n * Wrap a standard ConflictResolver to also return metadata about which fields conflicted.\n * Compares local and remote keys to detect differing fields.\n */\nexport function withConflictMeta(resolver: ConflictResolver): ConflictResolverWithMeta {\n return (local, remote) => {\n const conflictedFields: string[] = []\n const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)])\n for (const key of allKeys) {\n const lv = local[key]\n const rv = remote[key]\n if (!shallowEqual(lv, rv)) {\n conflictedFields.push(key)\n }\n }\n\n const data = resolver(local, remote)\n\n // Determine how it was resolved using structural comparison\n let resolvedBy: \"local\" | \"remote\" | \"merged\" = \"merged\"\n if (shallowEqual(data, local)) resolvedBy = \"local\"\n else if (shallowEqual(data, remote)) resolvedBy = \"remote\"\n\n return {\n data,\n meta: {\n conflictedFields,\n resolvedBy,\n timestamp: Date.now(),\n },\n }\n }\n}\n\n/** Compare two timestamp values. Handles both numeric (epoch) and string (ISO-8601) timestamps. */\nfunction compareTimestamps(a: unknown, b: unknown): boolean {\n if (typeof a === \"number\" && typeof b === \"number\") return a >= b\n return String(a ?? \"\") >= String(b ?? \"\")\n}\n\n/**\n * Creates a conflict resolver that merges arrays by ID with per-item\n * timestamp comparison, and uses document-level timestamp for scalars.\n *\n * For arrays: builds a union of both sets keyed by `idKey`. When both\n * sides have the same item, the one with the newer `timestampKey` wins.\n * For scalars: the document with the newer `documentTimestampKey` wins.\n *\n * @example\n * ```ts\n * const merge = createUnionMerge()\n * const sync = new SyncManager({ ..., onConflict: merge })\n * ```\n */\nexport function createUnionMerge(options?: {\n /** Key used to identify items in arrays (default: \"id\"). */\n idKey?: string\n /** Key used for per-item timestamp comparison (default: \"updatedAt\"). */\n timestampKey?: string\n /** Key used for document-level timestamp comparison (default: \"timestamp\"). */\n documentTimestampKey?: string\n}): ConflictResolver {\n const idKey = options?.idKey ?? \"id\"\n const tsKey = options?.timestampKey ?? \"updatedAt\"\n const docTsKey = options?.documentTimestampKey ?? \"timestamp\"\n\n return (local, remote) => {\n const result: Record<string, unknown> = {}\n const localNewer = compareTimestamps(local[docTsKey], remote[docTsKey])\n const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)])\n\n for (const key of allKeys) {\n const lv = local[key]\n const rv = remote[key]\n\n // Both sides have arrays \u2014 attempt ID-based union\n if (Array.isArray(lv) && Array.isArray(rv)) {\n const map = new Map<unknown, Record<string, unknown>>()\n\n // Seed with remote items\n for (const item of rv) {\n if (item && typeof item === \"object\" && idKey in item) {\n map.set((item as Record<string, unknown>)[idKey], item as Record<string, unknown>)\n } else {\n map.set(Symbol(), item as Record<string, unknown>)\n }\n }\n\n // Overlay local items (per-item timestamp wins)\n for (const item of lv) {\n if (item && typeof item === \"object\" && idKey in item) {\n const localItem = item as Record<string, unknown>\n const id = localItem[idKey]\n const remoteItem = map.get(id)\n if (!remoteItem) {\n map.set(id, localItem)\n } else {\n if (compareTimestamps(localItem[tsKey], remoteItem[tsKey])) {\n map.set(id, localItem)\n }\n }\n } else {\n map.set(Symbol(), item as Record<string, unknown>)\n }\n }\n\n result[key] = [...map.values()]\n } else if (lv !== undefined && rv !== undefined) {\n // Scalar: document-level timestamp wins\n result[key] = localNewer ? lv : rv\n } else {\n // Only one side has the key\n result[key] = lv ?? rv\n }\n }\n\n return result\n }\n}\n\n/**\n * Creates a conflict resolver that handles soft-deleted items (tombstones).\n * Extends union merge with tombstone awareness: if an item exists on one side\n * with a `deletedAtKey` set, that deletion is respected even if the other side\n * still has the item alive \u2014 as long as the deletion timestamp is newer.\n */\nexport function createSoftDeleteResolver(options?: {\n idKey?: string\n timestampKey?: string\n documentTimestampKey?: string\n /** Key marking an item as deleted (default: \"_deletedAt\"). */\n deletedAtKey?: string\n}): ConflictResolver {\n const idKey = options?.idKey ?? \"id\"\n const tsKey = options?.timestampKey ?? \"updatedAt\"\n const deletedAtKey = options?.deletedAtKey ?? \"_deletedAt\"\n const baseMerge = createUnionMerge(options)\n\n return (local, remote) => {\n const merged = baseMerge(local, remote)\n\n // Build a tombstone map from both sides: id \u2192 deletedAt timestamp\n const tombstones = new Map<unknown, unknown>()\n for (const source of [local, remote]) {\n for (const key of Object.keys(source)) {\n const arr = source[key]\n if (!Array.isArray(arr)) continue\n for (const item of arr) {\n if (item && typeof item === \"object\" && idKey in item && deletedAtKey in item) {\n const rec = item as Record<string, unknown>\n const id = rec[idKey]\n const deletedAt = rec[deletedAtKey]\n if (typeof deletedAt === \"number\" || typeof deletedAt === \"string\") {\n const existing = tombstones.get(id)\n if (existing == null || compareTimestamps(deletedAt, existing)) tombstones.set(id, deletedAt)\n }\n }\n }\n }\n }\n\n // For merged arrays, ensure tombstoned items stay deleted\n // (don't resurrect an item if its tombstone is newer than its updatedAt)\n for (const key of Object.keys(merged)) {\n const value = merged[key]\n if (!Array.isArray(value)) continue\n\n merged[key] = value.filter((item) => {\n if (!item || typeof item !== \"object\" || !(idKey in item)) return true\n const rec = item as Record<string, unknown>\n const id = rec[idKey]\n const deletedAt = tombstones.get(id)\n if (deletedAt == null) return true\n // Keep the item if it has a deletedAt (it's the tombstone itself)\n if (rec[deletedAtKey] != null) return true\n // Filter out alive items that have a newer tombstone\n return compareTimestamps(rec[tsKey], deletedAt) && rec[tsKey] !== deletedAt\n })\n }\n\n return merged\n }\n}\n\n/**\n * Simple resolver: the document with the newer timestamp wins entirely.\n * No per-field or per-item merging.\n */\nexport function timestampWinner(\n timestampKey = \"timestamp\",\n): ConflictResolver {\n return (local, remote) => {\n return compareTimestamps(local[timestampKey], remote[timestampKey])\n ? local\n : remote\n }\n}\n\n/**\n * Remove expired tombstones from an array of items.\n * Items with a `deletedAtKey` older than `ttlMs` are pruned.\n *\n * @param items - Array of items, some with a deletedAt timestamp\n * @param ttlMs - Time-to-live in ms for tombstones (default: 30 days)\n * @param deletedAtKey - Key marking deletion timestamp (default: \"_deletedAt\")\n */\nexport function pruneTombstones<T extends Record<string, unknown>>(\n items: T[],\n ttlMs = 30 * 24 * 60 * 60 * 1000,\n deletedAtKey = \"_deletedAt\",\n): T[] {\n const cutoff = Date.now() - ttlMs\n return items.filter((item) => {\n const deletedAt = item[deletedAtKey]\n if (deletedAt == null) return true\n if (typeof deletedAt === \"number\") return deletedAt > cutoff\n if (typeof deletedAt === \"string\") return new Date(deletedAt).getTime() > cutoff\n return false\n })\n}\n", "export interface Snapshot {\n timestamp: number\n label: string\n data: string\n}\n\nexport interface SnapshotHistoryOptions {\n /** Maximum number of snapshots to retain. Oldest are trimmed first. Default: 20. */\n maxSnapshots?: number\n /** localStorage key for persistence. Pass to enable auto-save/load. */\n storageKey?: string\n}\n\nexport class SnapshotHistory {\n private snapshots: Snapshot[] = []\n private readonly maxSnapshots: number\n private readonly storageKey: string | undefined\n\n constructor(options?: SnapshotHistoryOptions) {\n this.maxSnapshots = options?.maxSnapshots ?? 20\n this.storageKey = options?.storageKey\n\n if (this.storageKey) {\n try {\n const raw = localStorage.getItem(this.storageKey)\n if (raw) {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) this.snapshots = parsed\n }\n } catch { /* corrupted or unavailable \u2014 start fresh */ }\n }\n }\n\n /** Take a labeled snapshot of the given data. */\n take(label: string, data: Record<string, unknown>): void {\n this.snapshots.push({\n timestamp: Date.now(),\n label,\n data: JSON.stringify(data),\n })\n if (this.snapshots.length > this.maxSnapshots) {\n this.snapshots = this.snapshots.slice(-this.maxSnapshots)\n }\n this.persist()\n }\n\n /** Restore data from a snapshot at the given index. Returns undefined if index is invalid or data is corrupt. */\n restore(index: number): Record<string, unknown> | undefined {\n const snapshot = this.snapshots[index]\n if (!snapshot) return undefined\n try {\n return JSON.parse(snapshot.data)\n } catch {\n return undefined\n }\n }\n\n /** List available snapshots (metadata only, no data payload). */\n list(): Array<{ timestamp: number; label: string }> {\n return this.snapshots.map(({ timestamp, label }) => ({ timestamp, label }))\n }\n\n /** Clear all snapshots. */\n clear(): void {\n this.snapshots = []\n this.persist()\n }\n\n private persist(): void {\n if (!this.storageKey) return\n try {\n localStorage.setItem(this.storageKey, JSON.stringify(this.snapshots))\n } catch { /* quota exceeded \u2014 skip silently */ }\n }\n}\n", "/** Minimal state needed by polling utilities. */\nexport interface PollableState {\n online: boolean\n syncing: boolean\n}\n\nconst DEFAULT_INTERVALS: Record<string, number> = {\n \"slow-2g\": 120_000,\n \"2g\": 60_000,\n \"3g\": 30_000,\n \"4g\": 10_000,\n}\n\nconst DEFAULT_FALLBACK_MS = 15_000\n\n/**\n * Start periodic pulling at a fixed interval.\n * Skips pulls when offline or already syncing.\n * Returns a cleanup function that stops polling.\n */\nexport function startPolling(\n pullFn: () => Promise<void>,\n getState: () => PollableState,\n intervalMs = 30_000,\n): () => void {\n const timer = setInterval(() => {\n const { online, syncing } = getState()\n if (online && !syncing) pullFn().catch((err) => { console.error(\"[Starfish] poll failed:\", err) })\n }, intervalMs)\n\n return () => clearInterval(timer)\n}\n\nexport interface AdaptivePollingOptions {\n /** Override the base interval in ms. If set, skips network quality detection. */\n intervalMs?: number\n /** Custom mapping from effectiveType to interval in ms. */\n intervals?: Record<string, number>\n}\n\nexport interface AdaptivePollingControls {\n pause: () => void\n resume: () => void\n stop: () => void\n}\n\n/**\n * Start polling with adaptive intervals based on network quality.\n * Uses the Network Information API (`navigator.connection.effectiveType`) when available.\n * Returns controls to pause, resume, or stop polling.\n */\nexport function startAdaptivePolling(\n pullFn: () => Promise<void>,\n getState: () => PollableState,\n options?: AdaptivePollingOptions,\n): AdaptivePollingControls {\n let intervalMs: number\n\n if (options?.intervalMs != null) {\n intervalMs = options.intervalMs\n } else {\n const intervals = options?.intervals ?? DEFAULT_INTERVALS\n let effectiveType: string | undefined\n if (typeof navigator !== \"undefined\" && \"connection\" in navigator) {\n effectiveType = (navigator as unknown as { connection: { effectiveType?: string } }).connection.effectiveType\n }\n intervalMs = (effectiveType != null ? intervals[effectiveType] : undefined) ?? DEFAULT_FALLBACK_MS\n }\n\n let paused = false\n\n const timer = setInterval(() => {\n if (paused) return\n const { online, syncing } = getState()\n if (online && !syncing) pullFn().catch((err) => { console.error(\"[Starfish] adaptive poll failed:\", err) })\n }, intervalMs)\n\n return {\n pause: () => { paused = true },\n resume: () => { paused = false },\n stop: () => clearInterval(timer),\n }\n}\n", "/**\n * Request deduplication: prevents multiple concurrent identical GET requests.\n * If a GET request is in-flight for a URL, subsequent identical GET requests\n * return the same Promise. POST/PUT/DELETE/PATCH are never deduped.\n */\nexport function createDedupFetch(\n baseFetch: typeof globalThis.fetch = globalThis.fetch.bind(globalThis),\n): typeof globalThis.fetch {\n const inflightGets = new Map<string, Promise<Response>>()\n\n return (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const method = (init?.method ?? \"GET\").toUpperCase()\n\n // Only dedup GET requests\n if (method !== \"GET\") {\n return baseFetch(input, init)\n }\n\n const url = typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url\n\n const existing = inflightGets.get(url)\n if (existing) {\n // Return a clone \u2014 the original is reserved for cloning only\n return existing.then((res) => res.clone())\n }\n\n // Store a promise that resolves to a response we keep solely for cloning.\n // The first caller also gets a clone, ensuring the \"master\" body is never consumed.\n const promise = baseFetch(input, init)\n .then((res) => res)\n .finally(() => {\n inflightGets.delete(url)\n })\n\n inflightGets.set(url, promise)\n\n // First caller also gets a clone so the cached response body stays unconsumed\n return promise.then((res) => res.clone())\n }) as typeof globalThis.fetch\n}\n", "/** Encryption modes supported by the Starfish server. */\nexport type EncryptionMode = \"none\" | \"delegated\"\n\n/** Append-only configuration exposed via GET /config. */\nexport interface AppendOnlyClientInfo {\n /** Append-only strategy. Only `\"by_timestamp\"` is currently supported. */\n type: \"by_timestamp\"\n /** Array field name in the stored document. Defaults to \"items\". */\n field?: string\n /** false = no storage write (replaces queueOnly). true/absent = append to array. */\n persist?: boolean\n}\n\n/** Per-collection metadata returned by GET /config. */\nexport interface CollectionClientInfo {\n name: string\n maxBodyBytes: number\n encryption: EncryptionMode\n allowedMimeTypes: string[]\n pullOnly?: boolean\n pushOnly?: boolean\n appendOnly?: AppendOnlyClientInfo\n ttlMs?: number\n forceFullFetch?: boolean\n}\n\n/** Response shape of GET /config. */\nexport interface ConfigResponse {\n collections: CollectionClientInfo[]\n namespaces?: Record<string, { collections: CollectionClientInfo[] }>\n}\n\n/**\n * Fetch the server's collection manifest from GET /config.\n *\n * @param baseUrl - Base URL of the Starfish server (e.g. `\"https://api.example.com/v1\"`).\n * @param options.headers - Optional request headers (e.g. `Authorization`).\n * @throws {Error} if the server returns a non-2xx response.\n */\nexport async function fetchServerConfig(\n baseUrl: string,\n options?: { headers?: Record<string, string> },\n): Promise<ConfigResponse> {\n const url = `${baseUrl.replace(/\\/$/, \"\")}/config`\n const res = await fetch(url, {\n method: \"GET\",\n headers: options?.headers,\n })\n if (!res.ok) {\n throw new Error(`fetchServerConfig: ${res.status} ${res.statusText}`)\n }\n return res.json() as Promise<ConfigResponse>\n}\n", "/**\n * IndexedDB-based storage adapter for Zustand persistence.\n * Implements the same interface as Zustand's StateStorage (getItem/setItem/removeItem).\n * Supports larger data than localStorage (typically 50MB+).\n */\n\nexport interface IndexedDBStorageOptions {\n /** Database name. Default: \"starfish\" */\n dbName?: string\n /** Object store name. Default: \"state\" */\n storeName?: string\n}\n\nexport interface AsyncStateStorage {\n getItem: (name: string) => Promise<string | null>\n setItem: (name: string, value: string) => Promise<void>\n removeItem: (name: string) => Promise<void>\n}\n\nfunction openDB(dbName: string, storeName: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(dbName, 1)\n request.onupgradeneeded = () => {\n const db = request.result\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName)\n }\n }\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n}\n\nfunction idbRequest<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n}\n\nexport function createIndexedDBStorage(\n opts?: IndexedDBStorageOptions,\n): AsyncStateStorage {\n const dbName = opts?.dbName ?? \"starfish\"\n const storeName = opts?.storeName ?? \"state\"\n let dbPromise: Promise<IDBDatabase> | null = null\n\n function getDB(): Promise<IDBDatabase> {\n if (!dbPromise) {\n dbPromise = openDB(dbName, storeName).catch((err) => {\n dbPromise = null // Reset so next call retries\n throw err\n })\n }\n return dbPromise\n }\n\n return {\n async getItem(name: string): Promise<string | null> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readonly\")\n const store = tx.objectStore(storeName)\n const result = await idbRequest(store.get(name))\n return result ?? null\n },\n\n async setItem(name: string, value: string): Promise<void> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readwrite\")\n const store = tx.objectStore(storeName)\n await idbRequest(store.put(value, name))\n },\n\n async removeItem(name: string): Promise<void> {\n const db = await getDB()\n const tx = db.transaction(storeName, \"readwrite\")\n const store = tx.objectStore(storeName)\n await idbRequest(store.delete(name))\n },\n }\n}\n", "/**\n * Data export/import helpers for Starfish sync data.\n * Supports JSON and CSV formats.\n */\n\nexport interface ExportOptions {\n /** Output format. Default: \"json\" */\n format?: \"json\" | \"csv\"\n /** Pretty-print JSON output. Default: false */\n pretty?: boolean\n}\n\n/**\n * Export data to a string representation.\n * JSON: serializes the full object.\n * CSV: flattens top-level keys into columns. Array values are JSON-encoded.\n */\nexport function exportData(\n data: Record<string, unknown>,\n opts?: ExportOptions,\n): string {\n const format = opts?.format ?? \"json\"\n\n if (format === \"json\") {\n return opts?.pretty\n ? JSON.stringify(data, null, 2)\n : JSON.stringify(data)\n }\n\n // CSV export: each top-level key becomes a column\n return toCsv(data)\n}\n\n/**\n * Import data from a string representation.\n */\nexport function importData(\n raw: string,\n format: \"json\" | \"csv\" = \"json\",\n): Record<string, unknown> {\n if (format === \"json\") {\n const parsed = JSON.parse(raw)\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"Expected a JSON object\")\n }\n return parsed as Record<string, unknown>\n }\n\n return fromCsv(raw)\n}\n\n/**\n * Export data to a Blob suitable for download.\n */\nexport function exportToBlob(\n data: Record<string, unknown>,\n opts?: ExportOptions,\n): Blob {\n const format = opts?.format ?? \"json\"\n const content = exportData(data, opts)\n const mimeType = format === \"csv\" ? \"text/csv;charset=utf-8\" : \"application/json;charset=utf-8\"\n return new Blob([content], { type: mimeType })\n}\n\nfunction toCsv(data: Record<string, unknown>): string {\n const keys = Object.keys(data)\n const header = keys.map(escapeCsvField).join(\",\")\n\n const values = keys.map((k) => {\n const v = data[k]\n if (v === null || v === undefined) return \"\"\n if (typeof v === \"object\") return escapeCsvField(JSON.stringify(v))\n return escapeCsvField(String(v))\n })\n\n return `${header}\\n${values.join(\",\")}`\n}\n\nfunction fromCsv(raw: string): Record<string, unknown> {\n const lines = raw.trim().split(\"\\n\")\n if (lines.length < 2) {\n throw new Error(\"CSV must have at least a header row and a data row\")\n }\n\n const headers = parseCsvLine(lines[0]!)\n const values = parseCsvLine(lines[1]!)\n\n const result: Record<string, unknown> = {}\n for (let i = 0; i < headers.length; i++) {\n const key = headers[i]!\n const val = values[i] ?? \"\"\n // Try to parse JSON values\n try {\n result[key] = JSON.parse(val)\n } catch {\n result[key] = val\n }\n }\n return result\n}\n\nfunction escapeCsvField(field: string): string {\n if (field.includes(\",\") || field.includes('\"') || field.includes(\"\\n\")) {\n return `\"${field.replace(/\"/g, '\"\"')}\"`\n }\n return field\n}\n\nfunction parseCsvLine(line: string): string[] {\n const result: string[] = []\n let current = \"\"\n let inQuotes = false\n\n for (let i = 0; i < line.length; i++) {\n const ch = line[i]!\n if (inQuotes) {\n if (ch === '\"' && line[i + 1] === '\"') {\n current += '\"'\n i++\n } else if (ch === '\"') {\n inQuotes = false\n } else {\n current += ch\n }\n } else {\n if (ch === '\"') {\n inQuotes = true\n } else if (ch === \",\") {\n result.push(current)\n current = \"\"\n } else {\n current += ch\n }\n }\n }\n result.push(current)\n return result\n}\n", "/**\n * Background Sync API integration for pending changes.\n * Uses the Web Background Sync API to retry failed sync operations\n * when connectivity is restored, even if the app is closed.\n */\n\nexport interface BackgroundSyncOptions {\n /** Sync event tag. Default: \"starfish-sync\" */\n tag?: string\n}\n\n/** Check if the Background Sync API is supported in the current environment. */\nexport function isBackgroundSyncSupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n \"serviceWorker\" in navigator &&\n \"SyncManager\" in globalThis\n )\n}\n\n/**\n * Register a background sync event with the active service worker.\n * Returns true if registration succeeded, false if not supported or no active SW.\n */\nexport async function registerBackgroundSync(\n opts?: BackgroundSyncOptions,\n): Promise<boolean> {\n if (!isBackgroundSyncSupported()) return false\n\n const tag = opts?.tag ?? \"starfish-sync\"\n\n try {\n const registration = await navigator.serviceWorker.ready\n // @ts-expect-error - SyncManager types may not be available\n await registration.sync.register(tag)\n return true\n } catch {\n return false\n }\n}\n", "/**\n * Service Worker utilities for offline support and PWA functionality.\n */\n\nexport interface ServiceWorkerOptions {\n /** Scope for the service worker registration. */\n scope?: string\n /** Called when an updated service worker is available. */\n onUpdate?: (registration: ServiceWorkerRegistration) => void\n}\n\n/** Check if service workers are supported in the current environment. */\nexport function isServiceWorkerSupported(): boolean {\n return typeof navigator !== \"undefined\" && \"serviceWorker\" in navigator\n}\n\n/**\n * Register a service worker for offline support.\n * Returns the registration, or null if not supported.\n */\nexport async function registerServiceWorker(\n scriptUrl: string,\n opts?: ServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (!isServiceWorkerSupported()) return null\n\n try {\n const registration = await navigator.serviceWorker.register(scriptUrl, {\n scope: opts?.scope,\n })\n\n if (opts?.onUpdate) {\n registration.onupdatefound = () => {\n const installingWorker = registration.installing\n if (installingWorker) {\n installingWorker.onstatechange = () => {\n if (\n installingWorker.state === \"installed\" &&\n navigator.serviceWorker.controller\n ) {\n opts.onUpdate!(registration)\n }\n }\n }\n }\n }\n\n return registration\n } catch {\n return null\n }\n}\n\n/** Unregister all service worker registrations. Returns true if any were unregistered. */\nexport async function unregisterServiceWorkers(): Promise<boolean> {\n if (!isServiceWorkerSupported()) return false\n\n try {\n const registrations = await navigator.serviceWorker.getRegistrations()\n let unregistered = false\n for (const registration of registrations) {\n const result = await registration.unregister()\n if (result) unregistered = true\n }\n return unregistered\n } catch {\n return false\n }\n}\n", "/**\n * React Suspense integration for Starfish sync data.\n * Creates resources that throw Promises while loading (Suspense protocol).\n */\n\ntype SuspenseStatus = \"pending\" | \"resolved\" | \"rejected\"\n\ninterface SuspenseResource<T> {\n /** Read the resource value. Throws a Promise while pending (Suspense protocol). */\n read(): T\n}\n\n/**\n * Create a Suspense-compatible resource from an async fetcher.\n * The first call to `read()` triggers the fetch. While loading, `read()` throws\n * a Promise (which React Suspense catches to show a fallback). Once resolved,\n * `read()` returns the value synchronously.\n *\n * @example\n * ```tsx\n * const resource = createSuspenseResource(() => syncManager.pull())\n * function MyComponent() {\n * const data = resource.read() // throws while loading, returns data when ready\n * return <div>{JSON.stringify(data)}</div>\n * }\n * ```\n */\nexport function createSuspenseResource<T>(\n fetcher: () => Promise<T>,\n): SuspenseResource<T> {\n let status: SuspenseStatus = \"pending\"\n let result: T\n let error: unknown\n let promise: Promise<void> | null = null\n\n function init(): Promise<void> {\n if (promise) return promise\n promise = fetcher().then(\n (value) => {\n status = \"resolved\"\n result = value\n },\n (err) => {\n status = \"rejected\"\n error = err\n },\n )\n return promise\n }\n\n return {\n read(): T {\n switch (status) {\n case \"pending\":\n throw init()\n case \"resolved\":\n return result\n case \"rejected\":\n throw error\n }\n },\n }\n}\n", "import type { StoreApi } from \"zustand/vanilla\"\nimport type { StarfishStore } from \"./bindings/zustand.js\"\nimport type { SyncManager } from \"./sync.js\"\n\n// \u2500\u2500 Shared types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DebouncedSyncOptions {\n /**\n * How long to wait after the last `notify()` call before pushing (default: 2000 ms).\n * Shorter values reduce latency; longer values batch more edits into a single push.\n */\n delayMs?: number\n /**\n * Emit a warning when the estimated encrypted payload exceeds this byte count (default: 900 KB).\n * The estimate multiplies the JSON size by 1.34 (base64 overhead for encrypted blobs).\n * Set to `Infinity` to disable.\n */\n warnBytes?: number\n /**\n * Block the push when the estimated encrypted payload exceeds this byte count (default: 1 MB).\n * Prevents cryptic 413 errors from the server. Set to `Infinity` to disable.\n */\n maxBytes?: number\n /**\n * Serialize store data to a sync document before pushing.\n * Called inside the debounce timer, so it always captures the latest state.\n * If omitted, `store.getState().data` is used as-is.\n */\n serialize?: (currentData: Record<string, unknown>) => Record<string, unknown>\n /**\n * Called when the estimated payload size exceeds `warnBytes` but is still below `maxBytes`.\n * Use to show a warning in the UI.\n */\n onSizeWarning?: (estimatedBytes: number) => void\n /**\n * Called when the estimated payload size exceeds `maxBytes`.\n * The push is blocked. Use to alert the user that data needs to be pruned.\n * If omitted, a console error is printed.\n */\n onSizeExceeded?: (estimatedBytes: number) => void\n}\n\nexport interface DebouncedSync {\n /**\n * Schedule a push. If called again within `delayMs`, the timer resets.\n * Safe to call on every domain store mutation.\n */\n notify: () => void\n /** Cancel any pending debounced push. Does not affect an already-in-flight push. */\n cancel: () => void\n}\n\nexport interface DebouncedPushOptions {\n /**\n * How long to wait after the last `notify()` call before pushing (default: 2000 ms).\n */\n delayMs?: number\n /**\n * Required: provides the document to push when the debounce timer fires.\n * Called inside the timer so it always captures the latest state.\n */\n serialize: () => Record<string, unknown>\n /**\n * Emit a warning when the estimated encrypted payload exceeds this byte count (default: 900 KB).\n * Set to `Infinity` to disable.\n */\n warnBytes?: number\n /**\n * Block the push when the estimated encrypted payload exceeds this byte count (default: 1 MB).\n * Set to `Infinity` to disable.\n */\n maxBytes?: number\n /**\n * Called when the estimated payload size exceeds `warnBytes` but is below `maxBytes`.\n */\n onSizeWarning?: (estimatedBytes: number) => void\n /**\n * Called when the estimated payload size exceeds `maxBytes`. The push is blocked.\n * If omitted, a console error is printed.\n */\n onSizeExceeded?: (estimatedBytes: number) => void\n /**\n * Called when `syncManager.push()` throws. Default: `console.warn`.\n */\n onError?: (err: unknown) => void\n}\n\nexport interface DebouncedPush {\n /**\n * Schedule a push. If called again within `delayMs`, the timer resets.\n */\n notify: () => void\n /** Cancel any pending debounced push. Does not affect an already-in-flight push. */\n cancel: () => void\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst DEFAULT_DELAY_MS = 2000\nconst DEFAULT_WARN_BYTES = 900 * 1024 // 900 KB\nconst DEFAULT_MAX_BYTES = 1024 * 1024 // 1 MB\n\ninterface SizeGuardOptions {\n warnBytes: number\n maxBytes: number\n onSizeWarning?: (bytes: number) => void\n onSizeExceeded?: (bytes: number) => void\n}\n\n/** Returns true if the push should be blocked. */\nfunction checkPayloadSize(doc: Record<string, unknown>, opts: SizeGuardOptions): boolean {\n // Estimate encrypted payload size. AES-GCM output is similar to input size;\n // base64 encoding adds ~33% overhead, plus a small IV/tag overhead.\n const estimatedBytes = Math.ceil(JSON.stringify(doc).length * 1.34)\n\n if (estimatedBytes > opts.maxBytes) {\n if (opts.onSizeExceeded) {\n opts.onSizeExceeded(estimatedBytes)\n } else {\n console.error(\n `[starfish] Push blocked: estimated payload ${(estimatedBytes / 1024).toFixed(0)} KB ` +\n `exceeds limit of ${(opts.maxBytes / 1024).toFixed(0)} KB. Prune your data before syncing.`,\n )\n }\n return true\n }\n\n if (estimatedBytes > opts.warnBytes) {\n if (opts.onSizeWarning) {\n opts.onSizeWarning(estimatedBytes)\n } else {\n console.warn(\n `[starfish] Payload approaching limit: estimated ${(estimatedBytes / 1024).toFixed(0)} KB ` +\n `(warn threshold: ${(opts.warnBytes / 1024).toFixed(0)} KB).`,\n )\n }\n }\n\n return false\n}\n\n/**\n * Creates a debounced push helper that coalesces rapid mutations into a single sync.\n *\n * Designed to be called on every domain store mutation (e.g., every keystroke).\n * The push is delayed by `delayMs` after the **last** call, so typing quickly\n * results in one push, not one per character.\n *\n * Also estimates the encrypted payload size before pushing and warns / blocks\n * if it approaches the server's body size limit.\n *\n * ```ts\n * const { notify } = createDebouncedSync(starfishStore, {\n * serialize: () => ({ tasks: taskStore.getState().tasks }),\n * })\n *\n * // Call on every domain store mutation:\n * taskStore.subscribe(() => notify())\n * ```\n */\nexport function createDebouncedSync(\n store: StoreApi<StarfishStore>,\n options: DebouncedSyncOptions = {},\n): DebouncedSync {\n const {\n delayMs = DEFAULT_DELAY_MS,\n warnBytes = DEFAULT_WARN_BYTES,\n maxBytes = DEFAULT_MAX_BYTES,\n serialize,\n onSizeWarning,\n onSizeExceeded,\n } = options\n\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n function notify(): void {\n cancel()\n timer = setTimeout(() => {\n timer = null\n const current = store.getState().data\n const doc = serialize ? serialize(current) : current\n\n if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded })) return\n\n store.getState().set(() => doc)\n }, delayMs)\n }\n\n return { notify, cancel }\n}\n\n/**\n * Creates a debounced push helper that calls `syncManager.push()` directly,\n * without requiring a Zustand store.\n *\n * Use this for one-way publishing workflows: public pages, derived snapshots,\n * or any case where you want to push data without a full `createStarfishStore` setup.\n *\n * ```ts\n * const syncManager = new SyncManager({ client, pullPath, pushPath })\n *\n * const { notify, cancel } = createDebouncedPush(syncManager, {\n * serialize: () => buildPublicPageDocument(),\n * })\n *\n * // Push after every relevant store mutation:\n * planningStore.subscribe(() => notify())\n *\n * // Clean up on teardown:\n * cancel()\n * ```\n */\nexport function createDebouncedPush(\n syncManager: SyncManager,\n options: DebouncedPushOptions,\n): DebouncedPush {\n const {\n delayMs = DEFAULT_DELAY_MS,\n warnBytes = DEFAULT_WARN_BYTES,\n maxBytes = DEFAULT_MAX_BYTES,\n serialize,\n onSizeWarning,\n onSizeExceeded,\n onError,\n } = options\n\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n function notify(): void {\n cancel()\n timer = setTimeout(() => {\n timer = null\n const doc = serialize()\n\n if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded })) return\n\n syncManager.push(doc).catch((err: unknown) => {\n if (onError) {\n onError(err)\n } else {\n console.warn(\"[starfish] Push failed:\", err)\n }\n })\n }, delayMs)\n }\n\n return { notify, cancel }\n}\n", "import type { StoreApi } from \"zustand/vanilla\"\nimport type { StarfishStore } from \"./bindings/zustand.js\"\n\n// \u2500\u2500 Types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Minimal interface matching React Native's `AppState` module.\n * Pass `AppState` from `react-native` directly.\n */\nexport interface AppStateModule {\n addEventListener: (\n type: \"change\",\n listener: (state: string) => void,\n ) => { remove: () => void }\n}\n\n/**\n * Minimal interface matching `@react-native-community/netinfo`'s default export.\n * Pass `NetInfo` from `@react-native-community/netinfo` directly.\n */\nexport interface NetInfoModule {\n addEventListener: (\n listener: (state: { isConnected: boolean | null }) => void,\n ) => () => void\n}\n\nexport interface MobileLifecycleDeps {\n /** React Native `AppState` module. */\n appState: AppStateModule\n /**\n * Optional: NetInfo module from `@react-native-community/netinfo`.\n * When provided, connectivity changes are forwarded to `store.getState().setOnline()`.\n */\n netInfo?: NetInfoModule\n}\n\nexport interface MobileLifecycleOptions {\n /**\n * Pull remote changes when the app returns to the foreground.\n * Only pulls if the store is online and not already syncing.\n * Default: `true`.\n */\n pullOnForeground?: boolean\n /**\n * Flush dirty data when the app transitions to the background.\n * Only flushes if the store has unsaved changes.\n * Default: `true`.\n */\n flushOnBackground?: boolean\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Wires React Native app lifecycle events to a Starfish store.\n *\n * - **Background**: flushes pending changes before the OS suspends the app.\n * - **Foreground**: pulls remote changes when the user returns to the app.\n * - **NetInfo**: forwards connectivity changes to `store.getState().setOnline()`.\n *\n * Uses dependency injection so no `react-native` or `netinfo` imports are needed\n * in this package. Pass the modules directly:\n *\n * ```ts\n * import { AppState } from \"react-native\"\n * import NetInfo from \"@react-native-community/netinfo\"\n * import { createMobileLifecycle } from \"@drakkar.software/starfish-client\"\n *\n * // Call once, after the store is created:\n * const cleanup = createMobileLifecycle(\n * store,\n * { appState: AppState, netInfo: NetInfo },\n * )\n *\n * // In a React component (e.g. root layout):\n * useEffect(() => cleanup, [])\n * ```\n *\n * @returns A cleanup function that removes all event listeners.\n */\nexport function createMobileLifecycle(\n store: StoreApi<StarfishStore>,\n deps: MobileLifecycleDeps,\n options: MobileLifecycleOptions = {},\n): () => void {\n const { pullOnForeground = true, flushOnBackground = true } = options\n\n const appSub = deps.appState.addEventListener(\"change\", (appState) => {\n if (appState === \"background\" && flushOnBackground) {\n if (store.getState().dirty) {\n store.getState().flush().catch((err) => { console.error(\"[Starfish] background flush failed:\", err) })\n }\n } else if (appState === \"active\" && pullOnForeground) {\n const { online, syncing } = store.getState()\n if (online && !syncing) {\n store.getState().pull().catch((err) => { console.error(\"[Starfish] foreground pull failed:\", err) })\n }\n }\n // \"inactive\" (iOS transition) and other states are intentionally ignored\n })\n\n let netUnsub: (() => void) | null = null\n if (deps.netInfo) {\n netUnsub = deps.netInfo.addEventListener(({ isConnected }) => {\n store.getState().setOnline(!!isConnected)\n })\n }\n\n return () => {\n appSub.remove()\n netUnsub?.()\n }\n}\n", "// \u2500\u2500 Types \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Serializer/deserializer pair for one slice of application state.\n *\n * `serialize` snapshots the current state into a plain object.\n * `restore` applies a snapshot (potentially from a different app version after migration).\n */\nexport interface StoreSlice<T = unknown> {\n /**\n * Snapshot the current state of this slice into a serializable value.\n * Called during `serialize()`.\n */\n serialize: () => T\n /**\n * Apply a snapshot to this slice.\n * Called during `restore()` \u2014 data may be from an older schema version after migration.\n */\n restore: (data: T) => void\n}\n\n/**\n * A versioned backup document produced by `MultiStoreSync.serialize()`.\n * Safe to pass to `store.set()` as the Starfish sync document.\n */\nexport interface BackupDocument<T = Record<string, unknown>> {\n /** Schema version declared in `createMultiStoreSync`. */\n version: number\n /** Unix timestamp (ms) when this backup was created. */\n timestamp: number\n /** Serialized slice data, keyed by slice name. */\n data: T\n}\n\n/**\n * A migration function that transforms data from one version to the next.\n * Receives the full `data` object and must return an updated `data` object.\n * Only the `data` field is passed; `version` and `timestamp` are managed automatically.\n */\nexport type MultiStoreMigrationFn = (data: Record<string, unknown>) => Record<string, unknown>\n\nexport interface MultiStoreSyncOptions<T extends Record<string, unknown>> {\n /**\n * Named slices to include in the backup document.\n * Each slice provides `serialize()` and `restore()` methods.\n *\n * @example\n * ```ts\n * slices: {\n * tasks: {\n * serialize: () => taskStore.getState().tasks,\n * restore: (data) => taskStore.setState({ tasks: data }),\n * },\n * settings: {\n * serialize: () => settingsStore.getState().settings,\n * restore: (data) => settingsStore.setState({ settings: data }),\n * },\n * }\n * ```\n */\n slices: { [K in keyof T]: StoreSlice<T[K]> }\n /**\n * Current schema version. Increment when slices are added, renamed, or their shape changes.\n * Used to detect forward-incompatible documents from future app versions.\n */\n version: number\n /**\n * Optional migration chain. Key is the version number that produced the data;\n * value is a function that upgrades it to the next version.\n *\n * Migrations run sequentially from the document version up to the current version.\n *\n * @example\n * ```ts\n * migrations: {\n * 1: (data) => ({ ...data, settings: { ...data.settings, theme: \"light\" } }),\n * 2: (data) => ({ ...data, tasks: data.todos, todos: undefined }),\n * }\n * ```\n */\n migrations?: Record<number, MultiStoreMigrationFn>\n}\n\n/**\n * Returned by `createMultiStoreSync`. Serialize and restore coordinated multi-store state.\n */\nexport interface MultiStoreSync<T extends Record<string, unknown>> {\n /**\n * Snapshot all slices into a `BackupDocument`.\n * Pass the result to `starfishStore.getState().set(() => multiSync.serialize())`.\n */\n serialize: () => BackupDocument<T>\n /**\n * Apply a `BackupDocument` to all slices, running migrations as needed.\n *\n * Throws if the document version is newer than the current version (forward-incompatible).\n * Silently migrates older documents.\n */\n restore: (doc: BackupDocument) => void\n /** Current schema version as declared in options. */\n readonly version: number\n}\n\n// \u2500\u2500 Implementation \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\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates a multi-store sync coordinator.\n *\n * Collects multiple application stores into a single Starfish sync document,\n * with versioned schema migrations for backward compatibility.\n *\n * ```ts\n * const multiSync = createMultiStoreSync({\n * slices: {\n * tasks: {\n * serialize: () => taskStore.getState().tasks,\n * restore: (tasks) => taskStore.setState({ tasks }),\n * },\n * settings: {\n * serialize: () => settingsStore.getState().settings,\n * restore: (settings) => settingsStore.setState({ settings }),\n * },\n * },\n * version: 2,\n * migrations: {\n * // data from version 1 \u2192 upgrade to version 2\n * 1: (data) => ({ ...data, settings: { ...(data.settings as object), darkMode: false } }),\n * },\n * })\n *\n * // Push:\n * starfishStore.getState().set(() => multiSync.serialize())\n *\n * // Restore on pull (pass as onRemoteUpdate to createStarfishStore):\n * createStarfishStore({\n * name: \"app\",\n * syncManager,\n * onRemoteUpdate: (doc) => multiSync.restore(doc as BackupDocument),\n * })\n * ```\n */\nexport function createMultiStoreSync<T extends Record<string, unknown>>(\n options: MultiStoreSyncOptions<T>,\n): MultiStoreSync<T> {\n const { slices, version, migrations = {} } = options\n\n // Validate migration chain at construction time (fail fast)\n for (const fromVersion of Object.keys(migrations)) {\n const v = Number(fromVersion)\n if (isNaN(v) || v < 1) {\n throw new Error(`Migration key must be a positive integer, got: \"${fromVersion}\"`)\n }\n }\n\n function serialize(): BackupDocument<T> {\n const data = {} as T\n for (const key of Object.keys(slices) as Array<keyof T>) {\n data[key] = slices[key].serialize() as T[typeof key]\n }\n return { version, timestamp: Date.now(), data }\n }\n\n function restore(doc: BackupDocument): void {\n if (typeof doc !== \"object\" || doc === null) {\n throw new Error(\"restore: expected a BackupDocument object\")\n }\n\n const docVersion = doc.version ?? 1\n\n if (typeof docVersion !== \"number\" || !Number.isInteger(docVersion) || docVersion < 1) {\n throw new Error(`restore: invalid document version: ${String(doc.version)}`)\n }\n\n if (docVersion > version) {\n throw new Error(\n `restore: document version ${docVersion} is newer than current version ${version}. ` +\n `Update the app to restore this backup.`,\n )\n }\n\n // Run migrations sequentially from docVersion up to current version\n let data: Record<string, unknown> =\n typeof doc.data === \"object\" && doc.data !== null\n ? { ...(doc.data as Record<string, unknown>) }\n : {}\n\n for (let v = docVersion; v < version; v++) {\n const migration = migrations[v]\n if (!migration) continue\n try {\n data = migration(data)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(`restore: migration from version ${v} to ${v + 1} failed: ${msg}`)\n }\n }\n\n // Restore each slice\n for (const key of Object.keys(slices) as Array<keyof T>) {\n const sliceData = data[key as string]\n if (sliceData !== undefined) {\n slices[key].restore(sliceData as T[typeof key])\n }\n }\n }\n\n return { serialize, restore, version }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,yBAAyB;AAElC,SAAS,mBAAAA,kBAAiB,mBAAmB;AAC7C,SAAS,qBAAqB,2CAA2C;;;ACFzE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACJA,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,cAAc;AACZ,UAAM,eAAe;AACrB,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YACkB,QACA,MAChB;AACA,UAAM,QAAQ,MAAM,KAAK,IAAI,EAAE;AAHf;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;;;ADLA,IAAM,uBAAuB;AAiD7B,SAAS,cAAc,KAAsB;AAC3C,QAAM,OAAO,gBAAgB,GAA8B;AAC3D,MAAI,OAAO,SAAS,YAAY;AAC9B,WAAO,KAAK,IAAI;AAAA,EAClB;AACA,QAAM,UAAW,WAAwG;AACzH,MAAI,QAAS,QAAO,QAAQ,KAAK,MAAM,OAAO,EAAE,SAAS,QAAQ;AACjE,QAAM,IAAI,MAAM,6BAA6B;AAC/C;AAMO,IAAM,iBAAN,MAAqB;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKD;AAAA,EAEhB,YAAY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,IAAI,OAAO,CAAC,EAAE;AAAA,IAC7E;AAEA,QAAI,aAAa,SAAS;AACxB,YAAM,IAAI;AAAA,QACR,6BAA6B,UAAU,kCAAkC,OAAO;AAAA,MAElF;AAAA,IACF;AAGA,QAAI,OACF,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,OACzC,EAAE,GAAI,IAAI,KAAiC,IAC3C,CAAC;AAEP,aAAS,IAAI,YAAY,IAAI,SAAS,KAAK;AACzC,YAAM,YAAY,WAAW,CAAC;AAC9B,UAAI,CAAC,UAAW;AAChB,UAAI;AACF,eAAO,UAAU,IAAI;AAAA,MACvB,SAAS,KAAK;AACZ,cAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,cAAM,IAAI,MAAM,mCAAmC,CAAC,OAAO,IAAI,CAAC,YAAY,GAAG,EAAE;AAAA,MACnF;AAAA,IACF;AAGA,eAAW,OAAO,OAAO,KAAK,MAAM,GAAqB;AACvD,YAAM,YAAY,KAAK,GAAa;AACpC,UAAI,cAAc,QAAW;AAC3B,eAAO,GAAG,EAAE,QAAQ,SAA0B;AAAA,MAChD;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,SAAS,QAAQ;AACvC;",
|
|
6
6
|
"names": ["stableStringify", "stableStringify", "stableStringify"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakkar.software/starfish-client",
|
|
3
|
-
"version": "3.0.0-alpha.
|
|
3
|
+
"version": "3.0.0-alpha.7",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/Drakkar-Software/starfish.git",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
}
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@drakkar.software/starfish-protocol": "3.0.0-alpha.
|
|
63
|
+
"@drakkar.software/starfish-protocol": "3.0.0-alpha.7"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
66
|
"@legendapp/state": "^2.0.0",
|