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