@asiyst/sdk 0.1.21 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,29 @@
1
1
  'use strict';
2
2
 
3
+ var THREE = require('three');
4
+ var FBXLoader_js = require('three/examples/jsm/loaders/FBXLoader.js');
5
+ var GLTFLoader_js = require('three/examples/jsm/loaders/GLTFLoader.js');
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var THREE__namespace = /*#__PURE__*/_interopNamespace(THREE);
26
+
3
27
  // src/errors/index.ts
4
28
  var AsiystError = class extends Error {
5
29
  constructor(code, message) {
@@ -73,7 +97,7 @@ var ALL_ACTION_KINDS = [
73
97
  // src/core/constants.ts
74
98
  function resolveSdkVersion() {
75
99
  {
76
- return "0.1.20";
100
+ return "0.1.21";
77
101
  }
78
102
  }
79
103
  var SDK_VERSION = resolveSdkVersion();
@@ -310,6 +334,12 @@ function fallbackConfig() {
310
334
  version: 0,
311
335
  avatarName: "Asiyst",
312
336
  avatar: "avatar_default",
337
+ avatarId: void 0,
338
+ assetUrl: void 0,
339
+ thumbnailUrl: void 0,
340
+ publishedVersion: void 0,
341
+ animations: [],
342
+ branding: void 0,
313
343
  size: 96,
314
344
  position: "bottom-right",
315
345
  animation: "friendly",
@@ -333,22 +363,69 @@ function fallbackConfig() {
333
363
  elementSelectors: {}
334
364
  };
335
365
  }
366
+ function parseAnimations(value) {
367
+ if (!Array.isArray(value)) return void 0;
368
+ const list = [];
369
+ for (const item of value) {
370
+ if (isRecord(item) && typeof item.name === "string") {
371
+ list.push({
372
+ id: typeof item.id === "string" ? sanitizeText(item.id, 64) : void 0,
373
+ name: sanitizeText(item.name, 64),
374
+ intent: typeof item.intent === "string" ? sanitizeText(item.intent, 64) : void 0,
375
+ clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
376
+ loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
377
+ durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
378
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
379
+ });
380
+ }
381
+ }
382
+ return list;
383
+ }
384
+ function parseBranding(value) {
385
+ if (!isRecord(value)) return void 0;
386
+ return {
387
+ siteLogoUrl: typeof value.siteLogoUrl === "string" ? value.siteLogoUrl : null
388
+ };
389
+ }
336
390
  function normalizeProjectConfig(raw) {
337
391
  const base = fallbackConfig();
338
392
  if (!isRecord(raw)) {
339
393
  return base;
340
394
  }
395
+ const rawAvatarRecord = isRecord(raw.avatar) ? raw.avatar : void 0;
396
+ const avatarId = asString(
397
+ raw.avatarId ?? rawAvatarRecord?.avatarId ?? rawAvatarRecord?.id,
398
+ "",
399
+ 128
400
+ ) || void 0;
401
+ const assetUrl = typeof raw.assetUrl === "string" ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" ? rawAvatarRecord.assetUrl : void 0;
402
+ const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
403
+ const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : void 0;
404
+ const animations = parseAnimations(raw.animations ?? rawAvatarRecord?.animations);
405
+ const branding = parseBranding(raw.branding);
406
+ const avatarName = asString(
407
+ raw.avatarName ?? rawAvatarRecord?.name,
408
+ base.avatarName,
409
+ 40
410
+ );
411
+ const avatar = typeof raw.avatar === "string" ? asString(raw.avatar, base.avatar, 64) : avatarId ?? base.avatar;
341
412
  const position = ANCHORS.includes(raw.position) ? raw.position : base.position;
342
413
  return {
343
414
  schemaVersion: CONFIG_SCHEMA_VERSION,
344
415
  version: asNumber(raw.version, base.version, 0, Number.MAX_SAFE_INTEGER),
345
- avatarName: asString(raw.avatarName, base.avatarName, 40),
346
- avatar: asString(raw.avatar, base.avatar, 64),
416
+ avatarName,
417
+ avatar,
418
+ avatarId,
419
+ assetUrl,
420
+ thumbnailUrl,
421
+ publishedVersion,
422
+ animations,
423
+ branding,
347
424
  size: asNumber(raw.size, base.size, 48, 220),
348
425
  position,
349
426
  voice: typeof raw.voice === "string" ? sanitizeText(raw.voice, 64) : void 0,
350
427
  animation: asString(raw.animation, base.animation ?? "friendly", 40),
351
- theme: { ...base.theme, ...parseTheme(raw.theme) },
428
+ theme: { ...base.theme, ...parseTheme(raw.theme ?? rawAvatarRecord?.theme) },
352
429
  personality: parsePersonality(raw.personality),
353
430
  behavior: { ...base.behavior, ...parseBehavior(raw.behavior) },
354
431
  mode: raw.mode === "assist" ? "assist" : "guided",
@@ -435,6 +512,12 @@ var HttpTransport = class {
435
512
  constructor(options) {
436
513
  this.options = options;
437
514
  }
515
+ getApiBaseUrl() {
516
+ return this.options.apiBaseUrl;
517
+ }
518
+ getAvatarId() {
519
+ return this.options.avatarId;
520
+ }
438
521
  async request(req) {
439
522
  const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
440
523
  const requestId = req.requestId || generateRequestId();
@@ -531,13 +614,17 @@ var HttpTransport = class {
531
614
 
532
615
  // src/communication/CloudClient.ts
533
616
  var CloudClient = class {
534
- constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId) {
617
+ constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
535
618
  this.transport = transport;
536
619
  this.projectId = projectId;
537
620
  this.publicKey = publicKey;
538
621
  this.runtimeAuth = runtimeAuth;
622
+ this.avatarId = avatarId;
539
623
  this.inFlightConversations = /* @__PURE__ */ new Map();
540
624
  this.sessionId = sessionId;
625
+ if (!this.avatarId && typeof transport.getAvatarId === "function") {
626
+ this.avatarId = transport.getAvatarId();
627
+ }
541
628
  }
542
629
  setSessionId(sessionId) {
543
630
  this.sessionId = sessionId;
@@ -551,6 +638,18 @@ var CloudClient = class {
551
638
  getConversationId() {
552
639
  return this.conversationId;
553
640
  }
641
+ getAvatarId() {
642
+ return this.avatarId;
643
+ }
644
+ setAvatarId(avatarId) {
645
+ this.avatarId = avatarId;
646
+ }
647
+ getApiBaseUrl() {
648
+ if (typeof this.transport.getApiBaseUrl === "function") {
649
+ return this.transport.getApiBaseUrl();
650
+ }
651
+ return DEFAULT_API_BASE_URL;
652
+ }
554
653
  async getAuthToken(capability) {
555
654
  if (!this.runtimeAuth) return void 0;
556
655
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
@@ -565,33 +664,116 @@ var CloudClient = class {
565
664
  return this.inFlightToken;
566
665
  }
567
666
  async fetchConfig() {
667
+ const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
668
+ const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
669
+ const baseUrl = this.getApiBaseUrl();
670
+ const resolveAssetUrls = (raw) => {
671
+ const canonicalBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
672
+ if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
673
+ const av = { ...raw.avatar };
674
+ if (typeof av.assetUrl === "string" && av.assetUrl.startsWith("/")) {
675
+ av.assetUrl = new URL(av.assetUrl, canonicalBase).href;
676
+ }
677
+ if (typeof av.thumbnailUrl === "string" && av.thumbnailUrl.startsWith("/")) {
678
+ av.thumbnailUrl = new URL(av.thumbnailUrl, canonicalBase).href;
679
+ }
680
+ if (Array.isArray(av.animations)) {
681
+ av.animations = av.animations.map((item) => {
682
+ if (item && typeof item === "object") {
683
+ const animObj = item;
684
+ if (typeof animObj.assetUrl === "string" && animObj.assetUrl.startsWith("/")) {
685
+ return { ...animObj, assetUrl: new URL(animObj.assetUrl, canonicalBase).href };
686
+ }
687
+ }
688
+ return item;
689
+ });
690
+ }
691
+ raw.avatar = av;
692
+ }
693
+ if (typeof raw.assetUrl === "string" && raw.assetUrl.startsWith("/")) {
694
+ raw.assetUrl = new URL(raw.assetUrl, canonicalBase).href;
695
+ }
696
+ if (typeof raw.thumbnailUrl === "string" && raw.thumbnailUrl.startsWith("/")) {
697
+ raw.thumbnailUrl = new URL(raw.thumbnailUrl, canonicalBase).href;
698
+ }
699
+ if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
700
+ const br = { ...raw.branding };
701
+ if (typeof br.siteLogoUrl === "string" && br.siteLogoUrl.startsWith("/")) {
702
+ br.siteLogoUrl = new URL(br.siteLogoUrl, canonicalBase).href;
703
+ }
704
+ raw.branding = br;
705
+ }
706
+ return raw;
707
+ };
708
+ let lastError;
568
709
  try {
569
710
  const response = await this.runtimeRequest({
570
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
711
+ path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
571
712
  method: "GET",
572
713
  idempotent: true
573
714
  });
574
715
  if (response.ok && response.data) {
575
- return normalizeProjectConfig(response.data.config ?? response.data);
716
+ const dataObj = response.data.config ?? response.data;
717
+ return normalizeProjectConfig(resolveAssetUrls(dataObj));
576
718
  }
577
- } catch {
719
+ if (response.status === 404) {
720
+ lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
721
+ }
722
+ } catch (err) {
723
+ if (err instanceof Error) lastError = err;
578
724
  }
579
725
  try {
580
- const res = await fetch(`https://asiyst.com/api/v1/runtime/avatar?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}`, {
581
- headers: { Accept: "application/json" }
726
+ const runtimeResponse = await this.runtimeRequest({
727
+ path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
728
+ method: "GET",
729
+ idempotent: true
730
+ });
731
+ if (runtimeResponse.ok && runtimeResponse.data) {
732
+ return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
733
+ }
734
+ if (runtimeResponse.status === 404) {
735
+ lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
736
+ }
737
+ } catch (err) {
738
+ if (err instanceof Error) lastError = err;
739
+ }
740
+ try {
741
+ const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
742
+ const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
743
+ const res = await fetch(fullUrl, {
744
+ headers: {
745
+ Accept: "application/json",
746
+ "x-asiyst-public-key": this.publicKey
747
+ }
582
748
  });
583
749
  if (res.ok) {
584
750
  const body = await res.json();
585
- if (body?.avatar) {
586
- return normalizeProjectConfig({
587
- avatarName: body.avatar.name,
588
- avatarId: body.avatar.avatarId
589
- });
751
+ if (body && typeof body === "object") {
752
+ return normalizeProjectConfig(resolveAssetUrls(body));
753
+ }
754
+ } else {
755
+ const errorBody = await res.json().catch(() => ({}));
756
+ const errObj = errorBody?.error ?? errorBody;
757
+ const code = String(errObj?.code ?? "");
758
+ const message = String(errObj?.message ?? `HTTP ${res.status}`);
759
+ if (res.status === 404) {
760
+ throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
761
+ } else if (res.status === 401 || res.status === 403) {
762
+ throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
763
+ } else if (res.status >= 500) {
764
+ throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
590
765
  }
591
766
  }
592
- } catch {
767
+ } catch (err) {
768
+ if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
769
+ throw err;
770
+ }
771
+ if (err instanceof Error) lastError = err;
772
+ }
773
+ if (lastError) {
774
+ throw lastError;
593
775
  }
594
- return normalizeProjectConfig({});
776
+ throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
595
777
  }
596
778
  async heartbeat(metadata) {
597
779
  const response = await this.runtimeRequest({
@@ -696,18 +878,32 @@ var CloudClient = class {
696
878
  try {
697
879
  const origin = typeof window !== "undefined" ? window.location.origin : void 0;
698
880
  const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
881
+ const sanitizedMeta = {
882
+ sdkVersion: SDK_VERSION
883
+ };
884
+ for (const [key, val] of Object.entries(metadata)) {
885
+ if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
886
+ continue;
887
+ }
888
+ if (typeof val === "string") {
889
+ sanitizedMeta[key] = sanitizeText(val, 512);
890
+ } else if (typeof val === "number" || typeof val === "boolean") {
891
+ sanitizedMeta[key] = val;
892
+ } else if (val && typeof val === "object" && !Array.isArray(val)) {
893
+ sanitizedMeta[key] = val;
894
+ }
895
+ }
699
896
  const payload = {
700
897
  projectId: this.projectId,
701
898
  publicKey: this.publicKey,
702
899
  eventType,
703
900
  installationId,
704
901
  origin,
705
- metadata: {
706
- ...metadata,
707
- sdkVersion: SDK_VERSION
708
- }
902
+ metadata: sanitizedMeta
709
903
  };
710
- await fetch("https://asiyst.com/api/v1/events", {
904
+ const baseUrl = this.getApiBaseUrl();
905
+ const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
906
+ await fetch(targetUrl, {
711
907
  method: "POST",
712
908
  headers: {
713
909
  "Content-Type": "application/json",
@@ -1522,6 +1718,617 @@ var HighlightLayer = class {
1522
1718
  }
1523
1719
  };
1524
1720
 
1721
+ // src/avatar/AssetLoader.ts
1722
+ var GLB_MAGIC = 1179937895;
1723
+ var CHUNK_TYPE_JSON = 1313821514;
1724
+ var CHUNK_TYPE_BIN = 5130562;
1725
+ var AssetLoader = class {
1726
+ constructor() {
1727
+ this.inFlightController = null;
1728
+ this.createdObjectUrls = [];
1729
+ }
1730
+ async load(assetUrl, options) {
1731
+ const startTime = Date.now();
1732
+ const sanitizedUrl = sanitizeText(assetUrl.trim(), 2048);
1733
+ if (!sanitizedUrl) {
1734
+ throw new Error("Asset URL is required");
1735
+ }
1736
+ this.inFlightController = new AbortController();
1737
+ const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1738
+ const timeoutMs = options?.timeoutMs ?? 15e3;
1739
+ const timeoutId = setTimeout(() => {
1740
+ this.inFlightController?.abort();
1741
+ }, timeoutMs);
1742
+ try {
1743
+ const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1744
+ const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
1745
+ const isJsonExtension = /\.json$/i.test(cleanPath);
1746
+ const isFbxExtension = /\.fbx$/i.test(cleanPath);
1747
+ const isGlbExtension = /\.glb$/i.test(cleanPath);
1748
+ if (isImageExtension) {
1749
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1750
+ return {
1751
+ format: "image",
1752
+ url: sanitizedUrl,
1753
+ image: imageResult.element,
1754
+ width: imageResult.width,
1755
+ height: imageResult.height,
1756
+ durationMs: Date.now() - startTime
1757
+ };
1758
+ }
1759
+ let response;
1760
+ try {
1761
+ response = await fetch(sanitizedUrl, {
1762
+ method: "GET",
1763
+ headers: {
1764
+ Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1765
+ },
1766
+ signal: abortSignal
1767
+ });
1768
+ } catch (err) {
1769
+ if (err instanceof Error && err.name === "AbortError") {
1770
+ throw new Error("Avatar asset request timed out or was aborted");
1771
+ }
1772
+ throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
1773
+ }
1774
+ if (!response.ok) {
1775
+ throw new Error(`Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`);
1776
+ }
1777
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
1778
+ if (isJsonExtension || contentType.includes("application/json")) {
1779
+ const text = await response.text();
1780
+ let manifest;
1781
+ try {
1782
+ manifest = JSON.parse(text);
1783
+ } catch {
1784
+ throw new Error("Invalid avatar manifest: JSON decoding failed");
1785
+ }
1786
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1787
+ throw new Error("Invalid avatar manifest schema");
1788
+ }
1789
+ return {
1790
+ format: "manifest",
1791
+ url: sanitizedUrl,
1792
+ manifest,
1793
+ durationMs: Date.now() - startTime
1794
+ };
1795
+ }
1796
+ if (contentType.startsWith("image/")) {
1797
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1798
+ return {
1799
+ format: "image",
1800
+ url: sanitizedUrl,
1801
+ image: imageResult.element,
1802
+ width: imageResult.width,
1803
+ height: imageResult.height,
1804
+ durationMs: Date.now() - startTime
1805
+ };
1806
+ }
1807
+ const arrayBuffer = await response.arrayBuffer();
1808
+ if (arrayBuffer.byteLength < 12) {
1809
+ throw new Error("Avatar asset payload is too small to be a valid 3D container");
1810
+ }
1811
+ if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1812
+ const fbxHeader = this.parseFbxHeader(arrayBuffer);
1813
+ const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1814
+ return {
1815
+ format: "fbx",
1816
+ url: sanitizedUrl,
1817
+ buffer: arrayBuffer,
1818
+ version: fbxHeader.version,
1819
+ isBinary: fbxHeader.isBinary,
1820
+ resourcePath,
1821
+ durationMs: Date.now() - startTime
1822
+ };
1823
+ }
1824
+ const parsedGlb = this.parseGlb(arrayBuffer);
1825
+ return {
1826
+ format: "glb",
1827
+ url: sanitizedUrl,
1828
+ json: parsedGlb.json,
1829
+ bin: parsedGlb.bin,
1830
+ meshes: parsedGlb.meshes,
1831
+ embeddedImageUrls: parsedGlb.embeddedImageUrls,
1832
+ durationMs: Date.now() - startTime
1833
+ };
1834
+ } finally {
1835
+ clearTimeout(timeoutId);
1836
+ this.inFlightController = null;
1837
+ }
1838
+ }
1839
+ isFbxBuffer(buffer) {
1840
+ if (buffer.byteLength < 18) return false;
1841
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1842
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1843
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1844
+ return true;
1845
+ }
1846
+ const sample = new TextDecoder("utf-8").decode(bytes);
1847
+ return sample.startsWith("; FBX") || sample.includes("FBXHeaderExtension");
1848
+ }
1849
+ parseFbxHeader(buffer) {
1850
+ if (buffer.byteLength < 18) {
1851
+ throw new Error("Corrupted FBX asset: payload is too small to contain an FBX header");
1852
+ }
1853
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1854
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1855
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1856
+ if (buffer.byteLength < 27) {
1857
+ throw new Error("Corrupted binary FBX asset: payload is truncated");
1858
+ }
1859
+ const view = new DataView(buffer);
1860
+ const version = view.getUint32(23, true);
1861
+ if (version < 6400) {
1862
+ throw new Error(`Unsupported legacy FBX version: ${version}. Versions prior to 6.4 (6400) are not supported.`);
1863
+ }
1864
+ return { isBinary: true, version };
1865
+ }
1866
+ const textSample = new TextDecoder("utf-8").decode(bytes);
1867
+ if (textSample.startsWith("; FBX") || textSample.includes("FBXHeaderExtension")) {
1868
+ const match = textSample.match(/;\s*FBX\s*(\d+(?:\.\d+)?)/i);
1869
+ const version = match && match[1] ? Math.round(parseFloat(match[1]) * 1e3) : void 0;
1870
+ return { isBinary: false, version };
1871
+ }
1872
+ throw new Error("Invalid FBX container: header does not match Kaydara binary or ASCII FBX signatures");
1873
+ }
1874
+ isGlbBuffer(buffer) {
1875
+ if (buffer.byteLength < 4) return false;
1876
+ const view = new DataView(buffer);
1877
+ return view.getUint32(0, true) === GLB_MAGIC;
1878
+ }
1879
+ async loadImage(url, signal) {
1880
+ if (typeof Image === "undefined") {
1881
+ return { width: 96, height: 96 };
1882
+ }
1883
+ return new Promise((resolve, reject) => {
1884
+ const img = new Image();
1885
+ img.crossOrigin = "anonymous";
1886
+ const onAbort = () => {
1887
+ img.src = "";
1888
+ reject(new Error("Image loading aborted"));
1889
+ };
1890
+ if (signal) {
1891
+ if (signal.aborted) {
1892
+ return reject(new Error("Image loading aborted"));
1893
+ }
1894
+ signal.addEventListener("abort", onAbort, { once: true });
1895
+ }
1896
+ img.onload = () => {
1897
+ if (signal) signal.removeEventListener("abort", onAbort);
1898
+ resolve({
1899
+ element: img,
1900
+ width: img.naturalWidth || 96,
1901
+ height: img.naturalHeight || 96
1902
+ });
1903
+ };
1904
+ img.onerror = () => {
1905
+ if (signal) signal.removeEventListener("abort", onAbort);
1906
+ reject(new Error(`Failed to load avatar image asset from ${url}`));
1907
+ };
1908
+ img.src = url;
1909
+ });
1910
+ }
1911
+ parseGlb(buffer) {
1912
+ const view = new DataView(buffer);
1913
+ const magic = view.getUint32(0, true);
1914
+ if (magic !== GLB_MAGIC) {
1915
+ throw new Error(`Invalid GLB container header: expected 0x${GLB_MAGIC.toString(16)}, received 0x${magic.toString(16)}`);
1916
+ }
1917
+ const version = view.getUint32(4, true);
1918
+ if (version !== 2) {
1919
+ throw new Error(`Unsupported glTF version: ${version}. Only version 2 is supported.`);
1920
+ }
1921
+ const totalLength = view.getUint32(8, true);
1922
+ if (totalLength > buffer.byteLength) {
1923
+ throw new Error(`Corrupted GLB asset: declared byteLength ${totalLength} exceeds actual payload ${buffer.byteLength}`);
1924
+ }
1925
+ let offset = 12;
1926
+ let json = null;
1927
+ let bin = new Uint8Array(0);
1928
+ while (offset < buffer.byteLength) {
1929
+ if (offset + 8 > buffer.byteLength) {
1930
+ break;
1931
+ }
1932
+ const chunkLength = view.getUint32(offset, true);
1933
+ const chunkType = view.getUint32(offset + 4, true);
1934
+ const chunkStart = offset + 8;
1935
+ const chunkEnd = chunkStart + chunkLength;
1936
+ if (chunkEnd > buffer.byteLength) {
1937
+ throw new Error("Corrupted GLB chunk: chunk length exceeds container bounds");
1938
+ }
1939
+ if (chunkType === CHUNK_TYPE_JSON) {
1940
+ const jsonSlice = new Uint8Array(buffer, chunkStart, chunkLength);
1941
+ const jsonText = new TextDecoder("utf-8").decode(jsonSlice);
1942
+ try {
1943
+ json = JSON.parse(jsonText);
1944
+ } catch {
1945
+ throw new Error("Invalid GLB JSON chunk: parsing failed");
1946
+ }
1947
+ } else if (chunkType === CHUNK_TYPE_BIN) {
1948
+ bin = new Uint8Array(buffer, chunkStart, chunkLength);
1949
+ }
1950
+ offset = chunkEnd;
1951
+ }
1952
+ if (!json) {
1953
+ throw new Error("Invalid GLB asset: missing required JSON chunk");
1954
+ }
1955
+ const bufferViews = Array.isArray(json.bufferViews) ? json.bufferViews : [];
1956
+ const accessors = Array.isArray(json.accessors) ? json.accessors : [];
1957
+ const meshesDef = Array.isArray(json.meshes) ? json.meshes : [];
1958
+ const imagesDef = Array.isArray(json.images) ? json.images : [];
1959
+ const embeddedImageUrls = [];
1960
+ if (typeof URL !== "undefined" && typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
1961
+ for (const imgDef of imagesDef) {
1962
+ const bvIndex = typeof imgDef.bufferView === "number" ? imgDef.bufferView : void 0;
1963
+ if (bvIndex !== void 0 && bufferViews[bvIndex]) {
1964
+ const bv = bufferViews[bvIndex];
1965
+ const bOffset = typeof bv.byteOffset === "number" ? bv.byteOffset : 0;
1966
+ const bLength = typeof bv.byteLength === "number" ? bv.byteLength : 0;
1967
+ if (bOffset + bLength <= bin.byteLength) {
1968
+ const imgBytes = bin.slice(bOffset, bOffset + bLength);
1969
+ const mime = typeof imgDef.mimeType === "string" ? imgDef.mimeType : "image/png";
1970
+ const blob = new Blob([imgBytes], { type: mime });
1971
+ const objUrl = URL.createObjectURL(blob);
1972
+ this.createdObjectUrls.push(objUrl);
1973
+ embeddedImageUrls.push(objUrl);
1974
+ }
1975
+ }
1976
+ }
1977
+ }
1978
+ const meshes = [];
1979
+ for (const meshObj of meshesDef) {
1980
+ const meshName = typeof meshObj.name === "string" ? meshObj.name : void 0;
1981
+ const primitives = Array.isArray(meshObj.primitives) ? meshObj.primitives : [];
1982
+ for (const prim of primitives) {
1983
+ const attrs = typeof prim.attributes === "object" && prim.attributes !== null ? prim.attributes : {};
1984
+ const posAccessorIdx = typeof attrs.POSITION === "number" ? attrs.POSITION : void 0;
1985
+ if (posAccessorIdx === void 0 || !accessors[posAccessorIdx]) {
1986
+ continue;
1987
+ }
1988
+ const posAcc = accessors[posAccessorIdx];
1989
+ const posBvIdx = typeof posAcc.bufferView === "number" ? posAcc.bufferView : void 0;
1990
+ if (posBvIdx === void 0 || !bufferViews[posBvIdx]) {
1991
+ continue;
1992
+ }
1993
+ const posBv = bufferViews[posBvIdx];
1994
+ const posOffset = (typeof posBv.byteOffset === "number" ? posBv.byteOffset : 0) + (typeof posAcc.byteOffset === "number" ? posAcc.byteOffset : 0);
1995
+ const posCount = typeof posAcc.count === "number" ? posAcc.count : 0;
1996
+ const posBytes = posCount * 3 * 4;
1997
+ if (posOffset + posBytes > bin.byteLength) {
1998
+ continue;
1999
+ }
2000
+ const positions = new Float32Array(bin.buffer, bin.byteOffset + posOffset, posCount * 3);
2001
+ let normals;
2002
+ const normAccessorIdx = typeof attrs.NORMAL === "number" ? attrs.NORMAL : void 0;
2003
+ if (normAccessorIdx !== void 0 && accessors[normAccessorIdx]) {
2004
+ const normAcc = accessors[normAccessorIdx];
2005
+ const normBvIdx = typeof normAcc.bufferView === "number" ? normAcc.bufferView : void 0;
2006
+ if (normBvIdx !== void 0 && bufferViews[normBvIdx]) {
2007
+ const normBv = bufferViews[normBvIdx];
2008
+ const normOffset = (typeof normBv.byteOffset === "number" ? normBv.byteOffset : 0) + (typeof normAcc.byteOffset === "number" ? normAcc.byteOffset : 0);
2009
+ const normCount = typeof normAcc.count === "number" ? normAcc.count : 0;
2010
+ if (normOffset + normCount * 3 * 4 <= bin.byteLength) {
2011
+ normals = new Float32Array(bin.buffer, bin.byteOffset + normOffset, normCount * 3);
2012
+ }
2013
+ }
2014
+ }
2015
+ let indices;
2016
+ const idxAccessorIdx = typeof prim.indices === "number" ? prim.indices : void 0;
2017
+ if (idxAccessorIdx !== void 0 && accessors[idxAccessorIdx]) {
2018
+ const idxAcc = accessors[idxAccessorIdx];
2019
+ const idxBvIdx = typeof idxAcc.bufferView === "number" ? idxAcc.bufferView : void 0;
2020
+ if (idxBvIdx !== void 0 && bufferViews[idxBvIdx]) {
2021
+ const idxBv = bufferViews[idxBvIdx];
2022
+ const idxOffset = (typeof idxBv.byteOffset === "number" ? idxBv.byteOffset : 0) + (typeof idxAcc.byteOffset === "number" ? idxAcc.byteOffset : 0);
2023
+ const idxCount = typeof idxAcc.count === "number" ? idxAcc.count : 0;
2024
+ const compType = typeof idxAcc.componentType === "number" ? idxAcc.componentType : 5123;
2025
+ if (compType === 5123) {
2026
+ if (idxOffset + idxCount * 2 <= bin.byteLength) {
2027
+ indices = new Uint16Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2028
+ }
2029
+ } else if (compType === 5125) {
2030
+ if (idxOffset + idxCount * 4 <= bin.byteLength) {
2031
+ indices = new Uint32Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2032
+ }
2033
+ }
2034
+ }
2035
+ }
2036
+ meshes.push({
2037
+ name: meshName,
2038
+ positions,
2039
+ normals,
2040
+ indices
2041
+ });
2042
+ }
2043
+ }
2044
+ return {
2045
+ json,
2046
+ bin,
2047
+ meshes,
2048
+ embeddedImageUrls
2049
+ };
2050
+ }
2051
+ destroy() {
2052
+ if (this.inFlightController) {
2053
+ this.inFlightController.abort();
2054
+ this.inFlightController = null;
2055
+ }
2056
+ if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
2057
+ for (const objUrl of this.createdObjectUrls) {
2058
+ try {
2059
+ URL.revokeObjectURL(objUrl);
2060
+ } catch {
2061
+ }
2062
+ }
2063
+ }
2064
+ this.createdObjectUrls.length = 0;
2065
+ }
2066
+ };
2067
+ function anySignal(signals) {
2068
+ const controller = new AbortController();
2069
+ for (const sig of signals) {
2070
+ if (sig.aborted) {
2071
+ controller.abort();
2072
+ return controller.signal;
2073
+ }
2074
+ sig.addEventListener("abort", () => controller.abort(), { once: true });
2075
+ }
2076
+ return controller.signal;
2077
+ }
2078
+ var FbxRenderer = class {
2079
+ constructor() {
2080
+ this.canvas = null;
2081
+ this.renderer = null;
2082
+ this.scene = null;
2083
+ this.camera = null;
2084
+ this.modelRoot = null;
2085
+ this.mixer = null;
2086
+ this.animFrameId = null;
2087
+ this.lastTime = 0;
2088
+ this.facing = "right";
2089
+ this.currentPose = "idle";
2090
+ this.initialRenderCompleted = false;
2091
+ }
2092
+ async mount(container, asset, options) {
2093
+ const doc = container.ownerDocument;
2094
+ if (!doc) {
2095
+ throw new Error("Unable to access document DOM for 3D avatar viewport");
2096
+ }
2097
+ this.canvas = doc.createElement("canvas");
2098
+ this.canvas.className = "asiyst-avatar-canvas";
2099
+ this.canvas.setAttribute("role", "presentation");
2100
+ const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
2101
+ if (!glContext) {
2102
+ throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
2103
+ }
2104
+ const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2105
+ const size = options?.config?.size || 96;
2106
+ this.canvas.width = Math.round(size * dpr);
2107
+ this.canvas.height = Math.round(size * dpr);
2108
+ try {
2109
+ this.renderer = new THREE__namespace.WebGLRenderer({
2110
+ canvas: this.canvas,
2111
+ alpha: true,
2112
+ antialias: true,
2113
+ powerPreference: "low-power"
2114
+ });
2115
+ this.renderer.setPixelRatio(Math.min(dpr, 2));
2116
+ this.renderer.setSize(size, size, false);
2117
+ this.renderer.outputColorSpace = THREE__namespace.SRGBColorSpace;
2118
+ } catch (err) {
2119
+ const msg = err instanceof Error ? err.message : String(err);
2120
+ throw new Error(`Failed to initialize WebGLRenderer: ${msg}`);
2121
+ }
2122
+ this.scene = new THREE__namespace.Scene();
2123
+ this.camera = new THREE__namespace.PerspectiveCamera(40, 1, 0.1, 100);
2124
+ this.camera.position.set(0, 0, 3.4);
2125
+ const ambientLight = new THREE__namespace.AmbientLight(16777215, 1.2);
2126
+ this.scene.add(ambientLight);
2127
+ const keyLight = new THREE__namespace.DirectionalLight(16777215, 1.2);
2128
+ keyLight.position.set(2, 3.5, 3);
2129
+ this.scene.add(keyLight);
2130
+ const fillLight = new THREE__namespace.DirectionalLight(10859772, 0.6);
2131
+ fillLight.position.set(-2.5, -1, -1.5);
2132
+ this.scene.add(fillLight);
2133
+ let rawObject;
2134
+ let modelAnimations = [];
2135
+ if (asset.format === "fbx") {
2136
+ const manager = new THREE__namespace.LoadingManager();
2137
+ manager.onError = (itemUrl) => {
2138
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2139
+ console.warn(`[asiyst] Optional FBX texture resource could not be loaded: ${itemUrl}`);
2140
+ }
2141
+ };
2142
+ const loader = new FBXLoader_js.FBXLoader(manager);
2143
+ if (asset.resourcePath) {
2144
+ loader.setResourcePath(asset.resourcePath);
2145
+ }
2146
+ try {
2147
+ const parsedGroup = loader.parse(asset.buffer, asset.resourcePath || "");
2148
+ rawObject = parsedGroup;
2149
+ modelAnimations = parsedGroup.animations || [];
2150
+ } catch (parseErr) {
2151
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2152
+ throw new Error(`FBX decoding and parsing failed: ${msg}`);
2153
+ }
2154
+ } else {
2155
+ const loader = new GLTFLoader_js.GLTFLoader();
2156
+ try {
2157
+ const gltf = await new Promise((resolve, reject) => {
2158
+ const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2159
+ loader.parse(glbBuffer, asset.url, resolve, reject);
2160
+ });
2161
+ rawObject = gltf.scene;
2162
+ modelAnimations = gltf.animations || [];
2163
+ } catch (parseErr) {
2164
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2165
+ throw new Error(`GLB decoding and parsing failed: ${msg}`);
2166
+ }
2167
+ }
2168
+ const { meshCount, vertexCount: totalVertices } = this.validateGeometry(rawObject);
2169
+ const box = new THREE__namespace.Box3().setFromObject(rawObject);
2170
+ if (box.isEmpty()) {
2171
+ throw new Error("FBX asset geometry bounding box is empty");
2172
+ }
2173
+ const center = new THREE__namespace.Vector3();
2174
+ box.getCenter(center);
2175
+ const boxSize = new THREE__namespace.Vector3();
2176
+ box.getSize(boxSize);
2177
+ rawObject.position.x -= center.x;
2178
+ rawObject.position.y -= center.y;
2179
+ rawObject.position.z -= center.z;
2180
+ this.modelRoot = new THREE__namespace.Group();
2181
+ this.modelRoot.add(rawObject);
2182
+ this.scene.add(this.modelRoot);
2183
+ const maxDim = Math.max(boxSize.x, boxSize.y, boxSize.z);
2184
+ if (maxDim > 0) {
2185
+ const targetSpan = 1.85;
2186
+ const scale = targetSpan / maxDim;
2187
+ this.modelRoot.scale.setScalar(scale);
2188
+ }
2189
+ if (modelAnimations.length > 0) {
2190
+ this.mixer = new THREE__namespace.AnimationMixer(rawObject);
2191
+ const clip = modelAnimations[0];
2192
+ if (clip) {
2193
+ const action = this.mixer.clipAction(clip);
2194
+ action.play();
2195
+ }
2196
+ }
2197
+ container.replaceChildren();
2198
+ container.appendChild(this.canvas);
2199
+ try {
2200
+ this.renderer.render(this.scene, this.camera);
2201
+ this.initialRenderCompleted = true;
2202
+ } catch (renderErr) {
2203
+ const msg = renderErr instanceof Error ? renderErr.message : String(renderErr);
2204
+ throw new Error(`Initial FBX WebGL render failed: ${msg}`);
2205
+ }
2206
+ this.startLoop();
2207
+ this.setFacing(this.facing);
2208
+ this.setPose(this.currentPose);
2209
+ return {
2210
+ meshCount,
2211
+ vertexCount: totalVertices,
2212
+ animationCount: modelAnimations.length
2213
+ };
2214
+ }
2215
+ setFacing(direction) {
2216
+ this.facing = direction;
2217
+ if (this.modelRoot) {
2218
+ this.modelRoot.rotation.y = direction === "left" ? -0.35 : 0.35;
2219
+ }
2220
+ }
2221
+ setPose(pose) {
2222
+ this.currentPose = pose;
2223
+ if (!this.modelRoot) return;
2224
+ switch (pose) {
2225
+ case "point":
2226
+ this.modelRoot.rotation.z = -0.15;
2227
+ this.modelRoot.rotation.x = 0.08;
2228
+ break;
2229
+ case "think":
2230
+ this.modelRoot.rotation.z = 0.12;
2231
+ this.modelRoot.rotation.x = -0.1;
2232
+ break;
2233
+ case "celebrate":
2234
+ this.modelRoot.rotation.z = 0;
2235
+ this.modelRoot.rotation.x = -0.15;
2236
+ this.modelRoot.scale.multiplyScalar(1.05);
2237
+ break;
2238
+ default:
2239
+ this.modelRoot.rotation.z = 0;
2240
+ this.modelRoot.rotation.x = 0;
2241
+ break;
2242
+ }
2243
+ }
2244
+ isRendered() {
2245
+ return this.initialRenderCompleted;
2246
+ }
2247
+ validateGeometry(rawObject) {
2248
+ let totalVertices = 0;
2249
+ let meshCount = 0;
2250
+ rawObject.traverse((child) => {
2251
+ const mesh = child;
2252
+ if (mesh.isMesh && mesh.geometry) {
2253
+ meshCount++;
2254
+ const posAttr = mesh.geometry.attributes.position;
2255
+ if (posAttr) {
2256
+ totalVertices += posAttr.count;
2257
+ }
2258
+ }
2259
+ });
2260
+ if (meshCount === 0 || totalVertices === 0) {
2261
+ throw new Error("FBX asset contains no drawable 3D geometry");
2262
+ }
2263
+ return { meshCount, vertexCount: totalVertices };
2264
+ }
2265
+ getCanvas() {
2266
+ return this.canvas;
2267
+ }
2268
+ startLoop() {
2269
+ if (typeof requestAnimationFrame === "undefined") return;
2270
+ this.lastTime = typeof performance !== "undefined" ? performance.now() : Date.now();
2271
+ const tick = (now) => {
2272
+ if (!this.renderer || !this.scene || !this.camera) return;
2273
+ const current = now || (typeof performance !== "undefined" ? performance.now() : Date.now());
2274
+ const delta = Math.min(Math.max((current - this.lastTime) / 1e3, 0), 0.1);
2275
+ this.lastTime = current;
2276
+ if (this.mixer) {
2277
+ this.mixer.update(delta);
2278
+ }
2279
+ this.renderer.render(this.scene, this.camera);
2280
+ this.animFrameId = requestAnimationFrame(tick);
2281
+ };
2282
+ this.animFrameId = requestAnimationFrame(tick);
2283
+ }
2284
+ destroy() {
2285
+ if (this.animFrameId !== null && typeof cancelAnimationFrame !== "undefined") {
2286
+ cancelAnimationFrame(this.animFrameId);
2287
+ this.animFrameId = null;
2288
+ }
2289
+ if (this.mixer) {
2290
+ this.mixer.stopAllAction();
2291
+ this.mixer = null;
2292
+ }
2293
+ if (this.scene) {
2294
+ this.scene.traverse((obj) => {
2295
+ const mesh = obj;
2296
+ if (mesh.isMesh) {
2297
+ if (mesh.geometry) {
2298
+ mesh.geometry.dispose();
2299
+ }
2300
+ if (mesh.material) {
2301
+ if (Array.isArray(mesh.material)) {
2302
+ mesh.material.forEach((m) => {
2303
+ const mat = m;
2304
+ mat.map?.dispose();
2305
+ mat.dispose();
2306
+ });
2307
+ } else {
2308
+ const mat = mesh.material;
2309
+ mat.map?.dispose();
2310
+ mat.dispose();
2311
+ }
2312
+ }
2313
+ }
2314
+ });
2315
+ this.scene.clear();
2316
+ this.scene = null;
2317
+ }
2318
+ if (this.renderer) {
2319
+ this.renderer.dispose();
2320
+ this.renderer = null;
2321
+ }
2322
+ if (this.canvas) {
2323
+ this.canvas.remove();
2324
+ this.canvas = null;
2325
+ }
2326
+ this.camera = null;
2327
+ this.modelRoot = null;
2328
+ this.initialRenderCompleted = false;
2329
+ }
2330
+ };
2331
+
1525
2332
  // src/avatar/CssAvatarRenderer.ts
1526
2333
  var AVATAR_CSS = `
1527
2334
  .asiyst-avatar {
@@ -1544,10 +2351,80 @@ var AVATAR_CSS = `
1544
2351
  color: #fff;
1545
2352
  font: 700 14px/1.2 system-ui, sans-serif;
1546
2353
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
2354
+ position: relative;
2355
+ overflow: hidden;
2356
+ cursor: pointer;
2357
+ border: none;
2358
+ padding: 0;
2359
+ outline: none;
2360
+ background: #2563eb;
1547
2361
  }
1548
2362
  .asiyst-figure[data-pose="point"] { transform: rotate(-12deg); }
1549
2363
  .asiyst-figure[data-pose="think"] { opacity: 0.85; }
1550
2364
  .asiyst-figure[data-pose="celebrate"] { transform: scale(1.08); }
2365
+ .asiyst-avatar-viewport {
2366
+ position: absolute;
2367
+ inset: 0;
2368
+ width: 100%;
2369
+ height: 100%;
2370
+ display: grid;
2371
+ place-items: center;
2372
+ border-radius: inherit;
2373
+ overflow: hidden;
2374
+ pointer-events: none;
2375
+ }
2376
+ .asiyst-avatar-canvas {
2377
+ width: 100%;
2378
+ height: 100%;
2379
+ object-fit: contain;
2380
+ border-radius: inherit;
2381
+ display: block;
2382
+ pointer-events: none;
2383
+ }
2384
+ .asiyst-avatar-graphic {
2385
+ width: 100%;
2386
+ height: 100%;
2387
+ object-fit: cover;
2388
+ border-radius: inherit;
2389
+ display: block;
2390
+ pointer-events: none;
2391
+ }
2392
+ .asiyst-avatar-loader {
2393
+ width: 32px;
2394
+ height: 32px;
2395
+ border: 3px solid rgba(255, 255, 255, 0.35);
2396
+ border-top-color: #fff;
2397
+ border-radius: 50%;
2398
+ animation: asiyst-spin 0.8s linear infinite;
2399
+ }
2400
+ @keyframes asiyst-spin {
2401
+ to { transform: rotate(360deg); }
2402
+ }
2403
+ .asiyst-avatar-fallback {
2404
+ display: grid;
2405
+ place-items: center;
2406
+ width: 100%;
2407
+ height: 100%;
2408
+ position: relative;
2409
+ }
2410
+ .asiyst-avatar-fallback-badge {
2411
+ position: absolute;
2412
+ top: 8px;
2413
+ right: 8px;
2414
+ width: 14px;
2415
+ height: 14px;
2416
+ background: #ef4444;
2417
+ color: #fff;
2418
+ border-radius: 50%;
2419
+ font-size: 10px;
2420
+ line-height: 14px;
2421
+ text-align: center;
2422
+ }
2423
+ .asiyst-avatar-initial {
2424
+ font-size: 28px;
2425
+ font-weight: 700;
2426
+ line-height: 1;
2427
+ }
1551
2428
  .asiyst-bubble {
1552
2429
  max-width: 220px;
1553
2430
  background: #0f172a;
@@ -1560,6 +2437,7 @@ var AVATAR_CSS = `
1560
2437
  .asiyst-name { font: 600 12px/1 system-ui, sans-serif; color: #0f172a; }
1561
2438
  @media (prefers-reduced-motion: reduce) {
1562
2439
  .asiyst-avatar.asiyst-animate { transition: none; }
2440
+ .asiyst-avatar-loader { animation: none; }
1563
2441
  }
1564
2442
  `;
1565
2443
  var CssAvatarRenderer = class {
@@ -1568,6 +2446,14 @@ var CssAvatarRenderer = class {
1568
2446
  this.hidden = false;
1569
2447
  this.facing = "right";
1570
2448
  this.pose = "idle";
2449
+ this.accentColor = "#2563eb";
2450
+ this.avatarName = "Asiyst";
2451
+ // Asset loading & rendering state
2452
+ this.assetLoader = new AssetLoader();
2453
+ this.fbxRenderer = null;
2454
+ this.renderState = "idle";
2455
+ this.isAssetLoadedFlag = false;
2456
+ this.isFallbackFlag = true;
1571
2457
  }
1572
2458
  mount(container, config) {
1573
2459
  const doc = container.ownerDocument;
@@ -1581,6 +2467,10 @@ var CssAvatarRenderer = class {
1581
2467
  this.figure.type = "button";
1582
2468
  this.figure.className = "asiyst-figure";
1583
2469
  this.figure.setAttribute("aria-label", `${config.avatarName} assistant`);
2470
+ this.figure.setAttribute("data-state", this.renderState);
2471
+ this.viewport = doc.createElement("div");
2472
+ this.viewport.className = "asiyst-avatar-viewport";
2473
+ this.figure.appendChild(this.viewport);
1584
2474
  this.nameEl = doc.createElement("div");
1585
2475
  this.nameEl.className = "asiyst-name";
1586
2476
  this.bubble = doc.createElement("div");
@@ -1591,16 +2481,24 @@ var CssAvatarRenderer = class {
1591
2481
  this.applyConfig(config);
1592
2482
  }
1593
2483
  unmount() {
2484
+ this.assetLoader.destroy();
2485
+ if (this.fbxRenderer) {
2486
+ this.fbxRenderer.destroy();
2487
+ this.fbxRenderer = null;
2488
+ }
1594
2489
  this.root?.remove();
1595
2490
  this.root = void 0;
2491
+ this.figure = void 0;
2492
+ this.viewport = void 0;
1596
2493
  }
1597
2494
  applyConfig(config) {
1598
2495
  this.size = config.size;
2496
+ this.accentColor = config.theme.accent ?? "#2563eb";
2497
+ this.avatarName = config.avatarName;
1599
2498
  if (this.figure) {
1600
2499
  this.figure.style.width = `${config.size}px`;
1601
2500
  this.figure.style.height = `${config.size}px`;
1602
- this.figure.style.background = config.theme.accent ?? "#2563eb";
1603
- renderSafeText(this.figure, config.avatarName.slice(0, 1).toUpperCase());
2501
+ this.figure.style.background = this.accentColor;
1604
2502
  }
1605
2503
  if (this.nameEl) {
1606
2504
  renderSafeText(this.nameEl, config.avatarName);
@@ -1608,36 +2506,149 @@ var CssAvatarRenderer = class {
1608
2506
  if (this.root) {
1609
2507
  this.root.setAttribute("aria-label", config.avatarName);
1610
2508
  }
2509
+ if (!this.isAssetLoadedFlag && this.viewport) {
2510
+ this.renderFallback();
2511
+ }
1611
2512
  }
1612
- setPosition(x, y, animate) {
1613
- if (!this.root) {
1614
- return;
2513
+ async loadAsset(config) {
2514
+ const assetUrl = config.assetUrl ?? config.thumbnailUrl;
2515
+ if (!assetUrl) {
2516
+ this.renderState = "idle";
2517
+ this.isAssetLoadedFlag = false;
2518
+ this.isFallbackFlag = true;
2519
+ this.renderFallback();
2520
+ return false;
2521
+ }
2522
+ this.activeAssetUrl = assetUrl;
2523
+ this.renderState = "loading";
2524
+ this.isFallbackFlag = false;
2525
+ this.lastErrorMessage = void 0;
2526
+ if (this.figure) {
2527
+ this.figure.setAttribute("data-state", "loading");
2528
+ }
2529
+ this.renderLoader();
2530
+ try {
2531
+ const asset = await this.assetLoader.load(assetUrl);
2532
+ await this.renderLoadedAsset(asset, config);
2533
+ this.renderState = "ready";
2534
+ this.isAssetLoadedFlag = true;
2535
+ this.isFallbackFlag = false;
2536
+ this.loadedFormat = asset.format;
2537
+ if (this.figure) {
2538
+ this.figure.setAttribute("data-state", "ready");
2539
+ }
2540
+ return true;
2541
+ } catch (err) {
2542
+ const message = err instanceof Error ? err.message : "Failed to load avatar asset";
2543
+ this.lastErrorMessage = message;
2544
+ this.renderState = "error";
2545
+ this.isAssetLoadedFlag = false;
2546
+ this.isFallbackFlag = true;
2547
+ if (this.figure) {
2548
+ this.figure.setAttribute("data-state", "error");
2549
+ }
2550
+ this.renderFallback(true);
2551
+ return false;
2552
+ }
2553
+ }
2554
+ renderLoader() {
2555
+ if (!this.viewport) return;
2556
+ this.viewport.replaceChildren();
2557
+ const doc = this.viewport.ownerDocument;
2558
+ const loader = doc.createElement("div");
2559
+ loader.className = "asiyst-avatar-loader";
2560
+ loader.setAttribute("aria-label", `Loading ${this.avatarName}`);
2561
+ this.viewport.appendChild(loader);
2562
+ }
2563
+ async renderLoadedAsset(asset, config) {
2564
+ if (!this.viewport) return;
2565
+ if (this.fbxRenderer) {
2566
+ this.fbxRenderer.destroy();
2567
+ this.fbxRenderer = null;
2568
+ }
2569
+ if (asset.format === "fbx" || asset.format === "glb") {
2570
+ this.fbxRenderer = new FbxRenderer();
2571
+ this.renderMetrics = await this.fbxRenderer.mount(this.viewport, asset, {
2572
+ accentColor: this.accentColor,
2573
+ config
2574
+ });
2575
+ this.fbxRenderer.setFacing(this.facing);
2576
+ this.fbxRenderer.setPose(this.pose);
2577
+ } else if (asset.format === "image") {
2578
+ this.viewport.replaceChildren();
2579
+ const doc = this.viewport.ownerDocument;
2580
+ const img = doc.createElement("img");
2581
+ img.className = "asiyst-avatar-graphic";
2582
+ img.alt = `${config.avatarName} visual avatar`;
2583
+ img.src = asset.url;
2584
+ this.viewport.appendChild(img);
2585
+ } else if (asset.format === "manifest") {
2586
+ const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
2587
+ const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
2588
+ if (modelUrl) {
2589
+ const subAsset = await this.assetLoader.load(modelUrl);
2590
+ await this.renderLoadedAsset(subAsset, config);
2591
+ } else if (thumb) {
2592
+ this.viewport.replaceChildren();
2593
+ const doc = this.viewport.ownerDocument;
2594
+ const img = doc.createElement("img");
2595
+ img.className = "asiyst-avatar-graphic";
2596
+ img.alt = `${config.avatarName} visual avatar`;
2597
+ img.src = thumb;
2598
+ this.viewport.appendChild(img);
2599
+ } else {
2600
+ throw new Error("Manifest did not provide a drawable 3D asset or thumbnail URL");
2601
+ }
2602
+ }
2603
+ }
2604
+ renderFallback(isError = false) {
2605
+ if (!this.viewport) return;
2606
+ this.viewport.replaceChildren();
2607
+ const doc = this.viewport.ownerDocument;
2608
+ const fallback = doc.createElement("div");
2609
+ fallback.className = "asiyst-avatar-fallback";
2610
+ fallback.setAttribute("data-fallback", "true");
2611
+ if (isError) {
2612
+ fallback.setAttribute("data-state", "error");
2613
+ }
2614
+ const initial = doc.createElement("span");
2615
+ initial.className = "asiyst-avatar-initial";
2616
+ renderSafeText(initial, this.avatarName.slice(0, 1).toUpperCase());
2617
+ fallback.appendChild(initial);
2618
+ if (isError) {
2619
+ const badge = doc.createElement("span");
2620
+ badge.className = "asiyst-avatar-fallback-badge";
2621
+ badge.setAttribute("title", "Avatar asset failed to load");
2622
+ badge.textContent = "!";
2623
+ fallback.appendChild(badge);
1615
2624
  }
2625
+ this.viewport.appendChild(fallback);
2626
+ }
2627
+ setPosition(x, y, animate) {
2628
+ if (!this.root) return;
1616
2629
  this.root.classList.toggle("asiyst-animate", animate);
1617
2630
  this.root.style.left = `${x}px`;
1618
2631
  this.root.style.top = `${y}px`;
1619
2632
  }
1620
2633
  setFacing(direction) {
1621
2634
  this.facing = direction;
2635
+ this.fbxRenderer?.setFacing(direction);
1622
2636
  this.syncTransform();
1623
2637
  }
1624
2638
  setPose(pose) {
1625
2639
  this.pose = pose;
2640
+ this.fbxRenderer?.setPose(pose);
1626
2641
  this.figure?.setAttribute("data-pose", pose);
1627
2642
  this.syncTransform();
1628
2643
  }
1629
2644
  syncTransform() {
1630
- if (!this.figure) {
1631
- return;
1632
- }
2645
+ if (!this.figure) return;
1633
2646
  const face = this.facing === "left" ? "scaleX(-1)" : "";
1634
2647
  const pose = this.pose === "point" ? "rotate(-12deg)" : this.pose === "celebrate" ? "scale(1.08)" : "";
1635
2648
  this.figure.style.transform = `${face} ${pose}`.trim();
1636
2649
  }
1637
2650
  setSpeech(text) {
1638
- if (!this.bubble) {
1639
- return;
1640
- }
2651
+ if (!this.bubble) return;
1641
2652
  if (!text) {
1642
2653
  this.bubble.hidden = true;
1643
2654
  this.bubble.textContent = "";
@@ -1661,6 +2672,33 @@ var CssAvatarRenderer = class {
1661
2672
  getFigure() {
1662
2673
  return this.figure;
1663
2674
  }
2675
+ getViewport() {
2676
+ return this.viewport;
2677
+ }
2678
+ isAssetLoaded() {
2679
+ return this.isAssetLoadedFlag;
2680
+ }
2681
+ isRendered() {
2682
+ return this.isAssetLoadedFlag && (this.fbxRenderer ? this.fbxRenderer.isRendered() : true);
2683
+ }
2684
+ isFallbackActive() {
2685
+ return this.isFallbackFlag;
2686
+ }
2687
+ getRenderState() {
2688
+ return this.renderState;
2689
+ }
2690
+ getLoadedFormat() {
2691
+ return this.loadedFormat;
2692
+ }
2693
+ getAssetUrl() {
2694
+ return this.activeAssetUrl;
2695
+ }
2696
+ getLastError() {
2697
+ return this.lastErrorMessage;
2698
+ }
2699
+ getMetrics() {
2700
+ return this.renderMetrics;
2701
+ }
1664
2702
  };
1665
2703
 
1666
2704
  // src/accessibility/a11y.ts
@@ -2843,7 +3881,7 @@ var AsiystRuntime = class {
2843
3881
  origin: win.location.origin,
2844
3882
  environment: this.environment
2845
3883
  }) : void 0;
2846
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId);
3884
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
2847
3885
  this.config = new ConfigManager(options, this.cloud, this.events);
2848
3886
  this.analytics = new Analytics(options.projectId, this.cloud);
2849
3887
  this.host = new HostRoot(doc);
@@ -3003,13 +4041,77 @@ var AsiystRuntime = class {
3003
4041
  }
3004
4042
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
3005
4043
  void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
3006
- avatarId: this.options.avatarId ?? cfg.avatarName,
3007
- avatarName: cfg.avatarName
3008
- });
3009
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
3010
- avatarId: this.options.avatarId ?? cfg.avatarName,
3011
- avatarName: cfg.avatarName
4044
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4045
+ avatarName: cfg.avatarName,
4046
+ publishedVersion: cfg.publishedVersion
3012
4047
  });
4048
+ const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4049
+ if (assetTarget) {
4050
+ this.events.emit("asiyst:avatar:loading", {
4051
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4052
+ assetUrl: assetTarget
4053
+ });
4054
+ void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4055
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4056
+ assetUrl: assetTarget
4057
+ });
4058
+ try {
4059
+ const loaded = await this.renderer.loadAsset(cfg);
4060
+ if (loaded) {
4061
+ const format = this.renderer.getLoadedFormat();
4062
+ const assetUrl = this.renderer.getAssetUrl();
4063
+ const isRendered = this.renderer.isRendered();
4064
+ this.events.emit("asiyst:avatar:loaded", {
4065
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4066
+ assetUrl,
4067
+ format
4068
+ });
4069
+ void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4070
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4071
+ avatarName: cfg.avatarName,
4072
+ assetUrl,
4073
+ format,
4074
+ publishedVersion: cfg.publishedVersion
4075
+ });
4076
+ if (isRendered) {
4077
+ this.events.emit("asiyst:avatar:rendered", {
4078
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4079
+ format
4080
+ });
4081
+ void this.cloud.sendTelemetryEvent("avatar_rendered", {
4082
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4083
+ avatarName: cfg.avatarName,
4084
+ format,
4085
+ publishedVersion: cfg.publishedVersion
4086
+ });
4087
+ }
4088
+ } else {
4089
+ const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
4090
+ this.events.emit("asiyst:avatar:error", {
4091
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4092
+ error: err,
4093
+ stage: "renderer_init"
4094
+ });
4095
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4096
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4097
+ error: err,
4098
+ stage: "renderer_init"
4099
+ });
4100
+ }
4101
+ } catch (error) {
4102
+ const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
4103
+ this.events.emit("asiyst:avatar:error", {
4104
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4105
+ error: err,
4106
+ stage: "asset_fetch"
4107
+ });
4108
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4109
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4110
+ error: err,
4111
+ stage: "asset_fetch"
4112
+ });
4113
+ }
4114
+ }
3013
4115
  }
3014
4116
  getConnectionStatus() {
3015
4117
  return this.connectionStatus;
@@ -3258,8 +4360,11 @@ var Asiyst = {
3258
4360
  exports.ActionNotAllowedError = ActionNotAllowedError;
3259
4361
  exports.Asiyst = Asiyst;
3260
4362
  exports.AsiystError = AsiystError;
4363
+ exports.AssetLoader = AssetLoader;
3261
4364
  exports.AuthenticationError = AuthenticationError;
3262
4365
  exports.ConfigurationError = ConfigurationError;
4366
+ exports.CssAvatarRenderer = CssAvatarRenderer;
4367
+ exports.FbxRenderer = FbxRenderer;
3263
4368
  exports.InitializationError = InitializationError;
3264
4369
  exports.NetworkError = NetworkError;
3265
4370
  exports.SDK_VERSION = SDK_VERSION;