@asiyst/sdk 0.1.21 → 0.1.23

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.22";
75
79
  }
76
80
  }
77
81
  var SDK_VERSION = resolveSdkVersion();
@@ -89,6 +93,7 @@ var AVATAR_VIEWPORT_PADDING = 12;
89
93
  var AVATAR_TARGET_GAP = 16;
90
94
  var WEBSITE_MAP_TEXT_LIMIT = 80;
91
95
  var CONFIG_CACHE_TTL_MS = 1e3 * 60 * 10;
96
+ var HEARTBEAT_INTERVAL_MS = 45e3;
92
97
 
93
98
  // src/security/selectors.ts
94
99
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -131,11 +136,12 @@ var ANCHORS = [
131
136
  "top-left"
132
137
  ];
133
138
  var PUBLIC_IDENTIFIER_PATTERN = /^(?=.{1,128}$)[A-Za-z0-9_][A-Za-z0-9_-]*$/;
139
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
134
140
  function isValidPublicIdentifier(value) {
135
141
  if (typeof value !== "string") return false;
136
142
  const trimmed = value.trim();
137
143
  if (!trimmed || trimmed.length > 128) return false;
138
- if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)) {
144
+ if (UUID_PATTERN.test(trimmed)) {
139
145
  return false;
140
146
  }
141
147
  return PUBLIC_IDENTIFIER_PATTERN.test(trimmed);
@@ -308,6 +314,12 @@ function fallbackConfig() {
308
314
  version: 0,
309
315
  avatarName: "Asiyst",
310
316
  avatar: "avatar_default",
317
+ avatarId: void 0,
318
+ assetUrl: void 0,
319
+ thumbnailUrl: void 0,
320
+ publishedVersion: void 0,
321
+ animations: [],
322
+ branding: void 0,
311
323
  size: 96,
312
324
  position: "bottom-right",
313
325
  animation: "friendly",
@@ -331,22 +343,69 @@ function fallbackConfig() {
331
343
  elementSelectors: {}
332
344
  };
333
345
  }
346
+ function parseAnimations(value) {
347
+ if (!Array.isArray(value)) return void 0;
348
+ const list = [];
349
+ for (const item of value) {
350
+ if (isRecord(item) && typeof item.name === "string") {
351
+ list.push({
352
+ id: typeof item.id === "string" ? sanitizeText(item.id, 64) : void 0,
353
+ name: sanitizeText(item.name, 64),
354
+ intent: typeof item.intent === "string" ? sanitizeText(item.intent, 64) : void 0,
355
+ clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
356
+ loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
357
+ durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
358
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
359
+ });
360
+ }
361
+ }
362
+ return list;
363
+ }
364
+ function parseBranding(value) {
365
+ if (!isRecord(value)) return void 0;
366
+ return {
367
+ siteLogoUrl: typeof value.siteLogoUrl === "string" ? value.siteLogoUrl : null
368
+ };
369
+ }
334
370
  function normalizeProjectConfig(raw) {
335
371
  const base = fallbackConfig();
336
372
  if (!isRecord(raw)) {
337
373
  return base;
338
374
  }
375
+ const rawAvatarRecord = isRecord(raw.avatar) ? raw.avatar : void 0;
376
+ const avatarId = asString(
377
+ raw.avatarId ?? rawAvatarRecord?.avatarId ?? rawAvatarRecord?.id,
378
+ "",
379
+ 128
380
+ ) || void 0;
381
+ const assetUrl = typeof raw.assetUrl === "string" ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" ? rawAvatarRecord.assetUrl : void 0;
382
+ const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
383
+ const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : void 0;
384
+ const animations = parseAnimations(raw.animations ?? rawAvatarRecord?.animations);
385
+ const branding = parseBranding(raw.branding);
386
+ const avatarName = asString(
387
+ raw.avatarName ?? rawAvatarRecord?.name,
388
+ base.avatarName,
389
+ 40
390
+ );
391
+ const avatar = typeof raw.avatar === "string" ? asString(raw.avatar, base.avatar, 64) : avatarId ?? base.avatar;
339
392
  const position = ANCHORS.includes(raw.position) ? raw.position : base.position;
340
393
  return {
341
394
  schemaVersion: CONFIG_SCHEMA_VERSION,
342
395
  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),
396
+ avatarName,
397
+ avatar,
398
+ avatarId,
399
+ assetUrl,
400
+ thumbnailUrl,
401
+ publishedVersion,
402
+ animations,
403
+ branding,
345
404
  size: asNumber(raw.size, base.size, 48, 220),
346
405
  position,
347
406
  voice: typeof raw.voice === "string" ? sanitizeText(raw.voice, 64) : void 0,
348
407
  animation: asString(raw.animation, base.animation ?? "friendly", 40),
349
- theme: { ...base.theme, ...parseTheme(raw.theme) },
408
+ theme: { ...base.theme, ...parseTheme(raw.theme ?? rawAvatarRecord?.theme) },
350
409
  personality: parsePersonality(raw.personality),
351
410
  behavior: { ...base.behavior, ...parseBehavior(raw.behavior) },
352
411
  mode: raw.mode === "assist" ? "assist" : "guided",
@@ -433,6 +492,12 @@ var HttpTransport = class {
433
492
  constructor(options) {
434
493
  this.options = options;
435
494
  }
495
+ getApiBaseUrl() {
496
+ return this.options.apiBaseUrl;
497
+ }
498
+ getAvatarId() {
499
+ return this.options.avatarId;
500
+ }
436
501
  async request(req) {
437
502
  const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
438
503
  const requestId = req.requestId || generateRequestId();
@@ -529,13 +594,17 @@ var HttpTransport = class {
529
594
 
530
595
  // src/communication/CloudClient.ts
531
596
  var CloudClient = class {
532
- constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId) {
597
+ constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
533
598
  this.transport = transport;
534
599
  this.projectId = projectId;
535
600
  this.publicKey = publicKey;
536
601
  this.runtimeAuth = runtimeAuth;
602
+ this.avatarId = avatarId;
537
603
  this.inFlightConversations = /* @__PURE__ */ new Map();
538
604
  this.sessionId = sessionId;
605
+ if (!this.avatarId && typeof transport.getAvatarId === "function") {
606
+ this.avatarId = transport.getAvatarId();
607
+ }
539
608
  }
540
609
  setSessionId(sessionId) {
541
610
  this.sessionId = sessionId;
@@ -549,6 +618,18 @@ var CloudClient = class {
549
618
  getConversationId() {
550
619
  return this.conversationId;
551
620
  }
621
+ getAvatarId() {
622
+ return this.avatarId;
623
+ }
624
+ setAvatarId(avatarId) {
625
+ this.avatarId = avatarId;
626
+ }
627
+ getApiBaseUrl() {
628
+ if (typeof this.transport.getApiBaseUrl === "function") {
629
+ return this.transport.getApiBaseUrl();
630
+ }
631
+ return DEFAULT_API_BASE_URL;
632
+ }
552
633
  async getAuthToken(capability) {
553
634
  if (!this.runtimeAuth) return void 0;
554
635
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
@@ -563,36 +644,119 @@ var CloudClient = class {
563
644
  return this.inFlightToken;
564
645
  }
565
646
  async fetchConfig() {
647
+ const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
648
+ const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
649
+ const baseUrl = this.getApiBaseUrl();
650
+ const resolveAssetUrls = (raw) => {
651
+ const canonicalBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
652
+ if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
653
+ const av = { ...raw.avatar };
654
+ if (typeof av.assetUrl === "string" && av.assetUrl.startsWith("/")) {
655
+ av.assetUrl = new URL(av.assetUrl, canonicalBase).href;
656
+ }
657
+ if (typeof av.thumbnailUrl === "string" && av.thumbnailUrl.startsWith("/")) {
658
+ av.thumbnailUrl = new URL(av.thumbnailUrl, canonicalBase).href;
659
+ }
660
+ if (Array.isArray(av.animations)) {
661
+ av.animations = av.animations.map((item) => {
662
+ if (item && typeof item === "object") {
663
+ const animObj = item;
664
+ if (typeof animObj.assetUrl === "string" && animObj.assetUrl.startsWith("/")) {
665
+ return { ...animObj, assetUrl: new URL(animObj.assetUrl, canonicalBase).href };
666
+ }
667
+ }
668
+ return item;
669
+ });
670
+ }
671
+ raw.avatar = av;
672
+ }
673
+ if (typeof raw.assetUrl === "string" && raw.assetUrl.startsWith("/")) {
674
+ raw.assetUrl = new URL(raw.assetUrl, canonicalBase).href;
675
+ }
676
+ if (typeof raw.thumbnailUrl === "string" && raw.thumbnailUrl.startsWith("/")) {
677
+ raw.thumbnailUrl = new URL(raw.thumbnailUrl, canonicalBase).href;
678
+ }
679
+ if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
680
+ const br = { ...raw.branding };
681
+ if (typeof br.siteLogoUrl === "string" && br.siteLogoUrl.startsWith("/")) {
682
+ br.siteLogoUrl = new URL(br.siteLogoUrl, canonicalBase).href;
683
+ }
684
+ raw.branding = br;
685
+ }
686
+ return raw;
687
+ };
688
+ let lastError;
566
689
  try {
567
690
  const response = await this.runtimeRequest({
568
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
691
+ path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
569
692
  method: "GET",
570
693
  idempotent: true
571
694
  });
572
695
  if (response.ok && response.data) {
573
- return normalizeProjectConfig(response.data.config ?? response.data);
696
+ const dataObj = response.data.config ?? response.data;
697
+ return normalizeProjectConfig(resolveAssetUrls(dataObj));
574
698
  }
575
- } catch {
699
+ if (response.status === 404) {
700
+ lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
701
+ }
702
+ } catch (err) {
703
+ if (err instanceof Error) lastError = err;
576
704
  }
577
705
  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" }
706
+ const runtimeResponse = await this.runtimeRequest({
707
+ path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
708
+ method: "GET",
709
+ idempotent: true
710
+ });
711
+ if (runtimeResponse.ok && runtimeResponse.data) {
712
+ return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
713
+ }
714
+ if (runtimeResponse.status === 404) {
715
+ lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
716
+ }
717
+ } catch (err) {
718
+ if (err instanceof Error) lastError = err;
719
+ }
720
+ try {
721
+ const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
722
+ const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
723
+ const res = await fetch(fullUrl, {
724
+ headers: {
725
+ Accept: "application/json",
726
+ "x-asiyst-public-key": this.publicKey
727
+ }
580
728
  });
581
729
  if (res.ok) {
582
730
  const body = await res.json();
583
- if (body?.avatar) {
584
- return normalizeProjectConfig({
585
- avatarName: body.avatar.name,
586
- avatarId: body.avatar.avatarId
587
- });
731
+ if (body && typeof body === "object") {
732
+ return normalizeProjectConfig(resolveAssetUrls(body));
733
+ }
734
+ } else {
735
+ const errorBody = await res.json().catch(() => ({}));
736
+ const errObj = errorBody?.error ?? errorBody;
737
+ const code = String(errObj?.code ?? "");
738
+ const message = String(errObj?.message ?? `HTTP ${res.status}`);
739
+ if (res.status === 404) {
740
+ throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
741
+ } else if (res.status === 401 || res.status === 403) {
742
+ throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
743
+ } else if (res.status >= 500) {
744
+ throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
588
745
  }
589
746
  }
590
- } catch {
747
+ } catch (err) {
748
+ if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
749
+ throw err;
750
+ }
751
+ if (err instanceof Error) lastError = err;
752
+ }
753
+ if (lastError) {
754
+ throw lastError;
591
755
  }
592
- return normalizeProjectConfig({});
756
+ throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
593
757
  }
594
758
  async heartbeat(metadata) {
595
- const response = await this.runtimeRequest({
759
+ let response = await this.runtimeRequest({
596
760
  path: "/sdk/heartbeat",
597
761
  method: "POST",
598
762
  idempotent: true,
@@ -605,6 +769,21 @@ var CloudClient = class {
605
769
  timestamp: metadata.timestamp
606
770
  }
607
771
  }, "assistant:heartbeat");
772
+ if (response.status === 404) {
773
+ response = await this.runtimeRequest({
774
+ path: "/api/v1/sdk/heartbeat",
775
+ method: "POST",
776
+ idempotent: true,
777
+ body: {
778
+ project_id: this.projectId,
779
+ public_key: this.publicKey,
780
+ sdk_version: SDK_VERSION,
781
+ origin: metadata.origin,
782
+ environment: metadata.environment,
783
+ timestamp: metadata.timestamp
784
+ }
785
+ }, "assistant:heartbeat");
786
+ }
608
787
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
609
788
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
610
789
  const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -617,13 +796,22 @@ var CloudClient = class {
617
796
  };
618
797
  }
619
798
  async registerInstallation(registration) {
620
- const response = await this.transport.request({
799
+ let response = await this.transport.request({
621
800
  path: "/sdk/installations/register",
622
801
  method: "POST",
623
802
  body: registration,
624
803
  idempotent: true,
625
804
  sessionId: this.sessionId
626
805
  });
806
+ if (response.status === 404) {
807
+ response = await this.transport.request({
808
+ path: "/api/v1/sdk/installations/register",
809
+ method: "POST",
810
+ body: registration,
811
+ idempotent: true,
812
+ sessionId: this.sessionId
813
+ });
814
+ }
627
815
  if (!response.ok) {
628
816
  throw new NetworkError(`SDK installation registration failed (${response.status}).`);
629
817
  }
@@ -694,18 +882,32 @@ var CloudClient = class {
694
882
  try {
695
883
  const origin = typeof window !== "undefined" ? window.location.origin : void 0;
696
884
  const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
885
+ const sanitizedMeta = {
886
+ sdkVersion: SDK_VERSION
887
+ };
888
+ for (const [key, val] of Object.entries(metadata)) {
889
+ if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
890
+ continue;
891
+ }
892
+ if (typeof val === "string") {
893
+ sanitizedMeta[key] = sanitizeText(val, 512);
894
+ } else if (typeof val === "number" || typeof val === "boolean") {
895
+ sanitizedMeta[key] = val;
896
+ } else if (val && typeof val === "object" && !Array.isArray(val)) {
897
+ sanitizedMeta[key] = val;
898
+ }
899
+ }
697
900
  const payload = {
698
901
  projectId: this.projectId,
699
902
  publicKey: this.publicKey,
700
903
  eventType,
701
904
  installationId,
702
905
  origin,
703
- metadata: {
704
- ...metadata,
705
- sdkVersion: SDK_VERSION
706
- }
906
+ metadata: sanitizedMeta
707
907
  };
708
- await fetch("https://asiyst.com/api/v1/events", {
908
+ const baseUrl = this.getApiBaseUrl();
909
+ 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";
910
+ await fetch(targetUrl, {
709
911
  method: "POST",
710
912
  headers: {
711
913
  "Content-Type": "application/json",
@@ -1520,6 +1722,617 @@ var HighlightLayer = class {
1520
1722
  }
1521
1723
  };
1522
1724
 
1725
+ // src/avatar/AssetLoader.ts
1726
+ var GLB_MAGIC = 1179937895;
1727
+ var CHUNK_TYPE_JSON = 1313821514;
1728
+ var CHUNK_TYPE_BIN = 5130562;
1729
+ var AssetLoader = class {
1730
+ constructor() {
1731
+ this.inFlightController = null;
1732
+ this.createdObjectUrls = [];
1733
+ }
1734
+ async load(assetUrl, options) {
1735
+ const startTime = Date.now();
1736
+ const sanitizedUrl = sanitizeText(assetUrl.trim(), 2048);
1737
+ if (!sanitizedUrl) {
1738
+ throw new Error("Asset URL is required");
1739
+ }
1740
+ this.inFlightController = new AbortController();
1741
+ const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1742
+ const timeoutMs = options?.timeoutMs ?? 15e3;
1743
+ const timeoutId = setTimeout(() => {
1744
+ this.inFlightController?.abort();
1745
+ }, timeoutMs);
1746
+ try {
1747
+ const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1748
+ const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
1749
+ const isJsonExtension = /\.json$/i.test(cleanPath);
1750
+ const isFbxExtension = /\.fbx$/i.test(cleanPath);
1751
+ const isGlbExtension = /\.glb$/i.test(cleanPath);
1752
+ if (isImageExtension) {
1753
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1754
+ return {
1755
+ format: "image",
1756
+ url: sanitizedUrl,
1757
+ image: imageResult.element,
1758
+ width: imageResult.width,
1759
+ height: imageResult.height,
1760
+ durationMs: Date.now() - startTime
1761
+ };
1762
+ }
1763
+ let response;
1764
+ try {
1765
+ response = await fetch(sanitizedUrl, {
1766
+ method: "GET",
1767
+ headers: {
1768
+ Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1769
+ },
1770
+ signal: abortSignal
1771
+ });
1772
+ } catch (err) {
1773
+ if (err instanceof Error && err.name === "AbortError") {
1774
+ throw new Error("Avatar asset request timed out or was aborted");
1775
+ }
1776
+ throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
1777
+ }
1778
+ if (!response.ok) {
1779
+ throw new Error(`Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`);
1780
+ }
1781
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
1782
+ if (isJsonExtension || contentType.includes("application/json")) {
1783
+ const text = await response.text();
1784
+ let manifest;
1785
+ try {
1786
+ manifest = JSON.parse(text);
1787
+ } catch {
1788
+ throw new Error("Invalid avatar manifest: JSON decoding failed");
1789
+ }
1790
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1791
+ throw new Error("Invalid avatar manifest schema");
1792
+ }
1793
+ return {
1794
+ format: "manifest",
1795
+ url: sanitizedUrl,
1796
+ manifest,
1797
+ durationMs: Date.now() - startTime
1798
+ };
1799
+ }
1800
+ if (contentType.startsWith("image/")) {
1801
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1802
+ return {
1803
+ format: "image",
1804
+ url: sanitizedUrl,
1805
+ image: imageResult.element,
1806
+ width: imageResult.width,
1807
+ height: imageResult.height,
1808
+ durationMs: Date.now() - startTime
1809
+ };
1810
+ }
1811
+ const arrayBuffer = await response.arrayBuffer();
1812
+ if (arrayBuffer.byteLength < 12) {
1813
+ throw new Error("Avatar asset payload is too small to be a valid 3D container");
1814
+ }
1815
+ if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1816
+ const fbxHeader = this.parseFbxHeader(arrayBuffer);
1817
+ const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1818
+ return {
1819
+ format: "fbx",
1820
+ url: sanitizedUrl,
1821
+ buffer: arrayBuffer,
1822
+ version: fbxHeader.version,
1823
+ isBinary: fbxHeader.isBinary,
1824
+ resourcePath,
1825
+ durationMs: Date.now() - startTime
1826
+ };
1827
+ }
1828
+ const parsedGlb = this.parseGlb(arrayBuffer);
1829
+ return {
1830
+ format: "glb",
1831
+ url: sanitizedUrl,
1832
+ json: parsedGlb.json,
1833
+ bin: parsedGlb.bin,
1834
+ meshes: parsedGlb.meshes,
1835
+ embeddedImageUrls: parsedGlb.embeddedImageUrls,
1836
+ durationMs: Date.now() - startTime
1837
+ };
1838
+ } finally {
1839
+ clearTimeout(timeoutId);
1840
+ this.inFlightController = null;
1841
+ }
1842
+ }
1843
+ isFbxBuffer(buffer) {
1844
+ if (buffer.byteLength < 18) return false;
1845
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1846
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1847
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1848
+ return true;
1849
+ }
1850
+ const sample = new TextDecoder("utf-8").decode(bytes);
1851
+ return sample.startsWith("; FBX") || sample.includes("FBXHeaderExtension");
1852
+ }
1853
+ parseFbxHeader(buffer) {
1854
+ if (buffer.byteLength < 18) {
1855
+ throw new Error("Corrupted FBX asset: payload is too small to contain an FBX header");
1856
+ }
1857
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1858
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1859
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1860
+ if (buffer.byteLength < 27) {
1861
+ throw new Error("Corrupted binary FBX asset: payload is truncated");
1862
+ }
1863
+ const view = new DataView(buffer);
1864
+ const version = view.getUint32(23, true);
1865
+ if (version < 6400) {
1866
+ throw new Error(`Unsupported legacy FBX version: ${version}. Versions prior to 6.4 (6400) are not supported.`);
1867
+ }
1868
+ return { isBinary: true, version };
1869
+ }
1870
+ const textSample = new TextDecoder("utf-8").decode(bytes);
1871
+ if (textSample.startsWith("; FBX") || textSample.includes("FBXHeaderExtension")) {
1872
+ const match = textSample.match(/;\s*FBX\s*(\d+(?:\.\d+)?)/i);
1873
+ const version = match && match[1] ? Math.round(parseFloat(match[1]) * 1e3) : void 0;
1874
+ return { isBinary: false, version };
1875
+ }
1876
+ throw new Error("Invalid FBX container: header does not match Kaydara binary or ASCII FBX signatures");
1877
+ }
1878
+ isGlbBuffer(buffer) {
1879
+ if (buffer.byteLength < 4) return false;
1880
+ const view = new DataView(buffer);
1881
+ return view.getUint32(0, true) === GLB_MAGIC;
1882
+ }
1883
+ async loadImage(url, signal) {
1884
+ if (typeof Image === "undefined") {
1885
+ return { width: 96, height: 96 };
1886
+ }
1887
+ return new Promise((resolve, reject) => {
1888
+ const img = new Image();
1889
+ img.crossOrigin = "anonymous";
1890
+ const onAbort = () => {
1891
+ img.src = "";
1892
+ reject(new Error("Image loading aborted"));
1893
+ };
1894
+ if (signal) {
1895
+ if (signal.aborted) {
1896
+ return reject(new Error("Image loading aborted"));
1897
+ }
1898
+ signal.addEventListener("abort", onAbort, { once: true });
1899
+ }
1900
+ img.onload = () => {
1901
+ if (signal) signal.removeEventListener("abort", onAbort);
1902
+ resolve({
1903
+ element: img,
1904
+ width: img.naturalWidth || 96,
1905
+ height: img.naturalHeight || 96
1906
+ });
1907
+ };
1908
+ img.onerror = () => {
1909
+ if (signal) signal.removeEventListener("abort", onAbort);
1910
+ reject(new Error(`Failed to load avatar image asset from ${url}`));
1911
+ };
1912
+ img.src = url;
1913
+ });
1914
+ }
1915
+ parseGlb(buffer) {
1916
+ const view = new DataView(buffer);
1917
+ const magic = view.getUint32(0, true);
1918
+ if (magic !== GLB_MAGIC) {
1919
+ throw new Error(`Invalid GLB container header: expected 0x${GLB_MAGIC.toString(16)}, received 0x${magic.toString(16)}`);
1920
+ }
1921
+ const version = view.getUint32(4, true);
1922
+ if (version !== 2) {
1923
+ throw new Error(`Unsupported glTF version: ${version}. Only version 2 is supported.`);
1924
+ }
1925
+ const totalLength = view.getUint32(8, true);
1926
+ if (totalLength > buffer.byteLength) {
1927
+ throw new Error(`Corrupted GLB asset: declared byteLength ${totalLength} exceeds actual payload ${buffer.byteLength}`);
1928
+ }
1929
+ let offset = 12;
1930
+ let json = null;
1931
+ let bin = new Uint8Array(0);
1932
+ while (offset < buffer.byteLength) {
1933
+ if (offset + 8 > buffer.byteLength) {
1934
+ break;
1935
+ }
1936
+ const chunkLength = view.getUint32(offset, true);
1937
+ const chunkType = view.getUint32(offset + 4, true);
1938
+ const chunkStart = offset + 8;
1939
+ const chunkEnd = chunkStart + chunkLength;
1940
+ if (chunkEnd > buffer.byteLength) {
1941
+ throw new Error("Corrupted GLB chunk: chunk length exceeds container bounds");
1942
+ }
1943
+ if (chunkType === CHUNK_TYPE_JSON) {
1944
+ const jsonSlice = new Uint8Array(buffer, chunkStart, chunkLength);
1945
+ const jsonText = new TextDecoder("utf-8").decode(jsonSlice);
1946
+ try {
1947
+ json = JSON.parse(jsonText);
1948
+ } catch {
1949
+ throw new Error("Invalid GLB JSON chunk: parsing failed");
1950
+ }
1951
+ } else if (chunkType === CHUNK_TYPE_BIN) {
1952
+ bin = new Uint8Array(buffer, chunkStart, chunkLength);
1953
+ }
1954
+ offset = chunkEnd;
1955
+ }
1956
+ if (!json) {
1957
+ throw new Error("Invalid GLB asset: missing required JSON chunk");
1958
+ }
1959
+ const bufferViews = Array.isArray(json.bufferViews) ? json.bufferViews : [];
1960
+ const accessors = Array.isArray(json.accessors) ? json.accessors : [];
1961
+ const meshesDef = Array.isArray(json.meshes) ? json.meshes : [];
1962
+ const imagesDef = Array.isArray(json.images) ? json.images : [];
1963
+ const embeddedImageUrls = [];
1964
+ if (typeof URL !== "undefined" && typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
1965
+ for (const imgDef of imagesDef) {
1966
+ const bvIndex = typeof imgDef.bufferView === "number" ? imgDef.bufferView : void 0;
1967
+ if (bvIndex !== void 0 && bufferViews[bvIndex]) {
1968
+ const bv = bufferViews[bvIndex];
1969
+ const bOffset = typeof bv.byteOffset === "number" ? bv.byteOffset : 0;
1970
+ const bLength = typeof bv.byteLength === "number" ? bv.byteLength : 0;
1971
+ if (bOffset + bLength <= bin.byteLength) {
1972
+ const imgBytes = bin.slice(bOffset, bOffset + bLength);
1973
+ const mime = typeof imgDef.mimeType === "string" ? imgDef.mimeType : "image/png";
1974
+ const blob = new Blob([imgBytes], { type: mime });
1975
+ const objUrl = URL.createObjectURL(blob);
1976
+ this.createdObjectUrls.push(objUrl);
1977
+ embeddedImageUrls.push(objUrl);
1978
+ }
1979
+ }
1980
+ }
1981
+ }
1982
+ const meshes = [];
1983
+ for (const meshObj of meshesDef) {
1984
+ const meshName = typeof meshObj.name === "string" ? meshObj.name : void 0;
1985
+ const primitives = Array.isArray(meshObj.primitives) ? meshObj.primitives : [];
1986
+ for (const prim of primitives) {
1987
+ const attrs = typeof prim.attributes === "object" && prim.attributes !== null ? prim.attributes : {};
1988
+ const posAccessorIdx = typeof attrs.POSITION === "number" ? attrs.POSITION : void 0;
1989
+ if (posAccessorIdx === void 0 || !accessors[posAccessorIdx]) {
1990
+ continue;
1991
+ }
1992
+ const posAcc = accessors[posAccessorIdx];
1993
+ const posBvIdx = typeof posAcc.bufferView === "number" ? posAcc.bufferView : void 0;
1994
+ if (posBvIdx === void 0 || !bufferViews[posBvIdx]) {
1995
+ continue;
1996
+ }
1997
+ const posBv = bufferViews[posBvIdx];
1998
+ const posOffset = (typeof posBv.byteOffset === "number" ? posBv.byteOffset : 0) + (typeof posAcc.byteOffset === "number" ? posAcc.byteOffset : 0);
1999
+ const posCount = typeof posAcc.count === "number" ? posAcc.count : 0;
2000
+ const posBytes = posCount * 3 * 4;
2001
+ if (posOffset + posBytes > bin.byteLength) {
2002
+ continue;
2003
+ }
2004
+ const positions = new Float32Array(bin.buffer, bin.byteOffset + posOffset, posCount * 3);
2005
+ let normals;
2006
+ const normAccessorIdx = typeof attrs.NORMAL === "number" ? attrs.NORMAL : void 0;
2007
+ if (normAccessorIdx !== void 0 && accessors[normAccessorIdx]) {
2008
+ const normAcc = accessors[normAccessorIdx];
2009
+ const normBvIdx = typeof normAcc.bufferView === "number" ? normAcc.bufferView : void 0;
2010
+ if (normBvIdx !== void 0 && bufferViews[normBvIdx]) {
2011
+ const normBv = bufferViews[normBvIdx];
2012
+ const normOffset = (typeof normBv.byteOffset === "number" ? normBv.byteOffset : 0) + (typeof normAcc.byteOffset === "number" ? normAcc.byteOffset : 0);
2013
+ const normCount = typeof normAcc.count === "number" ? normAcc.count : 0;
2014
+ if (normOffset + normCount * 3 * 4 <= bin.byteLength) {
2015
+ normals = new Float32Array(bin.buffer, bin.byteOffset + normOffset, normCount * 3);
2016
+ }
2017
+ }
2018
+ }
2019
+ let indices;
2020
+ const idxAccessorIdx = typeof prim.indices === "number" ? prim.indices : void 0;
2021
+ if (idxAccessorIdx !== void 0 && accessors[idxAccessorIdx]) {
2022
+ const idxAcc = accessors[idxAccessorIdx];
2023
+ const idxBvIdx = typeof idxAcc.bufferView === "number" ? idxAcc.bufferView : void 0;
2024
+ if (idxBvIdx !== void 0 && bufferViews[idxBvIdx]) {
2025
+ const idxBv = bufferViews[idxBvIdx];
2026
+ const idxOffset = (typeof idxBv.byteOffset === "number" ? idxBv.byteOffset : 0) + (typeof idxAcc.byteOffset === "number" ? idxAcc.byteOffset : 0);
2027
+ const idxCount = typeof idxAcc.count === "number" ? idxAcc.count : 0;
2028
+ const compType = typeof idxAcc.componentType === "number" ? idxAcc.componentType : 5123;
2029
+ if (compType === 5123) {
2030
+ if (idxOffset + idxCount * 2 <= bin.byteLength) {
2031
+ indices = new Uint16Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2032
+ }
2033
+ } else if (compType === 5125) {
2034
+ if (idxOffset + idxCount * 4 <= bin.byteLength) {
2035
+ indices = new Uint32Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2036
+ }
2037
+ }
2038
+ }
2039
+ }
2040
+ meshes.push({
2041
+ name: meshName,
2042
+ positions,
2043
+ normals,
2044
+ indices
2045
+ });
2046
+ }
2047
+ }
2048
+ return {
2049
+ json,
2050
+ bin,
2051
+ meshes,
2052
+ embeddedImageUrls
2053
+ };
2054
+ }
2055
+ destroy() {
2056
+ if (this.inFlightController) {
2057
+ this.inFlightController.abort();
2058
+ this.inFlightController = null;
2059
+ }
2060
+ if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
2061
+ for (const objUrl of this.createdObjectUrls) {
2062
+ try {
2063
+ URL.revokeObjectURL(objUrl);
2064
+ } catch {
2065
+ }
2066
+ }
2067
+ }
2068
+ this.createdObjectUrls.length = 0;
2069
+ }
2070
+ };
2071
+ function anySignal(signals) {
2072
+ const controller = new AbortController();
2073
+ for (const sig of signals) {
2074
+ if (sig.aborted) {
2075
+ controller.abort();
2076
+ return controller.signal;
2077
+ }
2078
+ sig.addEventListener("abort", () => controller.abort(), { once: true });
2079
+ }
2080
+ return controller.signal;
2081
+ }
2082
+ var FbxRenderer = class {
2083
+ constructor() {
2084
+ this.canvas = null;
2085
+ this.renderer = null;
2086
+ this.scene = null;
2087
+ this.camera = null;
2088
+ this.modelRoot = null;
2089
+ this.mixer = null;
2090
+ this.animFrameId = null;
2091
+ this.lastTime = 0;
2092
+ this.facing = "right";
2093
+ this.currentPose = "idle";
2094
+ this.initialRenderCompleted = false;
2095
+ }
2096
+ async mount(container, asset, options) {
2097
+ const doc = container.ownerDocument;
2098
+ if (!doc) {
2099
+ throw new Error("Unable to access document DOM for 3D avatar viewport");
2100
+ }
2101
+ this.canvas = doc.createElement("canvas");
2102
+ this.canvas.className = "asiyst-avatar-canvas";
2103
+ this.canvas.setAttribute("role", "presentation");
2104
+ const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
2105
+ if (!glContext) {
2106
+ throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
2107
+ }
2108
+ const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2109
+ const size = options?.config?.size || 96;
2110
+ this.canvas.width = Math.round(size * dpr);
2111
+ this.canvas.height = Math.round(size * dpr);
2112
+ try {
2113
+ this.renderer = new THREE.WebGLRenderer({
2114
+ canvas: this.canvas,
2115
+ alpha: true,
2116
+ antialias: true,
2117
+ powerPreference: "low-power"
2118
+ });
2119
+ this.renderer.setPixelRatio(Math.min(dpr, 2));
2120
+ this.renderer.setSize(size, size, false);
2121
+ this.renderer.outputColorSpace = THREE.SRGBColorSpace;
2122
+ } catch (err) {
2123
+ const msg = err instanceof Error ? err.message : String(err);
2124
+ throw new Error(`Failed to initialize WebGLRenderer: ${msg}`);
2125
+ }
2126
+ this.scene = new THREE.Scene();
2127
+ this.camera = new THREE.PerspectiveCamera(40, 1, 0.1, 100);
2128
+ this.camera.position.set(0, 0, 3.4);
2129
+ const ambientLight = new THREE.AmbientLight(16777215, 1.2);
2130
+ this.scene.add(ambientLight);
2131
+ const keyLight = new THREE.DirectionalLight(16777215, 1.2);
2132
+ keyLight.position.set(2, 3.5, 3);
2133
+ this.scene.add(keyLight);
2134
+ const fillLight = new THREE.DirectionalLight(10859772, 0.6);
2135
+ fillLight.position.set(-2.5, -1, -1.5);
2136
+ this.scene.add(fillLight);
2137
+ let rawObject;
2138
+ let modelAnimations = [];
2139
+ if (asset.format === "fbx") {
2140
+ const manager = new THREE.LoadingManager();
2141
+ manager.onError = (itemUrl) => {
2142
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2143
+ console.warn(`[asiyst] Optional FBX texture resource could not be loaded: ${itemUrl}`);
2144
+ }
2145
+ };
2146
+ const loader = new FBXLoader(manager);
2147
+ if (asset.resourcePath) {
2148
+ loader.setResourcePath(asset.resourcePath);
2149
+ }
2150
+ try {
2151
+ const parsedGroup = loader.parse(asset.buffer, asset.resourcePath || "");
2152
+ rawObject = parsedGroup;
2153
+ modelAnimations = parsedGroup.animations || [];
2154
+ } catch (parseErr) {
2155
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2156
+ throw new Error(`FBX decoding and parsing failed: ${msg}`);
2157
+ }
2158
+ } else {
2159
+ const loader = new GLTFLoader();
2160
+ try {
2161
+ const gltf = await new Promise((resolve, reject) => {
2162
+ const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2163
+ loader.parse(glbBuffer, asset.url, resolve, reject);
2164
+ });
2165
+ rawObject = gltf.scene;
2166
+ modelAnimations = gltf.animations || [];
2167
+ } catch (parseErr) {
2168
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2169
+ throw new Error(`GLB decoding and parsing failed: ${msg}`);
2170
+ }
2171
+ }
2172
+ const { meshCount, vertexCount: totalVertices } = this.validateGeometry(rawObject);
2173
+ const box = new THREE.Box3().setFromObject(rawObject);
2174
+ if (box.isEmpty()) {
2175
+ throw new Error("FBX asset geometry bounding box is empty");
2176
+ }
2177
+ const center = new THREE.Vector3();
2178
+ box.getCenter(center);
2179
+ const boxSize = new THREE.Vector3();
2180
+ box.getSize(boxSize);
2181
+ rawObject.position.x -= center.x;
2182
+ rawObject.position.y -= center.y;
2183
+ rawObject.position.z -= center.z;
2184
+ this.modelRoot = new THREE.Group();
2185
+ this.modelRoot.add(rawObject);
2186
+ this.scene.add(this.modelRoot);
2187
+ const maxDim = Math.max(boxSize.x, boxSize.y, boxSize.z);
2188
+ if (maxDim > 0) {
2189
+ const targetSpan = 1.85;
2190
+ const scale = targetSpan / maxDim;
2191
+ this.modelRoot.scale.setScalar(scale);
2192
+ }
2193
+ if (modelAnimations.length > 0) {
2194
+ this.mixer = new THREE.AnimationMixer(rawObject);
2195
+ const clip = modelAnimations[0];
2196
+ if (clip) {
2197
+ const action = this.mixer.clipAction(clip);
2198
+ action.play();
2199
+ }
2200
+ }
2201
+ container.replaceChildren();
2202
+ container.appendChild(this.canvas);
2203
+ try {
2204
+ this.renderer.render(this.scene, this.camera);
2205
+ this.initialRenderCompleted = true;
2206
+ } catch (renderErr) {
2207
+ const msg = renderErr instanceof Error ? renderErr.message : String(renderErr);
2208
+ throw new Error(`Initial FBX WebGL render failed: ${msg}`);
2209
+ }
2210
+ this.startLoop();
2211
+ this.setFacing(this.facing);
2212
+ this.setPose(this.currentPose);
2213
+ return {
2214
+ meshCount,
2215
+ vertexCount: totalVertices,
2216
+ animationCount: modelAnimations.length
2217
+ };
2218
+ }
2219
+ setFacing(direction) {
2220
+ this.facing = direction;
2221
+ if (this.modelRoot) {
2222
+ this.modelRoot.rotation.y = direction === "left" ? -0.35 : 0.35;
2223
+ }
2224
+ }
2225
+ setPose(pose) {
2226
+ this.currentPose = pose;
2227
+ if (!this.modelRoot) return;
2228
+ switch (pose) {
2229
+ case "point":
2230
+ this.modelRoot.rotation.z = -0.15;
2231
+ this.modelRoot.rotation.x = 0.08;
2232
+ break;
2233
+ case "think":
2234
+ this.modelRoot.rotation.z = 0.12;
2235
+ this.modelRoot.rotation.x = -0.1;
2236
+ break;
2237
+ case "celebrate":
2238
+ this.modelRoot.rotation.z = 0;
2239
+ this.modelRoot.rotation.x = -0.15;
2240
+ this.modelRoot.scale.multiplyScalar(1.05);
2241
+ break;
2242
+ default:
2243
+ this.modelRoot.rotation.z = 0;
2244
+ this.modelRoot.rotation.x = 0;
2245
+ break;
2246
+ }
2247
+ }
2248
+ isRendered() {
2249
+ return this.initialRenderCompleted;
2250
+ }
2251
+ validateGeometry(rawObject) {
2252
+ let totalVertices = 0;
2253
+ let meshCount = 0;
2254
+ rawObject.traverse((child) => {
2255
+ const mesh = child;
2256
+ if (mesh.isMesh && mesh.geometry) {
2257
+ meshCount++;
2258
+ const posAttr = mesh.geometry.attributes.position;
2259
+ if (posAttr) {
2260
+ totalVertices += posAttr.count;
2261
+ }
2262
+ }
2263
+ });
2264
+ if (meshCount === 0 || totalVertices === 0) {
2265
+ throw new Error("FBX asset contains no drawable 3D geometry");
2266
+ }
2267
+ return { meshCount, vertexCount: totalVertices };
2268
+ }
2269
+ getCanvas() {
2270
+ return this.canvas;
2271
+ }
2272
+ startLoop() {
2273
+ if (typeof requestAnimationFrame === "undefined") return;
2274
+ this.lastTime = typeof performance !== "undefined" ? performance.now() : Date.now();
2275
+ const tick = (now) => {
2276
+ if (!this.renderer || !this.scene || !this.camera) return;
2277
+ const current = now || (typeof performance !== "undefined" ? performance.now() : Date.now());
2278
+ const delta = Math.min(Math.max((current - this.lastTime) / 1e3, 0), 0.1);
2279
+ this.lastTime = current;
2280
+ if (this.mixer) {
2281
+ this.mixer.update(delta);
2282
+ }
2283
+ this.renderer.render(this.scene, this.camera);
2284
+ this.animFrameId = requestAnimationFrame(tick);
2285
+ };
2286
+ this.animFrameId = requestAnimationFrame(tick);
2287
+ }
2288
+ destroy() {
2289
+ if (this.animFrameId !== null && typeof cancelAnimationFrame !== "undefined") {
2290
+ cancelAnimationFrame(this.animFrameId);
2291
+ this.animFrameId = null;
2292
+ }
2293
+ if (this.mixer) {
2294
+ this.mixer.stopAllAction();
2295
+ this.mixer = null;
2296
+ }
2297
+ if (this.scene) {
2298
+ this.scene.traverse((obj) => {
2299
+ const mesh = obj;
2300
+ if (mesh.isMesh) {
2301
+ if (mesh.geometry) {
2302
+ mesh.geometry.dispose();
2303
+ }
2304
+ if (mesh.material) {
2305
+ if (Array.isArray(mesh.material)) {
2306
+ mesh.material.forEach((m) => {
2307
+ const mat = m;
2308
+ mat.map?.dispose();
2309
+ mat.dispose();
2310
+ });
2311
+ } else {
2312
+ const mat = mesh.material;
2313
+ mat.map?.dispose();
2314
+ mat.dispose();
2315
+ }
2316
+ }
2317
+ }
2318
+ });
2319
+ this.scene.clear();
2320
+ this.scene = null;
2321
+ }
2322
+ if (this.renderer) {
2323
+ this.renderer.dispose();
2324
+ this.renderer = null;
2325
+ }
2326
+ if (this.canvas) {
2327
+ this.canvas.remove();
2328
+ this.canvas = null;
2329
+ }
2330
+ this.camera = null;
2331
+ this.modelRoot = null;
2332
+ this.initialRenderCompleted = false;
2333
+ }
2334
+ };
2335
+
1523
2336
  // src/avatar/CssAvatarRenderer.ts
1524
2337
  var AVATAR_CSS = `
1525
2338
  .asiyst-avatar {
@@ -1542,10 +2355,80 @@ var AVATAR_CSS = `
1542
2355
  color: #fff;
1543
2356
  font: 700 14px/1.2 system-ui, sans-serif;
1544
2357
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
2358
+ position: relative;
2359
+ overflow: hidden;
2360
+ cursor: pointer;
2361
+ border: none;
2362
+ padding: 0;
2363
+ outline: none;
2364
+ background: #2563eb;
1545
2365
  }
1546
2366
  .asiyst-figure[data-pose="point"] { transform: rotate(-12deg); }
1547
2367
  .asiyst-figure[data-pose="think"] { opacity: 0.85; }
1548
2368
  .asiyst-figure[data-pose="celebrate"] { transform: scale(1.08); }
2369
+ .asiyst-avatar-viewport {
2370
+ position: absolute;
2371
+ inset: 0;
2372
+ width: 100%;
2373
+ height: 100%;
2374
+ display: grid;
2375
+ place-items: center;
2376
+ border-radius: inherit;
2377
+ overflow: hidden;
2378
+ pointer-events: none;
2379
+ }
2380
+ .asiyst-avatar-canvas {
2381
+ width: 100%;
2382
+ height: 100%;
2383
+ object-fit: contain;
2384
+ border-radius: inherit;
2385
+ display: block;
2386
+ pointer-events: none;
2387
+ }
2388
+ .asiyst-avatar-graphic {
2389
+ width: 100%;
2390
+ height: 100%;
2391
+ object-fit: cover;
2392
+ border-radius: inherit;
2393
+ display: block;
2394
+ pointer-events: none;
2395
+ }
2396
+ .asiyst-avatar-loader {
2397
+ width: 32px;
2398
+ height: 32px;
2399
+ border: 3px solid rgba(255, 255, 255, 0.35);
2400
+ border-top-color: #fff;
2401
+ border-radius: 50%;
2402
+ animation: asiyst-spin 0.8s linear infinite;
2403
+ }
2404
+ @keyframes asiyst-spin {
2405
+ to { transform: rotate(360deg); }
2406
+ }
2407
+ .asiyst-avatar-fallback {
2408
+ display: grid;
2409
+ place-items: center;
2410
+ width: 100%;
2411
+ height: 100%;
2412
+ position: relative;
2413
+ }
2414
+ .asiyst-avatar-fallback-badge {
2415
+ position: absolute;
2416
+ top: 8px;
2417
+ right: 8px;
2418
+ width: 14px;
2419
+ height: 14px;
2420
+ background: #ef4444;
2421
+ color: #fff;
2422
+ border-radius: 50%;
2423
+ font-size: 10px;
2424
+ line-height: 14px;
2425
+ text-align: center;
2426
+ }
2427
+ .asiyst-avatar-initial {
2428
+ font-size: 28px;
2429
+ font-weight: 700;
2430
+ line-height: 1;
2431
+ }
1549
2432
  .asiyst-bubble {
1550
2433
  max-width: 220px;
1551
2434
  background: #0f172a;
@@ -1558,6 +2441,7 @@ var AVATAR_CSS = `
1558
2441
  .asiyst-name { font: 600 12px/1 system-ui, sans-serif; color: #0f172a; }
1559
2442
  @media (prefers-reduced-motion: reduce) {
1560
2443
  .asiyst-avatar.asiyst-animate { transition: none; }
2444
+ .asiyst-avatar-loader { animation: none; }
1561
2445
  }
1562
2446
  `;
1563
2447
  var CssAvatarRenderer = class {
@@ -1566,6 +2450,14 @@ var CssAvatarRenderer = class {
1566
2450
  this.hidden = false;
1567
2451
  this.facing = "right";
1568
2452
  this.pose = "idle";
2453
+ this.accentColor = "#2563eb";
2454
+ this.avatarName = "Asiyst";
2455
+ // Asset loading & rendering state
2456
+ this.assetLoader = new AssetLoader();
2457
+ this.fbxRenderer = null;
2458
+ this.renderState = "idle";
2459
+ this.isAssetLoadedFlag = false;
2460
+ this.isFallbackFlag = true;
1569
2461
  }
1570
2462
  mount(container, config) {
1571
2463
  const doc = container.ownerDocument;
@@ -1579,6 +2471,10 @@ var CssAvatarRenderer = class {
1579
2471
  this.figure.type = "button";
1580
2472
  this.figure.className = "asiyst-figure";
1581
2473
  this.figure.setAttribute("aria-label", `${config.avatarName} assistant`);
2474
+ this.figure.setAttribute("data-state", this.renderState);
2475
+ this.viewport = doc.createElement("div");
2476
+ this.viewport.className = "asiyst-avatar-viewport";
2477
+ this.figure.appendChild(this.viewport);
1582
2478
  this.nameEl = doc.createElement("div");
1583
2479
  this.nameEl.className = "asiyst-name";
1584
2480
  this.bubble = doc.createElement("div");
@@ -1589,16 +2485,24 @@ var CssAvatarRenderer = class {
1589
2485
  this.applyConfig(config);
1590
2486
  }
1591
2487
  unmount() {
2488
+ this.assetLoader.destroy();
2489
+ if (this.fbxRenderer) {
2490
+ this.fbxRenderer.destroy();
2491
+ this.fbxRenderer = null;
2492
+ }
1592
2493
  this.root?.remove();
1593
2494
  this.root = void 0;
2495
+ this.figure = void 0;
2496
+ this.viewport = void 0;
1594
2497
  }
1595
2498
  applyConfig(config) {
1596
2499
  this.size = config.size;
2500
+ this.accentColor = config.theme.accent ?? "#2563eb";
2501
+ this.avatarName = config.avatarName;
1597
2502
  if (this.figure) {
1598
2503
  this.figure.style.width = `${config.size}px`;
1599
2504
  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());
2505
+ this.figure.style.background = this.accentColor;
1602
2506
  }
1603
2507
  if (this.nameEl) {
1604
2508
  renderSafeText(this.nameEl, config.avatarName);
@@ -1606,36 +2510,149 @@ var CssAvatarRenderer = class {
1606
2510
  if (this.root) {
1607
2511
  this.root.setAttribute("aria-label", config.avatarName);
1608
2512
  }
2513
+ if (!this.isAssetLoadedFlag && this.viewport) {
2514
+ this.renderFallback();
2515
+ }
1609
2516
  }
1610
- setPosition(x, y, animate) {
1611
- if (!this.root) {
1612
- return;
2517
+ async loadAsset(config) {
2518
+ const assetUrl = config.assetUrl ?? config.thumbnailUrl;
2519
+ if (!assetUrl) {
2520
+ this.renderState = "idle";
2521
+ this.isAssetLoadedFlag = false;
2522
+ this.isFallbackFlag = true;
2523
+ this.renderFallback();
2524
+ return false;
2525
+ }
2526
+ this.activeAssetUrl = assetUrl;
2527
+ this.renderState = "loading";
2528
+ this.isFallbackFlag = false;
2529
+ this.lastErrorMessage = void 0;
2530
+ if (this.figure) {
2531
+ this.figure.setAttribute("data-state", "loading");
2532
+ }
2533
+ this.renderLoader();
2534
+ try {
2535
+ const asset = await this.assetLoader.load(assetUrl);
2536
+ await this.renderLoadedAsset(asset, config);
2537
+ this.renderState = "ready";
2538
+ this.isAssetLoadedFlag = true;
2539
+ this.isFallbackFlag = false;
2540
+ this.loadedFormat = asset.format;
2541
+ if (this.figure) {
2542
+ this.figure.setAttribute("data-state", "ready");
2543
+ }
2544
+ return true;
2545
+ } catch (err) {
2546
+ const message = err instanceof Error ? err.message : "Failed to load avatar asset";
2547
+ this.lastErrorMessage = message;
2548
+ this.renderState = "error";
2549
+ this.isAssetLoadedFlag = false;
2550
+ this.isFallbackFlag = true;
2551
+ if (this.figure) {
2552
+ this.figure.setAttribute("data-state", "error");
2553
+ }
2554
+ this.renderFallback(true);
2555
+ return false;
1613
2556
  }
2557
+ }
2558
+ renderLoader() {
2559
+ if (!this.viewport) return;
2560
+ this.viewport.replaceChildren();
2561
+ const doc = this.viewport.ownerDocument;
2562
+ const loader = doc.createElement("div");
2563
+ loader.className = "asiyst-avatar-loader";
2564
+ loader.setAttribute("aria-label", `Loading ${this.avatarName}`);
2565
+ this.viewport.appendChild(loader);
2566
+ }
2567
+ async renderLoadedAsset(asset, config) {
2568
+ if (!this.viewport) return;
2569
+ if (this.fbxRenderer) {
2570
+ this.fbxRenderer.destroy();
2571
+ this.fbxRenderer = null;
2572
+ }
2573
+ if (asset.format === "fbx" || asset.format === "glb") {
2574
+ this.fbxRenderer = new FbxRenderer();
2575
+ this.renderMetrics = await this.fbxRenderer.mount(this.viewport, asset, {
2576
+ accentColor: this.accentColor,
2577
+ config
2578
+ });
2579
+ this.fbxRenderer.setFacing(this.facing);
2580
+ this.fbxRenderer.setPose(this.pose);
2581
+ } else if (asset.format === "image") {
2582
+ this.viewport.replaceChildren();
2583
+ const doc = this.viewport.ownerDocument;
2584
+ const img = doc.createElement("img");
2585
+ img.className = "asiyst-avatar-graphic";
2586
+ img.alt = `${config.avatarName} visual avatar`;
2587
+ img.src = asset.url;
2588
+ this.viewport.appendChild(img);
2589
+ } else if (asset.format === "manifest") {
2590
+ const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
2591
+ const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
2592
+ if (modelUrl) {
2593
+ const subAsset = await this.assetLoader.load(modelUrl);
2594
+ await this.renderLoadedAsset(subAsset, config);
2595
+ } else if (thumb) {
2596
+ this.viewport.replaceChildren();
2597
+ const doc = this.viewport.ownerDocument;
2598
+ const img = doc.createElement("img");
2599
+ img.className = "asiyst-avatar-graphic";
2600
+ img.alt = `${config.avatarName} visual avatar`;
2601
+ img.src = thumb;
2602
+ this.viewport.appendChild(img);
2603
+ } else {
2604
+ throw new Error("Manifest did not provide a drawable 3D asset or thumbnail URL");
2605
+ }
2606
+ }
2607
+ }
2608
+ renderFallback(isError = false) {
2609
+ if (!this.viewport) return;
2610
+ this.viewport.replaceChildren();
2611
+ const doc = this.viewport.ownerDocument;
2612
+ const fallback = doc.createElement("div");
2613
+ fallback.className = "asiyst-avatar-fallback";
2614
+ fallback.setAttribute("data-fallback", "true");
2615
+ if (isError) {
2616
+ fallback.setAttribute("data-state", "error");
2617
+ }
2618
+ const initial = doc.createElement("span");
2619
+ initial.className = "asiyst-avatar-initial";
2620
+ renderSafeText(initial, this.avatarName.slice(0, 1).toUpperCase());
2621
+ fallback.appendChild(initial);
2622
+ if (isError) {
2623
+ const badge = doc.createElement("span");
2624
+ badge.className = "asiyst-avatar-fallback-badge";
2625
+ badge.setAttribute("title", "Avatar asset failed to load");
2626
+ badge.textContent = "!";
2627
+ fallback.appendChild(badge);
2628
+ }
2629
+ this.viewport.appendChild(fallback);
2630
+ }
2631
+ setPosition(x, y, animate) {
2632
+ if (!this.root) return;
1614
2633
  this.root.classList.toggle("asiyst-animate", animate);
1615
2634
  this.root.style.left = `${x}px`;
1616
2635
  this.root.style.top = `${y}px`;
1617
2636
  }
1618
2637
  setFacing(direction) {
1619
2638
  this.facing = direction;
2639
+ this.fbxRenderer?.setFacing(direction);
1620
2640
  this.syncTransform();
1621
2641
  }
1622
2642
  setPose(pose) {
1623
2643
  this.pose = pose;
2644
+ this.fbxRenderer?.setPose(pose);
1624
2645
  this.figure?.setAttribute("data-pose", pose);
1625
2646
  this.syncTransform();
1626
2647
  }
1627
2648
  syncTransform() {
1628
- if (!this.figure) {
1629
- return;
1630
- }
2649
+ if (!this.figure) return;
1631
2650
  const face = this.facing === "left" ? "scaleX(-1)" : "";
1632
2651
  const pose = this.pose === "point" ? "rotate(-12deg)" : this.pose === "celebrate" ? "scale(1.08)" : "";
1633
2652
  this.figure.style.transform = `${face} ${pose}`.trim();
1634
2653
  }
1635
2654
  setSpeech(text) {
1636
- if (!this.bubble) {
1637
- return;
1638
- }
2655
+ if (!this.bubble) return;
1639
2656
  if (!text) {
1640
2657
  this.bubble.hidden = true;
1641
2658
  this.bubble.textContent = "";
@@ -1659,6 +2676,33 @@ var CssAvatarRenderer = class {
1659
2676
  getFigure() {
1660
2677
  return this.figure;
1661
2678
  }
2679
+ getViewport() {
2680
+ return this.viewport;
2681
+ }
2682
+ isAssetLoaded() {
2683
+ return this.isAssetLoadedFlag;
2684
+ }
2685
+ isRendered() {
2686
+ return this.isAssetLoadedFlag && (this.fbxRenderer ? this.fbxRenderer.isRendered() : true);
2687
+ }
2688
+ isFallbackActive() {
2689
+ return this.isFallbackFlag;
2690
+ }
2691
+ getRenderState() {
2692
+ return this.renderState;
2693
+ }
2694
+ getLoadedFormat() {
2695
+ return this.loadedFormat;
2696
+ }
2697
+ getAssetUrl() {
2698
+ return this.activeAssetUrl;
2699
+ }
2700
+ getLastError() {
2701
+ return this.lastErrorMessage;
2702
+ }
2703
+ getMetrics() {
2704
+ return this.renderMetrics;
2705
+ }
1662
2706
  };
1663
2707
 
1664
2708
  // src/accessibility/a11y.ts
@@ -1996,6 +3040,9 @@ function isLikelyJavaScriptUrl(value) {
1996
3040
  const lower = value.trim().toLowerCase();
1997
3041
  return lower.startsWith("javascript:") || lower.startsWith("data:") || lower.startsWith("vbscript:") || lower.includes("eval(") || lower.includes("new function") || lower.includes("document.cookie");
1998
3042
  }
3043
+ function isLocalHost(host) {
3044
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
3045
+ }
1999
3046
  function validateWebsiteDomain(config, currentUrl) {
2000
3047
  const allowedDomains = config.allowedDomains.map((domain) => normalizeHost(domain));
2001
3048
  if (allowedDomains.length === 0) {
@@ -2004,7 +3051,16 @@ function validateWebsiteDomain(config, currentUrl) {
2004
3051
  try {
2005
3052
  const parsed = new URL(currentUrl);
2006
3053
  const host = normalizeHost(parsed.host);
2007
- const allowed = allowedDomains.some((domain) => host === domain || host.endsWith(`.${domain}`));
3054
+ const hostIsLocal = isLocalHost(host);
3055
+ const allowed = allowedDomains.some((domain) => {
3056
+ if (host === domain || host.endsWith(`.${domain}`)) {
3057
+ return true;
3058
+ }
3059
+ if (hostIsLocal && isLocalHost(domain)) {
3060
+ return true;
3061
+ }
3062
+ return false;
3063
+ });
2008
3064
  if (!allowed) {
2009
3065
  return { allowed: false, reason: "DOMAIN_NOT_AUTHORIZED" };
2010
3066
  }
@@ -2656,23 +3712,36 @@ var RuntimeAuth = class {
2656
3712
  const timeout = setTimeout(() => controller.abort(), 1e4);
2657
3713
  let response;
2658
3714
  try {
2659
- response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
3715
+ const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
3716
+ const payload = JSON.stringify({
3717
+ projectId: this.options.projectId,
3718
+ publicKey: this.options.publicKey,
3719
+ installationId: this.options.installationId,
3720
+ origin: this.options.origin,
3721
+ environment: this.options.environment,
3722
+ sdkVersion: SDK_VERSION,
3723
+ capabilities: [...RUNTIME_CAPABILITIES]
3724
+ });
3725
+ response = await fetch(`${baseUrl}/sdk/runtime/token`, {
2660
3726
  method: "POST",
2661
3727
  headers: {
2662
3728
  Accept: "application/json",
2663
3729
  "Content-Type": "application/json"
2664
3730
  },
2665
- body: JSON.stringify({
2666
- projectId: this.options.projectId,
2667
- publicKey: this.options.publicKey,
2668
- installationId: this.options.installationId,
2669
- origin: this.options.origin,
2670
- environment: this.options.environment,
2671
- sdkVersion: SDK_VERSION,
2672
- capabilities: [...RUNTIME_CAPABILITIES]
2673
- }),
3731
+ body: payload,
2674
3732
  signal: controller.signal
2675
3733
  });
3734
+ if (response.status === 404) {
3735
+ response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
3736
+ method: "POST",
3737
+ headers: {
3738
+ Accept: "application/json",
3739
+ "Content-Type": "application/json"
3740
+ },
3741
+ body: payload,
3742
+ signal: controller.signal
3743
+ });
3744
+ }
2676
3745
  } catch {
2677
3746
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
2678
3747
  } finally {
@@ -2819,6 +3888,9 @@ var AsiystRuntime = class {
2819
3888
  this.connectionStatus = "disconnected";
2820
3889
  this.verificationStatus = "not_detected";
2821
3890
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
3891
+ this.isHeartbeatInFlight = false;
3892
+ this.lastHeartbeatTime = 0;
3893
+ this.registrationSucceeded = false;
2822
3894
  if (!doc.body) {
2823
3895
  throw new InitializationError("document.body is not available");
2824
3896
  }
@@ -2826,7 +3898,7 @@ var AsiystRuntime = class {
2826
3898
  this.installationId = loadOrCreateInstallationId(options.projectId);
2827
3899
  this.visitorSessionId = options.visitorSessionId || `vsess_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
2828
3900
  const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2829
- this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
3901
+ this.environment = options.environment || (isLocalOrigin ? "development" : "production");
2830
3902
  const transport = new HttpTransport({
2831
3903
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2832
3904
  projectId: options.projectId,
@@ -2841,7 +3913,7 @@ var AsiystRuntime = class {
2841
3913
  origin: win.location.origin,
2842
3914
  environment: this.environment
2843
3915
  }) : void 0;
2844
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId);
3916
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
2845
3917
  this.config = new ConfigManager(options, this.cloud, this.events);
2846
3918
  this.analytics = new Analytics(options.projectId, this.cloud);
2847
3919
  this.host = new HostRoot(doc);
@@ -2923,91 +3995,82 @@ var AsiystRuntime = class {
2923
3995
  sdkVersion: SDK_VERSION
2924
3996
  });
2925
3997
  await this.registerInstallation();
2926
- const previousConnection = this.connectionStatus === "connected";
2927
- try {
2928
- const heartbeat = await this.cloud.heartbeat({
2929
- origin: window.location.origin,
2930
- environment: this.environment,
2931
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
3998
+ await this.sendHeartbeat();
3999
+ const doc = this.host.host.ownerDocument;
4000
+ this.startHeartbeatScheduler(doc);
4001
+ this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4002
+ void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4003
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4004
+ avatarName: cfg.avatarName,
4005
+ publishedVersion: cfg.publishedVersion
4006
+ });
4007
+ const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4008
+ if (assetTarget) {
4009
+ this.events.emit("asiyst:avatar:loading", {
4010
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4011
+ assetUrl: assetTarget
2932
4012
  });
2933
- this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
2934
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
2935
- if (heartbeat.ok) {
2936
- this.lifecycle.emit("sdk.connected", {
2937
- projectId: this.options.projectId,
2938
- origin: window.location.origin,
2939
- environment: this.environment,
2940
- installationId: this.installationId,
2941
- sdkVersion: SDK_VERSION
2942
- });
2943
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
2944
- this.lifecycle.emit("sdk.verified", {
2945
- projectId: this.options.projectId,
2946
- origin: window.location.origin,
2947
- environment: this.environment,
2948
- installationId: this.installationId,
2949
- sdkVersion: SDK_VERSION
4013
+ void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4014
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4015
+ assetUrl: assetTarget
4016
+ });
4017
+ try {
4018
+ const loaded = await this.renderer.loadAsset(cfg);
4019
+ if (loaded) {
4020
+ const format = this.renderer.getLoadedFormat();
4021
+ const assetUrl = this.renderer.getAssetUrl();
4022
+ const isRendered = this.renderer.isRendered();
4023
+ this.events.emit("asiyst:avatar:loaded", {
4024
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4025
+ assetUrl,
4026
+ format
2950
4027
  });
2951
- }
2952
- if (heartbeat.versionOutdated) {
2953
- this.lifecycle.emit("sdk.version_outdated", {
2954
- projectId: this.options.projectId,
2955
- origin: window.location.origin,
2956
- environment: this.environment,
2957
- installationId: this.installationId,
2958
- sdkVersion: SDK_VERSION
4028
+ void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4029
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4030
+ avatarName: cfg.avatarName,
4031
+ assetUrl,
4032
+ format,
4033
+ publishedVersion: cfg.publishedVersion
2959
4034
  });
2960
- }
2961
- } else {
2962
- const reason = heartbeat.verificationStatus ?? "unverified";
2963
- this.lifecycle.emit("sdk.verification_failed", {
2964
- projectId: this.options.projectId,
2965
- origin: window.location.origin,
2966
- environment: this.environment,
2967
- status: reason,
2968
- reason: "heartbeat_failed"
2969
- });
2970
- if (previousConnection) {
2971
- this.lifecycle.emit("sdk.disconnected", {
2972
- projectId: this.options.projectId,
2973
- origin: window.location.origin,
2974
- environment: this.environment,
2975
- installationId: this.installationId,
2976
- reason: "heartbeat_failed",
2977
- status: reason
4035
+ if (isRendered) {
4036
+ this.events.emit("asiyst:avatar:rendered", {
4037
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4038
+ format
4039
+ });
4040
+ void this.cloud.sendTelemetryEvent("avatar_rendered", {
4041
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4042
+ avatarName: cfg.avatarName,
4043
+ format,
4044
+ publishedVersion: cfg.publishedVersion
4045
+ });
4046
+ }
4047
+ } else {
4048
+ const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
4049
+ this.events.emit("asiyst:avatar:error", {
4050
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4051
+ error: err,
4052
+ stage: "renderer_init"
4053
+ });
4054
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4055
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4056
+ error: err,
4057
+ stage: "renderer_init"
2978
4058
  });
2979
4059
  }
2980
- }
2981
- } catch (error) {
2982
- this.connectionStatus = "offline";
2983
- this.verificationStatus = "error";
2984
- this.lifecycle.emit("sdk.verification_failed", {
2985
- projectId: this.options.projectId,
2986
- origin: window.location.origin,
2987
- environment: this.environment,
2988
- installationId: this.installationId,
2989
- reason: "heartbeat_failed",
2990
- category: error instanceof AuthenticationError ? "authorization" : "network"
2991
- });
2992
- if (previousConnection) {
2993
- this.lifecycle.emit("sdk.disconnected", {
2994
- projectId: this.options.projectId,
2995
- origin: window.location.origin,
2996
- environment: this.environment,
2997
- reason: "heartbeat_failed",
2998
- category: "network"
4060
+ } catch (error) {
4061
+ const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
4062
+ this.events.emit("asiyst:avatar:error", {
4063
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4064
+ error: err,
4065
+ stage: "asset_fetch"
4066
+ });
4067
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4068
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4069
+ error: err,
4070
+ stage: "asset_fetch"
2999
4071
  });
3000
4072
  }
3001
4073
  }
3002
- this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
3003
- 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
3010
- });
3011
4074
  }
3012
4075
  getConnectionStatus() {
3013
4076
  return this.connectionStatus;
@@ -3059,6 +4122,16 @@ var AsiystRuntime = class {
3059
4122
  return;
3060
4123
  }
3061
4124
  this.destroyed = true;
4125
+ if (this.heartbeatTimer) {
4126
+ clearInterval(this.heartbeatTimer);
4127
+ this.heartbeatTimer = void 0;
4128
+ }
4129
+ const doc = this.host.host.ownerDocument;
4130
+ if (doc && this.visibilityListener) {
4131
+ doc.removeEventListener("visibilitychange", this.visibilityListener);
4132
+ this.visibilityListener = void 0;
4133
+ }
4134
+ this.isHeartbeatInFlight = false;
3062
4135
  if (this.pagehideListener) {
3063
4136
  win.removeEventListener("pagehide", this.pagehideListener);
3064
4137
  }
@@ -3078,6 +4151,135 @@ var AsiystRuntime = class {
3078
4151
  this.events.removeAll();
3079
4152
  await this.analytics.destroy();
3080
4153
  }
4154
+ startHeartbeatScheduler(doc) {
4155
+ if (this.heartbeatTimer) {
4156
+ clearInterval(this.heartbeatTimer);
4157
+ }
4158
+ this.heartbeatTimer = setInterval(() => {
4159
+ if (!this.destroyed) {
4160
+ void this.sendHeartbeat(true);
4161
+ }
4162
+ }, HEARTBEAT_INTERVAL_MS);
4163
+ if (doc && typeof doc.addEventListener === "function") {
4164
+ this.visibilityListener = () => {
4165
+ if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4166
+ void this.sendHeartbeat(true);
4167
+ }
4168
+ };
4169
+ doc.addEventListener("visibilitychange", this.visibilityListener);
4170
+ }
4171
+ }
4172
+ async sendHeartbeat(_isPeriodic = false) {
4173
+ if (this.destroyed || this.isHeartbeatInFlight) {
4174
+ return false;
4175
+ }
4176
+ this.isHeartbeatInFlight = true;
4177
+ const previousConnection = this.connectionStatus === "connected";
4178
+ const origin = window.location.origin;
4179
+ const environment = this.environment;
4180
+ const installationId = this.installationId;
4181
+ try {
4182
+ if (!this.registrationSucceeded && installationId) {
4183
+ await this.registerInstallation();
4184
+ }
4185
+ const heartbeat = await this.cloud.heartbeat({
4186
+ origin,
4187
+ environment,
4188
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4189
+ });
4190
+ this.lastHeartbeatTime = Date.now();
4191
+ this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4192
+ this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
4193
+ if (heartbeat.ok) {
4194
+ if (!previousConnection) {
4195
+ this.events.emit("asiyst:runtime:connected", {
4196
+ projectId: this.options.projectId,
4197
+ status: "connected",
4198
+ environment,
4199
+ origin
4200
+ });
4201
+ this.lifecycle.emit("sdk.connected", {
4202
+ projectId: this.options.projectId,
4203
+ origin,
4204
+ environment,
4205
+ installationId,
4206
+ sdkVersion: SDK_VERSION
4207
+ });
4208
+ }
4209
+ if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
4210
+ this.lifecycle.emit("sdk.verified", {
4211
+ projectId: this.options.projectId,
4212
+ origin,
4213
+ environment,
4214
+ installationId,
4215
+ sdkVersion: SDK_VERSION
4216
+ });
4217
+ }
4218
+ if (heartbeat.versionOutdated) {
4219
+ this.lifecycle.emit("sdk.version_outdated", {
4220
+ projectId: this.options.projectId,
4221
+ origin,
4222
+ environment,
4223
+ installationId,
4224
+ sdkVersion: SDK_VERSION
4225
+ });
4226
+ }
4227
+ return true;
4228
+ } else {
4229
+ const reason = heartbeat.verificationStatus ?? "unverified";
4230
+ this.lifecycle.emit("sdk.verification_failed", {
4231
+ projectId: this.options.projectId,
4232
+ origin,
4233
+ environment,
4234
+ status: reason,
4235
+ reason: "heartbeat_failed"
4236
+ });
4237
+ if (previousConnection) {
4238
+ this.events.emit("asiyst:runtime:disconnected", {
4239
+ projectId: this.options.projectId,
4240
+ reason: "heartbeat_failed"
4241
+ });
4242
+ this.lifecycle.emit("sdk.disconnected", {
4243
+ projectId: this.options.projectId,
4244
+ origin,
4245
+ environment,
4246
+ installationId,
4247
+ reason: "heartbeat_failed",
4248
+ status: reason
4249
+ });
4250
+ }
4251
+ return false;
4252
+ }
4253
+ } catch (error) {
4254
+ this.connectionStatus = "offline";
4255
+ this.verificationStatus = "error";
4256
+ this.lifecycle.emit("sdk.verification_failed", {
4257
+ projectId: this.options.projectId,
4258
+ origin,
4259
+ environment,
4260
+ installationId,
4261
+ reason: "heartbeat_failed",
4262
+ category: error instanceof AuthenticationError ? "authorization" : "network"
4263
+ });
4264
+ if (previousConnection) {
4265
+ this.events.emit("asiyst:runtime:disconnected", {
4266
+ projectId: this.options.projectId,
4267
+ reason: "heartbeat_failed"
4268
+ });
4269
+ this.lifecycle.emit("sdk.disconnected", {
4270
+ projectId: this.options.projectId,
4271
+ origin,
4272
+ environment,
4273
+ installationId,
4274
+ reason: "heartbeat_failed",
4275
+ category: "network"
4276
+ });
4277
+ }
4278
+ return false;
4279
+ } finally {
4280
+ this.isHeartbeatInFlight = false;
4281
+ }
4282
+ }
3081
4283
  async registerInstallation() {
3082
4284
  const origin = window.location.origin;
3083
4285
  const environment = this.environment;
@@ -3099,6 +4301,7 @@ var AsiystRuntime = class {
3099
4301
  environment,
3100
4302
  sdk_version: SDK_VERSION
3101
4303
  });
4304
+ this.registrationSucceeded = true;
3102
4305
  return;
3103
4306
  } catch (error) {
3104
4307
  lastError = error;
@@ -3198,6 +4401,9 @@ var Asiyst = {
3198
4401
  getVerificationStatus() {
3199
4402
  return requireRuntime().getVerificationStatus();
3200
4403
  },
4404
+ isRuntimeConnected() {
4405
+ return requireRuntime().getConnectionStatus() === "connected";
4406
+ },
3201
4407
  avatar: {
3202
4408
  show() {
3203
4409
  withIsolation(() => requireRuntime().avatarApi().show());
@@ -3253,6 +4459,6 @@ var Asiyst = {
3253
4459
  }
3254
4460
  };
3255
4461
 
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 };
4462
+ 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
4463
  //# sourceMappingURL=index.js.map
3258
4464
  //# sourceMappingURL=index.js.map