TypeScript Examples
TypeScript examples demonstrate the gateway's services through @virtufin/api, over native gRPC in Node.
Service SDKs
| Package | Registry |
|---|---|
@virtufin/api |
Gitea npm |
@virtufin/api reaches every service through the gateway: state and pub/sub directly, WorkManager (and the
WebSocketFeed workers it runs) with invokeJson. It publishes under the @virtufin scope, so ordinary version ranges work:
"dependencies": {
"@virtufin/api": "^0.14.1",
"@virtufin/naming": "^0.15.0",
"@connectrpc/connect-node": "^2.1.0",
"smol-toml": "^1.3.0"
}
The apiKey and transport options the cluster needs exist since 0.8.12. Pin
what the feed currently has (typescript/package.json is the reference): the
feed keeps only recent versions, so an old range stops installing.
npm install @virtufin/api
Scoping is what makes this possible. npm resolves a private registry per
scope and has no per-package mechanism, so the previous unscoped names
could not be installed by name at all -- a bare npm install virtufin-api
went to registry.npmjs.org, where the name is unclaimed. Consumers had to pin
direct Gitea tarball URLs. If you are upgrading from that form, replace the
URLs with the ranges above and rename the imports.
Authentication
Configure .npmrc (see typescript/.npmrc for the worked version):
@virtufin:registry=https://gitea.haenerconsulting.com/api/packages/virtufin/npm/
//gitea.haenerconsulting.com/api/packages/virtufin/npm/:_authToken=<token>
The host is gitea.haenerconsulting.com, not the npm.* vanity alias.
Gitea advertises dist.tarball on gitea.* whatever host you query, and npm
matches auth tokens by URL prefix -- so the npm.* form fetches metadata
authenticated and then downloads the tarball from gitea.* without a token.
Keeping both under one host lets a single token line cover them.
Connecting: the context
Each example sets CONTEXT_NAME near its top, "demo" by default: a name in
~/.config/virtufin/api/contexts.toml (see Getting Started).
examples/context.ts reads the entry and builds the client:
import { experimental } from "@virtufin/naming";
import { apiClient, describe, loadContext } from "./context.js";
const CONTEXT_NAME = "demo"; // or "local" for a deploy-local backend
const context = loadContext(CONTEXT_NAME);
console.log(describe(context)); // context demo: api.virtufin.com:443 tls=true key=set
const client = apiClient(context);
apiClient uses native gRPC (createGrpcTransport from @connectrpc/connect-node) on the context's port,
the gateway's gRPC port that the C# and Python clients use too, with apiKeyInterceptor for x-api-key.
Key Patterns
// State: the service must be one the gateway registers ("statestore" on demo and local).
await client.saveState("statestore", "my-key", JSON.stringify({ hello: "virtufin" }));
const got = await client.getState("statestore", "my-key");
// WorkManager through the gateway, with its JSON requests.
const call = async (service: string, method: string, request: object) =>
JSON.parse((await client.invokeJson(service, method, JSON.stringify(request))).responseData || "{}");
// A WebSocket connection is a WebSocketFeed worker. It knows no venue: its config is a
// market-data-devkit venue preset (examples/websocketfeed.ts reads a copy of feeds/binance.json),
// every value a string (JSON values as their JSON text). A feed normally serves topics, mapped
// to venue items by rules market-data-devkit renders from the naming fragments (C# and Python);
// the TypeScript naming package has only the core fragment, so this is a raw feed: a fixed
// subscribe frame sent on every open, every frame to its publishtopic.
const preset = JSON.parse(readFileSync("examples/feeds/binance.json", "utf8")).config as Record<string, unknown>;
const presetConfig = Object.fromEntries(Object.entries(preset).map(([k, v]) => [k, typeof v === "string" ? v : JSON.stringify(v)]));
const nupkg = "https://nuget.haenerconsulting.com/api/packages/virtufin/nuget/package/" +
"Virtufin.Worker.WebSocketFeed/0.3.0/Virtufin.Worker.WebSocketFeed.0.3.0.nupkg";
const { id } = await call("workmanager", "CreateWorker", {
code_source: { url: nupkg, credential: { named: "virtufin" } },
mime_type: "application/x-dotnet-dll",
topics: ["wrk.websocketfeed.command.{worker_id}"],
config: {
...presetConfig,
subscribe: JSON.stringify([{ method: "SUBSCRIBE", params: ["btcusdt@depth@100ms"], id: 1 }]),
publishtopic: experimental("examples", "websocketfeed", "depth", "BTC_USDT"),
autoreload: "false",
},
});
try {
await call("workmanager", "StartWorker", { id });
// Commands go through InvokeWorkerCommand; the answer's data is base64 JSON.
const status = await call("workmanager", "InvokeWorkerCommand", { id, command: "status", content_type: "application/json" });
} finally {
await call("workmanager", "DeleteWorker", { id }); // on demo, never leave a connection behind
}
TypeScript workers
A worker can itself be TypeScript: the WorkManager's TypeScript engine runs a module
(text/x-typescript) or an npm package (application/x-npm) in a Node subprocess on a
Runtime pod, with the lifecycle of every worker
(engines). The module
exports Start(ctx)/Process(event)/Stop() or default-exports a worker from
@virtufin/worker-devkit (TypeScript workers);
its bare imports are installed at load, at their latest versions. typescript-worker.ts
deploys the files in typescript/workers/ as they are:
const { id } = await call("workmanager", "CreateWorker", {
mime_type: "text/x-typescript",
topics: [experimental("examples", "typescript-worker", "greet")],
code_source: { content: Buffer.from(readFileSync("workers/greeter.mts", "utf8")).toString("base64") },
// Config entries fill every input's attributes and are the worker's ctx.config.
config: { replytopic: experimental("examples", "typescript-worker", "greeting") },
});
await call("workmanager", "StartWorker", { id });
The same worker runs locally under the devkit's LocalWorkManager with the cluster's rules.