# Vivi Applet SDK

A small JavaScript library and example code for implementing Vivi Applets.


## Getting Started

1. Install the library
```sh
$ npm install @viviedu/applet-sdk
```
OR
```sh
$ pnpm add @viviedu/applet-sdk
```
OR
```sh
$ yarn add @viviedu/applet-sdk
```

2. Initialise the applet
```ts
import * as sdk from '@viviedu/applet-sdk';

// User-defined type for messages
type Msg = { type: 'greet', name: string };

const applet = await sdk.newApplet<Msg>();

// If you're passing custom_params during startApplet:
// User-defined type for params
type Param = { background: string }

const applet = await sdk.newApplet<Msg, Param>();
```

Alternatively, if it's known whether the code is running on the box/client. You can use `sdk.newBoxApplet<T>()`/`sdk.newClientApplet<T>()` instead of `sdk.newApplet<T>()`.

3. Send a command

```ts
await applet.send({ type: 'greet', name: 'World' });
```

4. Listen to and handle commands

```ts
applet.listen((msg) => {
  if (msg.type === 'greet') {
    console.log(`Hello, ${msg.name}!`);
  }
});
```

5. Use applet features

```ts
// `getUserRoles` is available only for client applets, and only if permitted.
// If not permitted, the method will be set to `null`.
const userRoles = applet.isClient && applet.getUserRoles
  ? await applet.getUserRoles()
  : null;
```


## API Documentation

We have autogenerated documentation here: <https://viviedu.github.io/vivi-applet-sdk/docs>.


## Examples

We have a few self-contained examples that implement a simple but complete chat application.

- [React (using hooks)](https://github.com/viviedu/vivi-applet-sdk/tree/master/examples/chat-react-modern)
- [React (using class components)](https://github.com/viviedu/vivi-applet-sdk/tree/master/examples/chat-react-classic)


## Development

If you're working on the SDK directly, it'll be necessary to be logged in to NPM so that the private `@vivinews/vivi-eslint-config` package can be installed.

An easy way to do this is to create a `.npmrc` file in the root of the repo and paste the "shared install token" (from 1Password).

Example:
```
//registry.npmjs.org/:_authToken=npm_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
