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