@spatius/avatarkit 1.3.4 → 1.3.5

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.
@@ -1,797 +0,0 @@
1
- import { St as ErrorCode, _t as generateTraceId, c as logEvent, h as hostOf, ht as isDebugMode, l as logMetric, t as logger, vt as AvatarError, y as recordHttpClientDuration } from "./logger-__jZD7QG.js";
2
- import { t as AvatarSDK } from "./AvatarSDK-DX8_-oyi.js";
3
- //#region config/app-config.ts
4
- const GLOBAL_FLAME_CDN_BASE = "https://cdn.spatialwalk.cloud/public";
5
- const CN_FLAME_CDN_BASE = "https://cdn.spatialwalk.top/public";
6
- function getFlameCdnBase(region) {
7
- return region.startsWith("cn-") ? CN_FLAME_CDN_BASE : GLOBAL_FLAME_CDN_BASE;
8
- }
9
- const APP_CONFIG = {
10
- testEnv: false,
11
- get debug() {
12
- return isDebugMode();
13
- },
14
- rendering: {
15
- /**
16
- * Sort mode
17
- * - 'balance': Performance first, sort first frame then reuse (default)
18
- * - 'quality': Quality first, re-sort every frame
19
- */
20
- sortMode: "balance" },
21
- camera: {
22
- position: [
23
- -.02,
24
- -.013,
25
- 1.5
26
- ],
27
- target: [
28
- 0,
29
- 0,
30
- 0
31
- ],
32
- fov: 22,
33
- near: .01,
34
- far: 100
35
- },
36
- animation: { fps: 25 },
37
- audio: { sampleRate: 16e3 },
38
- avatar: {
39
- baseAssetsPath: "",
40
- wasmPath: "./wasm/avatar_core_wasm.js"
41
- },
42
- flame: {
43
- cdnBase: GLOBAL_FLAME_CDN_BASE,
44
- unifiedModelPath: "unified_model_body.pb.gz"
45
- },
46
- wasm: {
47
- logLevel: "basic",
48
- enableValidation: false,
49
- enablePerformanceMetrics: true
50
- }
51
- };
52
- //#endregion
53
- //#region utils/error-utils.ts
54
- /**
55
- * Error Utility Functions
56
- * Provides consistent error handling and formatting across the application
57
- */
58
- /**
59
- * Convert unknown error to a readable error message string
60
- *
61
- * @param err - Unknown error object (could be Error, string, object, etc.)
62
- * @returns Formatted error message string
63
- *
64
- * @example
65
- * try {
66
- * riskyOperation()
67
- * } catch (err) {
68
- * const message = errorToMessage(err)
69
- * logger.error('Operation failed:', message)
70
- * }
71
- */
72
- function errorToMessage(err) {
73
- if (err instanceof Error) return err.message;
74
- if (typeof err === "string") return err;
75
- if (typeof err === "object" && err !== null) {
76
- if ("message" in err && typeof err.message === "string") return err.message;
77
- try {
78
- return JSON.stringify(err);
79
- } catch {
80
- return String(err);
81
- }
82
- }
83
- return String(err);
84
- }
85
- //#endregion
86
- //#region utils/pwa-cache-manager.ts
87
- /**
88
- * PWA Cache Manager
89
- * Manages Service Worker Cache for character resources and template resources
90
- * @internal
91
- */
92
- /**
93
- * PWA Cache Manager
94
- * Manages character resources cache (per character) and template resources cache (versioned)
95
- */
96
- var PwaCacheManager = class PwaCacheManager {
97
- static TEMPLATE_RESOURCE_VERSION = "1.0.0";
98
- static TEMPLATE_CACHE_NAME = `spatius-sdk-template-cache-${PwaCacheManager.TEMPLATE_RESOURCE_VERSION}`;
99
- static TEMPLATE_VERSION_STORAGE_KEY = "spatius-sdk-template-cache-version";
100
- static CHARACTER_CACHE_PREFIX = "spatius-sdk-character-";
101
- static CHARACTER_CACHE_SUFFIX = "-cache";
102
- static MAX_CHARACTER_CACHE_ENTRIES = 1e3;
103
- /**
104
- * Check if Cache API is supported
105
- * @internal
106
- */
107
- static isSupported() {
108
- return typeof caches !== "undefined";
109
- }
110
- /**
111
- * Get character cache name
112
- * @internal
113
- */
114
- static getCharacterCacheName(characterId) {
115
- return `${PwaCacheManager.CHARACTER_CACHE_PREFIX}${characterId}${PwaCacheManager.CHARACTER_CACHE_SUFFIX}`;
116
- }
117
- /**
118
- * Get character resource from cache
119
- * @internal
120
- */
121
- static async getCharacterResource(characterId, url) {
122
- if (!PwaCacheManager.isSupported()) return null;
123
- try {
124
- const cacheName = PwaCacheManager.getCharacterCacheName(characterId);
125
- const response = await (await caches.open(cacheName)).match(url);
126
- if (response) {
127
- const arrayBuffer = await response.arrayBuffer();
128
- logger.log(`[PwaCacheManager] Character resource cache hit: ${url}`);
129
- return arrayBuffer;
130
- }
131
- return null;
132
- } catch (error) {
133
- logger.warn(`[PwaCacheManager] Failed to get character resource from cache:`, error);
134
- return null;
135
- }
136
- }
137
- /**
138
- * Put character resource into cache
139
- * @internal
140
- */
141
- static async putCharacterResource(characterId, url, data) {
142
- if (!PwaCacheManager.isSupported()) return;
143
- try {
144
- const cacheName = PwaCacheManager.getCharacterCacheName(characterId);
145
- const cache = await caches.open(cacheName);
146
- const keys = await cache.keys();
147
- if (keys.length >= PwaCacheManager.MAX_CHARACTER_CACHE_ENTRIES) {
148
- const oldestKey = keys[0];
149
- await cache.delete(oldestKey);
150
- logger.log(`[PwaCacheManager] Character cache full, deleted oldest entry: ${oldestKey.url}`);
151
- }
152
- await cache.put(url, new Response(data));
153
- logger.log(`[PwaCacheManager] Character resource cached: ${url}`);
154
- } catch (error) {
155
- logger.warn(`[PwaCacheManager] Failed to put character resource to cache:`, error);
156
- }
157
- }
158
- /**
159
- * Get template resource from cache
160
- * @internal
161
- */
162
- static async getTemplateResource(url) {
163
- if (!PwaCacheManager.isSupported()) return null;
164
- try {
165
- const response = await (await caches.open(PwaCacheManager.TEMPLATE_CACHE_NAME)).match(url);
166
- if (response) {
167
- const arrayBuffer = await response.arrayBuffer();
168
- logger.log(`[PwaCacheManager] Template resource cache hit: ${url}`);
169
- return arrayBuffer;
170
- }
171
- return null;
172
- } catch (error) {
173
- logger.warn(`[PwaCacheManager] Failed to get template resource from cache:`, error);
174
- return null;
175
- }
176
- }
177
- /**
178
- * Put template resource into cache
179
- * Template resources have no quantity limit, permanently retained until version update
180
- * @internal
181
- */
182
- static async putTemplateResource(url, data) {
183
- if (!PwaCacheManager.isSupported()) return;
184
- try {
185
- await (await caches.open(PwaCacheManager.TEMPLATE_CACHE_NAME)).put(url, new Response(data));
186
- logger.log(`[PwaCacheManager] Template resource cached: ${url}`);
187
- } catch (error) {
188
- logger.warn(`[PwaCacheManager] Failed to put template resource to cache:`, error);
189
- }
190
- }
191
- /**
192
- * Clear character cache
193
- * @internal
194
- */
195
- static async clearCharacterCache(characterId) {
196
- if (!PwaCacheManager.isSupported()) return;
197
- try {
198
- const cacheName = PwaCacheManager.getCharacterCacheName(characterId);
199
- await caches.delete(cacheName);
200
- logger.log(`[PwaCacheManager] Character cache cleared: ${characterId}`);
201
- } catch (error) {
202
- logger.warn(`[PwaCacheManager] Failed to clear character cache:`, error);
203
- }
204
- }
205
- /**
206
- * Check template cache version, clear cache if version changed
207
- * Uses independent template resource version (not dependent on SDK version), allowing different SDK versions to share the same template resource cache
208
- * @returns true if version changed and cache was cleared, false otherwise
209
- * @internal
210
- */
211
- static async checkTemplateCacheVersion() {
212
- if (!PwaCacheManager.isSupported()) return false;
213
- try {
214
- const currentTemplateVersion = PwaCacheManager.TEMPLATE_RESOURCE_VERSION;
215
- const storedVersion = localStorage.getItem(PwaCacheManager.TEMPLATE_VERSION_STORAGE_KEY);
216
- if (storedVersion !== currentTemplateVersion) {
217
- if (storedVersion) {
218
- const oldCacheName = `spatius-sdk-template-cache-${storedVersion}`;
219
- await caches.delete(oldCacheName).catch(() => {});
220
- }
221
- localStorage.setItem(PwaCacheManager.TEMPLATE_VERSION_STORAGE_KEY, currentTemplateVersion);
222
- logger.log(`[PwaCacheManager] Template cache version changed: ${storedVersion} -> ${currentTemplateVersion}, old cache cleared`);
223
- return true;
224
- }
225
- return false;
226
- } catch (error) {
227
- logger.warn(`[PwaCacheManager] Failed to check template cache version:`, error);
228
- return false;
229
- }
230
- }
231
- };
232
- //#endregion
233
- //#region core/AvatarDownloader.ts
234
- /**
235
- * Get cache information for a resource
236
- * Detects browser cache, CDN cache, and PWA (Service Worker) cache
237
- */
238
- function getCacheInfo(url, response) {
239
- const resourceTiming = performance.getEntriesByName(url, "resource")[0];
240
- const transferSize = resourceTiming?.transferSize ?? 0;
241
- const deliveryType = resourceTiming?.deliveryType;
242
- const hasServiceWorker = typeof navigator !== "undefined" && navigator.serviceWorker?.controller !== null;
243
- const isPwaCache = transferSize === 0 && hasServiceWorker && (deliveryType === "cache" || deliveryType === "serviceworker") && resourceTiming?.duration !== void 0 && resourceTiming.duration > 0;
244
- const isBrowserCache = transferSize === 0 && !isPwaCache && (!hasServiceWorker || deliveryType === "cache") && resourceTiming?.duration !== void 0 && resourceTiming.duration > 0;
245
- const cfCacheStatus = response.headers.get("cf-cache-status");
246
- const xCache = response.headers.get("x-cache");
247
- const xSwiftCacheTime = response.headers.get("x-swift-cache-time");
248
- const cdnCacheStatus = cfCacheStatus || xCache || xSwiftCacheTime;
249
- let isCdnCache = false;
250
- if (cdnCacheStatus) {
251
- const statusLower = cdnCacheStatus.toLowerCase();
252
- if (statusLower === "hit" || statusLower === "hits" || statusLower.includes("hit")) {
253
- if (!statusLower.includes("miss") && !statusLower.includes("dynamic") && !statusLower.includes("bypass")) isCdnCache = true;
254
- }
255
- }
256
- let cacheHit = false;
257
- let cacheType = "none";
258
- if (isPwaCache) {
259
- cacheHit = true;
260
- cacheType = "pwa";
261
- } else if (isBrowserCache) {
262
- cacheHit = true;
263
- cacheType = "browser";
264
- } else if (isCdnCache) {
265
- cacheHit = true;
266
- cacheType = "cdn";
267
- }
268
- return {
269
- cacheHit,
270
- cacheType,
271
- transferSize,
272
- cdnCacheStatus: cdnCacheStatus || void 0
273
- };
274
- }
275
- /**
276
- * 把整次角色加载的资产下载汇总成**一条** Transaction。
277
- *
278
- * 成败取「最差的一片」:任一片 transport error 即整次记 transport error;否则取
279
- * 状态码最大的那个(4xx/5xx 会盖过 200)。这样后端按状态码切出的成功率,含义是
280
- * 「这次加载的资产是否全部拿到」——与用户实际体验一致,一片挂了角色就出不来。
281
- *
282
- * duration 传整体耗时而非单片,与 `download_avatar_assets_latency` 同口径。
283
- */
284
- function recordAssetTransaction(outcomes, durationMs, operation = ASSET_OPERATION) {
285
- const real = outcomes.filter((o) => !o.skipped);
286
- if (real.length === 0) return;
287
- recordHttpClientDuration({
288
- operation,
289
- method: "GET",
290
- durationMs,
291
- statusCode: real.some((o) => o.statusCode === void 0) ? void 0 : real.reduce((max, o) => Math.max(max, o.statusCode ?? 0), 0),
292
- serverAddress: real[0].host
293
- });
294
- }
295
- /**
296
- * Transaction 的 `operation` 取值。必须低基数:资产 URL 带 avatar id 与文件名,
297
- * 直接当维度会让时间序列随角色数无限增长。要定位「哪个文件挂了」用
298
- * `download_avatar_assets_failed` log,它带 resource/url/error。
299
- */
300
- const ASSET_OPERATION = "/assets/character";
301
- const TEMPLATE_OPERATION = "/assets/template";
302
- async function downloadResource(url, options) {
303
- const { signal, characterId, resourceType, maxRetries = 3, outcomes } = options || {};
304
- const outcomeSlotIndex = outcomes ? outcomes.length : -1;
305
- if (outcomes) outcomes.push({ host: hostOf(url) });
306
- if (signal?.aborted) throw new Error("Download cancelled");
307
- try {
308
- let cached = null;
309
- let pwaCacheSubtype = void 0;
310
- if (characterId) {
311
- cached = await PwaCacheManager.getCharacterResource(characterId, url);
312
- if (cached) pwaCacheSubtype = "character";
313
- } else if (resourceType === "template") {
314
- cached = await PwaCacheManager.getTemplateResource(url);
315
- if (cached) pwaCacheSubtype = "template";
316
- }
317
- if (cached) {
318
- const response = new Response(cached);
319
- await new Promise((resolve) => setTimeout(resolve, 0));
320
- const cacheInfo = getCacheInfo(url, response);
321
- cacheInfo.cacheHit = true;
322
- cacheInfo.cacheType = "pwa";
323
- cacheInfo.pwaCacheSubtype = pwaCacheSubtype;
324
- if (outcomes && outcomeSlotIndex >= 0) outcomes[outcomeSlotIndex] = {
325
- host: hostOf(url),
326
- skipped: true
327
- };
328
- return {
329
- data: cached,
330
- cacheInfo
331
- };
332
- }
333
- let lastError = null;
334
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
335
- if (signal?.aborted) throw new Error("Download cancelled");
336
- const outcomeSlot = { host: hostOf(url) };
337
- if (outcomes) outcomes[outcomeSlotIndex] = outcomeSlot;
338
- try {
339
- const response = await fetch(url, { signal });
340
- outcomeSlot.statusCode = response.status;
341
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
342
- const arrayBuffer = await response.arrayBuffer();
343
- const contentLength = response.headers.get("content-length");
344
- if (contentLength) {
345
- const expectedSize = parseInt(contentLength, 10);
346
- if (!isNaN(expectedSize) && arrayBuffer.byteLength < expectedSize) throw new Error(`Download incomplete: received ${arrayBuffer.byteLength} bytes, expected ${expectedSize} bytes`);
347
- }
348
- if (characterId) PwaCacheManager.putCharacterResource(characterId, url, arrayBuffer).catch((err) => {
349
- logger.warn(`[downloadResource] Failed to cache character resource:`, err);
350
- });
351
- else if (resourceType === "template") PwaCacheManager.putTemplateResource(url, arrayBuffer).catch((err) => {
352
- logger.warn(`[downloadResource] Failed to cache template resource:`, err);
353
- });
354
- await new Promise((resolve) => setTimeout(resolve, 0));
355
- return {
356
- data: arrayBuffer,
357
- cacheInfo: getCacheInfo(url, response)
358
- };
359
- } catch (err) {
360
- if (err instanceof Error && (err.name === "AbortError" || err.message === "Download cancelled")) throw err;
361
- lastError = err instanceof Error ? err : new Error(String(err));
362
- if (attempt < maxRetries) logger.warn(`[downloadResource] Attempt ${attempt}/${maxRetries} failed for ${url}, retrying immediately...`);
363
- }
364
- }
365
- throw lastError || /* @__PURE__ */ new Error(`Failed to download ${url} after ${maxRetries} attempts`);
366
- } catch (err) {
367
- if (err instanceof Error && (err.name === "AbortError" || err.message === "Download cancelled")) throw err;
368
- const msg = errorToMessage(err);
369
- throw new Error(`[downloadResource] ${url} → ${msg}`);
370
- }
371
- }
372
- var AvatarDownloader = class {
373
- baseAssetsPath;
374
- constructor(baseAssetsPath = "/") {
375
- this.baseAssetsPath = baseAssetsPath;
376
- }
377
- /**
378
- * Load unified template model (single gzip-compressed file)
379
- * Includes PWA cache, retry, integrity check, and telemetry
380
- * @internal
381
- */
382
- async loadUnifiedTemplate() {
383
- await PwaCacheManager.checkTemplateCacheVersion();
384
- const startTime = Date.now();
385
- const cdnBase = getFlameCdnBase(AvatarSDK.configuration?.region || "us-west");
386
- const { unifiedModelPath } = APP_CONFIG.flame;
387
- const url = `${cdnBase}/${unifiedModelPath}`;
388
- logger.log(`📥 Loading unified template from: ${url}`);
389
- const cached = await PwaCacheManager.getTemplateResource(url);
390
- if (cached) {
391
- const duration = Date.now() - startTime;
392
- logger.log(`✅ Unified template loaded from cache (${(cached.byteLength / 1024 / 1024).toFixed(1)} MB)`);
393
- logMetric("template_resources_load_measure", duration, {
394
- file_count: 1,
395
- cache_hit: true,
396
- cache_type: "pwa"
397
- });
398
- return { unifiedModel: cached };
399
- }
400
- const maxRetries = 3;
401
- let lastError = null;
402
- const templateOutcomes = [];
403
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
404
- const outcomeSlot = { host: hostOf(url) };
405
- templateOutcomes[0] = outcomeSlot;
406
- try {
407
- const response = await fetch(url);
408
- outcomeSlot.statusCode = response.status;
409
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
410
- let buffer;
411
- if (APP_CONFIG.flame.unifiedModelPath.endsWith(".gz")) {
412
- const decompressedStream = response.body.pipeThrough(new DecompressionStream("gzip"));
413
- buffer = await new Response(decompressedStream).arrayBuffer();
414
- } else buffer = await response.arrayBuffer();
415
- logger.log(`✅ Unified template loaded (${(buffer.byteLength / 1024 / 1024).toFixed(1)} MB)`);
416
- PwaCacheManager.putTemplateResource(url, buffer).catch((err) => {
417
- logger.warn(`[loadUnifiedTemplate] Failed to cache:`, err);
418
- });
419
- logMetric("template_resources_load_measure", Date.now() - startTime, {
420
- file_count: 1,
421
- cache_hit: false,
422
- cache_type: "none"
423
- });
424
- recordAssetTransaction(templateOutcomes, Date.now() - startTime, TEMPLATE_OPERATION);
425
- return { unifiedModel: buffer };
426
- } catch (err) {
427
- lastError = err instanceof Error ? err : new Error(String(err));
428
- if (attempt < maxRetries) logger.warn(`[loadUnifiedTemplate] Attempt ${attempt}/${maxRetries} failed, retrying...`);
429
- }
430
- }
431
- recordAssetTransaction(templateOutcomes, Date.now() - startTime, TEMPLATE_OPERATION);
432
- throw lastError || /* @__PURE__ */ new Error(`Failed to download unified template after ${maxRetries} attempts`);
433
- }
434
- /**
435
- * Load camera settings from CharacterMeta (optional)
436
- * @internal
437
- */
438
- async loadCameraSettings(characterMeta, options) {
439
- const { signal } = options || {};
440
- const cameraUrl = characterMeta.camera?.resource?.remote;
441
- if (!cameraUrl) {
442
- logger.log("ℹ️ No camera resource URL provided");
443
- return;
444
- }
445
- if (signal?.aborted) throw new Error("Load cancelled");
446
- try {
447
- logger.log(`📥 Loading camera info from: ${cameraUrl}`);
448
- const { data: arrayBuffer } = await downloadResource(cameraUrl, {
449
- signal,
450
- characterId: characterMeta.characterId ?? void 0,
451
- resourceType: "character"
452
- });
453
- const text = new TextDecoder().decode(arrayBuffer);
454
- const cameraSettings = JSON.parse(text);
455
- logger.log("✅ Camera info loaded:", cameraSettings);
456
- return cameraSettings;
457
- } catch (error) {
458
- logger.warn("⚠️ Failed to load camera info, using default:", error);
459
- return;
460
- }
461
- }
462
- /**
463
- * Load character data from CharacterMeta (iOS compatible)
464
- * @internal
465
- */
466
- async loadCharacterData(characterMeta, options) {
467
- const { progressCallback = null, signal, useCompressedModel = false } = options || {};
468
- if (signal?.aborted) throw new Error("Download cancelled");
469
- const totalStartTime = Date.now();
470
- const shapeUrl = characterMeta.models?.shape?.resource?.remote;
471
- const pointCloudUrl = useCompressedModel ? characterMeta.models?.gsStandard?.xrResource?.remote ?? characterMeta.models?.gsStandard?.resource?.remote : characterMeta.models?.gsStandard?.resource?.remote;
472
- const idleAnimationUrl = characterMeta.animations?.frameIdle?.resource?.remote;
473
- const monoAnimationUrl = characterMeta.animations?.frameMono?.resource?.remote;
474
- if (!shapeUrl || !pointCloudUrl) throw new Error("Missing required resources: shape or gsStandard (point cloud)");
475
- const filesToLoad = [{
476
- key: "shape",
477
- url: shapeUrl,
478
- filename: "shape.pb"
479
- }, {
480
- key: "pointCloud",
481
- url: pointCloudUrl,
482
- filename: "point_cloud.ply"
483
- }];
484
- if (idleAnimationUrl) filesToLoad.push({
485
- key: "idleAnimation",
486
- url: idleAnimationUrl,
487
- filename: "idle.pb",
488
- optional: true
489
- });
490
- if (monoAnimationUrl) filesToLoad.push({
491
- key: "monoAnimation",
492
- url: monoAnimationUrl,
493
- filename: "mono.pb",
494
- optional: true
495
- });
496
- let loadedFiles = 0;
497
- const totalFiles = filesToLoad.length;
498
- const updateProgress = (filename, loaded) => {
499
- if (progressCallback) {
500
- if (loaded) loadedFiles++;
501
- progressCallback({
502
- stage: "character",
503
- filename,
504
- loaded: loadedFiles,
505
- total: totalFiles,
506
- progress: loadedFiles / totalFiles
507
- });
508
- }
509
- };
510
- const characterData = {};
511
- const cacheInfos = [];
512
- /** 各片的 HTTP 结果,收尾时汇总成一条 Transaction(见 recordAssetTransaction)。 */
513
- const httpOutcomes = [];
514
- const parallelStartTime = Date.now();
515
- const downloadPromises = filesToLoad.map(async ({ key, url, filename, optional }) => {
516
- updateProgress(filename, false);
517
- try {
518
- const { data: arrayBuffer, cacheInfo } = await downloadResource(url, {
519
- signal,
520
- characterId: characterMeta.characterId ?? void 0,
521
- resourceType: "character",
522
- outcomes: httpOutcomes
523
- });
524
- if (key === "shape") characterData.shape = arrayBuffer;
525
- else if (key === "pointCloud") characterData.pointCloud = arrayBuffer;
526
- else if (key === "idleAnimation") characterData.idleAnimation = arrayBuffer;
527
- else if (key === "monoAnimation") characterData.monoAnimation = arrayBuffer;
528
- cacheInfos.push(cacheInfo);
529
- updateProgress(filename, true);
530
- return {
531
- key,
532
- success: true,
533
- size: arrayBuffer.byteLength
534
- };
535
- } catch (error) {
536
- if (error instanceof Error && (error.name === "AbortError" || error.message === "Download cancelled")) {
537
- logEvent("download_avatar_assets_cancelled", "info", { avatar_id: characterMeta.characterId ?? "unknown" });
538
- throw error;
539
- }
540
- if (!optional) {
541
- const errorMessage = error instanceof Error ? error.message : String(error);
542
- logEvent("download_avatar_assets_failed", "error", {
543
- avatar_id: characterMeta.characterId ?? "unknown",
544
- description: `Failed to download required resource: ${filename}`,
545
- resource: key,
546
- url,
547
- error: errorMessage
548
- });
549
- throw error;
550
- }
551
- logger.warn(`⚠️ Optional resource ${filename} failed to load:`, error);
552
- updateProgress(filename, true);
553
- return {
554
- key,
555
- success: false,
556
- size: 0
557
- };
558
- }
559
- });
560
- try {
561
- await Promise.all(downloadPromises);
562
- } finally {
563
- recordAssetTransaction(httpOutcomes, Date.now() - totalStartTime);
564
- }
565
- const parallelDuration = Date.now() - parallelStartTime;
566
- const totalDuration = Date.now() - totalStartTime;
567
- if (!characterData.shape || !characterData.pointCloud) {
568
- const reason = "Failed to load character data";
569
- logEvent("download_avatar_assets_failed", "error", {
570
- avatar_id: characterMeta.characterId ?? "unknown",
571
- description: reason
572
- });
573
- throw new Error(reason);
574
- }
575
- const cacheHit = cacheInfos.length > 0 && cacheInfos.every((info) => info.cacheHit);
576
- const cacheType = cacheInfos[0]?.cacheType || "none";
577
- const totalSize = Object.values(characterData).reduce((sum, buffer) => {
578
- return sum + (buffer ? buffer.byteLength : 0);
579
- }, 0);
580
- logMetric("download_avatar_assets_latency", totalDuration, {
581
- resolution: "default",
582
- use_compressed_model: useCompressedModel,
583
- file_count: filesToLoad.length,
584
- cache_hit: cacheHit,
585
- cache_type: cacheType
586
- }, {
587
- avatar_id: characterMeta.characterId ?? "unknown",
588
- parallel_duration: parallelDuration,
589
- total_size: totalSize
590
- });
591
- return {
592
- data: characterData,
593
- cacheHit,
594
- cacheType
595
- };
596
- }
597
- /**
598
- * Preload all resources (template + character data + camera info + settings)
599
- * @internal
600
- */
601
- async preloadResources(characterMeta, options) {
602
- const { progressCallback = null, signal, useCompressedModel = false } = options || {};
603
- if (signal?.aborted) throw new Error("Preload cancelled");
604
- const [characterResult, preloadCameraSettings] = await Promise.all([this.loadCharacterData(characterMeta, {
605
- signal,
606
- useCompressedModel,
607
- progressCallback: (info) => {
608
- if (progressCallback) progressCallback({
609
- ...info,
610
- stage: `character-${info.stage}`
611
- });
612
- }
613
- }), this.loadCameraSettings(characterMeta, { signal })]);
614
- return {
615
- characterData: characterResult.data,
616
- preloadCameraSettings,
617
- characterSettings: characterMeta.characterSettings,
618
- cacheHit: characterResult.cacheHit,
619
- cacheType: characterResult.cacheType
620
- };
621
- }
622
- /**
623
- * Get AvatarKit SDK API Client (region-templated endpoint composed by AvatarSDK.getEnvironmentConfig).
624
- * Used for: character details and resource URLs (public endpoints, no auth required)
625
- * Note: This endpoint does not require authentication, so we don't add X-App-Id or Authorization headers
626
- * to avoid CORS preflight requests for simple GET requests
627
- */
628
- getSdkApiClient() {
629
- return { async request(url, options = {}) {
630
- const baseUrl = AvatarSDK.getEnvironmentConfig().sdkApiBaseUrl;
631
- const fullUrl = baseUrl + url;
632
- const headers = {};
633
- const method = options.method || "GET";
634
- if (method !== "GET" && options.body) headers["Content-Type"] = "application/json";
635
- const operation = url.split("?")[0].replace(/\/v2\/avatar\/[^/?]+/, "/v2/avatar/{id}");
636
- let serverAddress;
637
- try {
638
- serverAddress = new URL(baseUrl).host;
639
- } catch {}
640
- const startMs = performance.now();
641
- try {
642
- const response = await fetch(fullUrl, {
643
- method,
644
- headers: {
645
- ...headers,
646
- ...options.headers
647
- },
648
- body: options.body ? JSON.stringify(options.body) : void 0,
649
- signal: options.signal
650
- });
651
- recordHttpClientDuration({
652
- operation,
653
- method,
654
- durationMs: Math.round(performance.now() - startMs),
655
- statusCode: response.status,
656
- serverAddress
657
- });
658
- if (!response.ok) {
659
- let serverMessage = "";
660
- try {
661
- const body = await response.json();
662
- if (body?.errors && Array.isArray(body.errors) && body.errors.length > 0) {
663
- const e = body.errors[0];
664
- serverMessage = e.detail || e.title || e.message || JSON.stringify(e);
665
- } else serverMessage = body?.message || body?.error || JSON.stringify(body);
666
- } catch {
667
- serverMessage = response.statusText;
668
- }
669
- let error;
670
- if (response.status === 404) {
671
- const urlMatch = url.match(/\/v2\/(?:character|avatar)\/([^/?]+)/);
672
- const extractedCharacterId = urlMatch ? urlMatch[1] : "unknown";
673
- const callerTraceId = (options.headers || {})["x-sp-trace-id"];
674
- logEvent("avatar_id_unrecognized", "error", {
675
- avatar_id: extractedCharacterId,
676
- description: `HTTP 404: ${serverMessage}`,
677
- ...callerTraceId ? { trace_id: callerTraceId } : {}
678
- });
679
- error = new AvatarError(`HTTP 404: ${serverMessage}`, ErrorCode.avatarIDUnrecognized);
680
- } else error = new AvatarError(`HTTP ${response.status}: ${serverMessage}`, ErrorCode.failedToFetchAvatarMetadata);
681
- throw error;
682
- }
683
- try {
684
- return await response.json();
685
- } catch {
686
- throw new AvatarError("Avatar data is invalid. Please contact Spatius support.", ErrorCode.invalidAvatarMetadata);
687
- }
688
- } catch (err) {
689
- if (err instanceof AvatarError) throw err;
690
- recordHttpClientDuration({
691
- operation,
692
- method,
693
- durationMs: Math.round(performance.now() - startMs),
694
- serverAddress
695
- });
696
- throw new AvatarError("Failed to load avatar due to network issues, please check your connection and try again.", ErrorCode.failedToFetchAvatarMetadata);
697
- }
698
- } };
699
- }
700
- /**
701
- * Map the new `/v2/avatar/{id}` `AvatarAsset` payload onto the internal
702
- * `CharacterMeta` shape used by the existing download / render pipeline.
703
- *
704
- * The backend (grpc-gateway) serialises proto fields as camelCase JSON, so the
705
- * runtime object is loosely shaped like the generated `AvatarAsset`. We:
706
- * - lift `models.gs` into `models.gsStandard` (downloader/asset-count read gsStandard)
707
- * - rename `animations.frameFallback` → `animations.frameMono`
708
- * - fold the inline `camera` / `transform` into `characterSettings` so the
709
- * renderer's `resolveCameraConfig` reads structured values and no camera
710
- * resource is downloaded (top-level `camera` is intentionally left unset)
711
- * @internal
712
- */
713
- mapAvatarAssetToCharacterMeta(asset, avatarId) {
714
- const characterSettings = {
715
- ...asset.camera ? { camera: { ...asset.camera } } : {},
716
- ...asset.transform ? { transform: { ...asset.transform } } : {}
717
- };
718
- return {
719
- characterId: avatarId,
720
- version: asset.version ?? "",
721
- compatibilityFlags: asset.compatibilityFlags ?? [],
722
- updatedAt: asset.updatedAt,
723
- models: {
724
- shape: asset.models?.shape,
725
- gsStandard: asset.models?.gs
726
- },
727
- animations: {
728
- frameIdle: asset.animations?.frameIdle,
729
- frameMono: asset.animations?.frameFallback
730
- },
731
- customAnimations: asset.animations?.customAnimations ?? [],
732
- characterSettings
733
- };
734
- }
735
- /**
736
- * Get single avatar by ID from AvatarKit SDK API (v2 driven-ingress avatar API).
737
- * Domain: composed from region as api.${region}.spatius.ai
738
- * Auth: Public endpoint, no authentication required
739
- * Fetches the new `AvatarAsset` payload from `/v2/avatar/{id}` and maps it onto
740
- * the internal `CharacterMeta` shape consumed by the download / render pipeline:
741
- * - `models.gs` → `models.gsStandard`
742
- * - `animations.frameFallback` → `animations.frameMono`
743
- * - inline `camera` / `transform` → `characterSettings.{camera,transform}`
744
- * (so the renderer reads structured values directly and no camera resource is downloaded)
745
- * @internal
746
- */
747
- async getCharacterById(characterId, options) {
748
- const { signal } = options || {};
749
- const startTime = Date.now();
750
- const traceId = generateTraceId();
751
- try {
752
- if (signal?.aborted) throw new Error("Request cancelled");
753
- const response = await this.getSdkApiClient().request(`/v2/avatar/${characterId}`, {
754
- method: "GET",
755
- headers: { "x-sp-trace-id": traceId },
756
- signal
757
- });
758
- if (response?.errors && Array.isArray(response.errors) && response.errors.length > 0) {
759
- const firstError = response.errors[0];
760
- const serverMessage = firstError.detail || firstError.title || firstError.message || "Unknown server error";
761
- throw new AvatarError(`${firstError.code || firstError.status || "SERVER_ERROR"}: ${serverMessage}`, ErrorCode.failedToFetchAvatarMetadata);
762
- }
763
- logMetric("fetch_avatar_metadata_latency", Date.now() - startTime, {}, {
764
- avatar_id: characterId,
765
- trace_id: traceId
766
- });
767
- return this.mapAvatarAssetToCharacterMeta(response, characterId);
768
- } catch (error) {
769
- if (error instanceof Error && (error.name === "AbortError" || error.message === "Request cancelled")) {
770
- logEvent("fetch_avatar_metadata_cancelled", "info", {
771
- avatar_id: characterId ?? "unknown",
772
- trace_id: traceId
773
- });
774
- throw error;
775
- }
776
- logger.error("Failed to fetch character:", error);
777
- if (error instanceof AvatarError) {
778
- logEvent("fetch_avatar_metadata_failed", "error", {
779
- avatar_id: characterId ?? "unknown",
780
- description: error.message,
781
- trace_id: traceId
782
- });
783
- throw error;
784
- }
785
- const errorMessage = error && typeof error === "object" && "message" in error ? String(error.message) : "Failed to fetch character";
786
- const dataMessage = error && typeof error === "object" && "data" in error && typeof error.data === "object" && error.data?.message ? String(error.data.message) : null;
787
- logEvent("fetch_avatar_metadata_failed", "error", {
788
- avatar_id: characterId ?? "unknown",
789
- description: dataMessage || errorMessage,
790
- trace_id: traceId
791
- });
792
- throw new AvatarError("Failed to load avatar due to network issues, please check your connection and try again.", ErrorCode.failedToFetchAvatarMetadata);
793
- }
794
- }
795
- };
796
- //#endregion
797
- export { AvatarDownloader };