nestcore_flutter 1.11.1
nestcore_flutter: ^1.11.1 copied to clipboard
Official Flutter SDK for NestCore — auth (MFA, passkeys, SMS), Postgres queries, realtime, storage, and vector search for your backend.
1.11.1 #
1.11.1: Support dio 5.11 (fixes a compile error: dio 5.10 added DioExceptionType.transformTimeout, which the error interceptor's exhaustive switch did not handle). No API changes.
1.11.0 #
Changed — sessions are stored per project (branches) #
- A NestCore project has a Production and a Development branch (
my_appandmy_app__dev). A dev build and a prod build of the same app on one device no longer overwrite each other's sign-in: the session keys are scoped to the project slug (nestcore_session@my_app). - No sign-out on upgrade: a session saved by an earlier version moves to the new keys the first time it is read, only for the project that issued it (the token's
aud/iss). A Development build never picks up the Production session. Tokens without those claims (older servers) are kept as before. - Point a development build at the Development branch by giving it that branch's anon key (
NESTCORE_ANON_KEY); the slug comes from the key.
1.10.0 #
Added — your own embeddings (NestCore Agent "Sync to NestCore") #
- Client vectors, no provider call, nothing charged.
memory.add(content, embedding:, model:, dims:),memory.update(id, content:, embedding:, model:)(a vector only together with new content) andmemory.search(query, queryEmbedding:, model:, dims:);querymay now benullwhen a vector is given.dimsis checked against the vector length; a vector withoutmodel, an empty vector or a wrongdimsthrowsArgumentErrorbefore any request. Search compares only vectors of the same model and size. - Trust filter:
memory.search(..., trust: 'user')ortrust: ['tool', 'web']keeps memories whose reservedmetadata.trustword matches; collectionsearchtakes the sametrust(chunks or their document). - Batch memory:
memory.addMany(List<AiMemoryInput>)(≤ 100, →List<AiMemoryAddResult>),memory.searchMany(List<AiMemoryQuery>)(≤ 20, →List<AiMemorySearchResult>) andmemory.forgetMany(ids:, subjects:)(→ deleted count). Each added or searched item counts against the plan's memory quota; an invalid item fails the whole call with400 "item <i>: …".AiMemoryInput/AiMemoryQueryare the item types (and whatadd/searchsend). - Collection documents from pre-embedded chunks:
collections.from(name).addChunks([AiClientChunk(content:, embedding:, metadata:)], model:, dims:, title:, metadata:), oringest(AiDocumentSource.chunks(...)). The document isreadyat once (source refclient-chunks). The first client chunks fix the collection's model: another model answers409, and text/URL/storage documents then answer400. - Collection search by vector:
search(null, queryEmbedding:, model:, dims:)(the model must be the collection's).
Added — cloud credits #
ai.credits()→AiCredits(available,active,balanceUsd,monthlyCapUsd,spentThisMonthUsd,ownKeys,creditProviders): whether calls without the project's own provider key can be paid from the workspace's prepaid credit.- Error code
ErrorCodes.creditsExhausted(CREDITS_EXHAUSTED, 402) andNestCoreException.isCreditsExhausted,creditsReason(balance|spend_cap) andbuyUrl(also onAiExceptionand the deprecatedOrbitNestExceptionalias). Show the message with two actions, openbuyUrlor add your own key; don't retry. ai.openAiBaseUrl:<apiUrl>/api/project/<slug>/ai/openai/v1, for OpenAI client libraries (anon key as theapikeyheader, the access token as the bearer).
Added — project errors (since 1.9.0) #
ErrorCodes.quotaExceeded,projectPaused,agentProjectRestricted,notAnAgentProject, andNestCoreException.isProjectPaused/upgradeUrl.
1.9.0 #
Changed — OrbitNest is now NestCore #
- The package is renamed
orbitnest_studio_flutter→nestcore_flutter(repository: https://github.com/Orbitnest/nestcore_flutter). Replace the dependency in yourpubspec.yaml; the main import is nowpackage:nestcore_flutter/nestcore_flutter.dart. Releases oforbitnest_studio_flutterstop at 1.8.0. - Every public
OrbitNest*type is nowNestCore*:NestCoreClient,NestCoreAuth,NestCoreDatabase,NestCoreFunctions,NestCoreRealtime,NestCoreStorage,NestCoreAi,NestCoreMemory,NestCoreCollections,NestCoreException,NestCoreConstants,NestCoreLogger(plus the internalNestCoreHttpClient/NestCoreAnalytics). - The default API base URL is
https://api.nestcore.io. .envsettings areNESTCORE_ANON_KEY,NESTCORE_DEBUG,NESTCORE_API_TIMEOUTandNESTCORE_API_URL.- The SDK identifies itself as
X-Client-Info: nestcore-flutter/<version>; log tags (NestCore,NestCore.HTTP) and error texts (NestCoreException(...)) say NestCore. - Realtime offers the
nestcore-realtime-v1/nestcore.apikey.<key>/nestcore.user-jwt.<jwt>WebSocket subprotocols (the API accepts both these and the oldorbitnest.*ones). - Secure-storage keys are now
nestcore_session,nestcore_access_token,nestcore_refresh_token,nestcore_api_keyandnestcore_project_slug.
Compatibility — nothing breaks on upgrade #
- Deprecated aliases:
OrbitNestClient,OrbitNestAuth,OrbitNestDatabase,OrbitNestFunctions,OrbitNestRealtime,OrbitNestStorage,OrbitNestAi,OrbitNestMemory,OrbitNestCollections,OrbitNestException,OrbitNestConstantsandOrbitNestLoggeraretypedefs of the new types, soOrbitNestClient.create(...),on OrbitNestException catch,OrbitNestConstants.versionand friends keep compiling (with a deprecation warning). - Old import path:
package:nestcore_flutter/orbitnest_studio_flutter.dartre-exports the package (deprecated). - Old env names: each
ORBITNEST_*variable is still read when itsNESTCORE_*counterpart is unset or empty. - Users stay signed in: on first use the
TokenManagermoves values stored under the oldorbitnest_*secure-storage keys to thenestcore_*keys (only where the new key is empty) and deletes the old keys; sign-out clears both sets. - The aliases, the old import path and the
ORBITNEST_*fallback will be removed in a future major version.
1.8.0 #
Added — AI data (parity with the Node/Web SDK) #
client.memory:add(dedupes near-identical memories unlessdedupe: false),search(similarity,score,degradedkeyword fallback),list,get,update,remove,forget, and service-keysubjects/reembed. TypedAiMemory,AiMemoryMatch,AiMemorySearchResult.client.collections:create,list,get,update,delete, andfrom(name)→ingest(AiDocumentSource.text/url/storage, wait: true)(polls withwaitForuntilready/failed,TIMEOUTon expiry), hybridsearch(score, similarity, keyword match,**highlight, chunk + document),listDocuments,getDocument,remove,stats.client.ai.threads:create,list,get,delete, andfrom(id)→get,update,delete,messages,append(text, image URL orAiThreadPart.storageparts),run(aStream<ThreadRunEvent>:ThreadRunMessage,ThreadRunCitation,ThreadRunDelta,ThreadRunToolCall,ThreadRunToolResult, thenThreadRunDoneorThreadRunError; cancelling the subscription closes the connection and stops the run) andrunOnce. Run options:memory(true or atype:idsubject),collections,tools(AiThreadTool.memorySearch/collectionsSearch),maxContextTokens, model settings.client.ai.traces(...)(service key): per-call model, tokens, latency, cost and status.from(table)…semantic(column, query, k:, hybridColumn:, minSimilarity:)keeps the builder'seq/gt/inFilter/isFilter… filters andlimit(ask);database.semantic(table, column, query, filters: [SemanticFilter(...)])calls it directly. ReturnsSemanticResponse(rows with_similarityand_score, plusmodel).
Changed — Database #
textSearch(column, query, config:, type:)is now chainable with the other filters instead of throwingUnsupportedError(type:websearch(default),plain,phrase). New chainablenearest(column, vector, metric:, limit:). Queries that use either run as one parameterized SELECT through the SQL endpoint (identifiers checked and quoted, values bound; RLS applies);countis then the number of rows returned.update()/delete()andsemantic()refuse builders that use them.
Internal #
chatStreamand thread runs share one dart:io SSE helper (same cancel-closes-socket behaviour).
1.7.0 #
Added — AI gateway #
client.ai:chat,chatStream(aStream<AiStreamEvent>: text deltas, tool calls, done or error),embed(768-dim vectors) andmodels, through the project's own provider keys. Tool calling and image inputs (AiContentPart.imagewith a data URL). Cancelling the stream subscription closes the connection so the server stops generating.- Billed AI requests are never retried by the retry interceptor (
extra: {'noRetry': true}).
Fixed — Database #
deleteManyno longer deletes unrelated rows. It sent the filter values as ids (deleteMany('posts', filters: {'author_id': 12})ranDELETE … WHERE id = 12).delete/deleteManynow delete the rows whose columns equal all filters, andcountis the real number of rows deleted.updateManyrespects its filters (it ignored them and matched onvalues['id']).update/updateManyupdate every row matching all filters and report the real row count.from(table)works.execute(),insert(),update()anddelete()threwUnsupportedError. The builder now calls the API directly.select()filters, ordering, paging and columns are honoured. They were sent in PostgREST syntax the API ignores, so every call returned the first page of the whole table. Filters now go asfilter=column:operator:value, ordering assortBy/sortOrder, paging aslimitorfrom/to; columns are projected client-side.- Unsupported query features throw instead of returning wrong rows.
contains,containedBy,overlaps,range*,textSearch,or,and,isNotNull, more than oneorder, aliased/embedded selects, andinFiltervalues containing,throwUnsupportedError/ArgumentErrorbefore any request. Filter values may contain:(timestamps, URLs).update()/delete()on the builder accept equality filters only and refuse to run without a filter. sql()works. It sentparameters(the API field isparams, so every parameterised query got 400) and returned the response envelope as a single row. It now returns the rows, withcount= rows affected.vectorSearch()works again as a result.- Concurrent
database.*calls no longer hang or swap results. Calls were multiplexed through one bloc and settled the first waiting caller. Each call now returns its own future. insertMany()no longer hits the service-role-only bulk route (401). It inserts one row per request (not atomic) and returns the inserted rows.- Upsert throws
UnsupportedErrorinstead of silently doing a plain insert.insert(upsert: true),from().upsert()andfrom().insert([...])used to drop all but the first row; a list now inserts every row.
Fixed — Auth & sessions #
OrbitNestClient.create(anonKey:)works without a.envasset. It crashed withNotInitializedErrorfrom flutter_dotenv.- An offline cold start no longer logs the user out. A refresh that fails because of the network, a timeout, 408/429 or 5xx keeps the stored session and is retried on the next request. Only a refresh the server rejects (4xx) clears it.
- Ordinary 401s no longer fire
onSessionExpired. An anonymous caller's 401, a 401/403 on a retried request, a transient refresh failure, and any 401 from analytics are returned to the caller instead of signalling "session expired".onSessionExpiredfires only when the server rejects the refresh token. - No more silent downgrade to the anon key. A 401 "invalid signature" was replayed with the anon key and reported as success.
- Analytics sends the
apikeyheader with every request, and its 401s no longer trigger refresh-token rotation or logout. resetPassword()no longer throws after the password was reset. It returns{email, message}; the user signs in with the new password.verifySmsOtp()updates auth state (isAuthenticated,currentUser,onAuthStateChange), like a password sign-in.getUser()returns aUser(it cast aMaptoUser) and throws instead of hanging when no user is signed in.refreshSession()throws instead of hanging when the refresh fails.- Requests made while a token refresh is running wait for it instead of going out with the anon key (RLS saw no user); a refresh that fails offline keeps sending the user token. The 401 refresh-and-retry now keeps byte downloads and uploads working, and reuses a token another call already refreshed. Realtime refreshes once and reconnects when the server rejects the socket's token (close 4001).
Added #
updateUser(currentPassword:)— the API now requires the current password to change the email or password.auth.verifyEmailChange(code). Changing the email withupdateUser(email:, currentPassword:)now only sends a code to the new address; call this with that code to apply the change.codeonenrollMfaTotp,regenerateMfaRecoveryCodesandunenrollMfa— the API requires a current TOTP/recovery code once MFA is active.auth.deleteUser()— deletes the signed-in user's account and clears the local session.realtime.reconnect().
Fixed — Realtime #
- The socket carries the signed-in user's access token and reconnects on sign-in/sign-out, so RLS-scoped subscriptions see that user's rows.
unsubscribe()removes the server subscriptions (it sent the bare channel name, which matched nothing).untrack()sends the gateway'spresence.untrack, so it drops presence without leaving the channel.- Reconnect backoff now grows while the server is down (it reset to ~1 s).
- Server
errorframes reachchannel.eventsasRealtimeErrorEvent, and a channel'seventsstream only carries its own tables' changes.
Fixed — Errors #
- API error codes and structured fields reach callers.
OrbitNestException(andAuthException/DatabaseException/FunctionException) has a newbodywith the parsed error JSON, e.g.QUOTA_EXCEEDED'squota/plan/limit/usage.FunctionExceptionnow keeps the API'scodeandmessage(it reportedUNKNOWN_FUNCTION_ERROR). - Storage throws
StorageException. Everystorage.from(bucket)request method (upload,download,list,remove,createBucket) throws aStorageException(anOrbitNestException) with the API'sstatusCode,code,messageandbody— e.g. 402QUOTA_EXCEEDED, 403, 404 — instead of a rawDioException.downloaderrors are decoded too. - 402/403/429 (
QUOTA_EXCEEDED,PLAN_REQUIRED,MFA_ENROLLMENT_REQUIRED,SMS_RATE_LIMITED,SHARED_EMAIL_RATE_LIMITED, …) never refresh or end the session. A 429 that carries acodeis not retried.
Fixed — Other #
crash()sendserror_type,error_messageandstack_trace, so crashes group by type.dispose()flushes queued analytics and closes the session-expired stream.- Uploads are not retried with an already-sent
FormDatabody. - NestJS validation errors (
messageas a list) no longer crash the error interceptor. X-Client-Inforeports the real SDK version.
Deprecated #
orbitnest.jobs(needs the Studio admin API, always 401 from an app) andorbitnest.migrations(the routes do not exist). Use Studio or the OrbitNest CLI. They will be removed.
1.6.3 #
Fixed #
- One failing edge function no longer fails every call running beside it.
OrbitNestFunctionsmultiplexes concurrent invocations onto a single bloc and resolves them from its state stream. The success path routed a result to the one pending operation registered for that function name, but the error path completed every pending operation with whichever function happened to fail. An app whose dashboard fans outget-dashboard,get-groups,get-insightsand one function that had been deleted server-side therefore saw all four reported as broken — each carrying the deleted function's name — even though three of them returned 200. Failures now settle only their own caller. Regression test:test/functions_error_routing_test.dart.
1.6.2 #
Fixed #
- Users no longer logged out on every app restart after ~15 minutes. The
/auth/refreshroute authenticates off the refresh token in the request body and needs no Bearer access token, butAuthInterceptorwasn't skipping it. On a cold start the stored access token is already expired (15-min TTL), so attaching it to the refresh POST madeonRequesttrigger a proactive refresh that re-entered the very in-flight refresh future the POST belonged to — a self-deadlock. The refresh never completed, the session was cleared, and the app dropped to the login screen./auth/refreshis now treated as a token-less auth endpoint, so the cold-start refresh completes cleanly and an active user's session survives for the full refresh-token lifetime. Regression test:test/refresh_endpoint_no_token_test.dart.
1.6.1 #
Fixed #
- Session no longer lost on cold restart after a token refresh race. The
AuthBloc's session-refresh handler called
/auth/refreshdirectly instead of throughTokenManager's de-duplicated refresh. Because the backend rotates refresh tokens single-use, a refresh that raced a concurrent interceptor/proactive refresh could lose the race, 401, and then clear the session — even though the winning refresh had just persisted a valid rotated token. All refresh paths now share one in-flight request, so the race is gone. (Most visible right after registration, whose onboarding fires a burst of parallel authenticated requests.) - Background user reconciliation could clobber a rotated refresh token.
_reconcileStoredUserFromServerwrote back a session snapshot captured before itsgetUser()call; if that call refreshed the token, the stale token overwrote the rotated one. It now re-reads the latest stored session before merging the fresh user. storeSessionno longer overwrites a valid refresh token with an empty one. A partial payload lacking a refresh token would otherwise make the next cold start wipe the whole session; the existing refresh token is now preserved.
1.6.0 #
Fixed #
- MFA sign-in challenge is now surfaced. When an account has a verified MFA
factor,
signInWithPasswordpreviously threwSign in failedand dropped the server'schallenge_token, making it impossible to complete an MFA-gated login. It now returns{ mfa_required: true, challenge_token, factors }(no session) — passchallenge_tokentoverifyMfa(challengeToken:, code:)to finish signing in. verifyMfanow updates auth state. It previously stored the session token but leftisAuthenticated/currentUser/currentSessionand theonAuthStateChangestream unchanged, so apps couldn't tell the user had logged in. It now transitions to the authenticated state like a normal sign-in.
Added #
AuthResponsenow exposesmfaRequired,challengeToken,mfaFactors, and anisMfaRequiredgetter.- New
AuthMfaRequiredStatefor apps that drive auth via the BLoC stream directly.
1.5.1 #
Changed #
- Widened dependency constraints to support the latest stable releases of
flutter_bloc(9.x),flutter_dotenv(6.x), andflutter_secure_storage(10.x). - Raised the
diolower bound to^5.5.0(required forDioMediaType).
Removed #
- Dropped deprecated
flutter_secure_storageAndroid cipher options; data migrates automatically.
Added #
- Added an
example/with a minimal usage sample.
1.5.0 #
Added #
- Storage client: upload, download, list, remove, and
getPublicUrlwith image transforms.
1.4.0 #
Added #
- MFA recovery codes:
verifyMfaEnrollmentnow surfacesrecovery_codes, plus a newregenerateMfaRecoveryCodesmethod.
1.2.0 #
Added #
- Migrations client: trigger server-side migration runs, read status, and display logs (the SDK never executes migrations itself).
1.0.9 - 2026-02-23 #
Added #
- Automatic Token Refresh: Implemented automatic token refresh mechanism that triggers when tokens expire or are within 5 minutes of expiration
- Error Recovery with Retry: Added comprehensive retry logic with exponential backoff for network failures (408, 429, 500-504 errors)
- Query Builder Integration: Completed BLoC query builder integration with proper error handling
Improved #
- Token Management: Enhanced token manager with refresh callback support and automatic refresh detection
- Network Resilience: Added RetryInterceptor with configurable retry policies (aggressive, standard, conservative)
- Authentication Flow: Improved initialization flow to automatically attempt token refresh on expired tokens
- Error Messages: Better error messages for query builder usage
Fixed #
- Token refresh TODO implementation completed
- Query builder now provides clearer error messages when used incorrectly
- Automatic token refresh triggers on app initialization when needed
Technical Details #
- Added
RetryPolicyclass with configurable retry strategies - Added
RetryInterceptorfor automatic request retry with exponential backoff - Enhanced
TokenManagerwith refresh callback mechanism - Updated
AuthBlocto register refresh callback and handle automatic token refresh - Improved query builder error handling and documentation
1.0.8 Previous Release #
- Base implementation with auth, database, and edge functions support