import { EventEmitter } from './event-emitter.js'; import { RoolSpace } from './space.js'; import type { RoolClientConfig, RoolClientEvents, RoolSpaceInfo, CurrentUser, InvitePreview, InviteRedeemResult, AuthUser, PasswordSignInResult } from './types.js'; /** * Rool Client - Manages authentication, space lifecycle, and shared infrastructure. * * The client is lightweight - most operations happen on RoolSpace instances. * * Features: * - Authentication (login, logout, token management) * - Space lifecycle (list, create, delete, rename) * - Client-level subscription for lifecycle events * - User storage (cross-device key-value storage) */ export declare class RoolClient extends EventEmitter { private baseUrl; private urls; private authManager; private graphqlClient; private router; private subscriptionManager; private logger; private clientInfo; private _serverInfo; private openSpaces; private _storageCache; private _currentUser; constructor(config?: RoolClientConfig); /** * Initialize the client - should be called on app startup. * Processes any auth callback in the URL, sets up auto-refresh, * and starts real-time event subscription if authenticated. * @returns true if authenticated, false otherwise */ initialize(): Promise; /** * Start the realtime subscription and load the current user/storage. Shared * by initialize() and verify() — any path that lands the user in an * authenticated state needs this hydration. * * Hydration is best-effort and never throws: a backend outage must not read * as a logout. The subscription owns reconnect/backoff and refetches the user * on (re)connect (see ensureSubscribed), so a session that boots while the * server is down stays authenticated and self-heals when it returns. Only a * hard auth failure (401) ends the session, via the token layer. */ private hydrateAuthenticatedSession; /** * Fetch the current user and populate the storage cache, then emit * currentUserChanged. Cache is set before the emit so listeners reading * getAllUserStorage() in response see fresh storage. */ private fetchUserAndStorage; private setCurrentUser; /** * Clean up resources - call when destroying the client. */ destroy(): void; /** * Initiate login by redirecting to auth page. * @param appName - The name of the application requesting login (displayed on auth page) */ login(appName: string, params?: Record): Promise; /** * Initiate signup by redirecting to auth page. * @param appName - The name of the application requesting signup (displayed on auth page) * @param params - Optional additional query parameters to pass to the auth server */ signup(appName: string, params?: Record): Promise; /** * Complete an email verification flow using a token from the verification * email link. Exchanges the token for a live session and signs the user in * without a redirect. Intended to be called when the app detects a * `?verify=` query parameter on load. * * Returns true if the user is now signed in as a result. */ verify(token: string): Promise; /** * Complete a native sign-in (PKCE) from a deep-link callback URL. Call this * from the app's platform deep-link handler (e.g. Capacitor's `appUrlOpen`) * with the full callback URL. Exchanges the code for a live session. * * Returns true if the user is now signed in as a result. */ handleAuthRedirect(url: string): Promise; /** * Sign in with email + password. Resolves to `{ status: 'signed_in' }` once * authenticated, or `{ status: 'verify_required' }` when the account's email * isn't verified yet (a magic link has been emailed). Rejects with a * human-readable Error on bad credentials or server failure. */ signInWithPassword(email: string, password: string): Promise; /** * Request a magic sign-in link by email. The server emails a link; the user * completes sign-in by following it, which is finished via `verify()` / * `handleAuthRedirect()` when it lands back in the app. Resolves once the * email is accepted; rejects with a human-readable Error on a bad address. */ requestMagicLink(email: string): Promise; /** * Set or change the current user's password. Requires an authenticated session. * Password must be at least 8 characters and contain both letters and either * digits or symbols. * * Throws an Error with a human-readable message on validation or server failure. */ setPassword(password: string): Promise; /** * Logout - clear all tokens and state. */ logout(): void; /** * Check if user is currently authenticated (validates token is usable). */ isAuthenticated(): Promise; /** * Make an authenticated fetch request to the Rool API. * @internal Not part of the public API — use typed methods instead. * * @param path - Path relative to the base URL (e.g., '/billing/usage') * @param init - Standard fetch RequestInit options. Authorization header is added automatically. */ _api(path: string, init?: RequestInit): Promise; /** * Get auth identity decoded from JWT token. * For the Rool user (with server-assigned id), use currentUser. */ getAuthUser(): AuthUser; /** * Get the current Rool user (cached from initialize). * Available after successful authentication. */ get currentUser(): CurrentUser | null; get serverInfo(): { version: string; minimumSdkVersion?: string | null; compatibility: 'ok' | 'unsupported'; } | null; /** * List all spaces accessible to the user. */ listSpaces(): Promise; /** * Open a space with a real-time subscription. * Returns a live RoolSpace handle with conversation and file events. * Reuses an existing handle if the space is already open. * * Call space.close() when done to stop the subscription. */ openSpace(spaceId: string): Promise; /** * Create a new space. * Returns a RoolSpace handle with a real-time subscription. * Use the returned RoolSpace to work with objects, conversations, and AI. */ createSpace(name: string): Promise; /** * GraphQL client pinned to a space's owning node, rerouting on refusal. * Space-scoped mutations must not go to an arbitrary shard via the base URL. */ private scopedGraphqlClient; /** * Delete a space. * Note: This closes any cached open RoolSpace handle. */ deleteSpace(spaceId: string): Promise; /** * Duplicate an existing space. Returns a handle to the new space. */ duplicateSpace(sourceSpaceId: string, name: string): Promise; /** * Mark the current user for deletion (7-day grace period). * Irrecoverable after the grace period elapses. */ deleteCurrentUser(): Promise; /** * Import a space from a zip archive. * Creates a new space with the given name and imports objects, relations, and files. * Returns a RoolSpace handle. */ importArchive(name: string, archive: Blob): Promise; /** * Get the current Rool user from the server. * Returns the user's server-assigned id, email, plan, and credits. */ getCurrentUser(): Promise; /** * Look up an invite link by its token, without redeeming it. * Does not require authentication. */ previewInvite(token: string): Promise; /** * Redeem an invite link, joining the space it belongs to. */ redeemInvite(token: string): Promise; /** * Update the current user's profile. * - name: display name * - slug: used in app publishing URLs (3-32 chars, start with letter, lowercase alphanumeric/hyphens/underscores) */ updateCurrentUser(input: { name?: string; slug?: string; marketingOptIn?: boolean; }): Promise; /** * Get a value from user storage (sync read from in-memory cache). * Cache is populated from the server on initialize(). * Returns undefined if key doesn't exist. */ getUserStorage(key: string): T | undefined; /** * Set a value in user storage. * Updates in-memory cache immediately, then syncs to server. * Pass undefined/null to delete the key. * Storage is limited to 10MB total. */ setUserStorage(key: string, value: unknown): void; /** * Get all user storage data (sync read from local cache). */ getAllUserStorage(): Record; /** * Report an event to the server. * Fire-and-forget — errors are logged but not propagated. */ reportEvent(event: string, url?: string): void; private get restClient(); /** * Ensure the client-level event subscription is active. * Called automatically when opening spaces. * @internal */ private ensureSubscribed; /** * Disconnect from real-time events. * @internal */ private unsubscribe; /** * Generate a unique 6-character alphanumeric ID. */ static generateId(): string; /** * Execute an arbitrary GraphQL query or mutation. * @internal Not part of the public API — use typed methods instead. */ _graphql(query: string, variables?: Record): Promise; /** * Handle a client-level event from the subscription. * @internal */ private handleClientEvent; /** * Handle a user storage change from SSE (remote update). * Updates cache and emits event if value actually changed. * @internal */ private handleUserStorageChanged; } //# sourceMappingURL=client.d.ts.map