# The host API

> What your extension's code can call, on which side, with which permission, and the rules every call follows.

Page: https://songstress.app/docs/develop/api/

The API is one object, `songstress`, imported from the entry the code is written for:

```ts title="src/server.ts"
import { songstress } from 'songstress/server' // the server entry
```

`songstress/client` is the client entry's, and `songstress` alone is what both have. The
[API reference](/docs/develop/reference/songstress/) has every type.

## The namespaces [#the-namespaces]

The server entry's `songstress`:

The API of the server entry: code that runs on the user's own server, in
a sandbox, for every member and every app.

| Field | Type | Description |
|---|---|---|
| `hooks` | `ServerHooks` | What happens on the server, for every member who granted it: plays, favourites, library changes. |
| `ui` | `ServerUi` | The renderers of the extension's pages, panels and status items, and notices and refreshes for one member. |
| `settings` | `ServerSettings` | The extension's settings, the server's and, with `{ userId }`, each member's. |
| `storage` | `ServerStore` | The extension's own small store, as a whole and for each member. Permission `storage`. |
| `secrets` | `Secrets` | Sealed credentials. Permission `secrets`. |
| `providers` | `Providers` | One registry for each kind of source the extension adds. Permission `providers`. |
| `jobs` | `Jobs` | The handlers of declared jobs, and starting a run. Permission `jobs`. |
| `routes` | `Routes` | The handlers of declared routes. Permission `routes`. |
| `signIn` | `SignInRegistry` | The handler of the declared sign-in. Permission `secrets`. |
| `library` | `Library` | Reading the library. Permission `library.read`. |
| `users` | `Users` | Reading members' ids and names. Permission `users.read`. |
| `commands` | `Commands` | The handlers of the extension's declared commands. |
| `net` | `Net` | The only way to the network. Permission `network`. |
| `host` | `Host` | What the code runs in: the API version, the side, and on the client the app. |

The client entry's:

The API of the client entry: code that runs inside one app, in a sandbox,
for the member signed in there, while the app is open.

| Field | Type | Description |
|---|---|---|
| `hooks` | `ClientHooks` | This device's player, live, while the app is open. |
| `commands` | `ClientCommands` | The handlers of the extension's commands, and running one of its server commands. |
| `ui` | `ClientUi` | The renderers of the extension's pages, panels and status items, and notices in this app. |
| `player` | `Player` | This device's player. Permissions `listening.read` and `player.control`. |
| `queue` | `Queue` | This device's queue. Permissions `listening.read` and `player.control`. |
| `settings` | `Settings` | The extension's settings, as Songstress keeps them. |
| `storage` | `Store` | The extension's own small store. Permission `storage`. |
| `net` | `Net` | The only way to the network. Permission `network`. |
| `host` | `Host` | What the code runs in: the API version, the side, and on the client the app. |

## Rules for every call [#rules-for-every-call]

- **Registration gives back a disposable.** Every `on…` and every `register` returns an object with `dispose()`.
  Everything is disposed for you when the extension stops.
- **Calls to the host answer with a promise.** Registration is the exception: it is immediate.
- **One member at a time.** On the server one extension serves every member, so a call that concerns one names them:
  `songstress.settings.get('token', { userId })`, `songstress.storage.set(key, value, { userId })`. In an app the
  member is the one signed in and is never named. A member's part of the store is the part their own client code
  sees.
