UNPKG

crann

Version:

Effortless State Synchronization for Web Extensions

78 lines (77 loc) 3.04 kB
/** * Crann v2 Agent * * Client-side connection to a Crann store. * Runs in content scripts, popup, sidepanel, etc. */ import type { ConfigSchema, ValidatedConfig, DerivedState, DerivedActions, StateChanges } from "../store/types"; import type { AgentOptions, AgentAPI, AgentConnectionInfo } from "./types"; export declare class Agent<TConfig extends ConfigSchema> implements AgentAPI<TConfig> { private readonly config; private readonly options; private readonly porter; private _state; private _agentInfo; private _isConnected; private _isDisconnected; private readonly subscribers; private readonly readyCallbacks; private readonly disconnectCallbacks; private readonly reconnectCallbacks; private readyPromise; private readyResolve; private readonly actionsProxy; constructor(config: ValidatedConfig<TConfig>, options?: AgentOptions); ready(): Promise<DerivedState<TConfig>>; onReady(callback: (state: DerivedState<TConfig>) => void): () => void; getState(): DerivedState<TConfig>; get state(): DerivedState<TConfig>; setState(state: Partial<DerivedState<TConfig>>): Promise<void>; subscribe(callbackOrKeys: ((changes: StateChanges<TConfig>, state: DerivedState<TConfig>) => void) | Array<keyof DerivedState<TConfig>>, maybeCallback?: (changes: StateChanges<TConfig>, state: DerivedState<TConfig>) => void): () => void; get actions(): DerivedActions<TConfig>; getInfo(): AgentConnectionInfo | null; onDisconnect(callback: () => void): () => void; onReconnect(callback: (state: DerivedState<TConfig>) => void): () => void; disconnect(): void; private setupMessageHandlers; private notifySubscribers; private createActionsProxy; private buildDefaultState; private assertNotDisconnected; } /** * Connect to a Crann store from a client context. * * This should be called in content scripts, popup, sidepanel, or other * extension contexts that need to access the store. Uses the config's * `name` to find and connect to the matching store in the service worker. * * @param config - Validated config from createConfig() (must match store's config) * @param options - Optional connection options * @param options.debug - Enable debug logging * @returns An Agent instance for interacting with the store * * @example * // content.ts * import { createConfig, connectStore } from 'crann'; * * const config = createConfig({ * name: 'myFeature', * count: { default: 0, persist: 'local' }, * }); * * const agent = connectStore(config); * * // Wait for connection and initial state * const state = await agent.ready(); * console.log('Initial count:', state.count); * * // Subscribe to changes * agent.subscribe((changes, state) => { * console.log('State changed:', changes); * }); * * // Call actions * await agent.actions.increment(); */ export declare function connectStore<TConfig extends ConfigSchema>(config: ValidatedConfig<TConfig>, options?: AgentOptions): AgentAPI<TConfig>;