@pendral/docuflow
v0.1.0
Published
Official TypeScript SDK and CLI for DocuFlow: document intake, extraction and review, live events, the event feed and signed webhooks.
Readme
DocuFlow TypeScript SDK
The official TypeScript SDK and CLI for DocuFlow, document intake, extraction and review. Upload documents into queues, read the fields extracted from them with page and bounding box, approve or correct them, follow every change live or from the event log, and receive signed webhooks, with every request and response fully typed.
- The whole API. Documents and review, queues with their schemas, rules, learnings and evaluations, automations, sources, connections, destinations, webhooks, data sets, exports, views, search, analytics, AI spend and traces, the event log, batch and the request log: every endpoint an API key can call.
- Fully typed. Request bodies, queries and responses are generated from the API's own schemas, with no runtime dependencies.
- Safe retries. Every write carries an idempotency key that the API honours for 24 hours, so a retried upload never creates a second document.
- Events two ways. Follow document progress live, or consume the event log from a stored cursor so nothing is missed across restarts.
- Secure by default. HTTPS only, keys kept out of browsers and logs, webhook signatures verified in constant time.
- Runs anywhere. Node.js 20+, Bun, Deno, Vercel, Cloudflare Workers. ESM and CommonJS.
Installation
npm install @pendral/docuflowGetting started
Create an API key under Settings → API keys and set it as DOCUFLOW_API_KEY. A key acts in one workspace, as the
person who created it, narrowed to the scopes chosen for it.
import { readFile } from "node:fs/promises";
import DocuFlow from "@pendral/docuflow";
const docuflow = new DocuFlow(); // reads DOCUFLOW_API_KEY
// A queue is a family of documents with one schema.
const { queue } = await docuflow.queues.create({
name: "Invoices",
fields: [
{ key: "invoiceNumber", label: "Invoice number", type: "string", required: true },
{ key: "total", label: "Total", type: "number" },
],
});
// Upload. Processing runs in the background.
const { documents } = await docuflow.documents.upload({
queueId: queue.id,
files: [{ data: await readFile("invoice.pdf"), name: "invoice.pdf" }],
});
const documentId = documents[0]!.id;
// Wait for it to reach review: listens on the live event stream, and re-reads the document so nothing is missed.
await docuflow.documents.waitFor(documentId, { status: ["needs_review", "approved", "failed"] });
// Every field with its value, page, bounding box and confidence, and the same data as a plain object.
const { values, fields } = await docuflow.documents.fields.get(documentId);
console.log(values.invoiceNumber, values.total);
console.log(fields.map((f) => `${f.path} = ${f.value} (p${f.page}, ${f.confidence})`));
await docuflow.documents.approve(documentId);waitFor is built on the live stream. To follow it yourself:
for await (const event of docuflow.events.stream({ types: ["document.updated"] })) {
if (event.documentId === documentId) console.log(event.status, event.stage, event.progress);
if (event.documentId === documentId && event.status === "needs_review") break;
}One call extraction
extract uploads a file and holds the request until the document settles, up to four minutes:
const result = await docuflow.extract({ file, queue: "invoices" });
if ("values" in result) console.log(result.status, result.values);Pass fields instead of a queue for a one-off schema, or wait: false to get the id back at once.
Review
const document = await docuflow.documents.get(documentId); // pages, latest run, fields, timeline, comments
const { fields } = await docuflow.documents.fields.get(documentId);
const total = fields.find((f) => f.path === "total")!;
await docuflow.documents.fields.update(documentId, { updates: [{ id: total.id, value: "1249.00", status: "confirmed" }] });
const { issues } = await docuflow.documents.validation(documentId);
await docuflow.documents.reject(documentId, { reason: "Duplicate of INV-1042" });
await docuflow.documents.reopen(documentId);
await docuflow.documents.approve(documentId, { force: true }); // despite blocking validation errors
for await (const part of docuflow.documents.ask(documentId, { question: "What is the PO number?" })) {
if (part.t === "done") console.log(part.answer, part.citations);
}The event log
Every event the workspace produces is kept for 30 days, whether or not a webhook is subscribed, with the same evt_…
id and body a webhook receives. follow consumes it forward and keeps polling, so an integration behind a firewall, or
one that was down, picks up exactly where it stopped:
for await (const event of docuflow.events.log.follow({ after: await loadCursor(), types: ["document.approved"] })) {
if (event.type === "document.approved") await saveValues(event.data.document.id, event.data.fields);
await saveCursor(event.cursor);
}Delivery is at least once: deduplicate on event.id. docuflow.events.log.replay(eventId) sends a recorded event to
your webhooks again, verbatim.
Webhooks
Create a webhook once, keep its secret, and verify every delivery. Pass the raw request body, not parsed JSON.
const { webhook, secret } = await docuflow.webhooks.create({
name: "Production",
url: "https://example.com/webhooks/docuflow",
events: ["document.needs_review", "document.approved"],
});
// secret (whsec_…) is shown once. Store it as DOCUFLOW_WEBHOOK_SECRET.The handler works with Next.js route handlers, Hono, Bun, Deno and Workers:
import { createWebhookHandler } from "@pendral/docuflow/webhooks";
export const POST = createWebhookHandler({
secret: process.env.DOCUFLOW_WEBHOOK_SECRET!,
on: {
"document.approved": async (event) => {
await saveValues(event.data.document.id, event.data.fields);
},
},
});Unsigned or stale deliveries get a 400 and never reach your code; a handler that throws is a 500, so the delivery is retried. For Express or anything else, verify directly:
import { constructEvent, WebhookVerificationError } from "@pendral/docuflow/webhooks";
app.post("/webhooks/docuflow", express.raw({ type: "application/json" }), async (req: Request, res: Response) => {
try {
const event = await constructEvent(req.body, req.headers, process.env.DOCUFLOW_WEBHOOK_SECRET!);
await handle(event);
res.sendStatus(204);
} catch (error) {
if (error instanceof WebhookVerificationError) return res.status(400).send(error.message);
throw error;
}
});Deliveries are signed X-DocuFlow-Signature: sha256=<hex>, an HMAC-SHA256 of <X-DocuFlow-Timestamp>.<raw body>.
webhook destinations and scheduled exports sign the same way. webhooks.rotateSecret ends the old secret at once:
pass both to secret while you deploy the new one.
Queues, rules and automations
await docuflow.queues.update(queueId, { automation: "confident", threshold: 0.9 });
await docuflow.queues.rules.create(queueId, {
name: "Total is positive",
fieldPath: "total",
kind: "range",
config: { min: 0.01 },
level: "error",
});
const proposal = await docuflow.queues.schema.generate(queueId, { description: "US medical claim form" });
const run = await docuflow.queues.evals.create(queueId, {});
const { automations } = await docuflow.automations.list({ queueId });
const { runs } = await docuflow.automations.runs.list(automations[0]!.id, { matched: "true" });Pagination
List methods return the first page when awaited, and every item when iterated:
const page = await docuflow.documents.list({ status: "needs_review", limit: 50 });
console.log(page.data.length, page.hasNextPage(), page.nextCursor);
for await (const document of docuflow.documents.list({ status: ["needs_review", "failed"], queueId })) {
console.log(document.id, document.status);
}
const recent = await docuflow.audit.list({ action: "document." }).toArray({ max: 500 });Files
Uploads take a File, a Blob, bytes with a name ({ data, name }), or a Response you fetched. Downloads come back
as a raw Response:
const pdf = await docuflow.documents.file(documentId);
const page = await docuflow.documents.pages.image(documentId, 1);
const words = await docuflow.documents.pages.words(documentId, 1);
const csv = await docuflow.documents.export(documentId, { format: "csv" });
console.log(new Uint8Array(await pdf.arrayBuffer()).length, await csv.text(), words);Errors
Every failure is a DocuFlowError carrying status, a stable code, message, requestId and details.
import { PermissionDeniedError, PlanRequiredError, RateLimitError, BadRequestError } from "@pendral/docuflow";
try {
await docuflow.documents.approve(documentId);
} catch (error) {
if (error instanceof PermissionDeniedError) console.error("Needs", error.required);
else if (error instanceof PlanRequiredError) console.error("Needs the", error.requiredPlan, "plan");
else if (error instanceof BadRequestError) console.error(error.details);
else if (error instanceof RateLimitError) console.error(`Retry in ${error.retryAfter}s`);
else throw error;
}| Class | When |
| --- | --- |
| BadRequestError | The request is malformed or failed validation (400, 413, 415). details lists the issues. |
| AuthenticationError | The key is missing, invalid or revoked (401). |
| PlanRequiredError | The workspace's plan doesn't include this (plan_required) or is at a limit (plan_limit) (402). |
| PermissionDeniedError | The key's scopes, or its creator's role, lack the permission (403). required names it. |
| NotFoundError | Not in the key's workspace, or in a queue it cannot see (404). |
| ConflictError | The object is not in a state that allows this (409). |
| UnprocessableEntityError | An Idempotency-Key reused with a different body (422). |
| RateLimitError | Over the key's requests per minute (429). retryAfter says when to try again. |
| InternalServerError | Something failed on our side (5xx). Quote requestId to support. |
| APIConnectionError / APITimeoutError | The request never got a response. |
Branch on error.code, never on the message. docuflow.logs.list({ requestId }) finds the call in your workspace's
own request log.
Retries and idempotency
Rate limits, server errors and network failures are retried twice with backoff, honouring Retry-After. Every POST,
PUT, PATCH and DELETE sends an Idempotency-Key and its retries reuse it, so the API runs the write once and answers
every repeat with the first result. Pass your own key to make a write idempotent across your own retries, for example
a job that may run twice:
await docuflow.documents.upload({ queueId, files: [file] }, { idempotencyKey: `upload-${documentId}` });Response details
Await a call for its data, or use withResponse() for the raw response, request id and rate-limit state:
const { data, requestId, rateLimit, idempotentReplay } = await docuflow.documents.get(documentId).withResponse();docuflow.whoami() says which key is calling, the workspace it acts in, its effective permissions and its remaining
budget: the first call to make when something answers 403.
Batch
Up to 25 calls in one request, each authorized and validated exactly as if made directly:
const { results } = await docuflow.batch({
mode: "parallel",
requests: [
{ id: "doc", path: `/api/v2/documents/${documentId}` },
{ id: "approve", method: "POST", path: `/api/v2/documents/${documentId}/approve`, body: {} },
],
});
for (const result of results) console.log(result.id, result.status);Configuration
const docuflow = new DocuFlow({
apiKey: process.env.DOCUFLOW_API_KEY,
baseUrl: "https://docuflow.pendral.io", // only for another deployment
maxRetries: 2,
timeoutMs: 60_000,
});| Option | Default | |
| --- | --- | --- |
| apiKey | DOCUFLOW_API_KEY | Your dfk_… key. |
| baseUrl | DOCUFLOW_BASE_URL, then https://docuflow.pendral.io | Must be HTTPS (plain HTTP only to localhost). |
| maxRetries | 2 | Per request. Override per call with { maxRetries }. |
| timeoutMs | 60000 | Per attempt (extract waits up to 300000). Override per call with { timeoutMs }. |
| logLevel | DOCUFLOW_LOG, then warn | off, error, warn, info or debug. Never logs keys, headers or bodies. |
| fetch | global fetch | Supply your own for proxies, instrumentation or tests. |
| defaultHeaders | | Sent with every request. Cannot replace the credential. |
Every call also takes { signal, timeoutMs, maxRetries, idempotencyKey, headers } as its last argument.
Keep API keys on your server. The client refuses to start in a browser unless you pass dangerouslyAllowBrowser: true.
For an endpoint newer than this SDK, docuflow.request("documents.get", { path: { id } }) calls any operation by id,
and docuflow.raw("GET", "/api/v2/...") calls any path, both with the client's credentials, retries and errors.
Command line
The package includes the docuflow CLI.
npx -p @pendral/docuflow docuflow whoami
npx -p @pendral/docuflow docuflow tail # live document progress
npx -p @pendral/docuflow docuflow events --follow --events document.approved
npx -p @pendral/docuflow docuflow listen --forward-to http://localhost:3000/webhooks/docuflow
npx -p @pendral/docuflow docuflow request GET documents --query status=needs_reviewlisten forwards the workspace's events to a local URL, signed exactly like real webhook deliveries with a secret it
prints, so you can build your webhook handler without exposing your machine.
Requirements
- Node.js 20 or later, or any runtime with
fetchand Web Crypto - TypeScript 5 or later, if you use TypeScript
Support
See the documentation for guides and the full API reference. For help, contact your
DocuFlow account team and include the requestId from the error or the X-Request-Id response header.
License
Proprietary. Copyright © 2026 Pendral, Inc. All rights reserved. See LICENSE.
