@peerbots/face 0.0.0-stage → 0.1.0

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.
Files changed (50) hide show
  1. package/README.md +30 -2
  2. package/dist/VizijFaceView-3fvAa51G.d.ts +57 -0
  3. package/dist/chunk-AT25NYX2.js +211 -0
  4. package/dist/chunk-AT25NYX2.js.map +1 -0
  5. package/dist/chunk-T7QJ6B66.js +1475 -0
  6. package/dist/chunk-T7QJ6B66.js.map +1 -0
  7. package/dist/chunk-XHICGN32.js +62 -0
  8. package/dist/chunk-XHICGN32.js.map +1 -0
  9. package/dist/index.cjs +4353 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +525 -0
  12. package/dist/index.js +1408 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/pixi.cjs +2403 -0
  15. package/dist/pixi.cjs.map +1 -0
  16. package/dist/pixi.d.ts +9 -0
  17. package/dist/pixi.js +882 -0
  18. package/dist/pixi.js.map +1 -0
  19. package/dist/vizij.cjs +1546 -0
  20. package/dist/vizij.cjs.map +1 -0
  21. package/dist/vizij.d.ts +2 -0
  22. package/dist/vizij.js +193 -0
  23. package/dist/vizij.js.map +1 -0
  24. package/package.json +114 -4
  25. package/public/FaceAssets/Hugo/cheek.png +0 -0
  26. package/public/FaceAssets/Hugo/concerned_l.png +0 -0
  27. package/public/FaceAssets/Hugo/concerned_r.png +0 -0
  28. package/public/FaceAssets/Hugo/happy_l.png +0 -0
  29. package/public/FaceAssets/Hugo/happy_r.png +0 -0
  30. package/public/FaceAssets/Hugo/hugo_spritesheet.json +97 -0
  31. package/public/FaceAssets/Hugo/hugo_spritesheet.png +0 -0
  32. package/public/FaceAssets/Hugo/neutral_l.png +0 -0
  33. package/public/FaceAssets/Hugo/neutral_r.png +0 -0
  34. package/public/FaceAssets/Hugo/sad_l.png +0 -0
  35. package/public/FaceAssets/Hugo/sad_r.png +0 -0
  36. package/public/FaceAssets/Hugo/sleepy_l.png +0 -0
  37. package/public/FaceAssets/Hugo/sleepy_r.png +0 -0
  38. package/public/FaceAssets/Hugo/surprised_l.png +0 -0
  39. package/public/FaceAssets/Hugo/surprised_r.png +0 -0
  40. package/public/FaceAssets/Icons/Concerned.png +0 -0
  41. package/public/FaceAssets/Icons/Neutral.png +0 -0
  42. package/public/FaceAssets/Icons/Sad.png +0 -0
  43. package/public/FaceAssets/Icons/Sleep.png +0 -0
  44. package/public/FaceAssets/Icons/Surprised.png +0 -0
  45. package/public/FaceAssets/Misty/misty_spritesheet.json +97 -0
  46. package/public/FaceAssets/Misty/misty_spritesheet.png +0 -0
  47. package/public/FaceAssets/Robotic/robotic_spritesheet.json +97 -0
  48. package/public/FaceAssets/Robotic/robotic_spritesheet.png +0 -0
  49. package/public/FaceAssets/Vizij/Hugo.glb +0 -0
  50. package/public/FaceAssets/Vizij/brand.svg +15 -0
