@colixsystems/filestore-client
v0.16.3
Published
Typed client for the AppStudio Filestore subsystem (folders, file archive, previews, presigned object streaming, sharing, trash) at /filestore/*, plus BankID file signing at /signatures and signing rounds at /signing-rounds. snake_case JSON wire contract,
Readme
@colixsystems/filestore-client
Typed client for the AppStudio Filestore subsystem — the file archive mounted at /filestore/*. It covers:
- files — the file archive: list, get metadata, multipart upload, rename/move, copy (including across spaces), soft-delete, and preview via
files.{list,get,upload,update,copy,remove,preview}. - folders — folder tree CRUD via
folders.{list,create,update,remove}. - shares — folder-scoped permissions (the Filestore ACL) via
shares.{list,create,remove,sharedWithMe}. Permissions live on folders only (no file-level grant); each grant gives a user/group aVIEW/DOWNLOAD/MANAGEtier on a folder. Folder visibility (INHERIT/RESTRICTED) is set viafolders.update(id, { visibility }). - trash — the recycle bin: list trashed items, restore, and permanent purge via
trash.{list,restoreFile,restoreFolder,purgeFile,purgeFolder}. - presigned object streaming —
objectUrl(token)builds the byte-stream URL andfetchObject(token)fetches it.
What this is NOT. This is the Filestore subsystem client for external / server-side integrations and the widget runtime. It is not the Asset Manager. The widget host injects an instance into
WidgetContext.filestore, where the SDK hooksuseFilestoreFiles/useFilestoreFolders/useFileSignatureread it (mirroring how@colixsystems/datastore-clientbacksWidgetContext.datastore). For non-widget use you instantiate it yourself withcreateFilestoreClient({ baseUrl, getToken, getTenantId }).
Status
v0.16.3 — published to npm as @colixsystems/filestore-client.
0.16.3 (internal): carries the newer transport the clients share. The exported
withRetrynow also takes an optionalsignal: aborting it ends the attempt in flight or the wait before the next one at once, and rejects with codeCANCELLED, status 0. Its typed options now also listretries, which it already read. The client's own methods send, retry and fail exactly as before.
0.16.2 (fix): requests now go through the transport the clients share. A 429 on a read now waits for the server's
retry_after(the body, else theRetry-Afterheader) and surfaces at once when that is over 10 s;err.retryAfterstill carries the value. A body that fails to arrive after the status, a rendered PDF's bytes included, is aNETWORKerror, and a timeout's message readsNetwork failure: request timed out. No export, error class or request shape changed.
0.16.1 (fix): an idempotent read (GET) that fails to connect is now retried up to 3 times, as a 429 or 5xx already was; it used to fail at once. A read that hits the 10 s timeout is still not resent: the server may still be working on it. The retry loop is now the one the clients share. The exported
withRetryno longer resends an attempt that hit its own timeout, or one that rejected with a rawAbortError(a caller's cancel); it used to retry both. No export, error class or request shape changed.
0.16.0 (additive):
files.renderPdfandfiles.exportPdfbodies takeappend_file_ids— up to 20 stored PDFs whose pages follow the rendered HTML, in order. Each must be a PDF the caller may download; a refusal names it indetails.file_id(404FILE_NOT_FOUND, 403FILE_DOWNLOAD_NOT_PERMITTED, 422PDF_NOT_MERGEABLEfor a file that is not a readable PDF). PowersusePdfExport'sappendFileIds.
0.15.0 (breaking):
trash.list(query)now returns the{ data, meta }list envelope and takeslimit/offsetlike the other lists. Files and folders share one list, most recently deleted first, and each row carrieskind("file"or"folder"); file rows get the same absolutizedpresigned_urlandurlas before. A trashed file or folder inside a restricted folder the caller holds no grant on is no longer listed or counted. Callers readingfiles/foldersmust readdatainstead.
0.14.0 (additive): a signing round can name someone without an account.
signingRounds.prepare(fileId, signers)takes account ids as before, or entries{ app_user_id }/{ name, email }; an email signer is sent a 24-hour BankID signing link when the round is confirmed. In the manager view a place now hasid,kind("app_user"or"email"),link({ status, sent_at, expires_at, used_at, links_sent, can_resend }), andapp_user_idis null for an email place.signingRounds.resendLink(roundId, signerId, { email })replaces a place's link and sends a new one, to a corrected address when given. A refused signer'serrorsentry carriesindex, its place in the list.
0.13.0 (additive):
files.upload(formData, { recordId })names the row a record-space upload attaches to. When the host's datastore client holds a logged-out visitor's grant for that row (the sharedrecordAttachGrantsoption), the upload carries it inx-record-attach-grant, so a visitor can attach files to the row they just created. A visitor's upload is refused with 403ATTACHMENT_LIMIT_REACHEDonce the row holds ten files.
0.12.0 (additive): the
signingRoundsnamespace — signing a PDF by a fixed, ordered list of signers (/signing-rounds).overview(fileIds)is one read for up to 200 files: per file the caller can see, whether they manage its folder (can_manage), whether a round can be prepared (can_prepare), the current round as they may see it (round, with their own place andcan_sign) and whether the file is locked (locked);meta.rounds_enabledsays whether the workspace can start rounds at all.prepare(fileId, signerIds)creates the draft (its own 90 s timeout, never retried),preparedFile(roundId)returns a five-minute preview link (urlmade absolute likepresigned_url; only a server-relative path is accepted from the server, anything else rejects with codeINVALID_PREVIEW_URL) and the document'ssha256,confirm(roundId, sha256)opens the round,cancel(roundId)ends it, andlist(fileId)/get(roundId)read rounds. Errors now carry the server's refusal: everyFilestoreErrorhasserverCode(the server'scode, e.g.SIGNING_ROUNDS_NOT_ENABLED,FILE_IN_SIGNING_ROUND),errors(its per-field entries — one per refused signer, withapp_user_id,reasonandcharacters) andretryAfter(seconds). The class andcodeof the typed errors are unchanged; an error with no class of its own (409, 422) now has the server's code ascodewhere it was"UNKNOWN". Types:signatures.rosteris declared,signatures.cancelreturns what became of the order (not alwayscancelled), andSignInitiateResulthashint_code/message.
0.11.0 (additive):
files.renderPdf({ html })— render an HTML string to a PDF server-side (POST /pdf/export, the same headless-Chromium pipeline asexportPdf) and resolve to the bytes as anArrayBuffer, without saving anything. For a document the user views, prints or shares once rather than keeps. Powers the SDKusePdfExport().openPdf(). Needs an authenticated caller; a 413 means the rendered PDF exceeded the size cap, a 429 the per-user render rate, a 503 that every render slot stayed busy.
0.10.0 (additive):
files.copy(id, { space_type, owner_id, folder_id?, name? })— duplicate a file's current version into any space and folder the caller may add files to, including across spaces (project, public, and the caller's own personal space). The bytes are copied server-side, so the copy is independent of its source. Reading the source needs at leastDOWNLOAD; the destination needs upload permission and room in its storage quota. A name already taken at the destination lands asname (2).extand never replaces the existing file. Resolves to the new file record.
0.7.1 (typing fix): the
FilestoreFiletype declared acreated_atthe wire never sends — the same silent-undefinedtrap as the pre-0.7.0presigned_url/urlmismatch, and the cause of a blank "Uploaded" row in the Studio file panel (sc-3791). A file is stampeduploaded_at(plusuploaded_by_id), andupdated_atnow equalsuploaded_atuntil the file is actually modified after upload, so "has this changed?" is an exact comparison. Also declared:uploaded_by_name, the uploader's display name — resolved server-side for Studio callers only, so a widget always readsnull. No method signature or runtime behaviour changed.
0.7.0 (additive): every file record the client returns now carries a
urlalias of its absolutizedpresigned_url. The wire field ispresigned_url, butfile.urlis what widget authors and the AI widget agent reach for first — and reading the wrong name returnsundefinedsilently, so an image renders nothing with no error to trace. The alias is added in the one shared normalizer (withDisplayableUrl), sofiles.getand every row offiles.listagree;presigned_urlis unchanged and still present. Applies wherever that normalizer runs:files.{list,get,upload,update},trash.list, andshares.sharedWithMe. No method signature changed.
0.6.0 (additive):
files.exportPdf({ html, space_type, owner_id, folder_id?, file_name? })— render an HTML string to a PDF server-side and save it as a file in the Filestore. JSON body, snake_case verbatim; returns the created file record (with itspresigned_urlabsolutized like any other file). Same per-folder write check asfiles.upload.file_namedefaults todocument.pdfand is forced to ausePdfExport()hook; works identically on the web Player and the native export.
0.5.0 (breaking + additive): shares are now folder-scoped (the Filestore ACL, REQ-FSH). The polymorphic
target_type/target_idpair is gone:shares.list({ folder_id })lists a folder's grants,shares.create({ folder_id, subject_type, subject_id, permission })grants aVIEW/DOWNLOAD/MANAGEtier (re-granting updates the tier),shares.remove(id)revokes. Granting/listing/revoking is a MANAGE action on the folder (the backend 403s a non-manager, 404s an unseeable folder).shares.sharedWithMe()now returns{ folders, shares }(nofiles— permissions are folder-scoped). Folder visibility (INHERIT/RESTRICTED) is set via the existingfolders.update(id, { visibility }). Additive:signatures.roster(fileId, { limit, offset })— the MANAGE-gated signer roster (GET /signatures/roster): the file's folder audience, each annotated signed/not-signed,{ data, meta }withmeta.signed_count. Also:signatures.list(fileIds)is now self-scoped (the caller's own signatures only) — the backend contract tightened; the method signature is unchanged.
0.4.0 (fix):
presigned_urlon every file/preview the client returns is now absolutized against the client'sbaseUrlorigin. The backend mints presigned URLs as a relative path (/api/v1/filestore/object?token=…), which only resolves same-origin — so file thumbnails/downloads broke for a cross-origin web build (dev :5173 vs API :5000) and for the native export (a device has no page origin). The client now glues its own origin onto the relative path (leaving already-absolute URLs and same-origin relative bases untouched), so URLs work everywhere the client runs. Applies tofiles.{list,get,upload,update,preview},trash.list, andshares.sharedWithMe. No method signature changed.
0.3.0 (additive): added
signatures.list(fileIds)— a batch "is this file signed?" lookup (GET /signatures?subject_kind=file&file_ids=csv) returning the{ data, meta }envelope wheredatais the latest completedFileSignatureSummary({ signature_id, subject_file_id, signer_name, signed_at }) per accessible, signed file. Lets a file browser mark already-signed files without an N+1. No existing method changed.
0.2.0 (additive): added the
signaturesnamespace (REQ-SIGN) — BankID file signing over/signatures(NOT/filestore/*):signatures.initiate(fileId)→{ signature_id, order_ref, auto_start_token, qr, status };status(id)/cancel(id)/verify(id)key off the returnedsignature_id. The backend opens a sign order against theFsFile, hashes its bytes server-side, and verifies the proof offline before storing it. snake_case verbatim. No existing namespace changed. This release is also the first injected intoWidgetContext.filestore(read by the SDK filestore hooks), and corrects the multipart upload field-name docs to snake_case (space_type/owner_id/folder_id), matching what the controller actually reads.
Contract: snake_case JSON, no transform
The wire format for JSON bodies and query params is snake_case in both directions and that is the client contract too. The SDK does no case mapping:
- JSON request bodies are sent snake_case verbatim — you pass
{ space_type, owner_id, parent_folder_id }, not{ spaceType, ownerId, parentFolderId }. - Query params are sent snake_case verbatim —
space_type,owner_id,folder_id,parent_folder_id,file_id,type,q,limit,offset. - Response objects are returned snake_case verbatim — you read
row.created_at,row.owner_id,share.folder_id. (The one value the client rewrites ispresigned_url, resolved to an absolute URL against thebaseUrlorigin — see 0.4.0 above. It's a URL-origin fix, not a case transform.) - The list endpoints (
files.list,folders.list,shares.list,signatures.list,signatures.roster,signingRounds.list,signingRounds.overview) return the{ data, meta }envelope verbatim (no unwrap).trash.listreturns the envelope too, each row carryingkind("file"/"folder").shares.sharedWithMe()returns{ folders, shares }— NOT a{ data, meta }envelope.
Multipart upload field names
POST /filestore/files is multipart/form-data, which bypasses the backend's snake_case request middleware, so the file controller reads the form field names verbatim — and it reads them snake_case, the same as every JSON body. files.upload(formData) sends your FormData verbatim — you must use exactly these field names:
| FormData field | Required | Notes |
| --- | --- | --- |
| file | yes | The binary file part. |
| space_type | yes | e.g. PERSONAL / PROJECT. |
| owner_id | yes | The space owner id. |
| folder_id | no | Target folder id; omit for the space root. |
| file_name | no | The name to store the file under, preferred over the multipart filename. Send it when your transport does not name the part after the real file — the Expo export streams the file off disk, where it is named after a cache copy. Reduced to a basename, capped at 255 characters. |
Multipart fields travel in whatever casing the controller reads them in (multipart is not transformed); here that is snake_case, matching the rest of the wire contract.
Public API
import {
createFilestoreClient,
FilestoreError,
NotFoundError,
ForbiddenError,
ValidationError,
GoneError,
PayloadTooLargeError,
UnsupportedMediaTypeError,
RateLimitedError,
ServerError,
} from "@colixsystems/filestore-client";
const client = createFilestoreClient({
baseUrl: "https://api.appstudio.io/api/v1",
getToken: () => "Bearer ...", // Studio or AppUser JWT; "Bearer " prefix added if missing
getTenantId: () => "tenant_abc", // x-tenant-id header
getRequestHeaders: ({ namespace, operation }) => ({ "X-Trace": "..." }), // optional
// fetchImpl defaults to globalThis.fetch
// multipartFetchImpl sends FormData bodies; defaults to fetchImpl
});
// Files — list is { data, meta } verbatim; query keys are snake_case.
const { data: files, meta } = await client.files.list({
space_type: "PERSONAL",
owner_id: "user_123",
folder_id: "folder_1", // optional
q: "invoice", // optional
type: "image", // optional
limit: 50,
offset: 0,
});
const file = await client.files.get("file_1");
// Upload — multipart. FormData field NAMES are snake_case (see table above).
const fd = new FormData();
fd.append("file", blob, "photo.jpg");
fd.append("space_type", "PERSONAL");
fd.append("owner_id", "user_123");
fd.append("folder_id", "folder_1"); // optional
const uploaded = await client.files.upload(fd);
await client.files.update("file_1", { name: "renamed.jpg", folder_id: "folder_2" });
const copied = await client.files.copy("file_1", { space_type: "PUBLIC", owner_id: "tenant_1" });
await client.files.remove("file_1"); // soft delete -> trash
const preview = await client.files.preview("file_1");
// Folders
const { data: folders } = await client.folders.list({
space_type: "PROJECT",
owner_id: "project_9",
parent_folder_id: "folder_root", // optional
});
await client.folders.create({ name: "Docs", space_type: "PERSONAL", owner_id: "user_123", parent_folder_id: null });
await client.folders.update("folder_1", { name: "Renamed", parent_folder_id: "folder_0" });
await client.folders.remove("folder_1");
// Shares
const { data: shares } = await client.shares.list({ target_type: "FILE", target_id: "file_1" });
await client.shares.create({
target_type: "FILE",
target_id: "file_1",
subject_type: "USER",
subject_id: "user_456",
permission: "READ",
});
await client.shares.remove("share_1");
const inbox = await client.shares.sharedWithMe(); // { files, folders, shares } — AppUser only
// Trash
const { data: trashed, meta } = await client.trash.list({
space_type: "PERSONAL",
owner_id: "user_123",
limit: 50,
offset: 0,
}); // each row: { kind: "file" | "folder", ... }
await client.trash.restoreFile("file_1");
await client.trash.restoreFolder("folder_1");
await client.trash.purgeFile("file_1"); // permanent
await client.trash.purgeFolder("folder_1"); // permanent, recursive
// Presigned object streaming — the HMAC token IS the auth (no headers sent).
const href = client.objectUrl(token); // build a URL for <img>/<a>
const res = await client.fetchObject(token); // fetch the raw byte stream (Response)
// Signatures (BankID file signing — REQ-SIGN; hits /signatures, not /filestore)
const order = await client.signatures.initiate("file_1"); // { signature_id, qr, ... }
const st = await client.signatures.status(order.signature_id);
await client.signatures.cancel(order.signature_id);
const verdict = await client.signatures.verify(order.signature_id); // { valid, content_status, signed_by_others_since, seal, ... }
const roster = await client.signatures.roster("file_1", { limit: 50 }); // managers: who is expected to sign
// Signing rounds (a PDF signed by a fixed, ordered list of signers; hits /signing-rounds)
const { data, meta } = await client.signingRounds.overview(["file_1", "file_2"]);
// data[i]: { file_id, can_manage, can_prepare, round, locked }; meta.rounds_enabled
try {
const draft = await client.signingRounds.prepare("file_1", ["user_1", { name: "Bo Ek", email: "[email protected]" }]); // slow; never retried
const preview = await client.signingRounds.preparedFile(draft.id); // { url, sha256, expires_at, size_bytes }
await client.signingRounds.confirm(draft.id, preview.sha256); // the round is now OPEN
} catch (err) {
// err.serverCode: "SIGNING_ROUNDS_NOT_ENABLED", "SIGNATURE_TEXT_NOT_SUPPORTED", ...
// err.errors: one entry per refused signer — { app_user_id, message, reason, characters }
// err.retryAfter: seconds, on a 429 or 503
}
await client.signingRounds.resendLink("round_1", "place_1", { email: "[email protected]" }); // a new link, corrected address
await client.signingRounds.cancel("round_1");
// verdict.seal.sealed_at is the time on the seal's timestamp token.Surface
| Method | HTTP | Returns |
| --- | --- | --- |
| files.list(query) | GET /filestore/files | Page<FilestoreFile> ({ data, meta }) |
| files.get(id) | GET /filestore/files/{id} | FilestoreFile |
| files.upload(formData) | POST /filestore/files (multipart) | FilestoreFile |
| files.update(id, body) | PUT /filestore/files/{id} | FilestoreFile |
| files.copy(id, body) | POST /filestore/files/{id}/copy | FilestoreFile (the copy) |
| files.remove(id) | DELETE /filestore/files/{id} | void (soft delete) |
| files.preview(id) | GET /filestore/files/{id}/preview | Preview |
| folders.list(query) | GET /filestore/folders | Page<Folder> |
| folders.create(body) | POST /filestore/folders | Folder |
| folders.update(id, body) | PUT /filestore/folders/{id} | Folder |
| folders.remove(id) | DELETE /filestore/folders/{id} | void |
| shares.list(query) | GET /filestore/shares | Page<Share> |
| shares.create(body) | POST /filestore/shares | Share |
| shares.remove(id) | DELETE /filestore/shares/{id} | void |
| shares.sharedWithMe() | GET /filestore/shared-with-me | { files, folders, shares } (AppUser only) |
| trash.list(query) | GET /filestore/trash | { data, meta } (rows carry kind) |
| trash.restoreFile(id) | POST /filestore/trash/files/{id}/restore | FilestoreFile |
| trash.restoreFolder(id) | POST /filestore/trash/folders/{id}/restore | Folder |
| trash.purgeFile(id) | DELETE /filestore/trash/files/{id} | void (permanent) |
| trash.purgeFolder(id) | DELETE /filestore/trash/folders/{id} | void (permanent, recursive) |
| objectUrl(token) | builds GET /filestore/object?token=... | string (no request) |
| fetchObject(token) | GET /filestore/object?token=... | Response (raw byte stream) |
Query params (snake_case on the wire)
| Endpoint | Required | Optional |
| --- | --- | --- |
| files.list | space_type, owner_id | folder_id, q, type, limit, offset |
| folders.list | space_type, owner_id | parent_folder_id, q, limit, offset |
| shares.list | target_type, target_id | limit, offset |
| trash.list | space_type, owner_id | — |
Factory options
| Option | Type | Notes |
| --- | --- | --- |
| baseUrl | string | Required. The API base (e.g. .../api/v1). |
| getToken | () => string \| Promise<string> | Required. A Studio or AppUser JWT, or — for an external / server-side integration — an API key (as_…), which acts as the app user it is bound to; Bearer prefix added if missing. |
| getTenantId | () => string \| Promise<string> | Required. Returns the x-tenant-id value. |
| getRequestHeaders | ({ namespace, operation }) => object \| Promise<object> | Optional. Extra headers merged per request. namespace is one of files / folders / shares / trash. Not applied to objectUrl / fetchObject (the presigned token is the auth). |
| fetchImpl | typeof fetch | Optional. Defaults to globalThis.fetch. |
| multipartFetchImpl | typeof fetch | Optional. Sends FormData bodies (files.upload); defaults to fetchImpl. The Expo export passes a transport that streams the file off disk — Expo's fetch reads the whole file into the JS heap to build the body. |
Transport
| Concern | Behaviour |
| --- | --- |
| Auth header | From getToken (host-injected); Bearer prefix normalised. Not sent on fetchObject (token is the auth). |
| Tenant header | x-tenant-id from getTenantId. AppUser JWTs and API keys make their own tenantId authoritative server-side. |
| Multipart | files.upload sends FormData verbatim; no hand-set content-type so fetch supplies the boundary. |
| Retries | Idempotent GETs retried 3× with exponential backoff (200/400/800 ms) on a network failure, a 429 or a 5xx, but not after the 10 s timeout. A 429 waits for the server's retry_after (the body, else the Retry-After header); a wait over 10 s is not taken and the 429 surfaces at once. Mutations and uploads are not retried. |
| Timeouts | 10 s default, configurable per call via timeoutMs. |
| Error model | Typed FilestoreError hierarchy: NotFoundError (404), ForbiddenError (403), ValidationError (400), GoneError (410 — expired object token), PayloadTooLargeError (413 — file over the 5 GB cap), UnsupportedMediaTypeError (415), RateLimitedError (429), ServerError (5xx). |
| Platform | Browser and React Native / Node 18+ (uses fetch, FormData, AbortController). |
Dependencies
None. The client uses only platform fetch, FormData, and AbortController, all available in modern browsers, Node 18+, and React Native.
Tests
node --test srcFully self-contained — no npm install, no cross-package deps.
