sp_laravel_api 0.5.0
sp_laravel_api: ^0.5.0 copied to clipboard
Typed REST client and multi-broadcaster realtime client for the SP Laravel backend packages.
Changelog #
0.5.0 - 2026-11-30 #
- Added:
limitonTableGateway.listandserializeQuery, for reads that are not pages (a lookup by key, a top 10, a preview).list(where: [...], limit: 10)sendslimit=10and noper_page, so the host runs a plainLIMITwith noCOUNT(*).limitwithperPageorpagethrowsSpApiError(unencodableValue);limitwithcursoris allowed, andtotalstays off unless you passtotal: true. Withoutlimitnothing changes. Same behaviour aslimitin@sokpheak/sp-laravel-api.
0.4.0 - 2026-11-30 #
- Added:
updateandpatchtakeexpectedVersion(a number or numeric string). It is sent asexpected_version, so a table with a version column insp-laravel-api1.1.0 refuses a stale write with aSpApiErrorCode.conflicterror whosecurrentRecordis the stored row. The body you pass is not changed. AddedSpApiError.isConflict. Same behaviour asexpectedVersionandisConflictin@sokpheak/sp-laravel-api.
0.3.0 - 2026-11-29 #
- Added: a version conflict is its own error category. An HTTP 409, or a
200 { success: false }envelope witherror_code10016 (a staleexpected_versionon a table with a version column insp-laravel-api1.1.0), isSpApiErrorCode.conflictinstead ofunknown, andSpApiError.currentRecordholds the row the server has now (errors.current_record), ornull. The stored row is no longer flattened intofieldErrors['current_record']as text.SpApiErrorCodegainsconflictaftervalidation, so an exhaustiveswitchover it needs a new case. Same behaviour as@sokpheak/sp-laravel-api.
0.2.0 - 2026-10-30 #
-
Fix: the direct-to-storage requests of
uploadDirectanduploadMultipartno longer pass through the interceptors or default headers of the client'sDio. They use a bareDiothat shares only the transport (adapter and timeouts), so the bearer token thatattach(dio)fromsp_jwt_authadds to every request is not sent to S3 or R2 (storage rejects a presigned request that also carries anAuthorizationheader). A multipart upload also waits for the parts in flight before it aborts, and a failure or a stream error stops them. A cancelled upload rethrows a cancel error that does not hold the signed URL, and a transport failure on an upload call is rethrown without the underlying request (which carried the upload token and the key). -
BREAKING:
TableGateway.fetchLastandCursorPagination.lastPageneed asortand throwSpApiError(unencodableValue)before any request without one. They used to assumeSort('id', Order.asc), but the host's default sort depends on the table (created_atwhen it has one, else the primary key), so the old default could silently return the wrong rows. With a sort nothing changes: the sort is inverted for the request and the items are restored to canonical order. Pass the sort the list uses. Same behaviour aslastPagein@sokpheak/sp-laravel-api. -
BREAKING (fix): the attachment ids, record ids, table names and the
rpcPrefixthat go into a request path are now guarded: an empty,.or..value throwsSpApiError(unencodableValue)and nothing is sent (a URL parser would normalise it into a different route, and the call carries auth headers). AffectsviewBytes,link,unlink,getViewUrlandgetDownloadUrl; therpcPrefixis checked segment by segment (a prefix such as..ora//bthrows). Fix:getViewUrlandgetDownloadUrlhard-codedrpcand ignored a customrpcPrefix; they now use the client's prefix (an empty prefix drops the segment) and percent-encode the id (they inserted it raw before). With the default prefix and a plain id the URLs are unchanged. -
Added
serializeFilters: the query parameters forselect,where,or,search,distinct,trashedandsort, without any paging, for hosts that run their own list layer and setper_page,cursorand the rest themselves. It quotes values exactly likeserializeQuery, never returnsper_page,page,cursor,direction,cursor_columnortotal, and does not requireselect.serializeQueryis unchanged. -
Fix:
AttachmentsModule.uploadMultipartcould never succeed and uploaded nothing. It never read itsstream, calledrpc/create-multipart-upload(the route issp_attachments/rpc/...) and completed withparts: []while the backend requires at least one part, the upload token and its expiry. It now follows the real protocol:create-multipart-upload, per partsign-multipart-partand a PUT to the signed URL (no auth or tenant header, theETagresponse header is required), thencomplete-multipart-uploadwith the ordered parts. The stream is cut into exactpartSizeparts (default 8 MiB, at least 5 MiB, at most 10,000 parts,concurrencyparts at once, default 4); a failure aborts the upload once and rethrows the original error.totalBytesis now optional; new parameters:contentType,partSize,concurrency,onProgress,cancelToken,replaceOld,title,caption,tempTimeoutMinutes,tempTimeoutAt. Resume is not supported. Errors never contain a signed URL, the upload token or the key. -
Fix:
AttachmentsModule.uploadDirectcould never succeed against the backend. It calledrpc/create-upload-url(the route issp_attachments/rpc/create-upload-url), read anattachment_idthe backend does not return, and completed with{ attachment_id }whilecomplete-uploadrequireskey,upload_tokenandexpires_at. It now follows the real protocol:create-upload-url(filename,content_type,visibility,folder_id), a PUT of the bytes to the signed URL with the backend's headers and no auth or tenant header (or, on a local disk, the file posted tocomplete-upload), thencomplete-uploadwith the token, the record link (recordType,recordId,collection) and the shared fields (replaceOld,title,caption,tempTimeoutMinutes,tempTimeoutAt). New optional parameters:contentType,cancelTokenand those fields;folderis now sent asfolder_id. A failed upload is a typedSpApiErrorthat never contains the signed URL, the upload token or the key. -
AttachmentsModule.uploadsends the other fields the upload route validates:recordType,recordId,collection(the link),folderId,title,caption,replaceOld(replaces what is linked in the same collection of the record, deletes old files nothing else links to; needs a record),tempTimeoutMinutes/tempTimeoutAt(aStringor aDateTime; the server drops the offset, so a UTC value is only right when the host'sapp.timezoneis UTC) and, form upload only,width,height,fit,sizeNameandasTemp. When the server would silently ignore or override an option the call throwsSpApiError(unencodableValue)before any request (asTemp: truewith aprivate/publicvisibility, a timeout without a temporary upload, both timeouts,replaceOldwithout a record,sizeNamewithwidth/height/fit, awidthorheightbelow 1); only a truthy flag counts,asTemp: falsenever throws.visibilityis now nullable: when null the form still sendsprivate, unlessasTempis true. The server's own ranges (width and height 10 to 3000, title length, timeout cap) are not copied: its 422 reports them. -
debugoption that sendsX-Debug(D3):SpApi(debug: true)addsX-Debug: 1to every request andSpDebug.on()/SpDebug.merge(options)do it for one request (everyTableGatewaymethod andrpc), asking the SERVER for lazy-loading diagnostics and error debug details. It logs nothing on the client (seeSpLog). The header is added after the auth and tenant headers and before per-request headers, so an explicit per-requestX-Debug(even0) wins. The default sends no header. New file:lib/src/debug.dart. -
Optional redacted request logging (D1):
SpApi(logger: SpLogger(sink: ...))delivers oneSpLogEntryper HTTP attempt (method, redacted URL, status, duration, request id, attempt,code,errorCode). ModesSpLogMode.perRequest(default, only requests marked withoptions: SpLog.on(headers:, bodies:)),allandoff;SpLog.off()(orSpLog.merge(options, off: true)) keeps one request out of the log even inallmode. Headers and bodies are included only when asked for; redaction (sensitive header names, body and query keys at any depth, credentials in the URL, 2048-unit truncation,<N bytes>,<multipart>,<stream>) is built in and cannot be disabled, and request ids are sanitised. The redaction rules are shared with@sokpheak/sp-laravel-apithrough the same fixture: sensitive keys includepin,pwd,pass,sig,authorization,cookieand keys ending intokens,secrets,passwd,privatekey,signature,credential,otp,otp_code,recovery_codesand similar (error_code,country_code,idempotency_keystay visible); header names containingsignature,pass,otp,jwtorbearerare redacted; the URLs inLinkandRefreshheaders,key=valuepairs in URL fragments, comma-joinedFilter.anyOfkeys and dotted relation keys (sessions.pin) with a sensitive part, and filter groups (or=(...),and=(...)) andselectembed filters (rel(cols,col=op.value)) whose column path (sessions.token) has a sensitive segment are redacted. Only plain data is walked: any other object in a body (a model withtoJson, aSet) is logged as<object>; a body nested more than 100 levels is<unavailable>; JSON text is recognised after a BOM or NBSP; a query value holding a URL is redacted as a URL (2 levels); percent-decoding is tolerant and identical to the JS client. Redaction is a denylist of key names, not a guarantee. The sink runs inline; a sink that throws or returns a failingFuturenever changes the request result. Nothing changes for callers that do not setlogger. New files:lib/src/logging.dart; shared fixturetest/vectors/log_redaction.json. -
Fix (realtime recovery): a rejoin whose confirmation arrives late, during the retry backoff, stops instead of sending more subscribe frames and reporting a false
onSubscribeFailed. On a final rejoin failureonRecoverednow fires beforeonSubscribeFailed, and an exception thrown byonSubscribeFailedis caught, so it no longer surfaces as an uncaught error or keepsonRecoveredfrom firing. Unsubscribing (or a timed-outsubscribeabandoning) the last channel a recovery was waiting for now completes the recovery. -
Fix: a realtime socket that dies silently is now detected and replaced. After a pong timeout the client closes the socket and handles the loss itself:
onDisconnectedfires once and it reconnects. Before,WebSocketTransport.close()emitted noonDone, soisConnectedstayed true and nothing reconnected.onAppResumednow reconnects at once while a ping is unanswered and, after a long pause, sends a ping at once (before, it calledconnect(), which returned at once on a connected client), so a socket that died in the background is replaced afterpongTimeout. A new connection no longer reportsisHealthy == falsebecause of a ping sent on the previous one. -
Behaviour change:
SpRealtime.onAppResumedandonNetworkChangedreconnect only a client in use: one started withconnect()(orsubscribe()) and not stopped withdisconnect()since. Before, an online event connected a fresh client (for example at app start, before login, sinceconnectivity_plusemits the current state when listened to), and a resume revived a client the app had disconnected and re-sent its old subscribe frames. Afterdispose()both do nothing instead of throwingStateError. -
Fix: a failed
SpRealtime.connectno longer sticks. Before, every laterconnect()returned the same failed future without trying again. A failed attempt is now retried afterreconnectDelay, doubling per consecutive failure up to 5 s, unless the client is offline, disconnected or disposed; a laterconnect(), resume or online event tries again at once. Reconnects started byonAppResumed,onNetworkChangedor the reconnect timer no longer raise uncaught errors. Aconnect()still waiting for the handshake now fails withSpApiError(network) when the socket closes first or whendisconnect()ordispose()is called, instead of never completing.onDisconnectedfires only for a connection that was established. -
SpApi.getBytesandAttachmentsModule.viewBytesnow returnUint8Listinstead ofList<int>. AUint8Listresponse is returned as the same instance (no copy); other lists are converted.Uint8Listis aList<int>, so existing callers keep compiling. Code that overrides or mocksgetBytesorviewBytes(for example a mocktail stub) must now return aUint8List, not aList<int>. -
Behaviour change:
SpRealtime.subscribenow completes only after the server confirms the channel withpusher_internal:subscription_succeeded, and can throwSpApiErrorwith codetimeoutaftersubscribeTimeout(default 10 seconds). A timed-out or authorization-failed subscribe leaves no registered intent. A second subscribe to a confirmed channel sends no new frame; concurrent subscribers on a pending channel share one confirmation. A failed re-subscribe after a reconnect is retried up tosubscribeAttempts(default 3) with exponential backoff fromsubscribeBackoff(default 300 ms, capped at 5 s) and then reported once through the newonSubscribeFailed(channel, error)callback. New optionalSpRealtimeconstructor parameters:subscribeTimeout,subscribeAttempts,subscribeBackoff,onSubscribeFailed. CustomRealtimeTransportimplementations and test fakes must deliverpusher_internal:subscription_succeededfor eachpusher:subscribe, orsubscribetimes out. They also must not emitonDonefor a connection they close withclose(), not even later (cancel the stream subscription first, asWebSocketTransportdoes):SpRealtimehandles that loss itself and may already be reconnecting, so a lateonDonewould tear down the new connection. Known limitation: the Pusher protocol has no correlation id, so a very late confirmation (more thansubscribeTimeout) of an abandoned subscribe frame can complete a newsubscribeto the same channel early. -
Docs: README install snippet now targets
^0.1.0; new sections forrpc,SpApiError, thesuccess: falseenvelope, pagination, the select rule,upsertavailability, retries, per-request options, attachments, realtime recovery and pairing withsp_jwt_auth. Samples are compile-checked inexample/readme_samples.dartand guarded bytest/readme_test.dart. The missing-selecterror namesrequireSelect: false. -
AttachmentsModule.upload(multipart form POST tosp_attachments/rpc/upload,bytesorfilePath,visibilitydefaultprivate),link/unlinkfor record attachments, andviewBytes(authenticatedGET rpc/{id}/view). Signed-URL methods and URL builders are unchanged. -
TableGateway.listandserializeQueryacceptdirection(nextorprev) andcursorColumn, sent asdirection=andcursor_column=. -
Behaviour change: an empty
cursoris now sent ascursor=(empty string) instead of being remapped to0; the backend treats both as the first page.cursor: nullstill sends no cursor. -
Behaviour change:
CursorPage.nextCursoris nowmeta['next_cursor']whenever the backend provides it, regardless of item count (previously only on full pages). It is null when absent; offset mode still yields no cursor. -
RecordEventnow exposeseventName(the broadcast event name),raw(the full payload as broadcast) andisRecord(true only when the payload has a stringtableand a maprecord). Non-record events such ascourier_location.updatedare delivered to thesubscribehandler with all fields inraw. A non-maprecordno longer yields surprises: it gives an emptyrecordandisRecord == false. -
Behaviour change: added
RecordAction.unknown. A payload with a missing or unrecognisedactionnow maps tounknowninstead ofcreated. Exhaustiveswitchstatements overRecordActionneed a new case. -
TableGateway.list/get/create/update/patch/remove/restore/upsertaccept optionalOptions? optionsandCancelToken? cancelToken, forwarded toSpApi.request(per-request headers win over tenant/auth headers). Existing calls are unchanged. -
SpApi.rpcaccepts optionalquery(query parameters),method(override; default stays POST with a body, GET otherwise) andoptions(DioOptionsmerged into the request). -
BREAKING (behaviour change):
SpApi.requestnow throwsSpApiError(status stays the HTTP status, e.g. 200) when a response with status < 400 has a JSON map body withsuccess: false. Error code 10002 on such a response is routed throughApiAuth.handleUnauthorized()and retried once, like a 401. Bytes responses and non-map bodies are unaffected. Opt out withSpApi(treatSuccessFalseAsError: false)to restore the 0.1.0 behaviour. -
SpApiError.retryAfternow also readserrors.retry_after_seconds(first element, int or numeric string; zero or negative ignored) as a last fallback after theRetry-Afterheader and bodyretry_after. The value remains infieldErrors. -
SpApiErrornow carries the transportcauseandstackTrace(the originatingDioException) for status 0 failures, plusisTransport/isHttpgetters.toString()never prints the cause. -
iterate(),fetchFirst(),fetchLast()andcursorPagination().firstPage()now sendcursor=(cursor mode) so the backend returnsnext_cursor;fetchPrevsendsdirection=prev;fetchLastkeepsprevCursornull on a single short page.listwith anullcursor is unchanged (offset mode). -
CursorPage.nextCursor/hasMore: the backend sendsnext_cursoron every non-empty page, so the real end of the data is an empty page; docs updated. -
Behaviour change:
SpApiError.isTransportis now true only fornetworkandtimeouterrors withstatus == 0; local errors (for example a missingselect) also have status 0 but are not transport failures. -
A
200success: falseenvelope now mapserror_codetoSpApiError.code(10002 unauthenticated, 10008 forbidden, 10009 notFound, 10004 validation, 10010 server; others unknown). -
Retried multipart uploads (after a 401, a 10002 envelope or a
RetryConfigretry) now send a freshFormDataclone instead of failing with "already finalized". -
Release note: the release containing the breaking
treatSuccessFalseAsErrordefault should be versioned 0.2.0.
0.1.0 - 2026-10-27 #
- First stable release of
sp_laravel_apifor Dart and Flutter. - Added configurable
RetryConfigwith exponential backoff, full jitter, andRetry-Afterheader parsing for transient HTTP errors. - Added remote OpenAPI schema resolution (
--url,--schema,--header,--token,--tenant) to typegen CLI. - Added
Sort.reversed()and cursor pagination boundary helpers (fetchFirst,fetchLast,fetchNext,fetchPrev,cursorPagination) onTableGateway.
0.1.0-beta.2 - 2026-10-27 #
- Verified automated GitHub Actions OIDC publishing pipeline to pub.dev.
- Enhanced CI hygiene tooling with default fallback checks.
0.1.0-beta.1 - 2026-10-27 #
- Initial beta release of
sp_laravel_apifor Dart and Flutter. - Typed
TableGatewaywith cursor and offset pagination. - Query builder serializing filters, relationships, and sorting.
- Multi-broadcaster realtime engine for Laravel Reverb, Pusher, Soketi, and Ably.
- Cross-platform support for VM, web, and Wasm.