package/dist/vizij.cjs ADDED
@@ -0,0 +1,1546 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/components/VizijFaceView.tsx
21
+ var VizijFaceView_exports = {};
22
+ __export(VizijFaceView_exports, {
23
+ VizijFaceView: () => VizijFaceView,
24
+ default: () => VizijFaceView_default
25
+ });
26
+ module.exports = __toCommonJS(VizijFaceView_exports);
27
+ var import_react2 = require("react");
28
+ var import_runtime_react = require("@vizij/runtime-react");
29
+
30
+ // src/store/FaceStoreContext.tsx
31
+ var import_react = require("react");
32
+ var import_zustand2 = require("zustand");
33
+
34
+ // src/store/createPeerbotsFaceStore.ts
35
+ var import_zustand = require("zustand");
36
+ var import_middleware = require("zustand/middleware");
37
+
38
+ // src/types/face.ts
39
+ var DEFAULT_FACE_MESSAGE = {
40
+ title: "Ready",
41
+ speech: "",
42
+ color: "Light Blue",
43
+ emotion: "Neutral"
44
+ };
45
+ var defaultFaceSettings = {
46
+ zoom: 1,
47
+ offset: { x: 0, y: 0 },
48
+ rotation: 0,
49
+ autoRotate: true,
50
+ showFullScreenButton: true,
51
+ showScrollButton: true,
52
+ amplitudeGain: 1,
53
+ vizijSettings: {
54
+ faceExpressivity: 1
55
+ },
56
+ pixiSettings: {
57
+ eyeDisplay: "default",
58
+ mouthDisplay: "default",
59
+ cheekDisplay: "default",
60
+ emotionDisplay: "emoticon"
61
+ },
62
+ selectedLanguage: "English",
63
+ speechQueueMode: "interrupt",
64
+ captions: {
65
+ enabled: false,
66
+ fontSize: 32,
67
+ offset: { x: 0, y: 0 }
68
+ }
69
+ };
70
+ function normalizeAssetBaseUrl(assetBaseUrl = "/FaceAssets") {
71
+ const trimmed = assetBaseUrl.trim();
72
+ if (!trimmed) {
73
+ return "/FaceAssets";
74
+ }
75
+ return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
76
+ }
77
+ function createBuiltInPixiFaces(assetBaseUrl) {
78
+ const base = normalizeAssetBaseUrl(assetBaseUrl);
79
+ return [
80
+ {
81
+ kind: "PixiFace",
82
+ type: "avatar",
83
+ name: "Hugo",
84
+ mouth: "Hugo",
85
+ eyes: {
86
+ kind: "spritesheet",
87
+ path: `${base}/Hugo/hugo_spritesheet.json`
88
+ },
89
+ cheeks: {
90
+ kind: "texture",
91
+ path: `${base}/Hugo/cheek.png`
92
+ },
93
+ eyebrows: "Hugo"
94
+ },
95
+ {
96
+ kind: "PixiFace",
97
+ type: "avatar",
98
+ name: "Simple",
99
+ mouth: "Ellipse",
100
+ eyes: {
101
+ kind: "spritesheet",
102
+ path: `${base}/Hugo/hugo_spritesheet.json`
103
+ },
104
+ cheeks: null,
105
+ eyebrows: null
106
+ },
107
+ {
108
+ kind: "PixiFace",
109
+ type: "avatar",
110
+ name: "Robotic",
111
+ mouth: "ZigZag",
112
+ eyes: {
113
+ kind: "spritesheet",
114
+ path: `${base}/Robotic/robotic_spritesheet.json`
115
+ },
116
+ cheeks: null,
117
+ eyebrows: null
118
+ },
119
+ {
120
+ kind: "PixiFace",
121
+ type: "text",
122
+ name: "Display",
123
+ showEmotion: "emoticon",
124
+ showText: true
125
+ }
126
+ ];
127
+ }
128
+ function createCustomVizijFace(glbUrl = "") {
129
+ return {
130
+ kind: "Vizij",
131
+ name: "Custom Face",
132
+ assetBundle: {
133
+ namespace: "custom",
134
+ glb: {
135
+ kind: "url",
136
+ src: glbUrl,
137
+ aggressiveImport: true
138
+ }
139
+ }
140
+ };
141
+ }
142
+ function createIncludedVizijFaces(assetBaseUrl) {
143
+ const base = normalizeAssetBaseUrl(assetBaseUrl);
144
+ return [
145
+ {
146
+ kind: "Vizij",
147
+ name: "Hugo - Expressive",
148
+ assetBundle: {
149
+ namespace: "hugo",
150
+ glb: {
151
+ kind: "url",
152
+ src: `${base}/Vizij/Hugo.glb`,
153
+ aggressiveImport: true
154
+ }
155
+ }
156
+ },
157
+ createCustomVizijFace("")
158
+ ];
159
+ }
160
+ function createBuiltInFaces(assetBaseUrl) {
161
+ return [
162
+ ...createBuiltInPixiFaces(assetBaseUrl),
163
+ ...createIncludedVizijFaces(assetBaseUrl)
164
+ ];
165
+ }
166
+ var builtInFaces = createBuiltInPixiFaces();
167
+ var customFace = createCustomVizijFace();
168
+ var includedVizijFaces = createIncludedVizijFaces();
169
+ var availableFaces = [...builtInFaces, ...includedVizijFaces];
170
+ var defaultFace = builtInFaces[0];
171
+
172
+ // src/store/faceRenderingSlice.ts
173
+ function clampUnit(value) {
174
+ if (Number.isNaN(value)) {
175
+ return 0;
176
+ }
177
+ return Math.max(-1, Math.min(1, value));
178
+ }
179
+ function mergeFaceSettings(base, patch) {
180
+ if (!patch) {
181
+ return {
182
+ ...base,
183
+ offset: { ...base.offset },
184
+ captions: {
185
+ ...base.captions,
186
+ offset: { ...base.captions.offset }
187
+ },
188
+ pixiSettings: base.pixiSettings ? { ...base.pixiSettings } : void 0,
189
+ vizijSettings: base.vizijSettings ? { ...base.vizijSettings } : void 0
190
+ };
191
+ }
192
+ return {
193
+ ...defaultFaceSettings,
194
+ ...base,
195
+ ...patch,
196
+ offset: {
197
+ ...defaultFaceSettings.offset,
198
+ ...base.offset || {},
199
+ ...patch.offset || {}
200
+ },
201
+ captions: {
202
+ ...defaultFaceSettings.captions,
203
+ ...base.captions || {},
204
+ ...patch.captions || {},
205
+ offset: {
206
+ ...defaultFaceSettings.captions.offset,
207
+ ...base.captions?.offset || {},
208
+ ...patch.captions?.offset || {}
209
+ }
210
+ },
211
+ pixiSettings: {
212
+ ...defaultFaceSettings.pixiSettings,
213
+ ...base.pixiSettings || {},
214
+ ...patch.pixiSettings || {}
215
+ },
216
+ vizijSettings: {
217
+ ...defaultFaceSettings.vizijSettings,
218
+ ...base.vizijSettings || {},
219
+ ...patch.vizijSettings || {}
220
+ }
221
+ };
222
+ }
223
+ function createFaceRenderingSlice(options = {}) {
224
+ const initialBaseUrl = normalizeAssetBaseUrl(options.assetBaseUrl);
225
+ const initialFaces = createBuiltInFaces(initialBaseUrl);
226
+ const initialSelectedFace = options.initialFace ?? initialFaces[0];
227
+ const initialMergedSettings = mergeFaceSettings(
228
+ defaultFaceSettings,
229
+ options.initialSettings
230
+ );
231
+ return (set, get) => ({
232
+ assetBaseUrl: initialBaseUrl,
233
+ availableFaces: initialFaces,
234
+ selectedFace: initialSelectedFace,
235
+ faceSettings: initialMergedSettings,
236
+ gaze: { x: 0, y: 0 },
237
+ setFace: (face) => {
238
+ set({ selectedFace: face });
239
+ },
240
+ setFaceByName: (name) => {
241
+ const found = get().availableFaces.find((f) => f.name === name);
242
+ if (found) {
243
+ set({ selectedFace: found });
244
+ }
245
+ },
246
+ setFaceSettings: (settings) => {
247
+ set((state) => ({
248
+ faceSettings: mergeFaceSettings(state.faceSettings, settings)
249
+ }));
250
+ },
251
+ resetPositioning: () => {
252
+ set((state) => ({
253
+ faceSettings: mergeFaceSettings(state.faceSettings, {
254
+ zoom: 1,
255
+ offset: { x: 0, y: 0 },
256
+ rotation: 0
257
+ })
258
+ }));
259
+ },
260
+ setGaze: (gaze) => {
261
+ set({
262
+ gaze: {
263
+ x: clampUnit(gaze.x),
264
+ y: clampUnit(gaze.y)
265
+ }
266
+ });
267
+ },
268
+ setLanguage: (lang) => {
269
+ set((state) => ({
270
+ faceSettings: mergeFaceSettings(state.faceSettings, {
271
+ selectedLanguage: lang
272
+ })
273
+ }));
274
+ },
275
+ setAssetBaseUrl: (assetBaseUrl) => {
276
+ const normalized = normalizeAssetBaseUrl(assetBaseUrl);
277
+ const updatedFaces = createBuiltInFaces(normalized);
278
+ const currentName = get().selectedFace?.name;
279
+ const matchingUpdated = updatedFaces.find((f) => f.name === currentName);
280
+ set({
281
+ assetBaseUrl: normalized,
282
+ availableFaces: updatedFaces,
283
+ selectedFace: matchingUpdated ?? get().selectedFace
284
+ });
285
+ }
286
+ });
287
+ }
288
+
289
+ // src/helpers/voice_helpers.ts
290
+ var languageDisplayNames = typeof Intl !== "undefined" && typeof Intl.DisplayNames === "function" ? new Intl.DisplayNames(["en"], { type: "language" }) : null;
291
+ function getLanguageName(code) {
292
+ if (!code) {
293
+ return "";
294
+ }
295
+ try {
296
+ const baseCode = code.split("-")[0];
297
+ if (!baseCode || !languageDisplayNames) {
298
+ return code;
299
+ }
300
+ return languageDisplayNames.of(baseCode) || code;
301
+ } catch (err) {
302
+ void err;
303
+ return code;
304
+ }
305
+ }
306
+ function formatVoiceDisplayName(rawName) {
307
+ if (!rawName) return "";
308
+ let name = rawName.replace(/^AWS - /, "").trim();
309
+ if (name.startsWith("aws:")) {
310
+ const parts = name.split(":");
311
+ name = parts[1] || name.slice(4);
312
+ }
313
+ if (!name.includes("com.apple.") && !name.includes("com.google.")) {
314
+ return name;
315
+ }
316
+ if (name.includes("com.google.")) {
317
+ const afterColon = name.split(":").pop() || name;
318
+ return afterColon.replace(/[-_]/g, " ").trim();
319
+ }
320
+ const siriMatch = name.match(
321
+ /siri_([a-zA-Z]+)_[a-zA-Z0-9-_]+?(?:_(compact|premium|enhanced))?$/i
322
+ );
323
+ if (siriMatch) {
324
+ const gender = siriMatch[1].charAt(0).toUpperCase() + siriMatch[1].slice(1).toLowerCase();
325
+ const quality = siriMatch[2] && siriMatch[2].toLowerCase() !== "compact" ? ` (${siriMatch[2].charAt(0).toUpperCase() + siriMatch[2].slice(1).toLowerCase()})` : "";
326
+ return `Siri ${gender}${quality}`;
327
+ }
328
+ const ttsMatch = name.match(
329
+ /com\.apple\.ttsbundle\.([a-zA-Z0-9]+)(?:-(compact|premium|enhanced))?/i
330
+ );
331
+ if (ttsMatch) {
332
+ const base = ttsMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
333
+ const quality = ttsMatch[2] && ttsMatch[2].toLowerCase() !== "compact" ? ` (${ttsMatch[2].charAt(0).toUpperCase() + ttsMatch[2].slice(1).toLowerCase()})` : "";
334
+ return `${base}${quality}`;
335
+ }
336
+ const speechMatch = name.match(
337
+ /com\.apple\.speech\.synthesis\.voice\.([a-zA-Z0-9_-]+)/i
338
+ );
339
+ if (speechMatch) {
340
+ return speechMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
341
+ }
342
+ const tierMatch = name.match(
343
+ /com\.apple\.voice\.(compact|enhanced|premium)\.[^.]+\.([a-zA-Z0-9_-]+)/i
344
+ );
345
+ if (tierMatch) {
346
+ const base = tierMatch[2].replace(/([a-z])([A-Z])/g, "$1 $2");
347
+ const quality = tierMatch[1].toLowerCase() !== "compact" ? ` (${tierMatch[1].charAt(0).toUpperCase() + tierMatch[1].slice(1).toLowerCase()})` : "";
348
+ return `${base}${quality}`;
349
+ }
350
+ const eloquenceMatch = name.match(
351
+ /com\.apple\.eloquence\.[^.]+\.([a-zA-Z0-9_-]+)/i
352
+ );
353
+ if (eloquenceMatch) {
354
+ return eloquenceMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
355
+ }
356
+ const segments = name.split(".");
357
+ let last = segments[segments.length - 1] || name;
358
+ last = last.replace(/[-_](compact|premium|enhanced)$/i, "");
359
+ last = last.replace(/([a-z])([A-Z])/g, "$1 $2");
360
+ last = last.replace(/[-_]/g, " ").trim();
361
+ return last || name;
362
+ }
363
+ function findMatchingVoice(voices, target) {
364
+ if (!target) return void 0;
365
+ const directUri = voices.find((v) => v.voiceURI === target);
366
+ if (directUri) return directUri;
367
+ const directName = voices.find((v) => v.name === target);
368
+ if (directName) return directName;
369
+ const targetClean = formatVoiceDisplayName(target).toLowerCase();
370
+ const cleanMatch = voices.find(
371
+ (v) => formatVoiceDisplayName(v.name).toLowerCase() === targetClean || formatVoiceDisplayName(v.voiceURI).toLowerCase() === targetClean
372
+ );
373
+ if (cleanMatch) return cleanMatch;
374
+ const lowerTarget = target.toLowerCase();
375
+ return voices.find(
376
+ (v) => v.voiceURI.toLowerCase() === lowerTarget || v.name.toLowerCase() === lowerTarget
377
+ );
378
+ }
379
+
380
+ // src/helpers/viseme_mapper.ts
381
+ var pollyVisemeToVizijPath = {
382
+ "@": "pose_pzzzfnvy",
383
+ a: "a",
384
+ e: "e_2",
385
+ E: "e",
386
+ f: "f",
387
+ i: "i",
388
+ k: "k",
389
+ l: "r",
390
+ o: "o",
391
+ O: "o_2",
392
+ p: "p",
393
+ r: "r",
394
+ s: "s",
395
+ S: "s",
396
+ t: "t",
397
+ T: "t_2",
398
+ u: "u",
399
+ sil: ""
400
+ };
401
+ var possiblePollyVisemes = Array.from(
402
+ new Set(Object.values(pollyVisemeToVizijPath).filter((v) => v.length > 0))
403
+ );
404
+ var CHAR_TO_POLLY_VISEME = {
405
+ a: "a",
406
+ b: "p",
407
+ c: "k",
408
+ d: "t",
409
+ e: "e",
410
+ f: "f",
411
+ g: "k",
412
+ h: "@",
413
+ i: "i",
414
+ j: "S",
415
+ k: "k",
416
+ l: "l",
417
+ m: "p",
418
+ n: "t",
419
+ o: "o",
420
+ p: "p",
421
+ q: "k",
422
+ r: "r",
423
+ s: "s",
424
+ t: "t",
425
+ u: "u",
426
+ v: "f",
427
+ w: "u",
428
+ x: "s",
429
+ y: "i",
430
+ z: "s"
431
+ };
432
+ function estimateVisemesFromText(text, msPerChar = 65) {
433
+ const cleaned = text.trim();
434
+ if (!cleaned) {
435
+ return [];
436
+ }
437
+ const visemes = [];
438
+ const durationSec = Math.max(0.03, msPerChar / 1e3);
439
+ for (const ch of cleaned.toLowerCase()) {
440
+ const mapped = CHAR_TO_POLLY_VISEME[ch] ?? "sil";
441
+ const prev = visemes[visemes.length - 1];
442
+ if (prev && prev.value === mapped) {
443
+ prev.time = Number((prev.time + durationSec).toFixed(4));
444
+ } else {
445
+ visemes.push({
446
+ time: Number(durationSec.toFixed(4)),
447
+ type: "viseme",
448
+ value: mapped
449
+ });
450
+ }
451
+ }
452
+ if (visemes[visemes.length - 1]?.value !== "sil") {
453
+ visemes.push({
454
+ time: 0.1,
455
+ type: "viseme",
456
+ value: "sil"
457
+ });
458
+ }
459
+ return visemes;
460
+ }
461
+
462
+ // src/services/AudioAnalyzer.ts
463
+ var AudioAnalyzer = class {
464
+ ctx = null;
465
+ analyzer = null;
466
+ data = null;
467
+ connectedElements = /* @__PURE__ */ new WeakSet();
468
+ connect(audio) {
469
+ if (typeof window === "undefined") {
470
+ return;
471
+ }
472
+ const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
473
+ if (!AudioContextCtor) {
474
+ return;
475
+ }
476
+ try {
477
+ if (!this.ctx) {
478
+ this.ctx = new AudioContextCtor();
479
+ this.analyzer = this.ctx.createAnalyser();
480
+ this.analyzer.fftSize = 256;
481
+ this.data = new Uint8Array(new ArrayBuffer(this.analyzer.frequencyBinCount));
482
+ }
483
+ if (!this.connectedElements.has(audio) && this.analyzer) {
484
+ const source = this.ctx.createMediaElementSource(audio);
485
+ source.connect(this.analyzer);
486
+ this.analyzer.connect(this.ctx.destination);
487
+ this.connectedElements.add(audio);
488
+ }
489
+ } catch (error) {
490
+ console.warn("AudioAnalyzer connect error:", error);
491
+ }
492
+ }
493
+ getAmplitude() {
494
+ if (!this.analyzer || !this.data) {
495
+ return 0;
496
+ }
497
+ this.analyzer.getByteTimeDomainData(this.data);
498
+ let sum = 0;
499
+ for (const v of this.data) {
500
+ const normalized = (v - 128) / 128;
501
+ sum += normalized * normalized;
502
+ }
503
+ return Math.sqrt(sum / this.data.length);
504
+ }
505
+ };
506
+ var audioAnalyzer = new AudioAnalyzer();
507
+
508
+ // src/services/ttsAudioCache.ts
509
+ function buildTtsCacheKey(params) {
510
+ const voice = params.voiceId.trim();
511
+ const engine = (params.engine ?? "default").trim() || "default";
512
+ const normalizedText = params.text.trim();
513
+ if (params.rate === void 0 && params.pitch === void 0) {
514
+ return `${voice}:${engine}:${normalizedText}`;
515
+ }
516
+ const rate = params.rate ?? 1;
517
+ const pitch = params.pitch ?? 1;
518
+ return `${voice}:${engine}:${rate}:${pitch}:${normalizedText}`;
519
+ }
520
+ async function blobToArrayBuffer(blob) {
521
+ if (typeof blob.arrayBuffer === "function") {
522
+ return blob.arrayBuffer();
523
+ }
524
+ return new Promise((resolve, reject) => {
525
+ const reader = new FileReader();
526
+ reader.onload = () => {
527
+ if (reader.result instanceof ArrayBuffer) {
528
+ resolve(reader.result);
529
+ } else {
530
+ reject(new Error("Failed to read Blob as ArrayBuffer"));
531
+ }
532
+ };
533
+ reader.onerror = () => {
534
+ reject(reader.error ?? new Error("FileReader error"));
535
+ };
536
+ reader.readAsArrayBuffer(blob);
537
+ });
538
+ }
539
+ var TtsAudioCache = class {
540
+ maxEntries;
541
+ enableIndexedDb;
542
+ dbName;
543
+ storeName;
544
+ memory = /* @__PURE__ */ new Map();
545
+ dbPromise = null;
546
+ constructor(options = {}) {
547
+ this.maxEntries = Math.max(1, options.maxEntries ?? 100);
548
+ this.enableIndexedDb = options.enableIndexedDb ?? true;
549
+ this.dbName = options.dbName ?? "peerbots-tts-cache";
550
+ this.storeName = options.storeName ?? "entries";
551
+ }
552
+ get size() {
553
+ return this.memory.size;
554
+ }
555
+ hasInMemory(key) {
556
+ return this.memory.has(key);
557
+ }
558
+ async get(key) {
559
+ const existing = this.memory.get(key);
560
+ if (existing) {
561
+ this.memory.delete(key);
562
+ this.memory.set(key, existing);
563
+ return existing;
564
+ }
565
+ const fromIdb = await this.readFromIndexedDb(key);
566
+ if (fromIdb) {
567
+ this.putInMemory(key, fromIdb);
568
+ return fromIdb;
569
+ }
570
+ return void 0;
571
+ }
572
+ async set(key, entry) {
573
+ const fullEntry = {
574
+ ...entry,
575
+ createdAt: entry.createdAt ?? Date.now()
576
+ };
577
+ this.putInMemory(key, fullEntry);
578
+ await this.writeToIndexedDb(key, fullEntry);
579
+ }
580
+ async delete(key) {
581
+ const removedMem = this.memory.delete(key);
582
+ const removedIdb = await this.deleteFromIndexedDb(key);
583
+ return removedMem || removedIdb;
584
+ }
585
+ async clear() {
586
+ this.memory.clear();
587
+ await this.clearIndexedDb();
588
+ }
589
+ createObjectUrl(entry) {
590
+ return URL.createObjectURL(entry.audioBlob);
591
+ }
592
+ putInMemory(key, entry) {
593
+ if (this.memory.has(key)) {
594
+ this.memory.delete(key);
595
+ }
596
+ this.memory.set(key, entry);
597
+ while (this.memory.size > this.maxEntries) {
598
+ const oldestKey = this.memory.keys().next().value;
599
+ if (oldestKey !== void 0) {
600
+ this.memory.delete(oldestKey);
601
+ } else {
602
+ break;
603
+ }
604
+ }
605
+ }
606
+ openDatabase() {
607
+ if (!this.enableIndexedDb || typeof indexedDB === "undefined") {
608
+ return Promise.resolve(null);
609
+ }
610
+ if (this.dbPromise) {
611
+ return this.dbPromise;
612
+ }
613
+ this.dbPromise = new Promise((resolve) => {
614
+ try {
615
+ const request = indexedDB.open(this.dbName, 1);
616
+ request.onupgradeneeded = () => {
617
+ const db = request.result;
618
+ if (!db.objectStoreNames.contains(this.storeName)) {
619
+ db.createObjectStore(this.storeName, { keyPath: "key" });
620
+ }
621
+ };
622
+ request.onsuccess = () => resolve(request.result);
623
+ request.onerror = () => resolve(null);
624
+ } catch (err) {
625
+ void err;
626
+ resolve(null);
627
+ }
628
+ });
629
+ return this.dbPromise;
630
+ }
631
+ async readFromIndexedDb(key) {
632
+ const db = await this.openDatabase();
633
+ if (!db) {
634
+ return void 0;
635
+ }
636
+ return new Promise((resolve) => {
637
+ try {
638
+ const tx = db.transaction(this.storeName, "readonly");
639
+ const store = tx.objectStore(this.storeName);
640
+ const req = store.get(key);
641
+ req.onsuccess = () => {
642
+ const record = req.result;
643
+ if (!record || !record.audioBuffer) {
644
+ resolve(void 0);
645
+ return;
646
+ }
647
+ resolve({
648
+ audioBlob: new Blob([record.audioBuffer], {
649
+ type: record.mimeType || "audio/mpeg"
650
+ }),
651
+ mimeType: record.mimeType || "audio/mpeg",
652
+ visemes: record.visemes,
653
+ amplitudeData: record.amplitudeData,
654
+ extrema: record.extrema,
655
+ createdAt: record.createdAt
656
+ });
657
+ };
658
+ req.onerror = () => resolve(void 0);
659
+ } catch (err) {
660
+ void err;
661
+ resolve(void 0);
662
+ }
663
+ });
664
+ }
665
+ async writeToIndexedDb(key, entry) {
666
+ const db = await this.openDatabase();
667
+ if (!db) {
668
+ return;
669
+ }
670
+ try {
671
+ const audioBuffer = await blobToArrayBuffer(entry.audioBlob);
672
+ await new Promise((resolve) => {
673
+ const tx = db.transaction(this.storeName, "readwrite");
674
+ const store = tx.objectStore(this.storeName);
675
+ const record = {
676
+ key,
677
+ audioBuffer,
678
+ mimeType: entry.mimeType,
679
+ visemes: entry.visemes,
680
+ amplitudeData: entry.amplitudeData,
681
+ extrema: entry.extrema,
682
+ createdAt: entry.createdAt
683
+ };
684
+ const req = store.put(record);
685
+ req.onsuccess = () => resolve();
686
+ req.onerror = () => resolve();
687
+ });
688
+ } catch (err) {
689
+ void err;
690
+ }
691
+ }
692
+ async deleteFromIndexedDb(key) {
693
+ const db = await this.openDatabase();
694
+ if (!db) {
695
+ return false;
696
+ }
697
+ return new Promise((resolve) => {
698
+ try {
699
+ const tx = db.transaction(this.storeName, "readwrite");
700
+ const store = tx.objectStore(this.storeName);
701
+ const req = store.delete(key);
702
+ req.onsuccess = () => resolve(true);
703
+ req.onerror = () => resolve(false);
704
+ } catch (err) {
705
+ void err;
706
+ resolve(false);
707
+ }
708
+ });
709
+ }
710
+ async clearIndexedDb() {
711
+ const db = await this.openDatabase();
712
+ if (!db) {
713
+ return;
714
+ }
715
+ await new Promise((resolve) => {
716
+ try {
717
+ const tx = db.transaction(this.storeName, "readwrite");
718
+ const store = tx.objectStore(this.storeName);
719
+ const req = store.clear();
720
+ req.onsuccess = () => resolve();
721
+ req.onerror = () => resolve();
722
+ } catch (err) {
723
+ void err;
724
+ resolve();
725
+ }
726
+ });
727
+ }
728
+ };
729
+ var defaultTtsAudioCache = new TtsAudioCache();
730
+
731
+ // src/store/faceSpeechSlice.ts
732
+ var FALLBACK_DEFAULT_VOICE = {
733
+ default: false,
734
+ lang: "en-US",
735
+ localService: false,
736
+ name: "en-US-Standard-B",
737
+ voiceURI: "en-US-Standard-B"
738
+ };
739
+ function isNativeSpeechSynthesisVoice(voice) {
740
+ if (!voice || typeof voice !== "object") {
741
+ return false;
742
+ }
743
+ if (typeof SpeechSynthesisVoice !== "undefined" && voice instanceof SpeechSynthesisVoice) {
744
+ return true;
745
+ }
746
+ return Object.prototype.toString.call(voice) === "[object SpeechSynthesisVoice]";
747
+ }
748
+ function matchesLanguage(voiceLang, selectedLang) {
749
+ if (!voiceLang || !selectedLang) {
750
+ return false;
751
+ }
752
+ return getLanguageName(voiceLang) === selectedLang || voiceLang === selectedLang || voiceLang.toLowerCase() === selectedLang.toLowerCase() || voiceLang.toLowerCase().startsWith(selectedLang.toLowerCase()) || selectedLang.toLowerCase().startsWith(voiceLang.toLowerCase());
753
+ }
754
+ function stopNativeSpeechSynthesis() {
755
+ if (typeof window !== "undefined" && "speechSynthesis" in window) {
756
+ try {
757
+ if (window.speechSynthesis.speaking || window.speechSynthesis.pending) {
758
+ window.speechSynthesis.cancel();
759
+ }
760
+ } catch (err) {
761
+ void err;
762
+ }
763
+ }
764
+ }
765
+ function createFaceSpeechSlice(sliceOptions = {}) {
766
+ let adapter = sliceOptions.speechAdapter ?? null;
767
+ const cache = sliceOptions.ttsCache === false ? null : sliceOptions.ttsCache ?? defaultTtsAudioCache;
768
+ const analyzer = sliceOptions.audioAnalyzer ?? audioAnalyzer;
769
+ const utteranceDeferMs = sliceOptions.utteranceDeferMs ?? 10;
770
+ let activeAudio = null;
771
+ let activeObjectUrl = null;
772
+ let activeUtterance = null;
773
+ let activeTimer = null;
774
+ let activeBoundaryTimer = null;
775
+ let activeGeneration = 0;
776
+ const revokeActiveObjectUrl = () => {
777
+ if (activeObjectUrl) {
778
+ try {
779
+ URL.revokeObjectURL(activeObjectUrl);
780
+ } catch (err) {
781
+ void err;
782
+ }
783
+ activeObjectUrl = null;
784
+ }
785
+ };
786
+ const cleanupActivePlayback = () => {
787
+ activeGeneration += 1;
788
+ if (activeTimer !== null) {
789
+ clearTimeout(activeTimer);
790
+ activeTimer = null;
791
+ }
792
+ if (activeBoundaryTimer !== null) {
793
+ clearTimeout(activeBoundaryTimer);
794
+ activeBoundaryTimer = null;
795
+ }
796
+ if (activeAudio) {
797
+ activeAudio.onplay = null;
798
+ activeAudio.onended = null;
799
+ activeAudio.onerror = null;
800
+ try {
801
+ activeAudio.pause();
802
+ activeAudio.currentTime = 0;
803
+ } catch (err) {
804
+ void err;
805
+ }
806
+ activeAudio = null;
807
+ }
808
+ revokeActiveObjectUrl();
809
+ if (activeUtterance) {
810
+ activeUtterance.onstart = null;
811
+ activeUtterance.onend = null;
812
+ activeUtterance.onerror = null;
813
+ activeUtterance.onboundary = null;
814
+ activeUtterance = null;
815
+ }
816
+ stopNativeSpeechSynthesis();
817
+ };
818
+ return (set, get) => {
819
+ const playNextFromQueue = () => {
820
+ const queue = get().speechQueue;
821
+ if (queue.length > 0) {
822
+ const [next, ...rest] = queue;
823
+ set({ speechQueue: rest });
824
+ void get().express(next.message, next.options);
825
+ }
826
+ };
827
+ const finishGeneration = (gen) => {
828
+ if (gen !== activeGeneration) {
829
+ return;
830
+ }
831
+ if (activeBoundaryTimer !== null) {
832
+ clearTimeout(activeBoundaryTimer);
833
+ activeBoundaryTimer = null;
834
+ }
835
+ activeAudio = null;
836
+ activeUtterance = null;
837
+ revokeActiveObjectUrl();
838
+ set({
839
+ isSpeaking: false,
840
+ speechStartTime: null,
841
+ currentAmplitude: 0
842
+ });
843
+ playNextFromQueue();
844
+ };
845
+ const expressImpl = async (message, options) => {
846
+ const speechText = (message.speech ?? "").trim();
847
+ const hasWords = speechText.length > 0;
848
+ if (sliceOptions.isSilent || options?.silent || !hasWords) {
849
+ set({
850
+ lastMessage: message,
851
+ isSpeaking: false
852
+ });
853
+ return;
854
+ }
855
+ const effectiveQueueMode = options?.queueMode ?? get().faceSettings?.speechQueueMode ?? "interrupt";
856
+ const currentlyPlaying = get().isSpeaking || activeAudio !== null || activeUtterance !== null || activeTimer !== null;
857
+ if (effectiveQueueMode === "queue" && currentlyPlaying) {
858
+ set((state) => ({
859
+ speechQueue: [...state.speechQueue, { message, options }]
860
+ }));
861
+ return;
862
+ }
863
+ cleanupActivePlayback();
864
+ const myGeneration = activeGeneration;
865
+ set({
866
+ lastMessage: message,
867
+ isSpeaking: true
868
+ });
869
+ const selectedVoice = get().getSelectedVoice();
870
+ const shouldUseAdapter = adapter !== null && typeof adapter.synthesizeSpeech === "function" && (adapter.canHandleVoice ? adapter.canHandleVoice(selectedVoice.voiceURI, selectedVoice) : true);
871
+ if (shouldUseAdapter && adapter?.synthesizeSpeech) {
872
+ try {
873
+ const cacheKey = buildTtsCacheKey({
874
+ voiceId: selectedVoice.voiceURI,
875
+ engine: selectedVoice.engine,
876
+ text: speechText
877
+ });
878
+ const cached = cache ? await cache.get(cacheKey) : void 0;
879
+ if (myGeneration !== activeGeneration) {
880
+ return;
881
+ }
882
+ let playbackUrl;
883
+ let shouldRevokeUrl = false;
884
+ let visemes = null;
885
+ let ampData = null;
886
+ let extrema = null;
887
+ if (cached && cache) {
888
+ playbackUrl = cache.createObjectUrl(cached);
889
+ shouldRevokeUrl = true;
890
+ visemes = cached.visemes ?? null;
891
+ ampData = cached.amplitudeData ?? null;
892
+ extrema = cached.extrema ?? null;
893
+ } else {
894
+ const synthesized = await adapter.synthesizeSpeech(
895
+ speechText,
896
+ selectedVoice.voiceURI,
897
+ {
898
+ engine: selectedVoice.engine,
899
+ language: get().faceSettings?.selectedLanguage
900
+ }
901
+ );
902
+ if (myGeneration !== activeGeneration) {
903
+ return;
904
+ }
905
+ visemes = synthesized.visemes ?? null;
906
+ ampData = synthesized.amplitudeData ?? null;
907
+ extrema = synthesized.extrema ?? null;
908
+ const mimeType = synthesized.mimeType || "audio/mpeg";
909
+ let blobToCache = null;
910
+ if (synthesized.audioBlob) {
911
+ blobToCache = synthesized.audioBlob;
912
+ } else if (synthesized.audioBuffer) {
913
+ blobToCache = new Blob([synthesized.audioBuffer], { type: mimeType });
914
+ }
915
+ if (blobToCache) {
916
+ if (cache) {
917
+ await cache.set(cacheKey, {
918
+ audioBlob: blobToCache,
919
+ mimeType,
920
+ visemes: synthesized.visemes,
921
+ amplitudeData: synthesized.amplitudeData,
922
+ extrema: synthesized.extrema
923
+ });
924
+ }
925
+ playbackUrl = URL.createObjectURL(blobToCache);
926
+ shouldRevokeUrl = true;
927
+ } else if (synthesized.audioUrl) {
928
+ playbackUrl = synthesized.audioUrl;
929
+ }
930
+ }
931
+ if (playbackUrl && typeof Audio !== "undefined") {
932
+ get().setSpokenVisemes(visemes);
933
+ get().setAmplitudeData(ampData, extrema);
934
+ const audio = new Audio(playbackUrl);
935
+ audio.crossOrigin = "anonymous";
936
+ activeAudio = audio;
937
+ if (shouldRevokeUrl) {
938
+ activeObjectUrl = playbackUrl;
939
+ }
940
+ analyzer.connect(audio);
941
+ audio.onplay = () => {
942
+ if (myGeneration !== activeGeneration) {
943
+ return;
944
+ }
945
+ set({
946
+ isSpeaking: true,
947
+ speechStartTime: performance.now()
948
+ });
949
+ const pollAmplitude = () => {
950
+ if (myGeneration === activeGeneration && activeAudio === audio && !audio.paused && !audio.ended) {
951
+ get().setCurrentAmplitude(analyzer.getAmplitude());
952
+ if (typeof requestAnimationFrame === "function") {
953
+ requestAnimationFrame(pollAmplitude);
954
+ }
955
+ } else if (myGeneration === activeGeneration) {
956
+ get().setCurrentAmplitude(0);
957
+ }
958
+ };
959
+ pollAmplitude();
960
+ };
961
+ audio.onended = () => {
962
+ finishGeneration(myGeneration);
963
+ };
964
+ audio.onerror = () => {
965
+ finishGeneration(myGeneration);
966
+ };
967
+ await audio.play();
968
+ return;
969
+ }
970
+ } catch (adapterError) {
971
+ console.warn(
972
+ "SpeechSynthesizerAdapter failed; falling back to Web Speech API:",
973
+ adapterError
974
+ );
975
+ if (myGeneration !== activeGeneration) {
976
+ return;
977
+ }
978
+ }
979
+ }
980
+ if (typeof window === "undefined" || typeof SpeechSynthesisUtterance === "undefined" || typeof window.speechSynthesis === "undefined") {
981
+ finishGeneration(myGeneration);
982
+ return;
983
+ }
984
+ const utterance = new SpeechSynthesisUtterance(speechText);
985
+ activeUtterance = utterance;
986
+ if (isNativeSpeechSynthesisVoice(selectedVoice)) {
987
+ utterance.voice = selectedVoice;
988
+ } else {
989
+ const nativeVoices = window.speechSynthesis.getVoices();
990
+ const matched = findMatchingVoice(nativeVoices, selectedVoice.voiceURI) || findMatchingVoice(nativeVoices, selectedVoice.name);
991
+ if (matched) {
992
+ utterance.voice = matched;
993
+ }
994
+ }
995
+ utterance.lang = selectedVoice.lang || get().faceSettings?.selectedLanguage || "en-US";
996
+ const estimatedVisemes = estimateVisemesFromText(speechText);
997
+ set({
998
+ spokenVisemes: estimatedVisemes,
999
+ amplitudeData: null,
1000
+ amplitudeExtrema: null,
1001
+ currentAmplitude: 0
1002
+ });
1003
+ utterance.onstart = () => {
1004
+ if (myGeneration !== activeGeneration) {
1005
+ return;
1006
+ }
1007
+ set({
1008
+ isSpeaking: true,
1009
+ speechStartTime: performance.now()
1010
+ });
1011
+ };
1012
+ utterance.onboundary = (event) => {
1013
+ if (myGeneration !== activeGeneration) {
1014
+ return;
1015
+ }
1016
+ if (event.name === "word") {
1017
+ get().setCurrentAmplitude(1);
1018
+ if (activeBoundaryTimer !== null) {
1019
+ clearTimeout(activeBoundaryTimer);
1020
+ }
1021
+ activeBoundaryTimer = setTimeout(() => {
1022
+ if (myGeneration === activeGeneration) {
1023
+ get().setCurrentAmplitude(0);
1024
+ }
1025
+ }, 100);
1026
+ }
1027
+ };
1028
+ utterance.onend = () => {
1029
+ finishGeneration(myGeneration);
1030
+ };
1031
+ utterance.onerror = (event) => {
1032
+ if (event.error === "not-allowed") {
1033
+ get().setSpeechAllowed(false);
1034
+ }
1035
+ finishGeneration(myGeneration);
1036
+ };
1037
+ const invokeSpeak = () => {
1038
+ activeTimer = null;
1039
+ if (myGeneration !== activeGeneration) {
1040
+ return;
1041
+ }
1042
+ try {
1043
+ if (window.speechSynthesis.paused) {
1044
+ window.speechSynthesis.resume();
1045
+ }
1046
+ window.speechSynthesis.speak(utterance);
1047
+ } catch (speakErr) {
1048
+ console.warn("SpeechSynthesis speak invocation error:", speakErr);
1049
+ finishGeneration(myGeneration);
1050
+ }
1051
+ };
1052
+ if (utteranceDeferMs <= 0) {
1053
+ invokeSpeak();
1054
+ } else {
1055
+ activeTimer = setTimeout(invokeSpeak, utteranceDeferMs);
1056
+ }
1057
+ };
1058
+ return {
1059
+ lastMessage: sliceOptions.initialMessage ?? DEFAULT_FACE_MESSAGE,
1060
+ isSpeaking: false,
1061
+ speechAllowed: false,
1062
+ selectedVoiceUri: null,
1063
+ availableVoices: [],
1064
+ spokenVisemes: null,
1065
+ amplitudeData: null,
1066
+ amplitudeExtrema: null,
1067
+ currentAmplitude: 0,
1068
+ speechStartTime: null,
1069
+ speechQueue: [],
1070
+ setSpeechAllowed: (allowed) => {
1071
+ set({ speechAllowed: allowed });
1072
+ },
1073
+ setAvailableVoices: (voices) => {
1074
+ set({ availableVoices: voices });
1075
+ },
1076
+ refreshVoices: async () => {
1077
+ const collected = [];
1078
+ const seen = /* @__PURE__ */ new Set();
1079
+ if (typeof window !== "undefined" && "speechSynthesis" in window) {
1080
+ const browserVoices = window.speechSynthesis.getVoices();
1081
+ for (const v of browserVoices) {
1082
+ if (!seen.has(v.voiceURI)) {
1083
+ seen.add(v.voiceURI);
1084
+ collected.push(v);
1085
+ }
1086
+ }
1087
+ }
1088
+ if (adapter?.fetchVoices) {
1089
+ try {
1090
+ const remoteVoices = await adapter.fetchVoices();
1091
+ for (const v of remoteVoices) {
1092
+ if (!seen.has(v.voiceURI)) {
1093
+ seen.add(v.voiceURI);
1094
+ collected.push(v);
1095
+ }
1096
+ }
1097
+ } catch (err) {
1098
+ console.warn("Failed to fetch adapter voices:", err);
1099
+ }
1100
+ }
1101
+ set({ availableVoices: collected });
1102
+ return collected;
1103
+ },
1104
+ getDefaultVoice: () => {
1105
+ const voices = get().availableVoices;
1106
+ const selectedLang = get().faceSettings?.selectedLanguage;
1107
+ if (selectedLang) {
1108
+ const langVoice = voices.find(
1109
+ (v) => matchesLanguage(v.lang, selectedLang)
1110
+ );
1111
+ if (langVoice) {
1112
+ return langVoice;
1113
+ }
1114
+ }
1115
+ const defaultFlagged = voices.find((v) => v.default === true);
1116
+ if (defaultFlagged) {
1117
+ return defaultFlagged;
1118
+ }
1119
+ if (voices.length > 0) {
1120
+ return voices[0];
1121
+ }
1122
+ return {
1123
+ ...FALLBACK_DEFAULT_VOICE,
1124
+ lang: selectedLang || "en-US"
1125
+ };
1126
+ },
1127
+ getSelectedVoice: () => {
1128
+ const uri = get().selectedVoiceUri;
1129
+ const voices = get().availableVoices;
1130
+ if (uri !== null) {
1131
+ const matched = findMatchingVoice(voices, uri);
1132
+ if (matched) {
1133
+ return matched;
1134
+ }
1135
+ }
1136
+ return get().getDefaultVoice();
1137
+ },
1138
+ setVoice: (voiceUri, voiceOptions) => {
1139
+ const prevVoice = get().selectedVoiceUri || get().getSelectedVoice()?.voiceURI;
1140
+ set({ selectedVoiceUri: voiceUri });
1141
+ if (!sliceOptions.isSilent && !voiceOptions?.silent && prevVoice && prevVoice !== voiceUri) {
1142
+ void get().express({
1143
+ title: "Switching voice",
1144
+ speech: "Switching voice",
1145
+ color: "Light Blue",
1146
+ emotion: "Neutral"
1147
+ });
1148
+ }
1149
+ },
1150
+ setSpokenVisemes: (visemes) => {
1151
+ set({ spokenVisemes: visemes });
1152
+ },
1153
+ setAmplitudeData: (data, extrema) => {
1154
+ set({
1155
+ amplitudeData: data,
1156
+ amplitudeExtrema: extrema
1157
+ });
1158
+ },
1159
+ setIsSpeaking: (isSpeaking) => {
1160
+ set({ isSpeaking });
1161
+ },
1162
+ setCurrentAmplitude: (amplitude) => {
1163
+ const gain = get().faceSettings?.amplitudeGain ?? 1;
1164
+ const scaled = amplitude * gain;
1165
+ const clamped = Number.isNaN(scaled) ? 0 : Math.min(1, Math.max(0, scaled));
1166
+ set({ currentAmplitude: clamped });
1167
+ },
1168
+ setSpeechAdapter: (nextAdapter) => {
1169
+ adapter = nextAdapter;
1170
+ },
1171
+ express: expressImpl,
1172
+ _express: expressImpl,
1173
+ stopSpeech: () => {
1174
+ cleanupActivePlayback();
1175
+ set({
1176
+ isSpeaking: false,
1177
+ speechStartTime: null,
1178
+ currentAmplitude: 0,
1179
+ spokenVisemes: null,
1180
+ amplitudeData: null,
1181
+ amplitudeExtrema: null,
1182
+ speechQueue: []
1183
+ });
1184
+ }
1185
+ };
1186
+ };
1187
+ }
1188
+
1189
+ // src/store/createPeerbotsFaceStore.ts
1190
+ function restorePersistedFace(persistedSelection, builtIns, fallback) {
1191
+ if (typeof persistedSelection === "string") {
1192
+ return builtIns.find((f) => f.name === persistedSelection) ?? fallback;
1193
+ }
1194
+ if (persistedSelection && typeof persistedSelection === "object") {
1195
+ const selectionObj = persistedSelection;
1196
+ if (typeof selectionObj.name === "string") {
1197
+ const found = builtIns.find((f) => f.name === selectionObj.name);
1198
+ if (found) {
1199
+ if (found.kind === "Vizij" && selectionObj.assetBundle && typeof selectionObj.assetBundle === "object") {
1200
+ const persistedBundle = selectionObj.assetBundle;
1201
+ const persistedGlb = persistedBundle.glb && typeof persistedBundle.glb === "object" ? persistedBundle.glb : {};
1202
+ return {
1203
+ ...found,
1204
+ assetBundle: {
1205
+ ...found.assetBundle,
1206
+ ...persistedBundle,
1207
+ glb: {
1208
+ ...found.assetBundle.glb,
1209
+ ...persistedGlb
1210
+ }
1211
+ }
1212
+ };
1213
+ }
1214
+ return found;
1215
+ }
1216
+ if (typeof selectionObj.kind === "string") {
1217
+ return persistedSelection;
1218
+ }
1219
+ }
1220
+ }
1221
+ return fallback;
1222
+ }
1223
+ function createPeerbotsFaceStore(options = {}) {
1224
+ const stateInitializer = (...args) => ({
1225
+ ...createFaceRenderingSlice(options)(...args),
1226
+ ...createFaceSpeechSlice(options)(...args)
1227
+ });
1228
+ if (!options.persistName) {
1229
+ return (0, import_zustand.createStore)()(stateInitializer);
1230
+ }
1231
+ const builtIns = createBuiltInFaces(options.assetBaseUrl);
1232
+ const fallbackFace = options.initialFace ?? builtIns[0];
1233
+ return (0, import_zustand.createStore)()(
1234
+ (0, import_middleware.persist)(stateInitializer, {
1235
+ name: options.persistName,
1236
+ version: 1,
1237
+ partialize: (state) => ({
1238
+ selectedFace: state.selectedFace,
1239
+ faceSettings: state.faceSettings,
1240
+ selectedVoiceUri: state.selectedVoiceUri,
1241
+ lastMessage: state.lastMessage
1242
+ }),
1243
+ merge: (persistedState, currentState) => {
1244
+ const persisted = persistedState ?? {};
1245
+ const restoredFace = restorePersistedFace(
1246
+ persisted.selectedFace,
1247
+ currentState.availableFaces,
1248
+ fallbackFace
1249
+ );
1250
+ const restoredSettings = persisted.faceSettings ? mergeFaceSettings(
1251
+ defaultFaceSettings,
1252
+ persisted.faceSettings
1253
+ ) : currentState.faceSettings;
1254
+ return {
1255
+ ...currentState,
1256
+ selectedFace: restoredFace,
1257
+ selectedVoiceUri: persisted.selectedVoiceUri ?? null,
1258
+ faceSettings: restoredSettings,
1259
+ lastMessage: persisted.lastMessage ?? options.initialMessage ?? DEFAULT_FACE_MESSAGE,
1260
+ isSpeaking: false
1261
+ };
1262
+ }
1263
+ })
1264
+ );
1265
+ }
1266
+ var globalFaceStore = createPeerbotsFaceStore({
1267
+ persistName: "faceSettings"
1268
+ });
1269
+
1270
+ // src/store/FaceStoreContext.tsx
1271
+ var import_jsx_runtime = require("react/jsx-runtime");
1272
+ var FaceStoreContext = (0, import_react.createContext)(null);
1273
+ function useFaceStoreInstance() {
1274
+ const context = (0, import_react.useContext)(FaceStoreContext);
1275
+ return context ?? globalFaceStore;
1276
+ }
1277
+ function useFaceStoreBase(selector) {
1278
+ const store = useFaceStoreInstance();
1279
+ return (0, import_zustand2.useStore)(store, selector);
1280
+ }
1281
+ var useFaceStore = Object.assign(useFaceStoreBase, {
1282
+ getState: () => globalFaceStore.getState(),
1283
+ setState: ((...args) => globalFaceStore.setState(...args)),
1284
+ subscribe: ((...args) => globalFaceStore.subscribe(...args))
1285
+ });
1286
+
1287
+ // src/helpers/color_mappers.ts
1288
+ var color_mapping = {
1289
+ "Light Blue": "#ABE3FA",
1290
+ Blue: "#5F94D6",
1291
+ Green: "#65C77D",
1292
+ Red: "#E6817E",
1293
+ Purple: "#9B86F3",
1294
+ Pink: "#EBA4E4",
1295
+ Yellow: "#F8EDB1",
1296
+ Orange: "#E6A575",
1297
+ Grey: "#CECECE",
1298
+ Black: "#4D4D4D",
1299
+ White: "#FDFEFE"
1300
+ };
1301
+ function hexToRgb(hex) {
1302
+ const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
1303
+ const expanded = hex.replace(shorthandRegex, (_m, r, g, b) => {
1304
+ return r + r + g + g + b + b;
1305
+ });
1306
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(expanded);
1307
+ return result ? {
1308
+ r: parseInt(result[1], 16),
1309
+ g: parseInt(result[2], 16),
1310
+ b: parseInt(result[3], 16)
1311
+ } : null;
1312
+ }
1313
+
1314
+ // src/types/labels.ts
1315
+ var DEFAULT_FACE_UI_LABELS = {
1316
+ loading: "Loading...",
1317
+ poweredBy: "Powered by",
1318
+ tapToEnableSound: "Tap to enable sound",
1319
+ allowSpeech: "Allow Speech",
1320
+ characterSelection: "Character & Voice",
1321
+ face: "Character",
1322
+ uploadGlb: "Upload .GLB Rig",
1323
+ vizijUploadGlb: "Upload a .glb file in Face Settings to preview Custom Face",
1324
+ vizijErrorPrefix: "3D Face Error:",
1325
+ faceCapabilities: "Face Capabilities",
1326
+ color: "Color",
1327
+ emotion: "Emotion",
1328
+ speech: "Speech",
1329
+ faceSpecificSettings: "Face-Specific Settings",
1330
+ faceExpressivity: "Face Expressivity",
1331
+ eyes: "Eyes",
1332
+ mouth: "Mouth",
1333
+ cheeks: "Cheeks",
1334
+ emotionDisplay: "Emotion Display",
1335
+ defaultOption: "Default",
1336
+ noneOption: "None",
1337
+ emoticon: "Emoticon",
1338
+ emoji: "Emoji",
1339
+ positioning: "Face Positioning",
1340
+ autoRotate: "Auto-Rotate",
1341
+ rotate: "Rotate 90\xB0",
1342
+ reset: "Reset",
1343
+ zoom: "Zoom",
1344
+ horizontalOffset: "Horizontal Offset",
1345
+ verticalOffset: "Vertical Offset",
1346
+ faceSettings: "Face Settings",
1347
+ onFaceButtons: "On-Face Controls",
1348
+ showFullScreenButton: "Show Fullscreen Button",
1349
+ showScrollButton: "Show Scroll-to-Top Button",
1350
+ speechBehavior: "Speech Playback Behavior",
1351
+ newButtonSpeech: "When new speech arrives",
1352
+ interruptSpeech: "Interrupt current speech",
1353
+ queueSpeech: "Queue after current speech",
1354
+ captions: "Captions",
1355
+ fontSize: "Caption Font Size",
1356
+ verticalPosition: "Vertical Position",
1357
+ voiceSelectorLanguage: "Language",
1358
+ voiceSelectorVoice: "Voice",
1359
+ unknownFaceType: "Unknown Face Type"
1360
+ };
1361
+ function resolveFaceUiLabels(overrides) {
1362
+ if (!overrides) {
1363
+ return DEFAULT_FACE_UI_LABELS;
1364
+ }
1365
+ return {
1366
+ ...DEFAULT_FACE_UI_LABELS,
1367
+ ...overrides
1368
+ };
1369
+ }
1370
+
1371
+ // src/components/VizijFaceView.tsx
1372
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1373
+ function VizijFallback({ labels }) {
1374
+ const { loading, error, ready } = (0, import_runtime_react.useVizijRuntime)();
1375
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center justify-center w-full h-full text-white bg-slate-900 p-4 text-sm", children: [
1376
+ (loading || !ready) && !error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { children: labels.loading }),
1377
+ error && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1378
+ labels.vizijErrorPrefix,
1379
+ " ",
1380
+ error.message
1381
+ ] })
1382
+ ] });
1383
+ }
1384
+ function VizijPoseSetter() {
1385
+ const { ready, animateValue, faceId, setInput } = (0, import_runtime_react.useVizijRuntime)();
1386
+ const settings = useFaceStore((state) => state.faceSettings);
1387
+ const lastMessage = useFaceStore((state) => state.lastMessage);
1388
+ const selectedFace = useFaceStore((state) => state.selectedFace);
1389
+ const spokenVisemes = useFaceStore((state) => state.spokenVisemes);
1390
+ const expressEmotion = (0, import_react2.useCallback)(
1391
+ (emotion) => {
1392
+ const expressivity = settings.vizijSettings?.faceExpressivity ?? 1;
1393
+ void animateValue(
1394
+ `rig/${faceId}/emotions/surprise.weight`,
1395
+ (emotion === "Surprised" ? 1 : 0) * expressivity,
1396
+ { duration: 0.2 }
1397
+ );
1398
+ void animateValue(
1399
+ `rig/${faceId}/emotions/happy.weight`,
1400
+ (emotion === "Happy" ? 1 : 0) * expressivity,
1401
+ { duration: 0.2 }
1402
+ );
1403
+ void animateValue(
1404
+ `rig/${faceId}/emotions/sad.weight`,
1405
+ (emotion === "Sad" ? 1 : 0) * expressivity,
1406
+ { duration: 0.2 }
1407
+ );
1408
+ void animateValue(
1409
+ `rig/${faceId}/emotions/concerned.weight`,
1410
+ (emotion === "Concerned" ? 1 : 0) * expressivity,
1411
+ { duration: 0.2 }
1412
+ );
1413
+ void animateValue(
1414
+ `rig/${faceId}/emotions/sleepy.weight`,
1415
+ (emotion === "Sleepy" ? 1 : 0) * expressivity,
1416
+ { duration: 0.2 }
1417
+ );
1418
+ },
1419
+ [animateValue, faceId, settings.vizijSettings?.faceExpressivity]
1420
+ );
1421
+ const expressColor = (0, import_react2.useCallback)(
1422
+ (color) => {
1423
+ const rgbColor = hexToRgb(color_mapping[color]) ?? {
1424
+ r: 0,
1425
+ g: 0,
1426
+ b: 0
1427
+ };
1428
+ void animateValue(`rig/${faceId}/background/color/r`, rgbColor.r / 255, {
1429
+ duration: 0.2
1430
+ });
1431
+ void animateValue(`rig/${faceId}/background/color/g`, rgbColor.g / 255, {
1432
+ duration: 0.2
1433
+ });
1434
+ void animateValue(`rig/${faceId}/background/color/b`, rgbColor.b / 255, {
1435
+ duration: 0.2
1436
+ });
1437
+ },
1438
+ [faceId, animateValue]
1439
+ );
1440
+ const expressViseme = (0, import_react2.useCallback)(
1441
+ (viseme, durationSec, prevViseme) => {
1442
+ const visemeVizijPath = pollyVisemeToVizijPath[viseme];
1443
+ const promises = [];
1444
+ if (viseme === "sil") {
1445
+ possiblePollyVisemes.forEach((target) => {
1446
+ promises.push(
1447
+ animateValue(`rig/${faceId}/visemes/${target}.weight`, 0, {
1448
+ duration: durationSec
1449
+ })
1450
+ );
1451
+ });
1452
+ } else if (visemeVizijPath) {
1453
+ promises.push(
1454
+ animateValue(`rig/${faceId}/visemes/${visemeVizijPath}.weight`, 1, {
1455
+ duration: durationSec
1456
+ })
1457
+ );
1458
+ if (prevViseme) {
1459
+ const prevMappedViseme = pollyVisemeToVizijPath[prevViseme];
1460
+ if (prevMappedViseme && prevMappedViseme !== visemeVizijPath) {
1461
+ promises.push(
1462
+ animateValue(
1463
+ `rig/${faceId}/visemes/${prevMappedViseme}.weight`,
1464
+ 0,
1465
+ { duration: durationSec }
1466
+ )
1467
+ );
1468
+ }
1469
+ }
1470
+ }
1471
+ return Promise.all(promises);
1472
+ },
1473
+ [animateValue, faceId]
1474
+ );
1475
+ const expressTimedVisemes = (0, import_react2.useCallback)(
1476
+ async (visemes) => {
1477
+ let prevViseme;
1478
+ for (const viseme of visemes) {
1479
+ const visemeValue = viseme.value;
1480
+ await expressViseme(visemeValue, viseme.time, prevViseme);
1481
+ prevViseme = visemeValue;
1482
+ }
1483
+ },
1484
+ [expressViseme]
1485
+ );
1486
+ (0, import_react2.useEffect)(() => {
1487
+ if (ready) {
1488
+ expressColor(lastMessage.color);
1489
+ expressEmotion(lastMessage.emotion);
1490
+ }
1491
+ }, [
1492
+ ready,
1493
+ lastMessage.color,
1494
+ lastMessage.emotion,
1495
+ expressColor,
1496
+ expressEmotion
1497
+ ]);
1498
+ (0, import_react2.useEffect)(() => {
1499
+ if (ready && selectedFace?.kind === "Vizij") {
1500
+ setInput(`rig/${faceId}/scene/scale/x`, settings.zoom);
1501
+ setInput(`rig/${faceId}/scene/scale/y`, settings.zoom);
1502
+ setInput(
1503
+ `rig/${faceId}/scene/translation/x`,
1504
+ (settings.offset?.x ?? 0) / 620 - 1
1505
+ );
1506
+ setInput(
1507
+ `rig/${faceId}/scene/translation/y`,
1508
+ (settings.offset?.y ?? 0) / 144 + 1
1509
+ );
1510
+ }
1511
+ }, [ready, selectedFace?.kind, faceId, setInput, settings]);
1512
+ (0, import_react2.useEffect)(() => {
1513
+ if (spokenVisemes !== null && ready) {
1514
+ void expressTimedVisemes(spokenVisemes);
1515
+ }
1516
+ }, [spokenVisemes, ready, expressTimedVisemes]);
1517
+ return null;
1518
+ }
1519
+ var ROTATION_CLASS = {
1520
+ 0: "rotate-0 w-full h-full",
1521
+ 90: "rotate-90 w-full h-full",
1522
+ 180: "rotate-180 w-full h-full",
1523
+ 270: "rotate-270 w-full h-full"
1524
+ };
1525
+ function VizijFaceView({ labels } = {}) {
1526
+ const uiLabels = resolveFaceUiLabels(labels);
1527
+ const selectedFace = useFaceStore((state) => state.selectedFace);
1528
+ const settings = useFaceStore((state) => state.faceSettings);
1529
+ if (selectedFace?.kind !== "Vizij") {
1530
+ return null;
1531
+ }
1532
+ const normalizedRot = (settings.rotation % 360 + 360) % 360;
1533
+ const rotClass = ROTATION_CLASS[normalizedRot] ?? ROTATION_CLASS[0];
1534
+ const glb = selectedFace.assetBundle?.glb;
1535
+ const hasGlbUrl = Boolean(glb) && "kind" in glb && glb.kind === "url" && Boolean(glb.src);
1536
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: rotClass, "data-testid": "vizij-face-view", children: hasGlbUrl ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_runtime_react.VizijRuntimeProvider, { assetBundle: selectedFace.assetBundle, autostart: true, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react2.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(VizijFallback, { labels: uiLabels }), children: [
1537
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_runtime_react.VizijRuntimeFace, { className: "bg-black w-full h-full" }),
1538
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(VizijPoseSetter, {})
1539
+ ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex items-center justify-center h-full text-white bg-slate-900 p-4 text-sm", children: uiLabels.vizijUploadGlb }) });
1540
+ }
1541
+ var VizijFaceView_default = VizijFaceView;
1542
+ // Annotate the CommonJS export names for ESM import in node:
1543
+ 0 && (module.exports = {
1544
+ VizijFaceView
1545
+ });
1546
+ //# sourceMappingURL=vizij.cjs.map