dartvex 0.4.2
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/authv2) 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
ConvexExceptionwithretryable: true, aTimeoutExceptionor anhttpClientException), 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
isAuthRefreshingistrueuntil a new token is accepted. The fetch is retried at once whenConvexClientConfig.connectivitySignalreports the network back and onreconnectNow()(whichdartvex_fluttercalls when the app resumes), including when the signal arrives while an attempt is still in flight. On native platforms,dart:ioSocketException,HttpExceptionandHandshakeExceptioncount as transient too; a fetcher built on another HTTP stack should wrap its network errors inConvexException(..., retryable: true). AnAuthSessionEndedErroror 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
FatalErrorfrom 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 validatingdartvex_auth2_convexon a device.
0.4.0 - 2026-11-20 #
Added #
QuerySuccess.fromCacheandQueryError.fromCache:trueon 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 everyConvexFunctionCaller(ConvexClient,ConvexClientWithAuth): a decodedStream<T>of a live query that subscribes on listen and unsubscribes on cancel, sofirst/take/await forrelease the subscription. Query errors areConvexExceptionstream errors, loading results are skipped, andskipCached: truedrops the warm seed.ConvexAuthClient.clearAuth()/ConvexClientWithAuth.clearAuth(): continue signed out without calling the provider. It releases the hold of a client created withexpectAuth: truewhen there is no session to restore, without keeping a second reference to the rawConvexClient. Breaking for implementors: classes thatimplement ConvexAuthClientmust addFuture<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
convexSyncApiVersionconstant moves ('1.51.0'), and with it the defaultConvexClientConfig.apiVersionsent 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 andConvexClientWithAuthemitsAuthUnauthenticated. 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 byAuthProvider.login/loginFromCachewhen 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.mutatetakes an optionalOptimisticUpdate, so code written against the interface (andConvexClientWithAuth) can apply optimistic updates. Breaking for implementors: classes thatimplement ConvexFunctionCallermust add the optionalOptimisticUpdate? optimisticUpdateparameter tomutate.ConvexClientConfig.expectAuth: whentrue, the client holds the socket until the firstsetAuth/setAuthWithRefresh/clearAuth, so no query ever runs unauthenticated. Mirrors the official client'sexpectAuth.ConvexCommitTsPlaceholder.instance: the server's$commitTsplaceholder (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 as1.0match1).ConvexPaginatedQuery.reset()restarts pagination from the first page with a fresh pagination id. The query also resets itself when the server reportsInvalidCursorfor an already-loaded page.ConvexPaginatedResult.hasPendingWrites, aggregated from the loaded pages.StoredQueryResult,StoredQuerySuccess,StoredQueryLoading, andStoredQueryErrorare exported. They were already referenced by the publicPageSubscription/PageInitialResultReadertypes.dartvexVersionandconvexSyncApiVersionconstants.ConvexStorage.uploadFileacceptsuseAction(generate the upload URL from an action) and atimeoutfor 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
ConnectivitySignalnow reports the backoff time it skipped to the server as aNetworkRecoveryReconnectevent, as the official client does. - Auth:
ConvexClientConfig.initialAuthTokenReuse(experimental, defaultfalse). When enabled, a cached token fromsetAuthWithRefreshthat 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 ofauthState, which does not replay) andConvexClient.currentAuthToken/ConvexClientWithAuth.currentAuthToken(the token currently in use, reflecting every refresh; the counterpart of the officialgetAuth()). - Auth: the
AuthTokenFetchertypedef used bysetAuthWithRefreshis now exported.
Changed #
- Parity baseline: this release is aligned with the official Convex
JavaScript client 1.49.0 (
convexon npm; 0.2.0 was aligned with 1.41.0). The defaultConvexClientConfig.apiVersionis now the exportedconvexSyncApiVersionconstant ('1.49.0', was'1.41.0'), bumped deliberately after diffing the official sync client sources. The defaultclientIdis nowdartvex-<package version>(dartvexVersion; it wasdart-dartvex). ConvexStorage.uploadFile'sfilenameis 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
ConvexExceptionwhen auth changes before it completes. It is no longer replayed under the new identity. - Breaking:
ConvexPaginatedQueryrejects apageSizeorloadMorecount below 1 with anArgumentError. - Breaking: encoding an
intbeyond ±2^53 that a float64 cannot represent exactly throws anArgumentErrorinstead of silently changing the value. UseconvexInt64/BigIntfor 64-bit integers. - Breaking: auth methods (
setAuth,setAuthWithRefresh,clearAuth,updateAuthToken) andreconnectNowon a closed client return a failed future instead of throwing synchronously. - Breaking:
ConvexClientrejects.convex.sitedeployment URLs (the HTTP actions host, which never served the sync protocol) with a descriptiveArgumentError. - Documented that
ConvexException.retryablemeans transient, not idempotent. An action that fails withretryable: trueafter a disconnect may already have run on the server. - Transport:
Connect.lastCloseReasonnow follows the official client: it is cleared once aConnecthas 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 reportsInactiveServer(wasServerInactivity). - Transport: with a fixed
reconnectBackoffschedule, 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 reportingconnectedwhile the socket was closed), so the coarse state agrees withConnectionStatus.isWebSocketConnected. TheConnectionStatedocs now spell out that a reconnect backoff wait is reported asdisconnected. - Transport (internal): the
ServerMessageHandlercallback no longer returns messages to send; that return path silently dropped messages while the socket was paused or disconnected. - Auth: Breaking:
ConvexClientConfig.authTokenTypemust be'User'or'Admin';ConvexClientnow throwsArgumentErrorfor any other value.'None'made the client report authenticated while the server treated it as anonymous. - Auth: Breaking (behavior):
setAuthWithRefresh'sonAuthChange(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
updateAuthTokenis 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
AuthProviderdocs now spell out the contractConvexClientWithAuthrelies on:loginFromCacheis the token refresh hook, must return a freshly issued token, and reports "no session" by throwing.AuthAuthenticated.userInfois 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 example1e17and100000000000000000).ConvexClientWithAuthmarks its token-refresh calls toAuthProvider.loginFromCache(Zone.current[#dartvex.authTokenRefresh]istrue), so a provider can let an explicitloginFromCache()supersede a pendinglogin()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. Alogin()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. Livesubscribe()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 throwsStateError: 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.streamnow 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
FatalErrorrolls back optimistic updates. Latermutate,action,query, andsubscribecalls 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 aConvexExceptionnaming the function and expected type.- Before the first successful connection, retries report
connectingrather thanreconnecting. - A logger that throws no longer breaks message processing. Optimistic update callbacks that throw during replay are logged at warn level.
- Query tokens treat
1and1.0arguments as the same query. ConvexPaginatedQuery:loadMoreno 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.
applyOptimisticUpdateno 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
connectingforever; the inactivity timer only acts on, and is only re-armed by, a live connection. - Transport: an exception thrown by
onTransitionMetricsis logged instead of dropping the Transition and forcing a reconnect on every subsequent one. - Transport:
initialBackoff: Duration.zerono 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.connectionRetrieskeeps counting with a fixedreconnectBackoffschedule (it stopped at the schedule length minus one), and changes to it are now republished onconnectionStatus. - 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
DartvexLoggercan no longer leave the transport stuck (_connectingnever cleared) or break the message queue; logger exceptions are swallowed. - Transport: a failing
Connectsend now triggers the usualFailedToSendMessagereconnect instead of escaping to the caller (for example out ofsetAuthWithRefresh'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
AuthErrorno 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, orsetAuthWithRefreshsupersedes it, instead of staying down until the stale token fetch returns. The reauth no longer blocks the handling of other server messages. - Auth:
setAuthWithRefreshno longer inherits the previous flow's pending confirmation (the old token's confirmation could count for the new flow), and anupdateAuthTokenduring 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-entrantsetAuthfrom anauthStatelistener is no longer overwritten. - Auth: a listener that clears auth from
onAuthChange(true)no longer crashes the confirmation handling; throwingonAuthChange/authStatelisteners are logged instead of breaking the auth flow. - Auth:
ConvexClientWithAuth.logout()supersedes the current flow before the provider's sign-out, so alogin()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 anauthStatelistener (it threwStateErroron the synchronous controller); states are delivered in order. - Auth: a failure of a superseded flow no longer cancels an in-progress
login(), and a failedlogin()/loginFromCache()while signed in keeps the existing session instead of signing the user out. - Auth: a token pushed by the provider after the
ConvexClientwas 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
setAuthWithRefreshtoken arrives, or withexpectAuth) 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
FatalErrornow reaches existing subscribers: a pendingquery()rejects, live subscriptions receive aQueryError, 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
disconnectedover a connection that a superseding auth call already re-established. - Auth: a server
AuthErrorhandled afterclose()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-transitionlogForFunction. 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 onQuerySuccess.logLinesas before. QuerySuccessnow 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.currentConnectionStatusand theconnectionStatusstream expose aConnectionStatussnapshot (isWebSocketConnected,isConnected,hasEverConnected,connectionCount,connectionRetries,inflightMutations,inflightActions,timeOfOldestInflightRequest,hasSyncedPastLastReconnect, plus derivedhasInflightRequestsandisLoading). The coarseConnectionStateenum and itsconnectionStatestream are unchanged and remain available as a derived convenience. AConnectionStatus.fromStatefactory derives a best-effort snapshot from a coarse state alone. Mirrors the official client'sconnectionState(). - Reactive pagination:
ConvexClient.paginatedQuery(name, args, {pageSize})returns aConvexPaginatedQuerythat loads the first page immediately and exposes the gapless concatenation of every loaded page as a reactive stream, with aConvexPaginationStatus, anisDoneflag, andloadMore(). 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. paginatedQueryis now part of theConvexFunctionCallerinterface (and delegated byConvexClientWithAuth), so generated typed bindings can open paginated queries through any caller. Breaking for implementors: classes thatimplement ConvexFunctionCaller(orConvexAuthClient) must add apaginatedQuerymember.- Optimistic updates: pass an
OptimisticUpdatetoConvexClient.mutateto 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 exportedOptimisticLocalStore(getQuery/getAllQueries/setQuery, with a string path, args map, anddynamicvalues). Mirrors the official client's optimistic update model. ConvexClientConfig.connectTimeoutbounds 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, andbackoffJitter. ConnectivitySignalandConvexClientConfig.connectivitySignalto 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.hasSyncedPastLastReconnectfield (which backsConnectionStatus.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(default10, matching the official Convex client) controls how early a token is proactively refreshed before it expires.ConvexClient.authRefreshing(aStream<bool>) andisAuthRefreshingreport when the client is recovering auth after a server rejection —truewhile the socket is stopped and a fresh token is fetched,falseonce it is confirmed. Use it to show an "authenticating…" indicator without surfacing the brief disconnect. Mirrors the official client'sAuthRefreshingsignal.- Protocol-level support for
Adminauth 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, andWebSocketAdapterFactory, so the existingConvexClientConfig.adapterFactorycustomization 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 bycreateDefaultWebSocketAdapter, letting platform integrations (such asdartvex_flutteron iOS/macOS) swap the default WebSocket transport for every client without per-client configuration. An explicitConvexClientConfig.adapterFactorystill takes precedence.createDefaultWebSocketAdapteris now exported.defaultHttpClientFactory/createDefaultHttpClient: the same process-wide seam for the SDK's HTTP requests.ConvexStorageuploads now construct their default client through it; an explicitly providedhttpClientstill 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
AuthErrorstops 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) minusrefreshTokenLeewaySeconds, instead of from the device wall clock (exp - now - 60). Refresh timing is now immune to device clock skew; tokens without aniatclaim do not schedule proactive refresh, and the delay is capped at 20 days. -
reconnectBackoffnow defaults to empty, selecting the exponential backoff model. Provide an explicit non-negative schedule to keep fixed delays. -
Connect.clientTsand transition transit metrics now read from a monotonic clock (a one-time wall-clock anchor plus a monotonicStopwatch) instead ofDateTime.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 Convexnullvalue. Use the newclearQuery(...)method to optimistically return a query to loading, matching the official client'ssetQuery(..., 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 betweensubscribe()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.getAllQuerieshands 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.setQuerynow deep-snapshots args before storing optimistic-only entries, so later caller-side mutation of nested args cannot change whatgetAllQueriesreports for that local overlay.ConvexPaginatedQuerynow deep-snapshots its base args at construction, so later caller-side mutation cannot change arguments used by futureloadMore()page subscriptions.- Raw errors emitted by custom
PageSubscription.resultsstreams are now surfaced asConvexPaginationStatus.errorsnapshots instead of escaping as unhandled zone errors or leaving the paginated query stuck loading. - Errors emitted by a configured
ConnectivitySignalstream 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.messagesorcloseEventsstream 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 uncaughtFormatExceptionthrown from the socket listener. The garbled message fails JSON parsing upstream instead, driving the normalInvalidServerMessagereconnect. - 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
reconnectNowbecame a no-op until the client was disposed or reauthed. An adapter whose in-flight socket dies must fail the pendingconnect()future (both built-in adapters do); theWebSocketAdapter.closeEventscontract now documents this. - An
AuthHandlefromsetAuthWithRefreshnow stays cancellable afterupdateAuthTokenpushes 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 laterhandle.cancel(), for example fromConvexClientWithAuth.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 aDateTime, aSet, or a$-prefixed field name) now fails the call immediately with anArgumentErrorinstead 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
PausedDuringResumereconnect whose deferred handshake rebuilds the query set, auth, and unsent requests instead of silently losing them. - A
mutate()oraction()raced by aclose()in the same event no longer reports a spurious unhandledConvexExceptionwhile 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
setAuthWithRefreshsuperseded 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 newersetAuthWithRefreshstill 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
AuthHandleof a supersededsetAuthWithRefreshflow 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 secondConnectframe onto the restarted attempt's socket and double-counting the connection.stop()now also closes a half-open socket, mirroring the official client'sstop()on a "connecting" socket. - Reconnect now re-declares the query set even when it is empty:
prepareReconnectalways emits aModifyQuerySet(baseVersion: 0, newVersion: 1), matching the official client'srestart(), 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
nulljournal as an empty journal, clearing any previously stored cursor before the next reconnect replay. - A transition modification that omits the
journalfield entirely now leaves the stored journal untouched, matching the official client'sjournal !== undefinedguard; only a presentnullclears 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
Connectframe 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()orclose()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.getFileUrlnow throws aConvexStorageExceptioninstead of aStateErrorwhen 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.uploadFilenow 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
PaginationResultobjects whosecontinueCursoris 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
QueryLoadingwhen 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
QueryLoadingpage 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.AuthLoadingdocumentation now matches the emitted auth states: it covers login/cache restore, while background token refreshes remain exposed viaauthRefreshing.timeOfOldestInflightRequestdocumentation 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 statuserror, avoiding invisible extra page subscriptions past the gap. Connecthandshakes now omitmaxObservedTimestampwhen no timestamp has been observed yet, matching the optional wire shape used by the reference client.jsonToConvexnow preserves incoming object field order on decode, matching the reference client; encoding remains canonical and sorted.- WebSocket
connectionCountnow advances only after a successful socket open, so failed pre-open connection attempts no longer inflate the nextConnectframe. - Resume after auth gating now sends
Authenticatebefore 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 nativeConvex-Clientheader. - 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
FatalErrornow terminates the connection — pending requests fail, the connection state becomesfatalError, 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/iatclaims 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$floatwire form, including-0.0on the web, where it was previously encoded as a plain0and 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
nullfor a missing storage object. - Aligns
TransitionChunkhandling with the current Convex protocol, including raw chunk payloads, zero-based part ordering, and invalid-chunk reconnects. - Treats protocol
Pingas a transport heartbeat without sending client protocol messages in response. - Hardens auth refresh against stale token fetches, stale
AuthErrormessages, 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
$floatencodings.
0.1.4 - 2026-04-30 #
Added #
ConvexClientConfig.connectImmediatelyto defer opening the WebSocket until the first backend operation, auth update, or explicit reconnect.- Structured query error payloads and server log lines on
QueryErrorand one-shotConvexExceptionfailures. - 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, andDartvexLogger ConvexClientConfiglogging 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