Initialization
Start the SDK with init, connect right away or on a click, and tear it down
Start the SDK with init. You give it a function that fetches a connection token from your backend, plus a NapsterCompanionApiConfig. By default the agent connects as soon as you call it. You can also show a launcher button and connect when the visitor clicks it.
Connect
init() — mount the widget and start the session
When the token is fetched
Why init takes a function, not a token
What you get back
The instance, and how to tell when the session is live
Start on click
A built-in launcher button that connects when clicked
Tear down
destroy() — close the connection and release the microphone
Connect
Pass a function that returns a token, and the SDK mounts the widget and starts connecting:
import { NapsterCompanionApiSdk } from "@touchcastllc/napster-companion-api";
import "@touchcastllc/napster-companion-api/styles";
async function getToken() {
const response = await fetch("/api/avatar-session", { method: "POST" });
const { token } = await response.json();
return token;
}
const instance = await NapsterCompanionApiSdk.init(getToken);<script src="https://cdn.jsdelivr.net/npm/@touchcastllc/napster-companion-api@2/lib/index.standalone.js"></script>
<script>
async function getToken() {
const response = await fetch("/api/avatar-session", { method: "POST" });
const { token } = await response.json();
return token;
}
window.napsterCompanionApiSDK.init(getToken);
</script>With no config, the agent appears as a floating widget in the bottom-right corner. To place it inside your own element instead, use an inline layout:
await NapsterCompanionApiSdk.init(getToken, {
layout: { type: "inline", mountContainer: "#avatar-container" },
});init(getToken, config?) takes two arguments:
| Argument | Type | Required | Description |
|---|---|---|---|
getToken | () => Promise<string> | Yes | A function that asks your backend for a new connection token and returns it. Return the token as-is; you don't need to decode it. |
config | NapsterCompanionApiConfig | No | Layout, style, features, and callbacks. See Configuration. |
/api/avatar-session is your own endpoint. It calls POST /public/agents/{agentId}/connections with your API key and returns the token from the response. Never call the Napster API from the browser: anyone who reads your page's source could copy the key.
When the token is fetched
Connection tokens expire within seconds, so the SDK fetches one itself at the last moment. It calls getToken once the visitor allows the microphone, right before it connects. If the visitor blocks the microphone, the SDK waits. It calls getToken only after a successful Check again. Each new session the launcher starts calls getToken again.
If you pass a token string instead of a function, init rejects and onError receives the same error. Its error.name is "TokenError" and its error.code is "TOKEN_ERROR". The SDK refuses a string because a token minted before the microphone prompt could expire while the visitor is still deciding.
If getToken throws, or returns an empty value, the SDK removes the widget, releases the microphone, and passes the error to onError. You get the error your function threw, or a TokenError for an empty token. You can then call init again to retry.
Retry only for the getToken error, and cap the number of retries. onError also reports other failures, and calling init while the widget is still on the page rejects with ALREADY_INITIALIZED. With the launcher, the card comes back on its own. Call the controller's start() to retry, not init.
What you get back
init returns a Promise<NapsterCompanionApiInstance>, the object you use to drive the session.
import { NapsterCompanionApiSdk } from "@touchcastllc/napster-companion-api";
import type { NapsterCompanionApiInstance } from "@touchcastllc/napster-companion-api";
const instance: NapsterCompanionApiInstance = await NapsterCompanionApiSdk.init(getToken);The promise resolves as soon as the widget is on the page, before the microphone prompt and before any connection exists. Commands you send at that point are dropped. To act when the session is live, use the onAvatarReady callback:
const instance = await NapsterCompanionApiSdk.init(getToken, {
onAvatarReady: (isReady) => {
if (isReady) {
// The session is live and ready for commands.
}
},
});For finer-grained progress, such as waiting for the microphone or the video arriving after the audio, use onSessionStatusChange. Read the sessionId getter for the live session identifier. See Methods for everything the instance exposes.
Start on click
By default the agent connects as soon as the page calls init. To let visitors start it when they're ready, turn on the built-in launcher with button.enabled. The SDK shows a small card with the agent's photo, and connects when the visitor clicks it:
const launcher = await NapsterCompanionApiSdk.init(getToken, {
button: {
enabled: true,
label: "Talk to an agent",
description: "Ask about your order",
},
agent: { photoUrl: "https://example.com/agent.jpg" },
});In this mode init resolves to a controller instead of an instance, and nothing is connected yet. When the session ends, whether the visitor presses End, the inactivity timeout runs out, or the connection drops, the launcher card comes back so the visitor can start again.
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Turn on the launcher. Without it, init connects immediately. |
label | string | "Talk to an agent" | The card's main text. |
description | string | — | A second line under the label. |
element | HTMLElement | string | — | Use your own button instead of the SDK's card. See Use your own button. |
alignment | "left" | "right" | "right" | Which side of the container the card sits on, for an inline layout. |
Set agent.photoUrl to show your agent's photo. The SDK uses the same photo on the launcher card, while the session loads, and on the microphone card. Without it, those show a generic placeholder.
The controller
| Method | Signature | Description |
|---|---|---|
start | () => Promise<NapsterCompanionApiInstance | null> | Start a session, as if the visitor clicked. Resolves once the microphone is settled and the token is fetched, not when the session is live. Resolves null if getToken fails (reported to onError), if the visitor ignores the microphone prompt for 30 seconds, or if you call end() or destroy() first. It never rejects. |
end | () => void | End the session. The launcher comes back and can start another. |
getInstance | () => NapsterCompanionApiInstance | null | The current session's instance, or null before the first start and after the session ends. |
destroy | () => void | Remove the launcher and end any session. |
const instance = await launcher.start();
if (instance) {
instance.muteMic();
}getInstance() can return an instance before the session is live. For example, it does while the connection is still being set up, or while the visitor has blocked the microphone and sees the Check again card. Use onAvatarReady to know when the session is up.
Use your own button
Already have a button on the page? Point button.element at it, and the SDK uses it instead of rendering a card:
await NapsterCompanionApiSdk.init(getToken, {
button: { enabled: true, element: "#talk-button" },
});The element must be on the page when you call init. If the selector matches nothing, init rejects.
The SDK listens for clicks on your element and cancels their default action, so a link or form button won't navigate or submit. It hides your element from the click until the session ends, and disables it if it's a form control. Then it restores the element as it was. It also sets a data-np-state attribute you can style: idle, connecting, or active. label, description, and alignment are ignored in this mode.
TypeScript
TypeScript picks the controller return type from the config you write inline. If you build the config in a variable first, add as const, or TypeScript types the result as an instance:
const options = { button: { enabled: true } } as const;
const launcher = await NapsterCompanionApiSdk.init(getToken, options);The controller's type is NapsterCompanionApiController. Import it with import type, the same way as NapsterCompanionApiInstance.
With persistence
With persistence on, ending a session normally reloads the page the visitor is on, and the launcher appears again after the reload. If the session fails to connect, the SDK removes the frame in place instead, without a reload. The SDK logs a console warning when you use both.
Tear down
Call destroy() when the widget leaves the page. It closes the WebRTC connection, removes the widget, and releases the microphone, plus any screen-share or face-tracking camera capture, if you were using those.
instance.destroy();In component frameworks, call it from your unmount hook. See the framework examples. If you don't call destroy(), the connection and media tracks stay open.
With the launcher, instance.destroy() only ends the current session, and the launcher comes back. To remove the launcher, call the controller's destroy().
The SDK runs one widget at a time. Calling init again before destroy() rejects with ALREADY_INITIALIZED. With the launcher, call the controller's destroy() before you call init again.