@saplings/client
v0.3.1
Published
Reusable Saplings client toolkit
Readme
@saplings/client
Typed, application-defined JSON endpoints for browser and Node fetch clients.
Install
npm install @saplings/clientQuick start
import { createClient, type Endpoint } from '@saplings/client';
type Project = { id: string };
const getProject: Endpoint<string, Project> = {
method: 'GET',
path: (id) => `/api/projects/${encodeURIComponent(id)}`,
parse(value) {
if (!value || typeof value !== 'object' || !('id' in value) || typeof value.id !== 'string')
throw new Error('Invalid project response');
return { id: value.id };
},
};
const client = createClient({ baseUrl: 'https://api.example.com' });
const project = await client.request(getProject, 'project-1');API and operational notes
Request paths must remain on the configured origin and redirects are rejected. The supplied parser must validate response data. Configure authentication, CSRF protection, cross-origin credentials, retries and API policy in the consuming application. Requests time out after 12 seconds by default and support AbortSignal. Errors expose the HTTP status, not response bodies.
Validation
Run the workspace build and pnpm test after making changes. Confirm application-specific behavior and accessibility in the consuming environment.
Query parameters
import { withQuery } from '@saplings/client';
const path = withQuery('/api/projects', { query: 'design & research', page: 0 });Query values are URL-encoded; null and undefined values are omitted. Choose retry, caching, CSRF and authentication behavior explicitly for your API.
Use getHeaders(signal) to resolve short-lived authorization or CSRF headers
for each request. Dynamic headers override static headers. The callback receives
the request cancellation signal; it must avoid logging credentials. The client
does not automatically retry unsafe operations.
Typed starter session
import { createStarterSessionClient } from '@saplings/client';
const session = createStarterSessionClient({ baseUrl: location.origin, readRetries: 1 });
await session.change({ login, password });
const { signedIn, canOperate } = await session.read();
await session.change({ logout: true });The client validates the response from the starter’s cookie-backed session endpoint. GET requests can retry HTTP 429, 502, 503 and 504 within the original deadline. Set readRetries between 0 (default) and 4. Writes execute once; callers can reconcile an uncertain outcome by reading the session again.
The typed starterCatalogPage endpoint accepts text, page, pageSize and optional sorting. Use client.request(starterCatalogPage, { text: 'billing', page: 0, pageSize: 20 }) to get validated SDK feature rows and counts.
A request aborted before it begins does not call the dynamic header provider or send a network request. HTTP error response bodies are discarded on a best-effort basis before returning the typed error.
