# chain-client-sdk-ts TypeScript client for a Ch∆In hub, for Node 20 and newer. It covers what a service in front of a hub needs: start a flow, follow it, ask what became of a detached run, list and decide approvals. The package ships the `chain.v1` `.proto` files verbatim from the platform repo and loads them at runtime, so there is no generated code that can drift from the contract. ```bash npm install chain-client-sdk-ts # not published yet: use a path or git dependency ``` ## Running a flow ```ts import { ChainClient, asText } from 'chain-client-sdk-ts'; const client = new ChainClient({ address: '127.0.0.1:50051', token: process.env.CHAIN_TOKEN, project: 'helloeco', }); const result = await client.submit({ flowYaml: await readFile('flows/verbrauchsausweis.yaml', 'utf8'), inputs: { consumption: { json: { kwh: 15400 } } }, idempotencyKey: stripeEvent.id, }); console.log(asText(result.outputs.report)); ``` Inputs: a string is text, an object tagged `json`, `bytes` or `file` is that kind, and any other object is sent as `json`. Outputs come back tagged, with `asText`, `asJson` and `asBytes` as readers. `idempotencyKey` is the caller's word for "this is the same request as before". A second submit with a key the hub has already seen returns the first run instead of starting a second one, which is what a payment webhook that retries needs. ## Following a run ```ts for await (const event of client.submitStream({ flowYaml, inputs })) { if (event.type === 'stepStarted') log.info({ step: event.step }, 'step started'); if (event.type === 'result') deliver(event.result.outputs); } ``` A run that fails throws a `ChainError` out of the loop, so the events seen so far stay valid and a failure is never a silent end of stream. Detached runs (`detach: true`) return once they have an id; `getStatus`, `getResult` and `cancel` take it from there. ## Approvals ```ts const waiting = await client.listApprovals({ project: 'helloeco' }); await client.decideApproval({ approvalId: waiting[0].approvalId, approve: true, reviewer: 'aussteller@example.org', }); ``` The hub records who decided and why. Where it can verify an identity behind the token, that identity wins over the `reviewer` field, so the field is a fallback and not a claim the hub trusts blindly. ## Errors Every failure is a `ChainError` with four fields worth branching on: | Field | What it says | |-------|--------------| | `kind` | the hub's own class: `flow_rejected`, `step_failed`, `step_timeout`, `approval_rejected`, `approval_timeout`, `unavailable`, `overloaded`, `precondition`, `not_found`, `conflict`, `forbidden`, `unauthenticated`, `timeout`, `cancelled`, `internal`, or `unknown` from a newer hub | | `family` | the coarse branch: `unreachable`, `rejected`, `failed`, `overloaded`, `auth`, `timeout`, `cancelled`, `internal` | | `reachedHub` | whether the hub answered at all | | `retryable` | true for `unreachable`, `overloaded` and `timeout` | `reachedHub` is the field that keeps a gateway honest. A refused connection and a hub reporting "the model host is down" both arrive as gRPC `UNAVAILABLE`; only the second one carries a class, so only the second one is the hub's own answer. The class travels in the `chain-error-kind` trailer of every error response (hub 0.25 and newer) and in `StreamError.kind` inside a stream. ## Testing against a fake hub The package carries a scriptable hub that speaks the same service from the same `.proto` files, so a gateway's tests need no hub binary, no module and no model. ```ts import { FakeHub } from 'chain-client-sdk-ts/fake-hub'; const hub = new FakeHub(); const address = await hub.start(); hub.succeeds({ report: 'zugestellt' }); // the next run finishes hub.fails('overloaded', 'too many runs'); // the next run is refused hub.waitsForApproval({ prompt: 'Zustellen?' }); // the next run waits await hub.stop(); // the hub is gone await hub.restart(); // it comes back, without the running runs ``` `hub.submits` and `hub.decisions` record what arrived, so a test can assert on what the gateway sent, not only on what it got back. `restart()` models what today's hub really does: run state lives in memory and is lost, while approvals live in SQLite and survive. A gateway has to treat "approval still pending after a restart" as a run it must start again. ## Development ```bash npm install npm test # type-check, then the hermetic suites npm run build # dist/ # the skew gate: the same client against a real hub binary CHAIN_BIN=../fai_chain/target/debug/chain npm test # refresh the contract after a platform change node scripts/sync-proto.mjs ../fai_chain ``` `npm test` runs the fake-hub suite, the payload and error-class unit tests, and the guard that the `.proto` copies still match both their recorded hashes and the platform repo. The real-hub suite skips itself when no binary is there. `.forgejo/workflows/ci.yml` runs the same two things in CI: the hermetic suite on every push, and a skew job that downloads a *released* hub and runs this client against it, because a client has to keep working against the hub operators actually run. The skew job needs the repository secret `CHAIN_RELEASE_READ_TOKEN` (a Forgejo job token cannot read release assets) and fails with that message rather than passing quietly when the secret is missing. ## License Apache 2.0. Copyright Dr. Stefan Flemming, Flemming.AI.