@ecs-doculink/studio-sdk
v0.3.0
Published
JavaScript/TypeScript SDK for the DocuLink Studio Customer API (REST + SSE + Socket.IO).
Maintainers
Readme
@ecs-doculink/studio-sdk
JavaScript / TypeScript SDK for the DocuLink Studio Customer API — REST document
processing, master data, and AI chat (SSE + Socket.IO). Works in Node 18+ (global
fetch) and modern browsers. Ships ESM + CJS + .d.ts.
⚠️ Breaking change in v0.3.0 — real-time subscription.
subscribeDocumentScan(...)now takes the TaskUUID (the task id you use for upload), not the DocumentScanUUID. The server broadcastsdoc-scanevents to roomdoc-scan-{TaskUUID}; a0.2.0subscription that passed the scan UUID received nothing. Each event's payloadUUIDis still the DocumentScanUUID. See../CHANGELOG.md.
Install
npm i @ecs-doculink/studio-sdkQuickstart
import { DoculinkClient } from '@ecs-doculink/studio-sdk';
const client = new DoculinkClient({
providerApiKey: 'PROVIDER_API_KEY_35_CHARS_..........',
customerApiKey: 'CUSTOMER_API_KEY_35_CHARS_..........',
email: '[email protected]', // optional
// baseURL / documentWsURL / chatWsURL default to the test environment.
});
// Authentication is automatic on the first authenticated call, but you can
// force it (and inspect the tokens) up front:
await client.authenticate();
const usage = await client.getUsage(); // { planCode, quotaPages, ... }Authentication & auto-refresh
The client calls POST /auth with your API keys and stores the access + refresh
tokens. Every authenticated request sends Authorization: Bearer <AccessToken>.
- If there is no access token yet, the client authenticates first.
- On HTTP
401, it refreshes the token (POST /refresh/token) and retries once. If refreshing fails, it re-authenticates with the API keys and retries once.
You may also pre-seed tokens to skip the initial login:
const client = new DoculinkClient({
providerApiKey, customerApiKey,
accessToken: savedAccess,
refreshToken: savedRefresh,
});Uploading a document
import { readFile } from 'node:fs/promises';
const bytes = new Uint8Array(await readFile('./invoice.pdf'));
const result = await client.uploadFile('TASK_UUID', {
File: { data: bytes, filename: 'invoice.pdf' }, // or a browser File/Blob
SchemaUUID: 'SCHEMA_UUID',
ReturnFormatUUID: 'RETURN_FORMAT_UUID',
ReturnFormatType: 'JSON', // 'JSON' | 'XML' | 'CSV'
ClientUUID: 'CLIENT_UUID', // optional
});
// Drive the pipeline (each returns a status string):
await client.ocrProcess('TASK_UUID', result.DocumentScanUUID);
await client.schemaProcess('TASK_UUID', result.DocumentScanUUID);
await client.mappingProcess('TASK_UUID', result.DocumentScanUUID);
const { JsonOutput } = await client.getJsonOutput('TASK_UUID', result.DocumentScanUUID);Real-time: document processing (Socket.IO)
// Subscribe with the TaskUUID (the `:taskid` used for upload). The task room
// streams `doc-scan` events for every scan in the task; use `u.UUID`
// (DocumentScanUUID) to tell them apart.
const sub = client.subscribeDocumentScan('TASK_UUID', {
onUpdate: (u) => console.log(u.UUID, u.Status, u.CurrentLog, u.Error),
onError: (e) => console.error(e),
});
// later
sub.close();Status values: "1" OCR, "2" Schema, "3" Mapping, "4" Completed,
"9" Error (exported as DocumentStatus).
Real-time: chat
SSE (recommended) — streams the assistant reply and resolves with the full message:
const { session_uuid } = await client.createChatSession(); // optional model arg
const message = await client.sendChatMessageStream(session_uuid, 'Hello!', (evt) => {
if (evt.event === 'stream_chunk') process.stdout.write(evt.chunk);
});
console.log('\nFinal:', message.Content);Sync — returns the full assistant message in one call:
const message = await client.sendChatMessageSync(session_uuid, 'Hello!');Socket.IO — subscribe, then send asynchronously (HTTP 202) and receive events:
const chatSub = client.subscribeChatSession(session_uuid, {
onChunk: (e) => process.stdout.write(e.chunk),
onEnd: (e) => console.log('\nDone:', e.message.Content),
onError: (e) => console.error(e.error),
});
await client.sendChatMessage(session_uuid, 'Hello!'); // 202, watch the socket
// later: chatSub.close();The two
joinpayloads differ intentionally: document scans join with a plain string room, chat sessions join with{ room }. This matches the server contract.
Errors
Every failed call throws an ApiError:
import { ApiError } from '@ecs-doculink/studio-sdk';
try {
await client.getUsage();
} catch (e) {
if (e instanceof ApiError) {
console.error(e.statusCode, e.status, e.message);
}
}An ApiError is thrown when HTTP status is >= 400 or when the response
envelope carries status: false (including billing rejections that return HTTP 200).
API surface
All 31 endpoints from the contract are implemented as camelCase async methods:
auth (authenticate, refreshAccessToken), account (getUsage),
company/client/schema/provider lookups, document processing
(uploadFile, ocrProcess, schemaProcess, mappingProcess, getJsonOutput,
getListDocumentScans, getDocumentScanById, deleteDocumentScan), master data
(getMyMasterDatas, updateMasterData), and chat
(createChatSession, sendChatMessage, sendChatMessageStream,
sendChatMessageSync, listChatSessions, getChatSession, getChatHistory,
deleteChatSession, getAvailableModels, getChatGuides).
Scripts
npm run build # tsup → dist (ESM + CJS + .d.ts)
npm test # vitest run
npm run typecheck # tsc --noEmitReference
Full REST reference: ../docs/index.html.
Contract (single source of truth for all four SDKs): ../CONTRACT.md.
License
MIT
