# TypeScript SDK

> Record and replay Node handlers with @kavachlabs/kavach. Node 22 or later, ESM, no runtime dependencies.

```bash
cd sdk/typescript && npm install && npm run build   # from a checkout of the Kavach repository
```

```ts
import { Recorder, maybeHost, Panic, HandlerError, GatewayError, type Handler } from "@kavachlabs/kavach";
```

Node 22 or later. ESM. No runtime dependencies. Works for JavaScript and TypeScript services.

## Handler

```ts
const handler: Handler = {
  async handle(env, input) {
    const at = env.now();                           // sync, recorded
    const id = env.random(8);                       // sync, recorded
    const flag = env.config("flag.beta");           // sync, Uint8Array | undefined
    const rate = await env.query("fx-rates", req);  // async, rejects with GatewayError
    env.emit("postgres:balances", bytes);           // delivered after the step succeeds
  },
  snapshot() { return bytes; },                     // optional
  restore(data) {},                                 // optional
  invariants() {                                    // optional
    return [{ name: "non_negative", check() { if (balance < 0) throw new Error(`balance ${balance}`); } }];
  },
};
```

Use `env` instead of `Date.now`, `Math.random` or `crypto`, `fetch`, and `process.env` for anything that can change what the handler does. `env` is invalid after its step ends.

## Async and ordering

- `now`, `nowNanos`, `random`, `config` and `emit` are synchronous.
- `query` returns a promise, but its place in the journal is reserved when `query()` is **called**, not when it resolves. `Promise.all([env.query(a), env.query(b)])` records `a` then `b` however the responses arrive.
- The order of reads must not depend on timing.
- Steps are serialised.

## Failures

| The handler | Marker | Message |
| --- | --- | --- |
| throws an `Error` | `panic` | `` `${err.name}: ${err.message}` ``, stack as data |
| throws a non-Error `x` | `panic` | `String(x)` |
| throws `new Panic(msg)` | `panic` | exactly `msg` |
| throws `new HandlerError(msg)` | `error` | exactly `msg` |
| ends ok but an invariant fails | `invariant` | the invariant's name |

## Recording

```ts
const rec = await Recorder.start({
  service: "ledger",
  handler,
  gateways: { "fx-rates": { call: (req) => fx.get(req), scope: "remote" } },
  deliver: async (outputs) => { for (const o of outputs) await sinks.write(o.sink, o.data); },
});

const result = await rec.step({ source: "kafka:wallet-events", position: "3:1042", data });
// never throws for handler failures; check result
await rec.flush({ durable: true });
await rec.close();
```

Options: `recorderCommand` (argv; else `KAVACH_RECORDER`; else `kavach-recorder` on `PATH`), `required`, `gateways`, `config`, `flags`, `deliver`, `log`, `snapshot` (start from a snapshot), journal settings (`dir`, `compression`, …), and `clock` / `random` overrides.

If the recorder cannot start, dies or reports a fatal error, the SDK logs loudly and keeps running steps. `required: true` makes `Recorder.start` reject instead.

## Replay host

```ts
await maybeHost(() => handler, { gateways });   // first thing in main
```

When the last argument is `kavach-host`, the process serves the CLI and exits. In host mode, `console.log`, `console.info`, `console.debug` and `process.stdout.write` go to stderr.

```bash
kavach replay incident.kavach --bin "node dist/main.js"
kavach diff incident.kavach --old "node /tmp/old/dist/main.js" --new "node dist/main.js"
```

## Example

From `sdk/typescript`, after the build above:

```bash
node dist/examples/ledger/main.js --in ../../examples/ledger/testdata/events.jsonl            # buggy
node dist/examples/ledger/main.js --in ../../examples/ledger/testdata/events.jsonl --fixed    # fixed
```

Source: https://www.thekavachlabs.com/docs/sdks/typescript
