@avatarfactory/react 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,84 @@
1
+ Avatar Factory SDK Licence
2
+ Version 1, 23 November 2026
3
+
4
+ Copyright (c) 2026 Avatar Factory Pte. Ltd. (UEN 202604531W), Singapore.
5
+ All rights reserved.
6
+
7
+ In short. Our client SDKs are proprietary. You may install and use them to
8
+ build apps that use the Avatar Factory service under your account, and ship
9
+ them inside your app to your end users, but you may not pass them on in any
10
+ other way. The licence ends when your account does. This summary is not part
11
+ of the licence.
12
+
13
+ This licence is between you and Avatar Factory Pte. Ltd. ("Avatar Factory",
14
+ "we"). It covers the software in this package or repository, its documentation
15
+ and any updates we give you (the "SDK"). By installing or using the SDK you
16
+ accept it. If you accept for a business, you confirm you may bind it, and "you"
17
+ means that business.
18
+
19
+ 1. What you need. You need an Avatar Factory account. The SDK is licensed only
20
+ while your account is open and you accept our Terms of Service at
21
+ https://avatarfactory.in/terms (the "Terms").
22
+
23
+ 2. What you may do. We grant you a non-exclusive, non-transferable, worldwide
24
+ licence, while your account is open, to:
25
+ (a) install, copy and use the SDK as needed to build, test and run apps,
26
+ websites and other products that use the Avatar Factory service under
27
+ your account ("your apps"), including apps you build for a client that
28
+ run under your account or the client's own Avatar Factory account;
29
+ (b) bundle, compile, minify and make the changes needed to make the SDK
30
+ work inside your apps; and
31
+ (c) distribute the SDK only as part of your apps, to your end users, for
32
+ use with your apps.
33
+
34
+ 3. What you may not do. You may not:
35
+ (a) distribute, publish, sublicense, sell, rent or lend the SDK, or any
36
+ part or changed version of it, on its own or in any way other than
37
+ 2(c), including on a package registry, as a library, SDK, plugin or
38
+ template for other developers, or under another name;
39
+ (b) use the SDK with any service other than Avatar Factory, or to build a
40
+ product that competes with the SDK or the Avatar Factory service;
41
+ (c) reverse engineer, decompile or disassemble the SDK, except to the
42
+ extent the law allows it despite this restriction;
43
+ (d) get around, disable or change usage metering, plan limits, allowed
44
+ domains, licence checks, safety features or AI notices;
45
+ (e) use the SDK to extract, copy or save characters, rigs, animations or
46
+ voices; or
47
+ (f) remove or change any copyright, licence or third-party notice.
48
+
49
+ 4. Your end users. Your terms with your end users must not give them more
50
+ rights in the SDK than this licence gives you, and must forbid them to
51
+ extract it from your apps.
52
+
53
+ 5. Third-party components. Parts of the SDK come from other projects and stay
54
+ under their own licences, listed in THIRD_PARTY_LICENSES.md (or
55
+ THIRD_PARTY_NOTICES.md). This licence does not limit the rights those
56
+ licences give you. When you distribute your apps, you must keep the notices
57
+ those licences require, for example on an acknowledgements or licences
58
+ screen.
59
+
60
+ 6. What the SDK does not cover. Characters, rigs, voices, the Avatar Factory
61
+ service and API, and our names and logos are not part of the SDK. You may
62
+ use them only under the Terms.
63
+
64
+ 7. Ownership. The SDK is licensed, not sold. Avatar Factory and its licensors
65
+ keep all rights not expressly granted. We may use feedback you give us
66
+ about the SDK freely.
67
+
68
+ 8. Updates. We may update the SDK. We may stop supporting an old version, and
69
+ may require you to update where security or the service needs it.
70
+
71
+ 9. Ending. This licence ends automatically when your account closes or the
72
+ Terms end. We may also end it by notice if you breach it and do not fix the
73
+ breach within 30 days of being told, or straight away for a serious breach
74
+ of section 3. When it ends you must stop using the SDK and stop
75
+ distributing your apps with it; you need not recall copies your end users
76
+ already have. Sections 3, 5, 6, 7, 10 and 11 continue.
77
+
78
+ 10. No warranty and liability. The SDK is provided as it is. What we promise
79
+ about it, and the limits on our liability, are set by the Terms, which
80
+ apply to the SDK as part of the service.
81
+
82
+ 11. Law. Singapore law governs this licence, and the courts of Singapore have
83
+ exclusive jurisdiction, as the Terms say. If this licence and the Terms
84
+ differ about the SDK, this licence applies.
package/README.md ADDED
@@ -0,0 +1,424 @@
1
+ # @avatarfactory/react
2
+
3
+ A React SDK for embedding real-time talking avatars with voice interaction, lip-sync, and live conversations — powered by Rive animations and Web Audio.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @avatarfactory/react @rive-app/react-webgl2
9
+ ```
10
+
11
+ ### Peer Dependencies
12
+
13
+ | Package | Version |
14
+ | ------------------------ | -------- |
15
+ | `react` | >= 18 |
16
+ | `react-dom` | >= 18 |
17
+ | `@rive-app/react-webgl2` | >= 4.29.0 |
18
+
19
+ ## Quick Start
20
+
21
+ ```tsx
22
+ import { AvatarProvider, Avatar, useAvatar } from "@avatarfactory/react";
23
+ import "@avatarfactory/react/styles.css";
24
+
25
+ function App() {
26
+ return (
27
+ <AvatarProvider
28
+ config={{
29
+ getSessionToken: async () => {
30
+ const res = await fetch("/api/avatar-token");
31
+ const { sessionToken } = await res.json();
32
+ return sessionToken;
33
+ },
34
+ avatar: { avatarId: "your-avatar-id" },
35
+ mode: "call",
36
+ }}
37
+ >
38
+ <MyAvatar />
39
+ </AvatarProvider>
40
+ );
41
+ }
42
+
43
+ function MyAvatar() {
44
+ const { isReady, start, stop } = useAvatar();
45
+
46
+ return (
47
+ <div>
48
+ <Avatar style={{ width: 400, height: 400 }} />
49
+ <button onClick={start} disabled={!isReady}>
50
+ Start
51
+ </button>
52
+ <button onClick={stop}>Stop</button>
53
+ </div>
54
+ );
55
+ }
56
+ ```
57
+
58
+ ## Authentication
59
+
60
+ You must provide **exactly one** of `apiKey`, `getSessionToken`, or `deployId` in your config.
61
+
62
+ ### Session Token Callback (Recommended)
63
+
64
+ Session tokens are short-lived, **single-use**, server-issued tokens. Because they are single-use, the SDK accepts a callback rather than a token string — the callback is invoked every time the SDK opens a WebSocket (initial connect and every reconnect after a disconnect), so each connection gets a fresh token. This is the **recommended approach** for production because credentials are never exposed to the browser.
65
+
66
+ ```tsx
67
+ <AvatarProvider
68
+ config={{
69
+ getSessionToken: async () => {
70
+ // Your backend endpoint generates a fresh session token on each call
71
+ const res = await fetch("/api/avatar-token");
72
+ const { sessionToken } = await res.json();
73
+ return sessionToken;
74
+ },
75
+ avatar: { avatarId: "your-avatar-id" },
76
+ }}
77
+ >
78
+ ```
79
+
80
+ The callback must return a `Promise<string>` resolving to a non-empty token. If the fetch fails or the resolved value is empty, the SDK emits a `SESSION_TOKEN_FETCH_FAILED` error and the connection attempt is aborted before any WebSocket is opened.
81
+
82
+ ### Deploy ID
83
+
84
+ A public deploy key — no backend required. Suitable for demos and prototyping.
85
+
86
+ ```tsx
87
+ <AvatarProvider
88
+ config={{
89
+ deployId: "af_deploy_...",
90
+ avatar: { avatarId: "your-avatar-id" },
91
+ }}
92
+ >
93
+ ```
94
+
95
+ ### API Key
96
+
97
+ > **Warning:** When using `apiKey`, your key is sent from the browser and is **visible to anyone** inspecting network traffic or client-side code. Only use this for development, internal tools, or prototyping.
98
+
99
+ ```tsx
100
+ <AvatarProvider
101
+ config={{
102
+ apiKey: "your-api-key",
103
+ avatar: { avatarId: "your-avatar-id" },
104
+ }}
105
+ >
106
+ ```
107
+
108
+ ## Modes
109
+
110
+ The SDK supports four modes, set via `config.mode`:
111
+
112
+ | Mode | Description | Key Method |
113
+ | ---------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------- |
114
+ | `"call"` | Bidirectional voice conversation. Mic is captured and streamed to the server. The avatar listens, thinks, and speaks back. | `start()` / `stop()` |
115
+ | `"tts"` | Text-to-speech. You send text, the avatar speaks it. | `speakText(text)` |
116
+ | `"audio"` | Audio-in. You provide pre-encoded audio, the avatar lip-syncs and plays it. | `speakAudio(audio)` |
117
+ | `"player"` | Fully pre-rendered. You provide a complete speech job and the avatar plays it. | `play(job)` |
118
+
119
+ Default mode is `"call"`.
120
+
121
+ ### Call Mode Example
122
+
123
+ ```tsx
124
+ <AvatarProvider
125
+ config={{
126
+ getSessionToken: async () => fetchSessionToken(),
127
+ avatar: { avatarId: "..." },
128
+ mode: "call",
129
+ controls: { enabled: true },
130
+ }}
131
+ >
132
+ <Avatar />
133
+ </AvatarProvider>
134
+ ```
135
+
136
+ ### TTS Mode Example
137
+
138
+ ```tsx
139
+ function TTSDemo() {
140
+ const { isReady, speakText } = useAvatar();
141
+
142
+ return (
143
+ <div>
144
+ <Avatar style={{ width: 400, height: 400 }} />
145
+ <button
146
+ disabled={!isReady}
147
+ onClick={() => speakText?.("Hello from Avatar Factory!")}
148
+ >
149
+ Speak
150
+ </button>
151
+ </div>
152
+ );
153
+ }
154
+ ```
155
+
156
+ ### Audio Mode Example
157
+
158
+ ```tsx
159
+ function AudioDemo() {
160
+ const { isReady, speakAudio } = useAvatar();
161
+
162
+ const handleFileUpload = async (file: File) => {
163
+ const buffer = await file.arrayBuffer();
164
+ speakAudio?.(buffer);
165
+ };
166
+
167
+ return (
168
+ <div>
169
+ <Avatar style={{ width: 400, height: 400 }} />
170
+ <input
171
+ type="file"
172
+ accept="audio/*"
173
+ disabled={!isReady}
174
+ onChange={(e) => {
175
+ const file = e.target.files?.[0];
176
+ if (file) handleFileUpload(file);
177
+ }}
178
+ />
179
+ </div>
180
+ );
181
+ }
182
+ ```
183
+
184
+ ### Player Mode Example
185
+
186
+ ```tsx
187
+ function PlayerDemo() {
188
+ const { isReady, play } = useAvatar();
189
+
190
+ const job = {
191
+ audioChunks: ["base64-encoded-audio..."],
192
+ alignments: [
193
+ {
194
+ characters: ["H", "e", "l", "l", "o"],
195
+ character_start_times_seconds: [0.0, 0.1, 0.2, 0.3, 0.4],
196
+ character_end_times_seconds: [0.1, 0.2, 0.3, 0.4, 0.5],
197
+ },
198
+ ],
199
+ };
200
+
201
+ return (
202
+ <div>
203
+ <Avatar style={{ width: 400, height: 400 }} />
204
+ <button onClick={() => play?.(job)} disabled={!isReady}>
205
+ Play
206
+ </button>
207
+ </div>
208
+ );
209
+ }
210
+ ```
211
+
212
+ ## API Reference
213
+
214
+ ### `<AvatarProvider>`
215
+
216
+ Wraps your component tree and initializes the avatar runtime.
217
+
218
+ ```tsx
219
+ <AvatarProvider config={config}>{children}</AvatarProvider>
220
+ ```
221
+
222
+ ### `<Avatar>`
223
+
224
+ Renders the avatar canvas with optional built-in controls. Must be used within `<AvatarProvider>`.
225
+
226
+ | Prop | Type | Description |
227
+ | --------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
228
+ | `className` | `string` | CSS class applied to the avatar's root container. |
229
+ | `style` | `React.CSSProperties` | Inline styles. Commonly used to set `width` and `height`. |
230
+ | `loader` | `React.ReactNode` | Custom element shown while the avatar animation file is loading. If omitted, a default spinner is displayed. |
231
+ | `errorFallback` | `React.ReactNode` | Custom element shown on a load error. |
232
+
233
+ ### `AvatarConfig`
234
+
235
+ Passed to `<AvatarProvider config={...}>`.
236
+
237
+ | Property | Type | Required | Description |
238
+ | ----------------- | ----------------------------------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
239
+ | `deployId` | `string` | One of `deployId`, `apiKey`, `getSessionToken` | Public deploy key — no backend needed. |
240
+ | `apiKey` | `string` | One of `deployId`, `apiKey`, `getSessionToken` | Direct API key. **Never expose in the browser in production.** |
241
+ | `getSessionToken` | `() => Promise<string>` | One of `deployId`, `apiKey`, `getSessionToken` | Callback that returns a short-lived session token. Invoked on every connect. Recommended for production. |
242
+ | `avatar` | `{ avatarId: string; layout?: Record<string, string>; voiceSettings?: AvatarVoiceSettings }` | Yes | `avatarId` — unique avatar identifier. `layout` — Rive layout overrides. `voiceSettings` — per-session voice tuning. |
243
+ | `mode` | `"call" \| "tts" \| "audio" \| "player"` | No | Interaction mode. Default: `"call"`. |
244
+ | `controls` | `{ enabled: boolean }` | No | Show built-in start/stop controls in `"call"` mode. |
245
+ | `greeting` | `{ enabled: boolean; job: AvatarSpeech }` | No | Auto-speak a greeting on connect. |
246
+ | `systemPrompt` | `string` | No | System instruction for the avatar's AI in `"call"` mode. |
247
+ | `useOwnVoice` | `boolean` | No | Use your own ElevenLabs key configured on the dashboard. |
248
+ | `debug` | `boolean` | No | Enable verbose console logging. |
249
+
250
+ ### `useAvatar()`
251
+
252
+ Hook to access avatar state and controls. Must be used within `<AvatarProvider>`.
253
+
254
+ ```tsx
255
+ const avatar = useAvatar();
256
+ ```
257
+
258
+ #### State
259
+
260
+ | Property | Type | Description |
261
+ | -------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
262
+ | `isReady` | `boolean` | Avatar loaded and ready to interact. Gate UI actions on this. |
263
+ | `isLoading` | `boolean` | Avatar animation file is downloading. |
264
+ | `isConnecting` | `boolean` | WebSocket connection is being established. |
265
+ | `isConnected` | `boolean` | WebSocket session is open and active. |
266
+ | `isSpeaking` | `boolean` | Avatar is currently speaking. |
267
+ | `isListening` | `boolean` | Avatar is listening for voice input (call mode only). |
268
+ | `isIdle` | `boolean` | Connected and ready but not speaking or listening. |
269
+ | `avatarId` | `string \| undefined` | Active avatar ID from config. |
270
+ | `error` | `AvatarError \| null` | Most recent error. Auto-clears after ~7 seconds. |
271
+ | `controls` | `{ enabled: boolean }` | Whether built-in controls are enabled. |
272
+
273
+ #### Methods
274
+
275
+ | Method | Signature | Description |
276
+ | ------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
277
+ | `start()` | `() => void` | Start the session. Opens mic in `"call"` mode. |
278
+ | `stop()` | `() => void` | Stop the session and disconnect. |
279
+ | `interrupt()` | `() => void` | Stop current speech immediately. |
280
+ | `speakText()` | `(text: string) => void` | Synthesize and speak a string. `"tts"` mode only. |
281
+ | `speakAudio()` | `(audio: ArrayBuffer \| Float32Array \| Blob) => void` | Speak from raw audio. `"audio"` mode only. |
282
+ | `play()` | `(job: AvatarSpeech) => void` | Play a pre-rendered speech job. `"player"` mode only. |
283
+ | `addLiveContext()` | `(args: LiveContextArgs) => void` | Inject context into the AI mid-session. `"call"` and `"tts"` modes only. |
284
+ | `on()` | `(event, handler) => void` | Subscribe to an avatar event. |
285
+ | `off()` | `(event, handler) => void` | Unsubscribe from an avatar event. |
286
+
287
+ ### `useAvatarEvent()`
288
+
289
+ Hook for subscribing to avatar events with automatic cleanup.
290
+
291
+ ```tsx
292
+ import { useAvatarEvent } from "@avatarfactory/react";
293
+
294
+ useAvatarEvent("speaking", () => console.log("Avatar started speaking"));
295
+ useAvatarEvent("error", (error) => console.error(error.code, error.message));
296
+ ```
297
+
298
+ ### Events
299
+
300
+ | Event | Callback Signature | Description |
301
+ | ----------- | ------------------------------ | ------------------------------------------------------------------------------ |
302
+ | `ready` | `() => void` | Avatar loaded and rendered on canvas. |
303
+ | `start` | `() => void` | Session connected and active. |
304
+ | `stop` | `() => void` | Session disconnected. |
305
+ | `speaking` | `() => void` | Speech playback started. |
306
+ | `interrupt` | `() => void` | Speech interrupted. |
307
+ | `error` | `(error: AvatarError) => void` | Runtime error. |
308
+
309
+ ### `AvatarError`
310
+
311
+ | Property | Type | Description |
312
+ | ------------- | -------------------------------- | -------------------------------------------------------------------- |
313
+ | `code` | `AvatarErrorCode` | Machine-readable error code. |
314
+ | `message` | `string` | Human-readable description. Safe to show to users. |
315
+ | `source` | `"sdk" \| "server" \| "network"` | Where the error originated. |
316
+ | `recoverable` | `boolean` | Whether the session can continue. |
317
+ | `cause` | `unknown` | Underlying error object, if available. |
318
+
319
+ #### Error Codes
320
+
321
+ | Code | Source | Description |
322
+ | ---------------------------- | --------- | --------------------------------------------------------------------------- |
323
+ | `WS_CONNECTION_FAILED` | `network` | WebSocket could not connect. |
324
+ | `WS_DISCONNECTED` | `network` | WebSocket dropped unexpectedly. |
325
+ | `WS_SOURCE_ERROR` | `network` | Low-level WebSocket error. |
326
+ | `SERVER_CLOSE_REQUESTED` | `server` | Server intentionally closed the session. |
327
+ | `SERVER_INTERNAL_ERROR` | `server` | Server-side internal error. |
328
+ | `MIC_PERMISSION_DENIED` | `sdk` | User denied microphone access. |
329
+ | `MIC_START_FAILED` | `sdk` | Mic permitted but failed to start. |
330
+ | `AVATAR_LOAD_FAILED` | `sdk` | Avatar animation file failed to load. |
331
+ | `AUDIO_CONTEXT_FAILED` | `sdk` | Web Audio context could not be created. |
332
+ | `SESSION_IDLE_TIMEOUT` | `sdk` | Session closed after ~2 minutes of inactivity. |
333
+ | `SESSION_TOKEN_FETCH_FAILED` | `sdk` | `getSessionToken` callback failed or returned empty. |
334
+ | `INVALID_MODE` | `sdk` | Unsupported mode value in config. |
335
+
336
+ ### Types
337
+
338
+ ```tsx
339
+ import type {
340
+ AvatarConfig,
341
+ AvatarMode,
342
+ AvatarSpeech,
343
+ AvatarVoiceSettings,
344
+ LiveContextArgs,
345
+ AvatarEventMap,
346
+ UseAvatarResult,
347
+ AvatarPublicProps,
348
+ } from "@avatarfactory/react";
349
+ ```
350
+
351
+ #### `AvatarSpeech`
352
+
353
+ ```tsx
354
+ type AvatarSpeech = {
355
+ audioChunks: string[]; // base64-encoded audio chunks
356
+ alignments: NormalizedAlignment[];
357
+ isGreeting?: boolean;
358
+ };
359
+
360
+ type NormalizedAlignment = {
361
+ characters: string[];
362
+ character_start_times_seconds: number[];
363
+ character_end_times_seconds: number[];
364
+ };
365
+ ```
366
+
367
+ #### `LiveContextArgs`
368
+
369
+ ```tsx
370
+ type LiveContextArgs = {
371
+ context: string; // non-empty, max 2000 characters
372
+ update?: boolean; // replace previously submitted context
373
+ };
374
+ ```
375
+
376
+ #### `AvatarVoiceSettings`
377
+
378
+ ```tsx
379
+ type AvatarVoiceSettings = {
380
+ visimeMs?: number; // viseme frame duration override (ms); default 40
381
+ voiceSpeed?: number; // forwarded to TTS engine
382
+ voiceStability?: number; // forwarded to TTS engine
383
+ similarityBoost?: number; // forwarded to TTS engine
384
+ };
385
+ ```
386
+
387
+ ## Styling
388
+
389
+ Import the bundled stylesheet once at your app entry point:
390
+
391
+ ```ts
392
+ import "@avatarfactory/react/styles.css";
393
+ ```
394
+
395
+ Override with these CSS classes:
396
+
397
+ | Class | Element |
398
+ | ------------------------ | ------------------------------ |
399
+ | `.rive-renderer-root` | Avatar container |
400
+ | `.rive-renderer-canvas` | Rive canvas |
401
+ | `.rive-renderer-overlay` | Overlay layer on top of canvas |
402
+ | `.rive-renderer-loader` | Loading indicator container |
403
+ | `.avatar-controls` | Built-in controls container |
404
+ | `.connectivity-dot` | Connection status indicator |
405
+
406
+ ## Caching
407
+
408
+ Avatar animation files are automatically cached in IndexedDB for faster subsequent loads. No configuration needed.
409
+
410
+ ## Browser Support
411
+
412
+ - Chrome / Edge (latest)
413
+ - Firefox (latest)
414
+ - Safari 16.4+ (macOS and iOS)
415
+
416
+ Requires: WebSocket, Web Audio API, AudioWorklet, IndexedDB.
417
+
418
+ ## Links
419
+
420
+ - [Documentation](https://avatarfactory-ui-demo.vercel.app/docs)
421
+
422
+ ## License
423
+
424
+ Proprietary. See [LICENSE](./LICENSE) for the full terms: you may use this SDK to build apps on the Avatar Factory service under your account and ship it inside those apps, but you may not redistribute, resell or republish it, or use it with another service.