Skip to main content

dartvex 0.4.2 copy "dartvex: ^0.4.2" to clipboard
dartvex: ^0.4.2 copied to clipboard

Pure Dart client for Convex with WebSocket sync, type-safe values, and reactive subscriptions. Works on iOS, Android, web, and desktop.

Changelog #

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased] #

0.4.2 - 2026-11-20 #

Changed #

  • Documentation: "The Dartvex ecosystem" table lists dartvex_auth2_convex, the Convex Auth (@convex-dev/auth v2) adapter, published as 0.1.0.

0.4.1 - 2026-11-20 #

Fixed #

  • A transient network outage no longer signs the user out. When a token fetch fails with a transient error (a ConvexException with retryable: true, a TimeoutException or an http ClientException), the client keeps the session and retries with a growing delay (1 s, 2 s, 5 s, 10 s, then every 30 s) instead of giving up:

    • the scheduled refresh, and the refetch after a cached token is confirmed, were not retried at all: the token expired silently;
    • after the server rejected an expired token, the reauth gave up after its two short retries (2.5 s) and signed the user out, although the session was still valid and the auth provider still held it.

    The client stays authenticated. During a background refresh the current token stays in use; during a reauth the socket stays stopped (no query or mutation reaches the server, public ones included) and isAuthRefreshing is true until a new token is accepted. The fetch is retried at once when ConvexClientConfig.connectivitySignal reports the network back and on reconnectNow() (which dartvex_flutter calls when the app resumes), including when the signal arrives while an attempt is still in flight. On native platforms, dart:io SocketException, HttpException and HandshakeException count as transient too; a fetcher built on another HTTP stack should wrap its network errors in ConvexException(..., retryable: true). An AuthSessionEndedError or a fetch returning no token still signs out; any other error still keeps the token without retrying during a background refresh, and signs out after the two short retries during a reauth.

  • A FatalError from the server now stops the auth refresh flow: the scheduled refresh (and its retries) no longer call the auth provider once the connection is terminated for good. This departs from the official client, which gives up after the short retries: Convex Auth access tokens live one minute, so short outages on mobile would otherwise sign users out often. Found while validating dartvex_auth2_convex on a device.

0.4.0 - 2026-11-20 #

Added #

  • QuerySuccess.fromCache and QueryError.fromCache: true on the warm seed a new subscription receives first, the result kept after an earlier subscription to the same query was cancelled. It can be stale until the server answers. Before, nothing told it apart from a server result.
  • ConvexWatch.watch<T>(name, args, {decode, skipCached}) on every ConvexFunctionCaller (ConvexClient, ConvexClientWithAuth): a decoded Stream<T> of a live query that subscribes on listen and unsubscribes on cancel, so first/take/await for release the subscription. Query errors are ConvexException stream errors, loading results are skipped, and skipCached: true drops the warm seed.
  • ConvexAuthClient.clearAuth() / ConvexClientWithAuth.clearAuth(): continue signed out without calling the provider. It releases the hold of a client created with expectAuth: true when there is no session to restore, without keeping a second reference to the raw ConvexClient. Breaking for implementors: classes that implement ConvexAuthClient must add Future<void> clearAuth().

Changed #

  • Compatibility target: Dartvex now tracks the official Convex JavaScript client 1.51.0 (was 1.49.0). The tracked sync protocol, auth and value encoding sources are unchanged between the two releases, so only the exported convexSyncApiVersion constant moves ('1.51.0'), and with it the default ConvexClientConfig.apiVersion sent in the WebSocket URL.

Fixed #

  • A background token refresh that fails with an AuthSessionEndedError (the provider reports the session as revoked or expired) now signs the client out at once: the transport auth is cleared and ConvexClientWithAuth emits AuthUnauthenticated. Before, the error was only logged and the client kept showing the user as signed in until the server rejected the current token. Any other refresh error is still treated as transient and keeps the session. A reauth after a server rejection no longer retries such an error. A refresh that fails after a newer token fetch started is ignored, like a refresh that succeeds late: it cannot end a session that fetch renewed.

0.3.0 - 2026-11-05 #

