TypeScript Client Library
The Virtufin API TypeScript client library (@virtufin/api) provides a high-level TypeScript interface for interacting with the Virtufin API gateway using gRPC-web.
Installation
From Gitea npm Registry
Map the @virtufin scope to the registry and add a token (scope: read:package):
cat >> ~/.npmrc <<'EOF'
@virtufin:registry=https://gitea.haenerconsulting.com/api/packages/virtufin/npm/
//gitea.haenerconsulting.com/api/packages/virtufin/npm/:_authToken=<your-gitea-token>
EOF
Use gitea.haenerconsulting.com, not the npm.* alias: Gitea advertises
dist.tarball on gitea.* whatever host you query, so the npm.* form fetches
metadata authenticated and then follows an unauthenticated redirect for the
payload — npm matches tokens by URL prefix.
Then install:
npm install @virtufin/api
From Local Source
{
"dependencies": {
"@virtufin/api": "file:path/to/src/typescript"
}
}
Overview
The client library provides the ApiClient class as the main entry point for all operations:
| Class | Description |
|---|---|
ApiClient |
Main entry point with async operations using Connect protocol |
Quick Start
import { ApiClient } from "@virtufin/api";
const client = new ApiClient({ url: "http://localhost:5001" });
// List available services
const services = await client.listServices();
console.log(`Services: ${services.services.join(", ")}`);
// Invoke a method with binary data
const encoder = new TextEncoder();
const requestData = encoder.encode(JSON.stringify({}));
const response = await client.invoke("workmanager", "ListWorkers", requestData);
// Or with JSON string directly
const jsonResponse = await client.invokeJson("workmanager", "ListWorkers", "{}");
ApiClient
The main client class providing async operations for service discovery, method invocation, and pub/sub.
Constructor
const client = new ApiClient({ url?: string, timeout?: number, apiKey?: string, transport?: Transport });
Parameters:
- url - The gateway base URL for gRPC-Web: "http://localhost:5001" for a local gateway (its HTTP/1.1 port),
"https://api.virtufin.com" for the cluster (TLS). Required unless transport is given.
- timeout - Request timeout in milliseconds (default: 30000)
- apiKey - Sent as x-api-key on every call. The cluster gateway requires it on every non-health RPC.
- transport - A ready-made Connect transport instead of gRPC-Web on url; see below.
Connecting to a cluster, and native gRPC in Node
The cluster ingress enforces an API key, over TLS:
const client = new ApiClient({ url: "https://api.virtufin.com", apiKey: process.env.VIRTUFIN_API_KEY });
In Node, native gRPC reaches the gateway's gRPC port (HTTP/2) directly: localhost:5002 locally, 443 on the
cluster. That is the port a contexts.toml entry names, and the one the C# and Python clients use. gRPC-Web
can't reach a local gateway's gRPC port: Node's fetch speaks HTTP/1.1 and that port is HTTP/2 only.
import { createGrpcTransport } from "@connectrpc/connect-node";
import { ApiClient, apiKeyInterceptor } from "@virtufin/api";
const transport = createGrpcTransport({
baseUrl: "https://api.virtufin.com:443", // or "http://localhost:5002"
interceptors: [apiKeyInterceptor(apiKey)],
});
const client = new ApiClient({ transport });
With transport, set the key through its interceptors as above; apiKey can't be added to a transport that is
already built, so passing both throws.
Methods
Service Discovery
listServices(): Promise<ListServicesResponse>
listMethods(service: string): Promise<ListMethodsResponse>
getMethodSchema(service: string, method: string, type: string): Promise<GetMethodSchemaResponse>
Example:
// Get all services
const services = await client.listServices();
console.log(`Services: ${services.services}`);
// Get methods for a service
const methods = await client.listMethods("workmanager");
for (const method of methods.methods) {
console.log(`Method: ${method.name}`);
console.log(` Input: ${method.inputType}`);
console.log(` Output: ${method.outputType}`);
console.log(` Streaming: ${method.isServerStreaming}`);
}
// Get method schema
const schema = await client.getMethodSchema("workmanager", "ListWorkers", "protobuf");
Method Invocation
invoke(service: string, method: string, requestData: Uint8Array): Promise<InvokeResponse>
invokeJson(service: string, method: string, requestData: string): Promise<InvokeJsonResponse>
Example:
// Simple invocation with Uint8Array
const encoder = new TextEncoder();
const requestData = encoder.encode("");
const response = await client.invoke("workmanager", "ListWorkers", requestData);
// With JSON request data
const response = await client.invokeJson("workmanager", "CreateWorker", JSON.stringify({
code_source: { url: "https://example.com/worker.py" },
mime_type: "text/x-python",
topic: "worker-commands",
}));
// Decode response
const decoder = new TextDecoder();
const responseData = decoder.decode(response.responseData);
console.log(`Response: ${responseData}`);
Pub/Sub Operations
publish(topic: string, cloudevent: CloudEvent): Promise<PublishResponse>
publishEvents(events: { topic: string; cloudevent: CloudEvent }[]): Promise<PublishEventsResponse>
listTopics(): Promise<ListTopicsResponse>
publishWithResult(topic: string, cloudevent: CloudEvent, replyTopic: string, opts?: {
timeout?: number;
correlationId?: string;
}): Promise<SubscribeResponse>
subscribe(topics: string[], opts?: { signal?: AbortSignal }): Promise<Subscription>
subscribe resolves once the API confirms the subscription (daprd holds it), so a
request published after the await cannot outrun it. The Subscription is an
AsyncIterable<SubscribeResponse>: read it once with for await; a stream failure or an
aborted signal rejects the loop. End it with close() or await using, which ends the
loop cleanly.
await using sub = await client.subscribe(["my-topic"]);
// Live from here: publish requests now, their replies cannot be missed.
for await (const evt of sub) {
console.log(evt.topic, evt.cloudevent?.type);
}
State Operations
saveState(service: string, key: string, value: string, opts?: {
etag?: string; publishChange?: boolean; includeValue?: boolean;
ttlSeconds?: number; createOnly?: boolean;
}): Promise<SaveStateResponse>
getState(service: string, key: string): Promise<GetStateResponse>
deleteState(service: string, key: string, opts?: {
etag?: string; publishChange?: boolean; includeValue?: boolean;
}): Promise<DeleteStateResponse>
queryState(service: string, query: string, limit?: number): Promise<QueryStateResponse>
getBulkState(service: string, keys: string[]): Promise<GetBulkStateResponse>
deleteBulkState(service: string, keys: string[], publishChange?: boolean): Promise<DeleteBulkStateResponse>
service selects the Dapr state store and must name a registered service (exact,
case-sensitive). It is not a namespace — see
security.md.
Writes report failure in-band: the gRPC call succeeds and
response.status.successisfalse. Check it — catching thrown errors alone will read a failed save as a success.deleteBulkStateadditionally returnsfailedKeyson partial failure, so you can retry the stragglers rather than the whole batch.
Trigger Operations
scheduleTrigger(name: string, targetTopic: string, opts?: {
schedule?: string; dueTime?: string; repeats?: number; ttl?: string; ownerWorkerId?: string;
}): Promise<ScheduleTriggerResponse>
getTrigger(name: string): Promise<GetTriggerResponse>
deleteTrigger(name: string): Promise<DeleteTriggerResponse>
listTriggers(ownerWorkerId?: string): Promise<ListTriggersResponse> // all, or only that worker's
schedule is a 6-field cron expression or an @every duration. When the trigger fires,
the API publishes an empty CloudEvent to targetTopic.
Config Operations
listConfigServices(): Promise<ListConfigServicesResponse>
getConfigService(name: string): Promise<GetConfigServiceResponse>
listConfigServices returns every registered entry including non-dialable ones (those
that exist only to resolve Dapr component names); listServices returns only the
backends the gateway can invoke.
Example — Publish:
import { create } from "@bufbuild/protobuf";
import { CloudEventSchema } from "./generated/cloudevents_pb.js";
const cloudevent = create(CloudEventSchema, {
id: crypto.randomUUID(),
source: "urn:my-app",
type: "my-event",
data: {
textData: JSON.stringify({ key: "value" }),
},
});
const response = await client.publish("my-topic", cloudevent);
console.log(`Published: ${response.status?.success}`);
Example — Request-Reply:
import { create } from "@bufbuild/protobuf";
import { CloudEventSchema } from "./generated/cloudevents_pb.js";
const cloudevent = create(CloudEventSchema, {
id: crypto.randomUUID(),
source: "urn:my-app",
type: "my-command",
data: {
textData: JSON.stringify({ command: "status" }),
},
});
const response = await client.publishWithResult(
"worker-commands",
cloudevent,
"worker-responses",
{ timeout: 10000 }
);
const decoder = new TextDecoder();
console.log(`Response: ${decoder.decode(response.cloudevent!.data!.textData)}`);
Example — Subscribe:
const events = client.subscribe(["workmanager"], ["updates"], ["created"]);
for await (const event of events) {
console.log(`Event: ${event.service}/${event.topic}`);
const decoder = new TextDecoder();
console.log(`Data: ${decoder.decode(event.data)}`);
}
Note on broadcast semantics: Pubsub.Subscribe is a per-API-process broadcast subscription — multiple in-process callers on the same topic all receive every message (per the Pub/Sub Topics spec §Subscription Implementation Pattern). If you need competing-consumer semantics, configure your Dapr component to use a consumer group (pubsub.kafka with a group, pubsub.rabbitmq with a queue).
Resource usage: publishWithResult shares one persistent gRPC pubsub.subscribe stream per reply topic across all callers (started lazily on first use, reconnecting with backoff if it drops) and demuxes responses by correlationid. The underlying Dapr subscription is created once and stays warm; per-call cost is one pending waiter entry. Readers are cancelled by close().
Resource Management
The client uses gRPC-web transport which manages connections automatically. No explicit close/dispose methods are required.
Dynamic Dispatch
The TypeScript client uses string-based method dispatch (no client.gateway.<service>.<method>() syntax — that pattern is only available in C# and Python). Pass the service name, method name, and JSON-serialized request as strings. The Gateway's InvokeJson RPC deserializes the JSON, runs the backend RPC, and returns a JSON-serialized response (the responseData field of InvokeJsonResponse).
The responseData field is a JSON string and must be parsed before use:
const resp = await client.invokeJson("workmanager", "ListWorkers", "{}");
const data = JSON.parse(resp.responseData ?? "{}");
// data.workers is the array of WorkerInfo messages
WorkManager
import { ApiClient } from "@virtufin/api";
const client = new ApiClient({ url: "http://localhost:5001" });
// ListWorkers — no request fields
const workersResp = await client.invokeJson("workmanager", "ListWorkers", "{}");
const workers = JSON.parse(workersResp.responseData ?? "{}").workers ?? [];
for (const w of workers) {
console.log(` ${w.id}: ${w.status} (${w.language})`);
}
// CreateWorker — CodeSource oneof (url | content), mime_type, topic
const createResp = await client.invokeJson("workmanager", "CreateWorker",
JSON.stringify({
code_source: { url: "https://example.com/worker.py" },
mime_type: "text/x-python",
topic: "worker-commands",
}),
);
const workerId = JSON.parse(createResp.responseData ?? "{}").id;
await client.invokeJson("workmanager", "StartWorker",
JSON.stringify({ id: workerId }),
);
A WebSocket connection (WebSocketFeed worker)
A WebSocket connection is a WebSocketFeed worker
of the WorkManager: create and start it, talk to it with InvokeWorkerCommand
(serve, send, publish, unpublish, status), remove it with DeleteWorker; a feed serving market topics takes its topics and topicitems from a market-data-devkit venue preset (feeds.config, or feeds.resolve/feeds.apply in Python).
const feedResp = await client.invokeJson("workmanager", "CreateWorker",
JSON.stringify({
code_source: { url: "<Virtufin.Worker.WebSocketFeed .nupkg URL>" },
mime_type: "application/x-dotnet-dll",
topics: ["wrk.websocketfeed.command.{worker_id}"],
config: { url: "wss://stream.example.com/feed", autoreload: "false", publishtopic: "x.examples.feed" },
}),
);
const feedId = JSON.parse(feedResp.responseData ?? "{}").id;
await client.invokeJson("workmanager", "StartWorker", JSON.stringify({ id: feedId }));
// InvokeWorkerCommand — payload is bytes (base64 in JSON); returns {"outputs": [...]}
const statusResp = await client.invokeJson("workmanager", "InvokeWorkerCommand",
JSON.stringify({ id: feedId, command: "status" }),
);
// DeleteWorker — closes the socket
await client.invokeJson("workmanager", "DeleteWorker", JSON.stringify({ id: feedId }));
Note: C# and Python expose the client.<service>.<method>(...) /
client.gateway.<service>.<method>(...) syntax. The TypeScript wrapper
deliberately uses string-based dispatch (see
proto-to-client-mapping spec
§Known Gaps #1) — the @connectrpc/connect transport doesn't have a clean
equivalent of DynamicObject / __getattr__ for runtime method resolution.
Generated Protos
The client includes generated protobuf classes from gateway_pb:
| Type | Description |
|---|---|
InvokeRequest |
Request for Invoke RPC |
InvokeResponse |
Response from Invoke RPC |
InvokeJsonRequest |
Request for JSON invocation |
InvokeJsonResponse |
Response from JSON invocation |
ListServicesRequest |
Request to list services |
ListServicesResponse |
List of available services |
ListMethodsRequest |
Request to list methods |
ListMethodsResponse |
List of methods for a service |
GetMethodSchemaRequest |
Request for method schema |
GetMethodSchemaResponse |
Schema details |
SubscribeRequest |
Subscribe to topics |
SubscribeResponse |
Event from subscription (topic + cloudevent) |
Example using generated protos:
import * as protos from "./generated/gateway_pb.js";
import { Gateway } from "./generated/gateway_connect.js";
// Create a custom request
const req = new protos.InvokeRequest({
service: "workmanager",
method: "ListWorkers",
requestData: new Uint8Array()
});
Naming Fragment
The package ships the api's naming fragment, virtufin.service.api (the state-change,
trigger and topic-catalog topics, the publication fence), as NAMING_FRAGMENTS (file name
to YAML text), the same file the C# and Python packages carry. TypeScript has no fragment
discovery, so compose it with @virtufin/naming:
import { FragmentDocument, NameRegistry } from "@virtufin/naming";
import { NAMING_FRAGMENTS } from "@virtufin/api";
const names = NameRegistry.compose(
Object.entries(NAMING_FRAGMENTS).map(([file, text]) => FragmentDocument.parse(text, file)),
);
const saved = names.entity("virtufin.service.api/state").topic("saved");
Error Handling
Invocation Errors
When method invocation fails, the client throws a ConnectError:
try {
const response = await client.invoke("workmanager", "UnknownMethod", new Uint8Array());
} catch (error) {
if (error instanceof ConnectError) {
console.log(`Invocation failed: ${error.message}`);
console.log(`Code: ${error.code}`);
}
}
Connection Errors
Connection failures throw standard network errors:
try {
const client = new ApiClient({ url: "http://invalid-host:5001" });
const services = await client.listServices();
} catch (error) {
console.log(`Connection failed: ${error.message}`);
}
Complete Example
import { ApiClient } from "@virtufin/api";
async function main() {
console.log("Virtufin API Client Demo");
console.log("========================\n");
const client = new ApiClient({ url: "http://localhost:5001" });
// Discover services
console.log("Available Services:");
const servicesResponse = await client.listServices();
for (const service of servicesResponse.services) {
console.log(` - ${service}`);
// List methods for each service
const methodsResponse = await client.listMethods(service);
for (const method of methodsResponse.methods.slice(0, 3)) {
const streaming = method.isServerStreaming ? " (stream)" : "";
console.log(` ${method.name}${streaming}`);
}
if (methodsResponse.methods.length > 3) {
console.log(` ... and ${methodsResponse.methods.length - 3} more`);
}
}
console.log();
// Invoke a method
console.log("Invoking workmanager.ListWorkers:");
try {
const encoder = new TextEncoder();
const response = await client.invoke("workmanager", "ListWorkers", encoder.encode(""));
const decoder = new TextDecoder();
console.log(`Response: ${decoder.decode(response.responseData)}`);
} catch (error) {
console.log(`Error: ${error}`);
}
}
main();
Protobuf Dependencies
The client library requires peer dependency:
{
"peerDependencies": {
"@bufbuild/protobuf": "^1.10.0"
}
}
Ensure your project installs the peer dependency:
npm install @bufbuild/protobuf
The proto files (gateway.proto, config.proto) are pre-compiled into the src/generated directory.