# Titli Video SDK for the web and Node.js

[![npm](https://img.shields.io/npm/v/titli-video-sdk.svg)](https://www.npmjs.com/package/titli-video-sdk)

One package for both halves of a web integration:

| Import | Runs in | What it is |
|---|---|---|
| `titli-video-sdk` | the browser | `TitliCall.join(url, token)`: joins a call or watches a live stream, with live events, gifts and a small built-in viewer UI. Works with the open-source LiveKit web client. |
| `titli-video-sdk/server` | Node.js 20+ | `TitliClient`: a zero-dependency client for the REST API (calls, tokens, participants, usage, receipts, live streams, gifts), plus webhook and receipt verification. |

## Quickstart: no backend (Quick mode)

Copy the **App Key** (`tak_…`) from the console (Projects → Quick mode) and add your site's origin there. The App Key
is not a secret: it only reaches the end-user routes, is bound to your origins and is fenced by spend and usage caps.

```js
import { TitliVideo } from 'titli-video-sdk';

TitliVideo.init({ appKey: 'tak_…', userId: 'user-42', userName: 'Asha' });
const call = await TitliVideo.startCall({ type: 'video', container: '#stage' });   // share call.callId
// the other person: await TitliVideo.joinCall(callId, { container: '#stage' });
```

Want full control from your own server instead? Use **Secure mode** below: your server mints tokens with its API key.


**How it fits together**

1. Your **server** holds the project API key (`key_id` + `key_secret`) from the [console](https://console-videosdk.titliapp.com).
2. When a user starts a call, your server creates the call and mints a token (`titli-video-sdk/server`).
3. Your server sends the `token` and `livekit_url` to the page.
4. The page joins with `TitliCall.join(livekitUrl, token)`.

Never put the key secret in a web page. Billing happens on our servers from the media server's own join and leave
events; nothing the page reports changes what is billed.

## Install

```sh
npm i titli-video-sdk livekit-client
```

`livekit-client` is needed only in the browser (a peer dependency; the server part has no dependencies).
Without a bundler, load both from a CDN:

```html
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2.15.6/dist/livekit-client.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/titli-video-sdk@0.2.0/titli-call.js"></script>
<!-- global: TitliCall -->
```

## Server: create a call and mint a token

```js
import { TitliClient } from 'titli-video-sdk/server';

const titli = new TitliClient({ keyId: process.env.TITLI_KEY_ID, keySecret: process.env.TITLI_KEY_SECRET });

// e.g. POST /calls/start in your own API, for a signed-in user
const call = await titli.createCall({ type: 'video', payerEndUserId: 'user_1001' });
const t = await titli.token(call.id, { endUserId: 'user_1001', role: 'user', name: 'Ravi' });
// send { livekit_url: t.livekit_url, token: t.token, call_id: call.id } to the page
```

## Browser: join

```js
import * as LivekitClient from 'livekit-client';
import TitliCall from 'titli-video-sdk';

const { livekit_url, token } = await (await fetch('/calls/start', { method: 'POST' })).json();
const session = await TitliCall.join(livekit_url, token, {
  livekit: LivekitClient,          // not needed when livekit-client is loaded as a global <script>
  container: '#stage',             // remote video (call) or the viewer UI (live stream) goes here
  onDisconnected: (e) => console.log('ended:', e.reason, e.userMessage),
});
// later
await session.leave();
```

Call mode turns on the microphone and, when the token allows it, the camera. A subscribe-only viewer token (from
`POST /v1/live-streams/:ref/join`) joins in viewer mode: nothing is published and no permission is asked.

Examples in this repository: `examples/browser/` (plain HTML) and `examples/node/` (call flow, webhook server, gifts
server). Full sample apps: https://github.com/titli-video-sdk.

## Server reference

Every method returns the API's JSON, and a non-2xx answer throws `TitliError` with `status`, `code`, `userMessage`
(a neutral sentence you can show your user as is), `userCode` and `error` (the API's whole error object):

```js
import { TitliClient, TitliError } from 'titli-video-sdk/server';

try {
  const t = await titli.token(callId, { endUserId: 'user_1001', role: 'user', name: 'Ravi', ttlSeconds: 600 });
  // t.token, t.livekit_url, t.expires_at, t.call_id, t.room, t.identity, t.role, t.type, t.max_video_resolution
} catch (e) {
  if (e instanceof TitliError && e.code === 'call_ended') { /* 409: the call is over; create a new call */ }
  else if (e instanceof TitliError && e.status === 402) { /* balance too low, or the project's daily cap */ }
  else throw e;
}
```

`ttlSeconds` (30 to your project's limit, normally 3600; default 600) limits when the token can be used to join, not
how long the call lasts. A token for a `type: "audio"` call can publish the microphone only.

Webhooks: `verifyWebhook(rawBody, req.headers['titli-signature'], process.env.TITLI_WEBHOOK_SECRET)` checks the
signature and rejects old deliveries. Receipts: `verifyReceipt(receipt, signature, publicKeyPem)` with the key from
`titli.publicKey()`. The REST API itself: [REST API reference](https://videosdk.titliapp.com/docs/rest-api). Plain cURL calls: `curl.md`.


## Live Hosts

The same join works for Live Hosts calls (your users calling Titli hosts): your server calls
`POST /v1/live-hosts/calls` and returns `livekit_url` and `token`; join with livekit-client `room.connect(livekitUrl, token)` in the browser, or any of our mobile SDKs.
No SDK change is needed. See [Live Hosts docs](https://videosdk.titliapp.com/docs/live-hosts).

## Viewer mode (Live Streamers Pool)

Watch a Titli host's live stream inside your app. The host's video and audio are relayed into a room `ls_<id>` as the participant `ls_host`. A viewer publishes nothing: no camera or microphone prompt, no local preview. The prebuilt screen shows her video full-screen with a small Titli watermark, the latest chat lines, gift toasts, a host-away banner, the viewer count, a leave button and an end message.

### 1. Get a viewer token on your server

Your backend (never the app) asks for a viewer token for one of your users:

```sh
curl -u "$TITLI_KEY_ID:$TITLI_KEY_SECRET" -X POST \
  https://api-videosdk.titliapp.com/v1/live-streams/<stream_ref>/join \
  -H 'Content-Type: application/json' \
  -d '{"end_user_id":"user_1001","name":"Ravi"}'
# -> {"viewer_id":"…","token":"eyJ…","livekit_url":"wss://…","room":"ls_…","expires_at":"…"}
```

`stream_ref` comes from `GET /v1/live-streams`. Send `livekit_url` and `token` to the app. The token is
subscribe-only (LiveKit grant `canPublish:false`, `canPublishData:false`, `canSubscribe:true`); the SDK sees that
and joins in viewer mode. Billing runs per second on our servers while the viewer is in the room and the host is on
air. Renew with `POST /v1/live-streams/:ref/token` before `expires_at`; call `…/leave` when the user closes the live.
Comments and gifts go through your server too (`…/comments`, `…/gifts`); they come back to every viewer as live events.
Gifts have their own section below.

### 2. Join as a viewer

Server side with this client:

```js
const v = await titli.joinLiveStream(streamRef, { endUserId: 'user_1001', name: 'Ravi' });
// send v.livekit_url and v.token to the browser or app; later:
await titli.renewLiveStreamToken(streamRef, { endUserId: 'user_1001' });
await titli.leaveLiveStream(streamRef, { endUserId: 'user_1001' });
```

Browser (`../browser/titli-call.js`, no build step; `../browser/viewer.html` is a working page):

```html
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2.15.6/dist/livekit-client.umd.js"></script>
<script src="titli-call.js"></script>
<div id="stage" style="height:80vh"></div>
<script type="module">
  // type="module" allows the top-level await; livekitUrl and viewerToken come from YOUR server
  const session = await TitliCall.join(livekitUrl, viewerToken, {
    container: '#stage',              // renders the viewer UI here
    mode: 'viewer',                   // optional: detected from the token
    onLiveEvent: (e) => console.log(e.type, e),
    onDisconnected: ({ reason }) => console.log('left', reason), // left | ended | kicked | server | removed | lost
  });
  session.on('live:gift', (e) => console.log(e.gift));
  // session.state: { connected, ended, viewers, hostAway, chat, liveEnd, host }; session.leave()
</script>
```

Helpers: `TitliCall.isViewerToken(token)`, `TitliCall.parseLiveEvent(data)`, `TitliCall.LIVE_TOPIC`. The browser join
example (`index.html`) also publishes nothing when given a viewer token.

### Live events

LiveKit data messages on topic `titli.live`, JSON `{type, …}`. Unknown types and malformed messages are ignored.

| type | fields | the prebuilt screen |
|---|---|---|
| `chat` | `id`, `at`, `from:{name, role}`, `text` (`role` = `host`, `viewer` or `partner`) | shows the last 5 lines |
| `gift` | `id`, `at`, `from:{name, role, endUserId}`, `gift:{giftId, name, iconUrl, animationUrl, count}` | toast "name sent N x Gift" |
| `host_away` / `host_back` | none | shows / clears the "host stepped away" banner |
| `viewers` | `viewers` (count) | viewer count in the top bar |
| `ended` | `reason` (`host_ended`, `admin_terminated`, …) | end message, then leaves after 3 s |
| `kicked` | `reason` | "removed" message, then leaves after 3 s |

On the wire the keys are snake_case (`gift_id`, `icon_url`, `animation_url`, `end_user_id`); `parseLiveEvent` gives
the camelCase shape above. `from.endUserId` is set only for your own users.

Call mode is unchanged: a normal call token behaves exactly as before. One event reaches a call too: `gift`, for
the gifts its own user sent (see Gifts).

## Gifts

Your users can send gifts to the Titli host they are in a call with, or whose live stream they watch. The gift list
is ours; you choose which gifts to show and what each one costs your user. Full reference: [Gifts docs](https://videosdk.titliapp.com/docs/gifts).

The browser never talks to our API for gifts. Your server lists the gifts and sends them with your API key; the
page gets the list from your server and asks your server to send.

### 1. Your server: the list and the send

`examples/node/gifts-server.mjs` is a complete example (the list, a send, the webhook and a clean-up for sends that stayed
open). The two calls:

```js
import { TitliClient, TitliError, giftsForApp, giftErrorForApp, giftRefusedBeforeDebit } from 'titli-video-sdk/server';

// The list. It carries your cost, your price and what you keep for every gift: keep that on your server.
// giftsForApp() leaves only what your user needs: gift_id, name, icon_url, animation_url, category, price, currency
// (and enabled, version, max_count).
const list = await titli.gifts();
res.json(giftsForApp(list));          // never send `cost` or `you_keep` to the app

// A send. The price is the one of YOUR list on your server, not a number the app sent.
const gift = list.gifts.find((g) => g.gift_id === giftId && !g.hidden);
if (!gift) return res.status(400).json({ error: { code: 'gift_unavailable' } });
const price = gift.price;
// The charge is keyed by client_request_id and remembers what it was for. A repeat of the same gift charges nothing
// more; the same ID for another gift, count or call is refused here, before anything is charged or sent.
if (!(await chargeYourUser(userId, price * count, { id: clientRequestId, what: `${callId}/${giftId}/${count}` }))) {
  return res.status(409).json({ error: { code: 'gift_idempotency_conflict' } });   // nothing to give back
}
try {
  // Always send expected_price = the price you charged, and the app's client_request_id unchanged.
  const sent = await titli.sendCallGift(callId, { giftId, count, clientRequestId, expectedPrice: price });
  // or: await titli.sendLiveStreamGift(streamRef, { endUserId, giftId, count, clientRequestId, expectedPrice: price });
  // "sent": done. "pending" (HTTP 202): keep the payment; gift.sent or gift.failed follows.
  res.status(sent.status === 'pending' ? 202 : 200).json({ id: sent.id, status: sent.status });
} catch (e) {
  if (!(e instanceof TitliError)) return res.status(502).json({ error: { code: 'unknown' } }); // no answer: keep the payment
  if (e.error.refunded === true || giftRefusedBeforeDebit(e)) await giveBack(clientRequestId); // the only two refunds here
  res.status(e.status).json(giftErrorForApp(e));       // { error: { code, user_message, user_message_hi?, user_code, refunded?, price? } }
}
```

**When your user gets their money back.** Only in these cases:

| Our answer | Your user's payment |
|---|---|
| `201` / `200` with `"status": "sent"` | Keep it |
| `202` with `"status": "pending"` | Keep it for now. `gift.sent` (keep) or `gift.failed` (give back) follows; you can also repeat the request with the same `client_request_id` or read `giftSends({ client_request_id })` |
| An error with `"refunded": true` | Give it back. The answer is final; a new try is a new gift with a new `client_request_id` |
| A `4xx` refusal: `gifts_disabled`, `gift_unavailable`, `gift_price_changed`, `gift_host_unavailable`, `gift_not_in_session`, `insufficient_balance`, `invalid_request` (`giftRefusedBeforeDebit(e)`) | Give it back: nothing was debited |
| `409 gift_idempotency_conflict` | **Do not give anything back.** That `client_request_id` belongs to an earlier gift, and that gift stands. Refuse it on your server before you charge |
| `429`, a `5xx` without `"refunded": true`, a timeout, no answer | **Keep it.** The gift may still be delivered and billed. Repeat the request with the **same** `client_request_id` (after `Retry-After` for a 429), or wait for the webhook |
| Webhook `gift.failed` (`{ gift, refunded: true }`) | Give it back, by `gift.client_request_id` |

Never give the money back just because the status is 400 or above.

```js
// Webhooks (verify Titli-Signature first, as in examples/node/webhook-server.mjs)
if (ev.event === 'gift.sent')   await markFinal(ev.data.gift.client_request_id);
if (ev.event === 'gift.failed') await giveBack(ev.data.gift.client_request_id);   // ev.data.refunded === true
```

Other gift calls of the client: `giftSettings()`, `updateGiftSettings({ enabled, defaultMarkupPct })`,
`updateGift(giftId, { hidden, price })`, `giftSends({ call_id | stream_ref | end_user_id | client_request_id })`, `giftSend(id)`,
`giftStats({ group })`.

### 2. The page

```js
const giftList = await (await fetch('/gifts')).json();           // from YOUR server
const session = await TitliCall.join(livekitUrl, token, {
  container: '#stage',
  giftCatalog: giftList,
  onSendGift: async (request) => {                                // ask YOUR server to send
    const r = await fetch(`/calls/${callId}/gifts`, { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(request) });   // { gift_id, count, client_request_id, expected_price }
    const body = await r.json();
    if (!r.ok) throw { status: r.status, ...body };   // { error: { code, user_message, … } } becomes a TitliGiftError
    return body;
  },
  onLiveEvent: (e) => { if (e.type === 'gift') playAnimation(e.gift.animationUrl); },
});
```

With a list that is on (`enabled: true`, at least one gift) and `onSendGift` set, a gift button appears in the
container, in a call and in viewer mode. It opens a small sheet: the gifts with their icon, name and your price, a
count (1 to `max_count` of the list, 99 when the list does not say) and Send. Without either, nothing is added. After
the call or live ended the button is gone and `send` rejects with `gift_not_in_session`. Colours come from the CSS variables `--titli-accent`,
`--titli-sheet-bg` and `--titli-sheet-ink` on the container; texts from `strings` (`gifts`, `sendGift`,
`sendingGift`, `giftFailed`, `giftSentByYou`, …).

Your own gift UI uses the same object, `session.gifts`:

| Member | Meaning |
|---|---|
| `enabled`, `list`, `version`, `currency`, `maxCount` | Is the list on (false when the list has no `enabled`), the gifts to show with your prices, the list's version, and the most gifts in one send |
| `setCatalog(json)` | Set or replace the list (what your server relayed); `null` clears it. The short `{ enabled, version }` object is treated as `applyBrief` |
| `isStale(brief)` / `applyBrief(brief)` | For the short `gifts: { enabled, version }` of a call-create or stream-join answer. `isStale` says whether your list has another version. `applyBrief` switches `enabled`, sets `needsReload` when stale, keeps the list, and returns true when you should fetch the list again |
| `canSend` | `enabled`, `onSendGift` is set, and the call or live has not ended (`ended`) |
| `send(gift, count)` | Makes a unique `clientRequestId` (UUID), calls `onSendGift(request)` and resolves with its result |
| `pendingRequest` / `clearPending()` | The request whose outcome is not known yet (no answer, 429, 5xx, or a result with `status: 'pending'`). Sending the same gift and count again repeats its `clientRequestId`. It is cleared by a clear answer, by the `gift` event of this user, or by `clearPending()` |
| `sending`, `lastRequest`, `lastError`, `needsReload` | State; `needsReload` is true after `gift_unavailable`, `gift_price_changed` or a stale brief: fetch the list again |
| `on('change' \| 'sent' \| 'error' \| 'reloadNeeded', fn)` | Events. `reloadNeeded` gets `{ code, giftId, price }`; the join option `onGiftsReloadNeeded` is the same |

```js
try {
  await session.gifts.send(session.gifts.list[0], 3);
} catch (e) {                                  // a TitliGiftError
  showToast(e.userMessageFor() || 'This gift could not be sent.');   // Hindi (user_message_hi) on a Hindi page, else English
  // e.retryable: the outcome is not known (no answer, 429, 5xx). Sending the same gift and count again reuses
  // e.request.clientRequestId, so it can never be charged twice.
  // e.refunded: the gift was not delivered and nothing stays charged. Final, like every other clear answer: the
  // next send is a new gift with a new id.
}
```

Keep the list fresh with the join option `onGiftsReloadNeeded` (or `session.gifts.on('reloadNeeded', …)`):

```js
onGiftsReloadNeeded: async ({ code, giftId, price }) => {     // gift_unavailable | gift_price_changed | version_changed
  session.gifts.setCatalog(await (await fetch('/gifts')).json());
},
```

After `gift_price_changed` the sheet already shows the new price from the answer (`price`), so your user sees it
and taps Send again to confirm. When your server answers `202` (`status: 'pending'`), resolve `onSendGift` with that
body: the gift is on its way, the user's payment is kept, and the `gift` event arrives in the call when it is
confirmed.

In viewer mode the toast says "You sent…" only for the gifts of this user. The user is read from the join token;
pass `endUserId` in the join options if you mint tokens another way.

`e.code` is one of `insufficient_balance`, `gifts_disabled`, `gift_unavailable`, `gift_price_changed`,
`gift_host_unavailable`, `gift_idempotency_conflict`, `gift_not_in_session`, `rate_limited`, `partner_unavailable`,
`invalid_request`, `unknown` (`TitliCall.GIFT_ERROR_CODES`). `partner_unavailable` is what a 503 carries; the older
name `service_unavailable` is read as the same code. `e.legacyCode` is `error.legacy_code` when your server relayed
it.

Helpers: `TitliCall.parseGiftCatalog(json)`, `TitliCall.formatGiftPrice(price, currency)`,
`TitliCall.newClientRequestId()`, `TitliCall.giftRequestBody(request)`, `TitliCall.TitliGiftError.from(body)`.
Tests: `node --test ../browser/test/gifts.test.js`.

## Links

- Website and docs: https://videosdk.titliapp.com
- Console (API keys): https://console-videosdk.titliapp.com
- Samples: https://github.com/titli-video-sdk
- Issues: https://github.com/titli-video-sdk/titli-video-sdk-js/issues
- Contact: hello@titliapp.com