Added #

  • AuthSessionEndedError: a marker interface for errors thrown by AuthProvider.login/loginFromCache when the provider's session no longer exists. A replacement login or restore failing with such an error signs the client out instead of keeping the previous session (which ran on the same, now dead, session) as authenticated. Other errors still keep a healthy previous session.
  • ConvexFunctionCaller.mutate takes an optional OptimisticUpdate, so code written against the interface (and ConvexClientWithAuth) can apply optimistic updates. Breaking for implementors: classes that implement ConvexFunctionCaller must add the optional OptimisticUpdate? optimisticUpdate parameter to mutate.
  • ConvexClientConfig.expectAuth: when true, the client holds the socket until the first setAuth / setAuthWithRefresh / clearAuth, so no query ever runs unauthenticated. Mirrors the official client's expectAuth.
  • ConvexCommitTsPlaceholder.instance: the server's $commitTs placeholder (an unresolved commit timestamp) now decodes to this exported singleton and encodes back to {"$commitTs": null} instead of failing the whole message.
  • convexToCanonicalJson, which encodes a value the way query tokens are keyed (integral doubles such as 1.0 match 1).
  • ConvexPaginatedQuery.reset() restarts pagination from the first page with a fresh pagination id. The query also resets itself when the server reports InvalidCursor for an already-loaded page.
  • ConvexPaginatedResult.hasPendingWrites, aggregated from the loaded pages.
  • StoredQueryResult, StoredQuerySuccess, StoredQueryLoading, and StoredQueryError are exported. They were already referenced by the public PageSubscription / PageInitialResultReader types.
  • dartvexVersion and convexSyncApiVersion constants.
  • ConvexStorage.uploadFile accepts useAction (generate the upload URL from an action) and a timeout for the upload request.
  • Transport: ConvexClient(onServerDisconnectError: ...), an experimental telemetry hook that receives a description of each abnormal server disconnect (a server close with a reason and a code other than 1000, 1001, 1005, or 4040). Mirrors the official client's unstable option.
  • Transport: a reconnect triggered by ConnectivitySignal now reports the backoff time it skipped to the server as a NetworkRecoveryReconnect event, as the official client does.
  • Auth: ConvexClientConfig.initialAuthTokenReuse (experimental, default false). When enabled, a cached token from setAuthWithRefresh that the server confirms is kept, and its refresh is scheduled from the token's remaining lifetime on the server's clock (from the confirming transition's clock skew), instead of being immediately replaced by a fresh fetch. Mirrors the official client's option.
  • Auth: ConvexClient.isAuthenticated (the current value of authState, which does not replay) and ConvexClient.currentAuthToken / ConvexClientWithAuth.currentAuthToken (the token currently in use, reflecting every refresh; the counterpart of the official getAuth()).
  • Auth: the AuthTokenFetcher typedef used by setAuthWithRefresh is now exported.

Changed #

  • Parity baseline: this release is aligned with the official Convex JavaScript client 1.49.0 (convex on npm; 0.2.0 was aligned with 1.41.0). The default ConvexClientConfig.apiVersion is now the exported convexSyncApiVersion constant ('1.49.0', was '1.41.0'), bumped deliberately after diffing the official sync client sources. The default clientId is now dartvex-<package version> (dartvexVersion; it was dart-dartvex).
  • ConvexStorage.uploadFile's filename is optional. It was never sent to Convex; it is only used in debug logs.
  • Breaking (behavior): a pending mutation or action sent under one auth identity now fails with a ConvexException when auth changes before it completes. It is no longer replayed under the new identity.
  • Breaking: ConvexPaginatedQuery rejects a pageSize or loadMore count below 1 with an ArgumentError.
  • Breaking: encoding an int beyond ±2^53 that a float64 cannot represent exactly throws an ArgumentError instead of silently changing the value. Use convexInt64 / BigInt for 64-bit integers.
  • Breaking: auth methods (setAuth, setAuthWithRefresh, clearAuth, updateAuthToken) and reconnectNow on a closed client return a failed future instead of throwing synchronously.
  • Breaking: ConvexClient rejects .convex.site deployment URLs (the HTTP actions host, which never served the sync protocol) with a descriptive ArgumentError.
  • Documented that ConvexException.retryable means transient, not idempotent. An action that fails with retryable: true after a disconnect may already have run on the server.
  • Transport: Connect.lastCloseReason now follows the official client: it is cleared once a Connect has been sent (a reauth stop/restart reports none), failed reconnect attempts no longer overwrite the original disconnect reason with raw exception text, and an inactivity timeout reports InactiveServer (was ServerInactivity).
  • Transport: with a fixed reconnectBackoff schedule, client-initiated reconnects (reconnectNow, a detected protocol error, an inactivity timeout) now use the 100ms client base, never waiting longer than the schedule's entry. Server/network closes still use the schedule verbatim.
  • Transport: a reauth's socket stop now publishes ConnectionState.disconnected (it used to keep reporting connected while the socket was closed), so the coarse state agrees with ConnectionStatus.isWebSocketConnected. The ConnectionState docs now spell out that a reconnect backoff wait is reported as disconnected.
  • Transport (internal): the ServerMessageHandler callback no longer returns messages to send; that return path silently dropped messages while the socket was paused or disconnected.
  • Auth: Breaking: ConvexClientConfig.authTokenType must be 'User' or 'Admin'; ConvexClient now throws ArgumentError for any other value. 'None' made the client report authenticated while the server treated it as anonymous.
  • Auth: Breaking (behavior): setAuthWithRefresh's onAuthChange(true) now fires once per auth flow, when the server first confirms it, instead of on every token refresh.
  • Auth: the refresh of a freshly fetched token is scheduled from its lifetime alone, so a device clock that runs ahead no longer causes a zero-delay refresh loop. A token pushed with updateAuthToken is judged against the server's clock when the server reports its skew, and otherwise waits at least 5 seconds.
  • Auth: a token fetch that throws while recovering from a server rejection is retried twice (after 500ms and 2s) before the user is signed out.
  • Auth: a server auth rejection is now logged at error level with the server's reason ("Failed to authenticate: ..., check your server auth config"), as the official client does.
  • Auth: the AuthProvider docs now spell out the contract ConvexClientWithAuth relies on: loginFromCache is the token refresh hook, must return a freshly issued token, and reports "no session" by throwing. AuthAuthenticated.userInfo is documented as a login-time snapshot.

Fixed #

  • A FatalError reaches every subscriber and fails a pending query() even when a listener changes auth while it is delivered; an auth change after a FatalError no longer moves subscriptions back to loading.
  • convexToCanonicalJson (query keys) gives an integral double and the equal int the same key beyond ±2^53 (for example 1e17 and 100000000000000000).
  • ConvexClientWithAuth marks its token-refresh calls to AuthProvider.loginFromCache (Zone.current[#dartvex.authTokenRefresh] is true), so a provider can let an explicit loginFromCache() supersede a pending login() while a background refresh does not.
  • Explicit auth changes clear live query results and optimistic layers until the server confirms the new identity. Late transitions and reentrant listeners cannot expose the previous user's data or refill a local cache after ConvexLocalClient.reset(). Same-user token refreshes retain results.
  • Upload timeouts abort the HTTP request, including on a shared client, instead of only stopping the wait. Requires http >=1.5.0.
  • ConvexClientWithAuth.logout() starts the provider's sign-out in the same synchronous step that stops the refresh flow, instead of after awaiting it. A login() started while the logout was pending could otherwise have its new session captured and revoked by the provider.
  • A token pushed by a login that is still running is no longer applied to the session it is replacing: it was written into the previous flow's bridge and sent to the server while the previous user was still installed, and kept if the login then failed. Pushes are now applied only to the flow's own bridge, once its provider call returned (the result's token is the one installed).
  • The WebSocket handshake checks for a pause raised while its session-restoring messages were being built on the synchronous path too (a listener notified of rolled-back optimistic updates may start an auth flow): it forces a clean reconnect instead of dropping the restored query set and replayed requests until the next reconnect.
  • query() / queryOnce() no longer resolve from the after-unsubscribe cache, which could return a stale value or re-throw an old error. Live subscribe() still seeds from the warm cache.
  • The after-unsubscribe cache is no longer refilled with results from a previous auth identity. Results kept across a reconnect still seed new subscribers.
  • Calling mutate, loadMore, cancel, or auth methods from inside a query, connection-status, or auth-state listener no longer throws StateError: Cannot fire new event.... Nested events are queued and delivered in order.
  • A listener that applies an optimistic update to another query in the same transition is no longer overwritten by the transition's precomputed result.
  • A second listener on a ConvexSubscription.stream now receives the current value, not only future changes.
  • close() no longer hangs when a subscription stream listener is paused.
  • resume() sends the auth and query-set messages before replayed requests.
  • A request queued during a reauth pause is no longer sent twice when the socket restarts.
  • A FatalError rolls back optimistic updates. Later mutate, action, query, and subscribe calls fail at once with the fatal error.
  • A server value that cannot be decoded fails only that query, mutation, or action. It no longer tears down the socket and loops reconnecting.
  • A mutation whose success response arrived before its timeout no longer fails with a timeout while waiting for the transition.
  • queryOnce<T> reports a type mismatch as a ConvexException naming the function and expected type.
  • Before the first successful connection, retries report connecting rather than reconnecting.
  • A logger that throws no longer breaks message processing. Optimistic update callbacks that throw during replay are logged at warn level.
  • Query tokens treat 1 and 1.0 arguments as the same query.
  • ConvexPaginatedQuery:
    • loadMore no longer chains from a stale continue cursor seeded from the cache. It waits for the first live page.
    • Ongoing page splits survive a same-range update.
    • No-op page updates no longer emit duplicate snapshots.
    • When the client closes, the query emits an error and completes instead of hanging.
  • applyOptimisticUpdate no longer reports duplicate changed query tokens.
  • Transport: ConvexClient.reconnectNow (and so the app-resume reconnect) now cuts short a pending reconnect backoff instead of doing nothing until the wait elapsed. It uses the 100ms client delay without advancing the backoff progression and without reporting the disconnect a second time.
  • Transport: client-initiated reconnects (reconnectNow, protocol errors, failed sends, inactivity timeouts) no longer wait for the platform's close event, which on a dead connection can take up to a minute on web.
  • Transport: a connect that returns without an open socket (for example after a stale inactivity timer closed it mid-handshake) is now retried instead of stalling the client in connecting forever; the inactivity timer only acts on, and is only re-armed by, a live connection.
  • Transport: an exception thrown by onTransitionMetrics is logged instead of dropping the Transition and forcing a reconnect on every subsequent one.
  • Transport: initialBackoff: Duration.zero no longer turns the backoff into NaN after 1024 retries, which permanently stopped reconnecting.
  • Transport: frames received before a close are now handled before the disconnect, so an action whose response arrived in the same read as the server's close is no longer failed as "Connection lost while action was in flight".
  • Transport: ConnectionStatus.connectionRetries keeps counting with a fixed reconnectBackoff schedule (it stopped at the schedule length minus one), and changes to it are now republished on connectionStatus.
  • Transport: frames still queued from a socket that a reauth stopped (or that was otherwise torn down) are dropped instead of being applied to the new session, where they forced a spurious reconnect.
  • Transport: a throwing DartvexLogger can no longer leave the transport stuck (_connecting never cleared) or break the message queue; logger exceptions are swallowed.
  • Transport: a failing Connect send now triggers the usual FailedToSendMessage reconnect instead of escaping to the caller (for example out of setAuthWithRefresh's socket resume), and an asynchronous handshake whose socket was replaced meanwhile is abandoned instead of being replayed onto the new socket.
  • Transport: Transition size metrics are measured without allocating a UTF-8 copy of every frame, and only when a metrics callback or warning log consumes them.
  • Transport: removed dead close-suppression bookkeeping from the web adapter; added loopback contract tests for the native adapter.
  • Auth: a server AuthError no longer signs the user out when a concurrent refresh had already applied the very token the reauth fetched; the session is kept and only a definitively rejected token logs out.
  • Auth: a socket stopped by a reauth is restarted as soon as a newer setAuth, clearAuth, or setAuthWithRefresh supersedes it, instead of staying down until the stale token fetch returns. The reauth no longer blocks the handling of other server messages.
  • Auth: setAuthWithRefresh no longer inherits the previous flow's pending confirmation (the old token's confirmation could count for the new flow), and an updateAuthToken during its initial fetch no longer leaves the caller with a no-op handle while the flow keeps running.
  • Auth: setAuth, clearAuth, and the auth failure paths now clear the transport token before reporting signed-out and do not report a stale result over a newer auth call, so a re-entrant setAuth from an authState listener is no longer overwritten.
  • Auth: a listener that clears auth from onAuthChange(true) no longer crashes the confirmation handling; throwing onAuthChange / authState listeners are logged instead of breaking the auth flow.
  • Auth: ConvexClientWithAuth.logout() supersedes the current flow before the provider's sign-out, so a login() started meanwhile is no longer torn down when the sign-out completes. Local state is cleared even if the provider throws.
  • Auth: ConvexClientWithAuth.login() / loginFromCache() can be called from an authState listener (it threw StateError on the synchronous controller); states are delivered in order.
  • Auth: a failure of a superseded flow no longer cancels an in-progress login(), and a failed login() / loginFromCache() while signed in keeps the existing session instead of signing the user out.
  • Auth: a token pushed by the provider after the ConvexClient was closed is logged instead of becoming an uncaught zone error.
  • A mutation or action issued while auth holds the socket pause (for example right as a setAuthWithRefresh token arrives, or with expectAuth) is no longer sent twice with the same request id, nor stranded until the next server message: the queue is left for the auth resume to send in order, and a request whose send failed is not requeued on top of the reconnect that already replays it.
  • A server FatalError now reaches existing subscribers: a pending query() rejects, live subscriptions receive a QueryError, and paginated queries move to the error status instead of loading forever.
  • Transport: when a send fails on a socket whose close is slow, the late cleanup of that socket no longer tears down the connection that already replaced it (a needless extra reconnect that failed actions sent on the new socket as lost).
  • Transport: a reauth whose socket close is slow no longer reports disconnected over a connection that a superseding auth call already re-established.
  • Auth: a server AuthError handled after close() is logged instead of becoming an uncaught zone error.
  • Auth: a logout() while a reauth is still stopping the socket no longer calls the provider's refresh hook (loginFromCache) for the ended session.
  • Auth: while a ConvexClientWithAuth.login() / loginFromCache() is pending, the live session's provider pushes are no longer dropped: a rotated token is applied, and a sign-out (null) push means a failed re-login signs the user out instead of restoring the dead session.

0.2.0 - 2026-06-12 #

Added #

  • Query function log lines are now also written to the configured logger (tag function, requestType: query) as each transition is applied, mirroring the official client's per-transition logForFunction. They are emitted once per transition from the raw query modifications — never re-emitted on a reactive cache or optimistic-overlay update — and remain available on QuerySuccess.logLines as before.
  • QuerySuccess now carries successful query log lines and whether optimistic writes are currently affecting the emitted value, so runtime adapters can surface pending-write state from the real client.
  • Rich connection status: ConvexClient.currentConnectionStatus and the connectionStatus stream expose a ConnectionStatus snapshot (isWebSocketConnected, isConnected, hasEverConnected, connectionCount, connectionRetries, inflightMutations, inflightActions, timeOfOldestInflightRequest, hasSyncedPastLastReconnect, plus derived hasInflightRequests and isLoading). The coarse ConnectionState enum and its connectionState stream are unchanged and remain available as a derived convenience. A ConnectionStatus.fromState factory derives a best-effort snapshot from a coarse state alone. Mirrors the official client's connectionState().
  • Reactive pagination: ConvexClient.paginatedQuery(name, args, {pageSize}) returns a ConvexPaginatedQuery that loads the first page immediately and exposes the gapless concatenation of every loaded page as a reactive stream, with a ConvexPaginationStatus, an isDone flag, and loadMore(). Each page is an ordinary query subscription, so loaded pages update reactively and stay gapless across reconnects via the query journals; oversized pages are transparently re-split. Mirrors the official client's paginated query engine.
  • paginatedQuery is now part of the ConvexFunctionCaller interface (and delegated by ConvexClientWithAuth), so generated typed bindings can open paginated queries through any caller. Breaking for implementors: classes that implement ConvexFunctionCaller (or ConvexAuthClient) must add a paginatedQuery member.
  • Optimistic updates: pass an OptimisticUpdate to ConvexClient.mutate to locally overlay query results the instant a mutation is sent. The overlay is replayed whenever fresh server data arrives while the mutation is pending and rolled back automatically when it completes (replaced by the authoritative result without flicker) or fails. Read and edit results through the exported OptimisticLocalStore (getQuery / getAllQueries / setQuery, with a string path, args map, and dynamic values). Mirrors the official client's optimistic update model.
  • ConvexClientConfig.connectTimeout bounds the WebSocket handshake so a dead connection no longer hangs on the platform TCP timeout before retrying.
  • Exponential reconnect backoff with jitter and server-reason classification, configurable via initialBackoff, maxBackoff, and backoffJitter.
  • ConnectivitySignal and ConvexClientConfig.connectivitySignal to reconnect immediately when the device regains network connectivity, cancelling any in-progress backoff.
  • Post-reconnect sync tracking across the local sync state, request manager, and base client: the client knows when every query, auth update, and request issued before a reconnect has been confirmed by the server. It is exposed as the public ConnectionStatus.hasSyncedPastLastReconnect field (which backs ConnectionStatus.isLoading) and drives the backoff reset and auth gating shipped in this release.
  • ConnectionState.fatalError, a terminal connection state entered when the server reports an unrecoverable error.
  • ConvexClientConfig.refreshTokenLeewaySeconds (default 10, matching the official Convex client) controls how early a token is proactively refreshed before it expires.
  • ConvexClient.authRefreshing (a Stream<bool>) and isAuthRefreshing report when the client is recovering auth after a server rejection — true while the socket is stopped and a fresh token is fetched, false once it is confirmed. Use it to show an "authenticating…" indicator without surfacing the brief disconnect. Mirrors the official client's AuthRefreshing signal.
  • Protocol-level support for Admin auth with optional user impersonation (LocalSyncState.setAdminAuth), including replay across reconnects. This is wire-completeness groundwork only — there is intentionally no client-facing admin API, since shipping an admin key in an app is a security hazard.
  • Exported WebSocketAdapter, WebSocketCloseEvent, and WebSocketAdapterFactory, so the existing ConvexClientConfig.adapterFactory customization point can be supplied with a custom transport implementation.
  • ConvexClientConfig.queryTimeout.
  • ConvexStorage.getFileUrl(..., useAction: true) for action-based URL resolvers.
  • defaultWebSocketAdapterOverride: a process-wide override consulted by createDefaultWebSocketAdapter, letting platform integrations (such as dartvex_flutter on iOS/macOS) swap the default WebSocket transport for every client without per-client configuration. An explicit ConvexClientConfig.adapterFactory still takes precedence. createDefaultWebSocketAdapter is now exported.
  • defaultHttpClientFactory / createDefaultHttpClient: the same process-wide seam for the SDK's HTTP requests. ConvexStorage uploads now construct their default client through it; an explicitly provided httpClient still takes precedence.

Changed #

  • Auth updates now gate the socket so requests can no longer be sent with absent or stale auth: the initial token fetch pauses the socket (buffering query-set changes and mutations, replayed together once the token is applied), and a reauth triggered by an AuthError stops the socket, fetches a fresh token, and restarts so it is replayed on a clean connection. Mirrors the official client's pause/resume and stop/restart auth gating.

  • Auth setup now mirrors the official client's initial-refetch behavior: when the cached token fetch returns no token, the client immediately retries with a forced refresh before reporting unauthenticated state.

  • A reconnect now replays the cached auth token from local state instead of re-fetching it from the auth provider, matching the official client. Token freshness on reconnect is driven by the scheduled refresh and by server AuthErrors, so a transient auth-provider failure during a reconnect can no longer silently sign the user out.

  • Auth token refresh is now scheduled from the token's own lifetime (exp - iat) minus refreshTokenLeewaySeconds, instead of from the device wall clock (exp - now - 60). Refresh timing is now immune to device clock skew; tokens without an iat claim do not schedule proactive refresh, and the delay is capped at 20 days.

  • reconnectBackoff now defaults to empty, selecting the exponential backoff model. Provide an explicit non-negative schedule to keep fixed delays.

  • Connect.clientTs and transition transit metrics now read from a monotonic clock (a one-time wall-clock anchor plus a monotonic Stopwatch) instead of DateTime.now(), so elapsed-time and server clock-skew estimates stay stable even when the device wall clock is corrected.

  • OptimisticLocalStore.setQuery(..., null) now represents the real Convex null value. Use the new clearQuery(...) method to optimistically return a query to loading, matching the official client's setQuery(..., undefined) behavior with an explicit Dart API.

Fixed #

  • The initial local emit of a fresh subscription now uses a deep snapshot of the args captured at subscribe() time. The first-listen microtask used to recompute the query token from the caller's live args map, so mutating that map between subscribe() and the first listen could resolve a different query's optimistic or cached value and emit it to the new subscriber. The wire path was already snapshot-protected inside the sync layer; the local read path now carries the same guarantee.
  • OptimisticLocalStore.getAllQueries hands optimistic updates deep copies of each query's args instead of the live stored maps. For server-backed entries those maps are the very args re-encoded into every reconnect's query-set replay, so an update mutating them could silently poison the replayed query set. This is a stricter immutability guard than the official JS client, which currently returns the stored args object from its local query result map.
  • OptimisticLocalStore.setQuery now deep-snapshots args before storing optimistic-only entries, so later caller-side mutation of nested args cannot change what getAllQueries reports for that local overlay.
  • ConvexPaginatedQuery now deep-snapshots its base args at construction, so later caller-side mutation cannot change arguments used by future loadMore() page subscriptions.
  • Raw errors emitted by custom PageSubscription.results streams are now surfaced as ConvexPaginationStatus.error snapshots instead of escaping as unhandled zone errors or leaving the paginated query stuck loading.
  • Errors emitted by a configured ConnectivitySignal stream are now caught and logged instead of surfacing as uncaught zone errors (isolate-fatal in a pure-Dart app). The restore subscription survives the error, so a later offline→online edge still reconnects immediately; losing a hint only means falling back to the normal reconnect backoff.
  • Errors emitted by a custom WebSocketAdapter.messages or closeEvents stream are now treated as a client-detected disconnect and drive the normal reconnect path instead of hanging the manager or surfacing as uncaught zone errors. The manager also closes the adapter on these failures even during a half-open connect, so built-in adapters can discard any late socket before the replacement reconnect proceeds.
  • Closing the late socket of a superseded native connect attempt now ignores close failures. That close typically runs on an already-dead network, and a failure on a socket nobody owns must not surface as an uncaught zone error.
  • The native WebSocket adapter decodes binary frames with allowMalformed, so a peer sending invalid UTF-8 can no longer crash a pure-Dart isolate with an uncaught FormatException thrown from the socket listener. The garbled message fails JSON parsing upstream instead, driving the normal InvalidServerMessage reconnect.
  • A close event from a superseded WebSocket is now ignored once a newer connection is open. Previously, when a socket's close on a dead network outlived the platform close timeout and its close event was only delivered after a fast reconnect (for example on a connectivity restore or app resume), the stale event was treated as the current connection closing — tearing down the healthy successor with a spurious disconnect and a scheduled reconnect. The official client cannot reach this state because it detaches the close handler from sockets it closes deliberately.
  • A superseded socket's close event is also ignored while the successor's connect attempt is still in flight. Previously a stale close landing in that window consumed the new attempt's close handling, so once the connect succeeded, the connection's next real close was silently dropped — no reconnect was ever scheduled again and even reconnectNow became a no-op until the client was disposed or reauthed. An adapter whose in-flight socket dies must fail the pending connect() future (both built-in adapters do); the WebSocketAdapter.closeEvents contract now documents this.
  • An AuthHandle from setAuthWithRefresh now stays cancellable after updateAuthToken pushes a new token into the same flow. Handles bind to the refresh-flow identity instead of the auth generation, so a token update — which supersedes in-flight fetches but keeps the flow alive — no longer silently orphans the caller's handle (previously a later handle.cancel(), for example from ConvexClientWithAuth.dispose(), became a no-op and left the scheduled token refresh running). A handle from a genuinely replaced flow still cannot tear down its successor.
  • Mutation, action, and subscription arguments are now validated and deep-snapshotted eagerly, when the call is made, matching the official client's eager convexToJson(args). An unsupported argument value (for example a DateTime, a Set, or a $-prefixed field name) now fails the call immediately with an ArgumentError instead of throwing later inside the transport send path — where it closed a healthy connection and was replayed by every reconnect, flapping the socket forever while the caller's future never resolved. The snapshot also means mutating a nested argument collection after the call can no longer change what is sent (or re-sent on reconnect).
  • A socket pause that lands while an asynchronous resume is still building its replay messages no longer drops them on a live connection: the resume now hands the drained messages to the transport without yielding when they are available synchronously (the production path), and an async resume that is re-paused mid-build forces a clean PausedDuringResume reconnect whose deferred handshake rebuilds the query set, auth, and unsent requests instead of silently losing them.
  • A mutate() or action() raced by a close() in the same event no longer reports a spurious unhandled ConvexException while the request future is failed in the microtask gap before the method's own await attaches; the error itself still reaches the caller unchanged.
  • A setAuthWithRefresh superseded while its initial token fetch was still pending no longer leaves the transport paused forever. setAuth, clearAuth, updateAuthToken, and a cancelled auth handle now release the socket pause inherited from the flow they replaced (resuming an unpaused socket is a no-op, and a flow superseded by a newer setAuthWithRefresh still hands the gating to that flow, which resumes on its own). Previously a logout — or any new fixed token — issued while the initial fetch was hung left every query and mutation buffering indefinitely, and the stall survived reconnects.
  • Cancelling the AuthHandle of a superseded setAuthWithRefresh flow is now a no-op instead of tearing down the current flow's refresh state (which could stop token refreshes for the active session).
  • A connect attempt superseded by a reauth stop()/restart() cycle while its socket was still opening now abandons its handshake instead of — in the worst interleaving — writing a second Connect frame onto the restarted attempt's socket and double-counting the connection. stop() now also closes a half-open socket, mirroring the official client's stop() on a "connecting" socket.
  • Reconnect now re-declares the query set even when it is empty: prepareReconnect always emits a ModifyQuerySet(baseVersion: 0, newVersion: 1), matching the official client's restart(), which sends one unconditionally on every reconnect. The previous behavior (sending nothing for an empty query set) was equivalent but is now byte-for-byte aligned with the official wire sequence.
  • Query journals now honor the protocol's explicit null journal as an empty journal, clearing any previously stored cursor before the next reconnect replay.
  • A transition modification that omits the journal field entirely now leaves the stored journal untouched, matching the official client's journal !== undefined guard; only a present null clears the stored cursor.
  • A mutation or action queued while the socket is paused for auth is no longer silently dropped when a concurrently arriving server message drains the outgoing queue: drained messages are re-queued through the normal flush path, so the request goes out on resume instead of hanging until the next reconnect.
  • The connect handshake no longer yields to the event loop between the Connect frame and the session-restoring messages, and an asynchronous connected-callback that gets paused mid-handshake forces a clean reconnect, so a pause landing during the handshake can no longer leave the connection without its re-declared query set and replayed requests.
  • Mutation and action function log lines are now routed to the configured logger for both successful and failed responses, matching the official client's response log handling while keeping structured failure logs sanitized.
  • A read-your-writes mutation replayed on reconnect no longer re-logs its function output. When the server re-sends the response for a mutation that has already completed and is only awaiting its transition, those duplicate log lines are now suppressed, matching the official client which skips already-completed requests before logging.
  • The native WebSocket adapter now drops messages from a socket that a later connect() or close() has already superseded, matching the web adapter. A closing socket's trailing frames can no longer reach the sync layer, where a stale transition would mismatch the reset version and force a spurious reconnect.
  • Auth reauth now matches the official client's retry budget: only a rejected fresh token counts toward the give-up limit, so a single cached-token rejection no longer shortens the number of fresh-token retries before the client falls back to unauthenticated.
  • A transient auth-provider failure during a scheduled token refresh no longer logs the user out. The internal auth token bridge now lets provider errors propagate (the auth manager already handles them per context) instead of collapsing every failure to a null token that read as a definitive logout, so a network blip while a token is still valid no longer ends the session — a genuine logout still flows through a server AuthError. Matches the official client, where a throwing token fetcher does not by itself log the user out.
  • The default WebSocket inactivity timeout now matches the official Convex client's 60-second threshold, reducing false reconnects while large messages are in flight.
  • An inactivity-timeout close that throws now falls back to a synthetic disconnect, so the client still reconnects instead of sitting idle on a dead socket when no close event arrives.
  • WebSocket close failures during reconnect, invalid-message recovery, shutdown, and auth revalidation are now best-effort, so a platform close error can no longer strand the client before reconnect or auth restart bookkeeping runs.
  • ConvexStorage.getFileUrl now throws a ConvexStorageException instead of a StateError when the resolver returns no URL (e.g. a missing or deleted file), so a normal runtime condition is no longer reported as API misuse.
  • ConvexStorage.uploadFile now validates malformed upload URL resolvers and successful upload responses with typed Dartvex exceptions instead of leaking runtime casts or JSON parse failures.
  • Reactive pagination now rejects malformed PaginationResult objects whose continueCursor is missing or non-string, preventing duplicate page loads or load loops.
  • Successful mutations and actions now surface server-side function log lines through the configured logger at info level, matching the official client's function-output visibility.
  • WebSocket reconnect paths that discover an already-closed adapter now run the same disconnect bookkeeping as normal close events, so state listeners and disconnect callbacks are not skipped before reconnecting.
  • Reactive pagination now tears down both split-half subscriptions when either half of a split page fails and falls back to the original un-split page (which covers the same range), retrying the split once the page produces a fresh result. A transient split failure no longer leaks subscriptions or pins the whole query to an error.
  • Auth confirmations are now ignored unless a token update is actually pending, and reauth confirmations no longer re-emit an already-authenticated public state.
  • Auth refresh flows now reset to unauthenticated state when a scheduled refresh returns no token, preventing stale refresh callbacks from resurrecting a failed auth flow.
  • Query subscriptions now emit QueryLoading when an optimistic update clears a live query, and one-shot queries ignore that loading state until a concrete success or error arrives.
  • Reactive paginated queries now consume QueryLoading page events, so a loaded page cleared by an optimistic update returns to loading instead of showing stale rows.
  • Reactive paginated queries now seed their first page synchronously from the current local/cache result when available, avoiding a loading flash on warm remounts.
  • Reactive paginated queries now seed split-half pages synchronously from warm local/cache results when available, avoiding a loading flash after an oversized page is re-split.
  • Reactive paginated queries now cancel in-flight split-half subscriptions when the original page returns to loading or changes before the split completes, preventing stale split results from replacing fresh data.
  • Mutations whose optimistic update throws now cancel their tracked request immediately, preventing the failed mutation from being sent by a later flush.
  • ConvexClientWithAuth.logout() now clears local auth state even if the provider logout call fails, preventing a stale authenticated wrapper after a best-effort sign-out.
  • AuthLoading documentation now matches the emitted auth states: it covers login/cache restore, while background token refreshes remain exposed via authRefreshing.
  • timeOfOldestInflightRequest documentation now describes its parked-mutation behavior instead of claiming exact parity with the official client.
  • Connection-state emissions now no-op after the client has closed its controller, preventing a concurrent fatal-error shutdown from being reclassified as an invalid server message.
  • Query subscriptions now seed each newly attached listener from the latest cached, remote, or optimistic value instead of only seeding the first listener from the value captured at subscribe time.
  • Reactive pagination now refuses loadMore() while any earlier page error is making the aggregate status error, avoiding invisible extra page subscriptions past the gap.
  • Connect handshakes now omit maxObservedTimestamp when no timestamp has been observed yet, matching the optional wire shape used by the reference client.
  • jsonToConvex now preserves incoming object field order on decode, matching the reference client; encoding remains canonical and sorted.
  • WebSocket connectionCount now advances only after a successful socket open, so failed pre-open connection attempts no longer inflate the next Connect frame.
  • Resume after auth gating now sends Authenticate before replaying query-set changes, matching reconnect ordering and avoiding auth-gated queries racing ahead of the refreshed identity.
  • Reconnect sync tracking now waits for every active query to be re-confirmed by the server, even when a cached remote result existed before reconnect, so reconnect backoff is reset only after the session proves healthy.
  • Deferred initial handshakes now no-op if a paused WebSocket closed before resume(), letting the scheduled reconnect rebuild the session instead of throwing from a send on a closed socket.
  • Persistent auth rejections now reach the retry cap and report the client as signed out instead of resetting the confirmation-attempt counter after every forced token refresh.
  • Optimistic updates that throw no longer leave behind poison layers that can wedge future server transitions into a reconnect loop.
  • Terminal auth failures now clear the refresh callback, so a rejected token is not refetched and reapplied by a later AuthError.
  • Cached token refresh scheduling now clamps to the token's remaining lifetime so aged cached tokens are refreshed before their actual expiration.
  • The default Convex sync API version is now 1.41.0, the official Convex client release 0.2.0 is aligned with, fixing browser WebSocket handshakes that cannot send the native Convex-Client header.
  • A Transition that reflects an auth version the client has already moved past no longer confirms auth (it is recognized as stale), matching the existing guard against stale AuthErrors. Prevents a superseded token from being reported as confirmed during rapid auth changes.
  • Reconnect backoff now resets only after the client has re-synced every query, auth update, and request that predated the reconnect, instead of on every Transition or response. A server that repeatedly drops the connection before the client proves itself now keeps backing off instead of hammering it.
  • An unrecoverable server FatalError now terminates the connection — pending requests fail, the connection state becomes fatalError, and no reconnect is attempted — instead of triggering a reconnect that could loop indefinitely.
  • WebSocket messages are now processed strictly in order. A handler that awaits (an auth refresh or a reconnect) can no longer interleave with the next incoming message.
  • Auth refresh scheduling reads the exp/iat claims defensively, so a malformed token can no longer raise a cast error that would otherwise escape into message handling and tear down the connection.
  • Paginated results stay a gapless prefix while a page is still loading: a not-yet-loaded page no longer hides behind later, already-loaded pages.
  • Special doubles (NaN, ±Infinity, and -0.0) now always encode through the tagged $float wire form, including -0.0 on the web, where it was previously encoded as a plain 0 and lost its sign.
  • The after-unsubscribe query-result seed cache is now bounded (evicting the least-recently-written entry), so a long-lived client that subscribes to many distinct queries no longer grows it without bound.
  • Throws a clear error when a storage URL resolver returns null for a missing storage object.
  • Aligns TransitionChunk handling with the current Convex protocol, including raw chunk payloads, zero-based part ordering, and invalid-chunk reconnects.
  • Treats protocol Ping as a transport heartbeat without sending client protocol messages in response.
  • Hardens auth refresh against stale token fetches, stale AuthError messages, and refresh scheduling that reused cached tokens.
  • Skips proactive auth refresh when a JWT omits iat, matching Convex's need for a known token lifetime before scheduling refresh.
  • Adds one-shot query timeout cleanup and safer disposal of temporary subscriptions.
  • Rejects invalid Convex JSON field names and finite $float encodings.

0.1.4 - 2026-04-30 #

Added #

  • ConvexClientConfig.connectImmediately to defer opening the WebSocket until the first backend operation, auth update, or explicit reconnect.
  • Structured query error payloads and server log lines on QueryError and one-shot ConvexException failures.
  • Client protocol metadata fields for Convex component paths and auth impersonation metadata.
  • Transport close diagnostics in WebSocket error logs.

Fixed #

  • Replays safe queued requests after reconnect, including unsent actions and mutations awaiting their read-your-writes transition.
  • Preserves pending request failures on dispose instead of leaving futures unresolved.
  • Avoids logging structured Convex error payloads from failed requests.

0.1.3 - 2026-03-22 #

Added #

  • ConvexClient.reconnectNow(String reason) — public method to force an immediate WebSocket reconnect, bypassing the backoff timer.

0.1.2 - 2026-03-21 #

Improved #

  • Added comprehensive dartdoc comments on all public API
  • Added example file for pub.dev scoring

0.1.1 - 2026-03-21 #

Added #

  • Structured opt-in logging via DartvexLogLevel, DartvexLogEvent, and DartvexLogger
  • ConvexClientConfig logging hooks for request, auth, storage, and transport diagnostics

0.1.0 - 2026-03-15 #

Added #

  • Pure Dart Convex sync client
  • WebSocket protocol implementation
  • Read-your-writes mutations
  • Multi-platform WebSocket (native + web)
  • Auth framework with pluggable providers
  • File storage helpers (ConvexStorage)
  • One-shot query (queryOnce)
  • Reconnection with exponential backoff
  • Transition chunk reassembly
  • Special value encoding
3
likes
160
points
4.57k
downloads

Documentation

API reference

Publisher

verified publisherandrefrelicot.dev

Weekly Downloads

Pure Dart client for Convex with WebSocket sync, type-safe values, and reactive subscriptions. Works on iOS, Android, web, and desktop.

Homepage
Repository (GitHub)
View/report issues
Contributing

Topics

#convex #realtime #websocket #sync #client

License

MIT (license)

Dependencies

collection, http, meta, uuid, web

More

Packages that depend on dartvex