- **Failure has a code.** A call that fails rejects with a `SongstressError` whose `code` is one of: `no-host` (the
  code isn't running inside Songstress, as in a test without the mock host), `permission-denied`, `not-available`
  (this side, app or build can't do it), `limit-exceeded` (a quota, a size, a rate or a deadline), `invalid` (a wrong
  argument, or something that doesn't exist), `failed`.
- **The player is asked, not commanded.** `player` and `queue` requests are carried out as a tap on the app's own
  controls would be. Adding to the queue never touches what is playing.

## Every call and its permission [#every-call-and-its-permission]

Read from the SDK's own record of its API:

| Call | Entry | Permission |
|---|---|---|
| `songstress.hooks.onPlay` | both, server, client | `listening.read` |
| `songstress.commands.register` | both, server, client | None |
| `songstress.ui.pages.register` | both, server, client | None |
| `songstress.ui.panels.register` | both, server, client | None |
| `songstress.ui.status.register` | both, server, client | None |
| `songstress.settings.get` | both, server, client | None |
| `songstress.settings.onChange` | both, server, client | None |
| `songstress.storage.get` | both, server, client | `storage` |
| `songstress.storage.set` | both, server, client | `storage` |
| `songstress.storage.delete` | both, server, client | `storage` |
| `songstress.storage.keys` | both, server, client | `storage` |
| `songstress.net.fetch` | both, server, client | `network` |
| `songstress.host.info` | both, server, client | None |
| `songstress.hooks.onScrobble` | server | `listening.read` |
| `songstress.hooks.onFavorite` | server | `listening.read` |
| `songstress.hooks.onPlaylistChange` | server | `library.read` |
| `songstress.hooks.onLibraryChange` | server | `library.read` |
| `songstress.hooks.onScanComplete` | server | `library.read` |
| `songstress.ui.notify` | server, client | None |
| `songstress.ui.refresh` | server, client | None |
| `songstress.secrets.get` | server | `secrets` |
| `songstress.secrets.set` | server | `secrets` |
| `songstress.secrets.delete` | server | `secrets` |
| `songstress.providers.search.register` | server | `providers` |
| `songstress.providers.lookup.register` | server | `providers` |
| `songstress.providers.links.register` | server | `providers` |
| `songstress.providers.lyrics.register` | server | `providers` |
| `songstress.providers.metadata.register` | server | `providers` |
| `songstress.providers.artwork.register` | server | `providers` |
| `songstress.providers.artistInfo.register` | server | `providers` |
| `songstress.providers.scrobble.register` | server | `providers` |
| `songstress.providers.recommend.register` | server | `providers` |
| `songstress.providers.play.register` | server | `providers` |
| `songstress.providers.download.register` | server | `providers` |
| `songstress.jobs.register` | server | `jobs` |
| `songstress.jobs.start` | server | `jobs` |
| `songstress.routes.register` | server | `routes` |
| `songstress.signIn.register` | server | `secrets` |
| `songstress.library.getSong` | server | `library.read` |
| `songstress.library.getAlbum` | server | `library.read` |
| `songstress.library.getArtist` | server | `library.read` |
| `songstress.library.getPlaylist` | server | `library.read` |
| `songstress.library.getAlbumSongs` | server | `library.read` |
| `songstress.library.getPlaylistSongs` | server | `library.read` |
| `songstress.library.search` | server | `library.read` |
| `songstress.users.get` | server | `users.read` |
| `songstress.users.list` | server | `users.read` |
| `songstress.hooks.onPause` | client | `listening.read` |
| `songstress.hooks.onTrackChange` | client | `listening.read` |
| `songstress.hooks.onSeek` | client | `listening.read` |
| `songstress.hooks.onVolumeChange` | client | None |
| `songstress.hooks.onQueueChange` | client | `listening.read` |
| `songstress.hooks.onProgress` | client | `listening.read` |
| `songstress.commands.execute` | client | None |
| `songstress.player.getState` | client | `listening.read` |
| `songstress.player.play` | client | `player.control` |
| `songstress.player.pause` | client | `player.control` |
| `songstress.player.next` | client | `player.control` |
| `songstress.player.previous` | client | `player.control` |
| `songstress.player.seek` | client | `player.control` |
| `songstress.queue.get` | client | `listening.read` |
| `songstress.queue.add` | client | `player.control` |

## The network [#the-network]

`net.fetch(url, request)` is the only way out, to the hosts your `network` permission names (and, from the server,
the `network.local` targets). The address a name resolves to is checked when connecting and on every redirect.

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

const answer = await songstress.net.fetch('https://api.tunelog.example/v1/me', {
  method: 'GET',
  headers: { accept: 'application/json' },
  timeoutMs: 10_000,
})
if (answer.status === 200) console.log(JSON.parse(answer.body))
```

A request, as plain data.

| Field | Type | Description |
|---|---|---|
| `method?` | `"DELETE" \| "GET" \| "HEAD" \| "PATCH" \| "POST" \| "PUT" \| undefined` | Left out, "GET". |
| `headers?` | `Record<string, string> \| undefined` | Sent as given. Without a `User-Agent` of its own the request says `songstress-extension/<API version>`; one named here replaces it, for a service that asks a client to say who it is. |
| `body?` | `string \| undefined` | The request's body, written as `bodyEncoding` says. |
| `bodyEncoding?` | `"base64" \| "text" \| undefined` | How `body` is written: as text (the default) or as base64 for bytes. |
| `responseEncoding?` | `"base64" \| "text" \| undefined` | How the answer's body is wanted: text (the default) or base64. |
| `timeoutMs?` | `number \| undefined` | Give up after this long. The host has its own limit, which wins. |
| `redirect?` | `"follow" \| "manual" \| undefined` | Left out, "follow": each hop is held to the hosts granted. "manual" hands back the redirect itself. |

An answer, as plain data.

| Field | Type | Description |
|---|---|---|
| `status` | `number` | The HTTP status of the answer: 200, 404. |
| `url` | `string` | The address that answered, after redirects. |
| `headers` | `Record<string, string>` | Header names in lowercase. |
| `body` | `string` | The answer's body, as text or as base64, as the request's `responseEncoding` asked. |

## Storage and secrets [#storage-and-secrets]

`storage` keeps your extension's own data, as JSON, under a quota the host sets. `secrets` keeps credentials sealed:
only the server entry reads them, and no app ever sees one. On the server, pass `{ userId }` to keep something as one
member's.

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

declare const userId: string

await songstress.storage.set('waiting', [], { userId })
const keys = await songstress.storage.keys('charts/')
await songstress.secrets.set('token', 'from the service', { userId })
```

The store as the server entry uses it: one part for the extension as a
whole, and with `{ userId }` one part for each member, which is the part
code in that member's apps sees. A sandbox is started and stopped as
needed: what must last goes here, not in a variable.

| Field | Type | Description |
|---|---|---|
| `get` | `<Value = unknown>(key: string, user?: ForUser) => Promise<Value \| undefined>` | What was last set under the key; undefined when nothing is. |
| `set` | `(key: string, value: unknown, user?: ForUser) => Promise<void>` | Keeps a JSON value under the key, in place of what was there. |
| `delete` | `(key: string, user?: ForUser) => Promise<void>` | Forgets a key, the extension's or, with `{ userId }`, one member's. |
| `keys` | `(prefix?: string, user?: ForUser) => Promise<string[]>` | The keys held, in order; those that start with `prefix` when given. |

The extension's own credentials: tokens it was handed, kept sealed, never
sent to an app and never shown again. Server entry; permission `secrets`.
For a key a person types, declare a setting of type "secret" instead.

| Field | Type | Description |
|---|---|---|
| `get` | `(key: string, user?: ForUser) => Promise<string \| undefined>` | A secret kept under this key, the extension's or, with `{ userId }`, one member's; undefined when there is none. |
| `set` | `(key: string, value: string, user?: ForUser) => Promise<void>` | Keeps a secret, sealed, under this key. |
| `delete` | `(key: string, user?: ForUser) => Promise<void>` | Forgets the secret under this key. |

## Jobs [#jobs]

A job is work on the server, shown in Activity while it runs. Declare it, and give it `every` (`15m`, `6h`, `1d`) to
run by itself; without it a job runs only when your code starts it.

Work the server runs in the background, on a schedule or when code asks, shown in Activity.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The job's name. Code registers its handler under it. |
| `title` | `string` | The job as Activity shows it. |
| `every?` | `string \| undefined` | How often the job runs by itself: a number and m, h or d (15m, 6h, 1d). Left out, the job runs only when code starts it. |

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

songstress.jobs.register('sync', async (run) => {
  const pages = 10
  for (let page = 1; page <= pages; page++) {
    run.progress(page, pages, `Page ${page} of ${pages}`)
  }
})

const runId = await songstress.jobs.start('sync')
```

Jobs (the manifest's `contributes.jobs`), each shown in Activity while it
runs. Server entry; permission `jobs`.

| Field | Type | Description |
|---|---|---|
| `register` | `(id: string, handler: JobHandler) => Disposable` | Registers the handler of a declared job. |
| `start` | `(id: string, input?: unknown) => Promise<string>` | Queues a run of one of the extension's jobs, with `input` (JSON) for its handler; resolves to the run's id. A job already waiting or running is not queued twice. |

A run is handed:

One run of a job.

| Field | Type | Description |
|---|---|---|
| `runId` | `string` | The run's id, as Activity knows it. |
| `input?` | `JsonValue \| undefined` | What `jobs.start` was given; undefined for a run on the job's own schedule. |
| `userId?` | `string \| undefined` | The member who started it, when one did. |
| `progress` | `(done: number, total?: number, note?: string) => void` | Tells Activity how far the run is: `done` of `total`, and a few words. |

## Routes [#routes]

JSON routes for signed-in callers, under a prefix that belongs to your extension. Two routes may not answer the same
method and path (`ROUTE_DUPLICATE`).

An HTTP route under the extension's own prefix on the server.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The route's name. Code registers its handler under it. |
| `method` | `"DELETE" \| "GET" \| "PATCH" \| "POST" \| "PUT"` | The HTTP method. |
| `path` | `string` | The path under the extension's own prefix: segments of lowercase letters, digits, dots, hyphens and underscores, or :name for a part the handler reads (/charts/:period). |

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

songstress.routes.register('chart', async (request) => {
  const top = (await songstress.storage.get<string[]>(`chart/${request.params.period}`, { userId: request.userId })) ?? []
  return { status: 200, body: { top } }
})
```

A handler is handed the request, and answers:

A request to one of the extension's routes.

| Field | Type | Description |
|---|---|---|
| `method` | `"DELETE" \| "GET" \| "PATCH" \| "POST" \| "PUT"` | The method the route was called with, one the manifest declares for it. |
| `params` | `Record<string, string>` | The `:name` parts of the route's path. |
| `query` | `Record<string, string>` | The query string's values, by name. |
| `body?` | `JsonValue \| undefined` | The request's JSON body, when it has one. |
| `userId` | `string` | The signed-in member who asked. A route is never open to the world. |

What a route answers: JSON, and nothing else.

| Field | Type | Description |
|---|---|---|
| `status?` | `number \| undefined` | Left out, 200. |
| `body?` | `unknown` | JSON. |

## Sign-in [#sign-in]

A sign-in to the service your extension reaches, which a person starts and ends in Songstress. It needs the server
entry and the `secrets` permission.

An account at a service the extension signs in to, for the server or for each member.

| Field | Type | Description |
|---|---|---|
| `scope` | `"server" \| "user"` | Whose account it is. "server": one account for the whole server, which its admin signs in. "user": each member's own, which they sign in themselves. |
| `title?` | `string \| undefined` | The service as the sign-in names it (Tunelog). Left out, the extension's name. |

```ts title="src/server.ts"
import { ProviderFailure, songstress } from 'songstress/server'

const service = 'https://tunelog.example/oauth'

songstress.signIn.register({
  // Where the person signs in. The service sends them back to redirectUrl, with state as it was.
  start({ redirectUrl, state }) {
    const back = `redirect_uri=${encodeURIComponent(redirectUrl)}&state=${encodeURIComponent(state)}`
    return { url: `${service}/authorize?response_type=code&client_id=songstress&${back}` }
  },
  // What came back, traded for the account's token, which stays in secrets.
  async finish({ url, redirectUrl }) {
    const code = /[?&]code=([^&#]+)/.exec(url)?.[1]
    if (!code) throw new ProviderFailure('sign-in-required', { message: 'Tunelog sent no code back.' })
    const body = `grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(redirectUrl)}`
    const headers = { 'content-type': 'application/x-www-form-urlencoded' }
    const answer = await songstress.net.fetch(`${service}/token`, { method: 'POST', headers, body })
    if (answer.status !== 200) throw new ProviderFailure('unavailable')
    const { token, name } = JSON.parse(answer.body)
    await songstress.secrets.set('token', token)
    return { account: name }
  },
  async signOut() {
    await songstress.secrets.delete('token')
  },
})
```

The two halves of a sign-in, and its end. A half that cannot be done
throws a `ProviderFailure`; anything else thrown counts as broken.

| Field | Type | Description |
|---|---|---|
| `start` | `(request: SignInStart) => Awaitable<SignInPage>` | The service's page for this sign-in. Keep what `finish` will need (a code verifier) in `songstress.secrets`: another instance may run it. |
| `finish` | `(returned: SignInReturn) => Awaitable<SignedIn>` | Trades what came back for the account's tokens, keeps them in `songstress.secrets`, and answers whose account it is. |
| `signOut?` | `((request: SignOutRequest) => Awaitable<void>) \| undefined` | Forgets the tokens, and tells the service when it has a way to. Left out, signing out only forgets the account's name. |

What `start` is handed.

| Field | Type | Description |
|---|---|---|
| `redirectUrl` | `string` | Where the service must send the person back: this server's own address for it. Register it with the service as the redirect address. |
| `state` | `string` | A one-time value the service must hand back unchanged (OAuth's `state`): Songstress finishes only the sign-in that carries it. |
| `userId?` | `string \| undefined` | The member signing in, for a sign-in of scope "user"; left out for the server's own. |

What `finish` is handed.

| Field | Type | Description |
|---|---|---|
| `url` | `string` | The address the person came back on, whole: what the service added to `redirectUrl` (a code, an error) is in it. |
| `redirectUrl` | `string` | The `redirectUrl` that `start` was handed, for a service that asks for it again. |
| `userId?` | `string \| undefined` | The member who signed in, for a sign-in of scope "user": the one `start` was handed. Keep their tokens as theirs. |

- **`start`** is handed `redirectUrl`, your server's own address for coming back, and `state`, a one-time value the
  service must hand back. It answers the `url` of the service's page. What `finish` will need (a code verifier) goes
  in `secrets`: another instance of the entry may run it.
- **`finish`** is handed the `url` the person came back on, whole. It keeps the account's tokens in `secrets` and
  answers the `account`: the name shown beside "Signed in as".
- **`signOut`** is optional. Songstress forgets the account whether it runs, fails or isn't there.

With `scope: "user"` (API 0.1.7), each member signs in to their own account from their own page of the extension,
and `start`, `finish` and `signOut` are each handed that member's `userId`: keep their tokens with
`secrets.set('token', token, { userId })`.

Songstress finishes only the sign-in whose `state` came back, once, within ten minutes of its start, and keeps the
account's name and nothing else. A server with no public address can't be sent back to, and refuses the start. While
there is no account, your other code throws `sign-in-required`.

## The library and members [#the-library-and-members]

With `library.read`, the server entry reads the catalogue: a song, an album, an artist or a playlist by id, the
songs of an album or a playlist, and a search. With `users.read`, it reads members' ids and display names, nothing
else.

```ts title="src/server.ts"
import { songstress } from 'songstress/server'

const found = await songstress.library.search('Kind of Blue', { types: ['album'], limit: 5 })
const people = await songstress.users.list()
```

Reading the library. Server entry; permission `library.read`.

| Field | Type | Description |
|---|---|---|
| `getSong` | `(id: string) => Promise<Song \| null>` | The song with this id, or null when the library has none. |
| `getAlbum` | `(id: string) => Promise<Album \| null>` | The album with this id, or null when the library has none. |
| `getArtist` | `(id: string) => Promise<Artist \| null>` | The artist with this id, or null when the library has none. |
| `getPlaylist` | `(id: string) => Promise<Playlist \| null>` | A public playlist by its id; null for one that does not exist or that its owner keeps private. |
| `getAlbumSongs` | `(albumId: string) => Promise<Song[]>` | An album's songs, in order. |
| `getPlaylistSongs` | `(playlistId: string) => Promise<Song[]>` | A public playlist's songs, in order. |
| `search` | `(text: string, options?: { types?: Exclude<LibraryType, 'playlist'>[]; limit?: number; }) => Promise<LibrarySearchResults>` | Searches songs, albums and artists by text. `limit` is for each kind (20 when left out, 100 at most). |

Reading who the members are. Server entry; permission `users.read`.

| Field | Type | Description |
|---|---|---|
| `get` | `(id: string) => Promise<User \| null>` | The member with this id, or null when there is none. |
| `list` | `() => Promise<User[]>` | Every member of the server. |

## The player and the queue [#the-player-and-the-queue]

In client code, with `listening.read`, `player.getState()` and `queue.get()` read this device's player. With
`player.control`, `play`, `pause`, `next`, `previous`, `seek(positionS)` and `queue.add(songIds, { next })` ask it
to act.

The player of the device the code runs on. Client entry. Reading needs
the permission `listening.read`; the rest needs `player.control`.

| Field | Type | Description |
|---|---|---|
| `getState` | `() => Promise<PlayerState>` | What the player is doing now: the song, where it is in it, whether it plays. |
| `play` | `() => Promise<void>` | Goes on playing after a pause. |
| `pause` | `() => Promise<void>` | Pauses what is playing. |
| `next` | `() => Promise<void>` | Skips to the next song in the queue. |
| `previous` | `() => Promise<void>` | Goes back to the song before, as the app's own Previous does. |
| `seek` | `(positionS: number) => Promise<void>` | Moves to a place in the current song, in seconds from its start. |

The queue of the device the code runs on. Client entry.

| Field | Type | Description |
|---|---|---|
| `get` | `() => Promise<QueueState>` | Permission `listening.read`. |
| `add` | `(songIds: string[], options?: { next?: boolean; }) => Promise<void>` | Adds library songs to the queue: at its end, or right after the current song with `next`. What is playing is never touched. Permission `player.control`. |
