@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.
@@ -6,15 +6,6 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
9
- var __exportAll = (all, no_symbols) => {
10
- let target = {};
11
- for (var name in all) __defProp(target, name, {
12
- get: all[name],
13
- enumerable: true
14
- });
15
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
- return target;
17
- };
18
9
  var __copyProps = (to, from, except, desc) => {
19
10
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
11
  key = keys[i];
@@ -30,4 +21,4 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
21
  enumerable: true
31
22
  }) : target, mod));
32
23
  //#endregion
33
- export { __exportAll as n, __toESM as r, __commonJSMin as t };
24
+ export { __toESM as n, __commonJSMin as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@spatius/avatarkit",
3
3
  "type": "module",
4
- "version": "1.3.4",
4
+ "version": "1.3.5",
5
5
  "packageManager": "pnpm@10.18.2",
6
6
  "description": "AvatarKit — real-time, audio-driven avatar rendering SDK for Web.",
7
7
  "homepage": "https://spatius.ai/",
@@ -1,569 +0,0 @@
1
- import { n as __exportAll } from "./rolldown-runtime-B-1-B7_t.js";
2
- import { t as AvatarSDK } from "./AvatarSDK-BMjjoYiZ.js";
3
- import { Mt as ErrorCode, S as recordHttpClientDuration, St as generateTraceId, c as logEvent, l as logMetric, t as logger, v as hostOf, wt as AvatarError } from "./logger-B_tTFAYq.js";
4
- import { n as APP_CONFIG, r as getFlameCdnBase, t as errorToMessage } from "./error-utils-B76Nf6d6.js";
5
- import { t as PwaCacheManager } from "./pwa-cache-manager-BxeZI1BU.js";
6
- //#region core/AvatarDownloader.ts
7
- var AvatarDownloader_exports = /* @__PURE__ */ __exportAll({ AvatarDownloader: () => AvatarDownloader });
8
- /**
9
- * Get cache information for a resource
10
- * Detects browser cache, CDN cache, and PWA (Service Worker) cache
11
- */
12
- function getCacheInfo(url, response) {
13
- const resourceTiming = performance.getEntriesByName(url, "resource")[0];
14
- const transferSize = resourceTiming?.transferSize ?? 0;
15
- const deliveryType = resourceTiming?.deliveryType;
16
- const hasServiceWorker = typeof navigator !== "undefined" && navigator.serviceWorker?.controller !== null;
17
- const isPwaCache = transferSize === 0 && hasServiceWorker && (deliveryType === "cache" || deliveryType === "serviceworker") && resourceTiming?.duration !== void 0 && resourceTiming.duration > 0;
18
- const isBrowserCache = transferSize === 0 && !isPwaCache && (!hasServiceWorker || deliveryType === "cache") && resourceTiming?.duration !== void 0 && resourceTiming.duration > 0;
19
- const cfCacheStatus = response.headers.get("cf-cache-status");
20
- const xCache = response.headers.get("x-cache");
21
- const xSwiftCacheTime = response.headers.get("x-swift-cache-time");
22
- const cdnCacheStatus = cfCacheStatus || xCache || xSwiftCacheTime;
23
- let isCdnCache = false;
24
- if (cdnCacheStatus) {
25
- const statusLower = cdnCacheStatus.toLowerCase();
26
- if (statusLower === "hit" || statusLower === "hits" || statusLower.includes("hit")) {
27
- if (!statusLower.includes("miss") && !statusLower.includes("dynamic") && !statusLower.includes("bypass")) isCdnCache = true;
28
- }
29
- }
30
- let cacheHit = false;
31
- let cacheType = "none";
32
- if (isPwaCache) {
33
- cacheHit = true;
34
- cacheType = "pwa";
35
- } else if (isBrowserCache) {
36
- cacheHit = true;
37
- cacheType = "browser";
38
- } else if (isCdnCache) {
39
- cacheHit = true;
40
- cacheType = "cdn";
41
- }
42
- return {
43
- cacheHit,
44
- cacheType,
45
- transferSize,
46
- cdnCacheStatus: cdnCacheStatus || void 0
47
- };
48
- }
49
- /**
50
- * 把整次角色加载的资产下载汇总成**一条** Transaction。
51
- *
52
- * 成败取「最差的一片」:任一片 transport error 即整次记 transport error;否则取
53
- * 状态码最大的那个(4xx/5xx 会盖过 200)。这样后端按状态码切出的成功率,含义是
54
- * 「这次加载的资产是否全部拿到」——与用户实际体验一致,一片挂了角色就出不来。
55
- *
56
- * duration 传整体耗时而非单片,与 `download_avatar_assets_latency` 同口径。
57
- */
58
- function recordAssetTransaction(outcomes, durationMs, operation = ASSET_OPERATION) {
59
- const real = outcomes.filter((o) => !o.skipped);
60
- if (real.length === 0) return;
61
- recordHttpClientDuration({
62
- operation,
63
- method: "GET",
64
- durationMs,
65
- statusCode: real.some((o) => o.statusCode === void 0) ? void 0 : real.reduce((max, o) => Math.max(max, o.statusCode ?? 0), 0),
66
- serverAddress: real[0].host
67
- });
68
- }
69
- /**
70
- * Transaction 的 `operation` 取值。必须低基数:资产 URL 带 avatar id 与文件名,
71
- * 直接当维度会让时间序列随角色数无限增长。要定位「哪个文件挂了」用
72
- * `download_avatar_assets_failed` log,它带 resource/url/error。
73
- */
74
- var ASSET_OPERATION = "/assets/character";
75
- var TEMPLATE_OPERATION = "/assets/template";
76
- async function downloadResource(url, options) {
77
- const { signal, characterId, resourceType, maxRetries = 3, outcomes } = options || {};
78
- const outcomeSlotIndex = outcomes ? outcomes.length : -1;
79
- if (outcomes) outcomes.push({ host: hostOf(url) });
80
- if (signal?.aborted) throw new Error("Download cancelled");
81
- try {
82
- let cached = null;
83
- let pwaCacheSubtype = void 0;
84
- if (characterId) {
85
- cached = await PwaCacheManager.getCharacterResource(characterId, url);
86
- if (cached) pwaCacheSubtype = "character";
87
- } else if (resourceType === "template") {
88
- cached = await PwaCacheManager.getTemplateResource(url);
89
- if (cached) pwaCacheSubtype = "template";
90
- }
91
- if (cached) {
92
- const response = new Response(cached);
93
- await new Promise((resolve) => setTimeout(resolve, 0));
94
- const cacheInfo = getCacheInfo(url, response);
95
- cacheInfo.cacheHit = true;
96
- cacheInfo.cacheType = "pwa";
97
- cacheInfo.pwaCacheSubtype = pwaCacheSubtype;
98
- if (outcomes && outcomeSlotIndex >= 0) outcomes[outcomeSlotIndex] = {
99
- host: hostOf(url),
100
- skipped: true
101
- };
102
- return {
103
- data: cached,
104
- cacheInfo
105
- };
106
- }
107
- let lastError = null;
108
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
109
- if (signal?.aborted) throw new Error("Download cancelled");
110
- const outcomeSlot = { host: hostOf(url) };
111
- if (outcomes) outcomes[outcomeSlotIndex] = outcomeSlot;
112
- try {
113
- const response = await fetch(url, { signal });
114
- outcomeSlot.statusCode = response.status;
115
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
116
- const arrayBuffer = await response.arrayBuffer();
117
- const contentLength = response.headers.get("content-length");
118
- if (contentLength) {
119
- const expectedSize = parseInt(contentLength, 10);
120
- if (!isNaN(expectedSize) && arrayBuffer.byteLength < expectedSize) throw new Error(`Download incomplete: received ${arrayBuffer.byteLength} bytes, expected ${expectedSize} bytes`);
121
- }
122
- if (characterId) PwaCacheManager.putCharacterResource(characterId, url, arrayBuffer).catch((err) => {
123
- logger.warn(`[downloadResource] Failed to cache character resource:`, err);
124
- });
125
- else if (resourceType === "template") PwaCacheManager.putTemplateResource(url, arrayBuffer).catch((err) => {
126
- logger.warn(`[downloadResource] Failed to cache template resource:`, err);
127
- });
128
- await new Promise((resolve) => setTimeout(resolve, 0));
129
- return {
130
- data: arrayBuffer,
131
- cacheInfo: getCacheInfo(url, response)
132
- };
133
- } catch (err) {
134
- if (err instanceof Error && (err.name === "AbortError" || err.message === "Download cancelled")) throw err;
135
- lastError = err instanceof Error ? err : new Error(String(err));
136
- if (attempt < maxRetries) logger.warn(`[downloadResource] Attempt ${attempt}/${maxRetries} failed for ${url}, retrying immediately...`);
137
- }
138
- }
139
- throw lastError || /* @__PURE__ */ new Error(`Failed to download ${url} after ${maxRetries} attempts`);
140
- } catch (err) {
141
- if (err instanceof Error && (err.name === "AbortError" || err.message === "Download cancelled")) throw err;
142
- const msg = errorToMessage(err);
143
- throw new Error(`[downloadResource] ${url} → ${msg}`);
144
- }
145
- }
146
- var AvatarDownloader = class {
147
- baseAssetsPath;
148
- constructor(baseAssetsPath = "/") {
149
- this.baseAssetsPath = baseAssetsPath;
150
- }
151
- /**
152
- * Load unified template model (single gzip-compressed file)
153
- * Includes PWA cache, retry, integrity check, and telemetry
154
- * @internal
155
- */
156
- async loadUnifiedTemplate() {
157
- await PwaCacheManager.checkTemplateCacheVersion();
158
- const startTime = Date.now();
159
- const cdnBase = getFlameCdnBase(AvatarSDK.configuration?.region || "us-west");
160
- const { unifiedModelPath } = APP_CONFIG.flame;
161
- const url = `${cdnBase}/${unifiedModelPath}`;
162
- logger.log(`📥 Loading unified template from: ${url}`);
163
- const cached = await PwaCacheManager.getTemplateResource(url);
164
- if (cached) {
165
- const duration = Date.now() - startTime;
166
- logger.log(`✅ Unified template loaded from cache (${(cached.byteLength / 1024 / 1024).toFixed(1)} MB)`);
167
- logMetric("template_resources_load_measure", duration, {
168
- file_count: 1,
169
- cache_hit: true,
170
- cache_type: "pwa"
171
- });
172
- return { unifiedModel: cached };
173
- }
174
- const maxRetries = 3;
175
- let lastError = null;
176
- const templateOutcomes = [];
177
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
178
- const outcomeSlot = { host: hostOf(url) };
179
- templateOutcomes[0] = outcomeSlot;
180
- try {
181
- const response = await fetch(url);
182
- outcomeSlot.statusCode = response.status;
183
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
184
- let buffer;
185
- if (APP_CONFIG.flame.unifiedModelPath.endsWith(".gz")) {
186
- const decompressedStream = response.body.pipeThrough(new DecompressionStream("gzip"));
187
- buffer = await new Response(decompressedStream).arrayBuffer();
188
- } else buffer = await response.arrayBuffer();
189
- logger.log(`✅ Unified template loaded (${(buffer.byteLength / 1024 / 1024).toFixed(1)} MB)`);
190
- PwaCacheManager.putTemplateResource(url, buffer).catch((err) => {
191
- logger.warn(`[loadUnifiedTemplate] Failed to cache:`, err);
192
- });
193
- logMetric("template_resources_load_measure", Date.now() - startTime, {
194
- file_count: 1,
195
- cache_hit: false,
196
- cache_type: "none"
197
- });
198
- recordAssetTransaction(templateOutcomes, Date.now() - startTime, TEMPLATE_OPERATION);
199
- return { unifiedModel: buffer };
200
- } catch (err) {
201
- lastError = err instanceof Error ? err : new Error(String(err));
202
- if (attempt < maxRetries) logger.warn(`[loadUnifiedTemplate] Attempt ${attempt}/${maxRetries} failed, retrying...`);
203
- }
204
- }
205
- recordAssetTransaction(templateOutcomes, Date.now() - startTime, TEMPLATE_OPERATION);
206
- throw lastError || /* @__PURE__ */ new Error(`Failed to download unified template after ${maxRetries} attempts`);
207
- }
208
- /**
209
- * Load camera settings from CharacterMeta (optional)
210
- * @internal
211
- */
212
- async loadCameraSettings(characterMeta, options) {
213
- const { signal } = options || {};
214
- const cameraUrl = characterMeta.camera?.resource?.remote;
215
- if (!cameraUrl) {
216
- logger.log("ℹ️ No camera resource URL provided");
217
- return;
218
- }
219
- if (signal?.aborted) throw new Error("Load cancelled");
220
- try {
221
- logger.log(`📥 Loading camera info from: ${cameraUrl}`);
222
- const { data: arrayBuffer } = await downloadResource(cameraUrl, {
223
- signal,
224
- characterId: characterMeta.characterId ?? void 0,
225
- resourceType: "character"
226
- });
227
- const text = new TextDecoder().decode(arrayBuffer);
228
- const cameraSettings = JSON.parse(text);
229
- logger.log("✅ Camera info loaded:", cameraSettings);
230
- return cameraSettings;
231
- } catch (error) {
232
- logger.warn("⚠️ Failed to load camera info, using default:", error);
233
- return;
234
- }
235
- }
236
- /**
237
- * Load character data from CharacterMeta (iOS compatible)
238
- * @internal
239
- */
240
- async loadCharacterData(characterMeta, options) {
241
- const { progressCallback = null, signal, useCompressedModel = false } = options || {};
242
- if (signal?.aborted) throw new Error("Download cancelled");
243
- const totalStartTime = Date.now();
244
- const shapeUrl = characterMeta.models?.shape?.resource?.remote;
245
- const pointCloudUrl = useCompressedModel ? characterMeta.models?.gsStandard?.xrResource?.remote ?? characterMeta.models?.gsStandard?.resource?.remote : characterMeta.models?.gsStandard?.resource?.remote;
246
- const idleAnimationUrl = characterMeta.animations?.frameIdle?.resource?.remote;
247
- const monoAnimationUrl = characterMeta.animations?.frameMono?.resource?.remote;
248
- if (!shapeUrl || !pointCloudUrl) throw new Error("Missing required resources: shape or gsStandard (point cloud)");
249
- const filesToLoad = [{
250
- key: "shape",
251
- url: shapeUrl,
252
- filename: "shape.pb"
253
- }, {
254
- key: "pointCloud",
255
- url: pointCloudUrl,
256
- filename: "point_cloud.ply"
257
- }];
258
- if (idleAnimationUrl) filesToLoad.push({
259
- key: "idleAnimation",
260
- url: idleAnimationUrl,
261
- filename: "idle.pb",
262
- optional: true
263
- });
264
- if (monoAnimationUrl) filesToLoad.push({
265
- key: "monoAnimation",
266
- url: monoAnimationUrl,
267
- filename: "mono.pb",
268
- optional: true
269
- });
270
- let loadedFiles = 0;
271
- const totalFiles = filesToLoad.length;
272
- const updateProgress = (filename, loaded) => {
273
- if (progressCallback) {
274
- if (loaded) loadedFiles++;
275
- progressCallback({
276
- stage: "character",
277
- filename,
278
- loaded: loadedFiles,
279
- total: totalFiles,
280
- progress: loadedFiles / totalFiles
281
- });
282
- }
283
- };
284
- const characterData = {};
285
- const cacheInfos = [];
286
- /** 各片的 HTTP 结果,收尾时汇总成一条 Transaction(见 recordAssetTransaction)。 */
287
- const httpOutcomes = [];
288
- const parallelStartTime = Date.now();
289
- const downloadPromises = filesToLoad.map(async ({ key, url, filename, optional }) => {
290
- updateProgress(filename, false);
291
- try {
292
- const { data: arrayBuffer, cacheInfo } = await downloadResource(url, {
293
- signal,
294
- characterId: characterMeta.characterId ?? void 0,
295
- resourceType: "character",
296
- outcomes: httpOutcomes
297
- });
298
- if (key === "shape") characterData.shape = arrayBuffer;
299
- else if (key === "pointCloud") characterData.pointCloud = arrayBuffer;
300
- else if (key === "idleAnimation") characterData.idleAnimation = arrayBuffer;
301
- else if (key === "monoAnimation") characterData.monoAnimation = arrayBuffer;
302
- cacheInfos.push(cacheInfo);
303
- updateProgress(filename, true);
304
- return {
305
- key,
306
- success: true,
307
- size: arrayBuffer.byteLength
308
- };
309
- } catch (error) {
310
- if (error instanceof Error && (error.name === "AbortError" || error.message === "Download cancelled")) {
311
- logEvent("download_avatar_assets_cancelled", "info", { avatar_id: characterMeta.characterId ?? "unknown" });
312
- throw error;
313
- }
314
- if (!optional) {
315
- const errorMessage = error instanceof Error ? error.message : String(error);
316
- logEvent("download_avatar_assets_failed", "error", {
317
- avatar_id: characterMeta.characterId ?? "unknown",
318
- description: `Failed to download required resource: ${filename}`,
319
- resource: key,
320
- url,
321
- error: errorMessage
322
- });
323
- throw error;
324
- }
325
- logger.warn(`⚠️ Optional resource ${filename} failed to load:`, error);
326
- updateProgress(filename, true);
327
- return {
328
- key,
329
- success: false,
330
- size: 0
331
- };
332
- }
333
- });
334
- try {
335
- await Promise.all(downloadPromises);
336
- } finally {
337
- recordAssetTransaction(httpOutcomes, Date.now() - totalStartTime);
338
- }
339
- const parallelDuration = Date.now() - parallelStartTime;
340
- const totalDuration = Date.now() - totalStartTime;
341
- if (!characterData.shape || !characterData.pointCloud) {
342
- const reason = "Failed to load character data";
343
- logEvent("download_avatar_assets_failed", "error", {
344
- avatar_id: characterMeta.characterId ?? "unknown",
345
- description: reason
346
- });
347
- throw new Error(reason);
348
- }
349
- const cacheHit = cacheInfos.length > 0 && cacheInfos.every((info) => info.cacheHit);
350
- const cacheType = cacheInfos[0]?.cacheType || "none";
351
- const totalSize = Object.values(characterData).reduce((sum, buffer) => {
352
- return sum + (buffer ? buffer.byteLength : 0);
353
- }, 0);
354
- logMetric("download_avatar_assets_latency", totalDuration, {
355
- resolution: "default",
356
- use_compressed_model: useCompressedModel,
357
- file_count: filesToLoad.length,
358
- cache_hit: cacheHit,
359
- cache_type: cacheType
360
- }, {
361
- avatar_id: characterMeta.characterId ?? "unknown",
362
- parallel_duration: parallelDuration,
363
- total_size: totalSize
364
- });
365
- return {
366
- data: characterData,
367
- cacheHit,
368
- cacheType
369
- };
370
- }
371
- /**
372
- * Preload all resources (template + character data + camera info + settings)
373
- * @internal
374
- */
375
- async preloadResources(characterMeta, options) {
376
- const { progressCallback = null, signal, useCompressedModel = false } = options || {};
377
- if (signal?.aborted) throw new Error("Preload cancelled");
378
- const [characterResult, preloadCameraSettings] = await Promise.all([this.loadCharacterData(characterMeta, {
379
- signal,
380
- useCompressedModel,
381
- progressCallback: (info) => {
382
- if (progressCallback) progressCallback({
383
- ...info,
384
- stage: `character-${info.stage}`
385
- });
386
- }
387
- }), this.loadCameraSettings(characterMeta, { signal })]);
388
- return {
389
- characterData: characterResult.data,
390
- preloadCameraSettings,
391
- characterSettings: characterMeta.characterSettings,
392
- cacheHit: characterResult.cacheHit,
393
- cacheType: characterResult.cacheType
394
- };
395
- }
396
- /**
397
- * Get AvatarKit SDK API Client (region-templated endpoint composed by AvatarSDK.getEnvironmentConfig).
398
- * Used for: character details and resource URLs (public endpoints, no auth required)
399
- * Note: This endpoint does not require authentication, so we don't add X-App-Id or Authorization headers
400
- * to avoid CORS preflight requests for simple GET requests
401
- */
402
- getSdkApiClient() {
403
- return { async request(url, options = {}) {
404
- const baseUrl = AvatarSDK.getEnvironmentConfig().sdkApiBaseUrl;
405
- const fullUrl = baseUrl + url;
406
- const headers = {};
407
- const method = options.method || "GET";
408
- if (method !== "GET" && options.body) headers["Content-Type"] = "application/json";
409
- const operation = url.split("?")[0].replace(/\/v2\/avatar\/[^/?]+/, "/v2/avatar/{id}");
410
- let serverAddress;
411
- try {
412
- serverAddress = new URL(baseUrl).host;
413
- } catch {}
414
- const startMs = performance.now();
415
- try {
416
- const response = await fetch(fullUrl, {
417
- method,
418
- headers: {
419
- ...headers,
420
- ...options.headers
421
- },
422
- body: options.body ? JSON.stringify(options.body) : void 0,
423
- signal: options.signal
424
- });
425
- recordHttpClientDuration({
426
- operation,
427
- method,
428
- durationMs: Math.round(performance.now() - startMs),
429
- statusCode: response.status,
430
- serverAddress
431
- });
432
- if (!response.ok) {
433
- let serverMessage = "";
434
- try {
435
- const body = await response.json();
436
- if (body?.errors && Array.isArray(body.errors) && body.errors.length > 0) {
437
- const e = body.errors[0];
438
- serverMessage = e.detail || e.title || e.message || JSON.stringify(e);
439
- } else serverMessage = body?.message || body?.error || JSON.stringify(body);
440
- } catch {
441
- serverMessage = response.statusText;
442
- }
443
- let error;
444
- if (response.status === 404) {
445
- const urlMatch = url.match(/\/v2\/(?:character|avatar)\/([^/?]+)/);
446
- const extractedCharacterId = urlMatch ? urlMatch[1] : "unknown";
447
- const callerTraceId = (options.headers || {})["x-sp-trace-id"];
448
- logEvent("avatar_id_unrecognized", "error", {
449
- avatar_id: extractedCharacterId,
450
- description: `HTTP 404: ${serverMessage}`,
451
- ...callerTraceId ? { trace_id: callerTraceId } : {}
452
- });
453
- error = new AvatarError(`HTTP 404: ${serverMessage}`, ErrorCode.avatarIDUnrecognized);
454
- } else error = new AvatarError(`HTTP ${response.status}: ${serverMessage}`, ErrorCode.failedToFetchAvatarMetadata);
455
- throw error;
456
- }
457
- try {
458
- return await response.json();
459
- } catch {
460
- throw new AvatarError("Avatar data is invalid. Please contact Spatius support.", ErrorCode.invalidAvatarMetadata);
461
- }
462
- } catch (err) {
463
- if (err instanceof AvatarError) throw err;
464
- recordHttpClientDuration({
465
- operation,
466
- method,
467
- durationMs: Math.round(performance.now() - startMs),
468
- serverAddress
469
- });
470
- throw new AvatarError("Failed to load avatar due to network issues, please check your connection and try again.", ErrorCode.failedToFetchAvatarMetadata);
471
- }
472
- } };
473
- }
474
- /**
475
- * Map the new `/v2/avatar/{id}` `AvatarAsset` payload onto the internal
476
- * `CharacterMeta` shape used by the existing download / render pipeline.
477
- *
478
- * The backend (grpc-gateway) serialises proto fields as camelCase JSON, so the
479
- * runtime object is loosely shaped like the generated `AvatarAsset`. We:
480
- * - lift `models.gs` into `models.gsStandard` (downloader/asset-count read gsStandard)
481
- * - rename `animations.frameFallback` → `animations.frameMono`
482
- * - fold the inline `camera` / `transform` into `characterSettings` so the
483
- * renderer's `resolveCameraConfig` reads structured values and no camera
484
- * resource is downloaded (top-level `camera` is intentionally left unset)
485
- * @internal
486
- */
487
- mapAvatarAssetToCharacterMeta(asset, avatarId) {
488
- return {
489
- characterId: avatarId,
490
- version: asset.version ?? "",
491
- compatibilityFlags: asset.compatibilityFlags ?? [],
492
- updatedAt: asset.updatedAt,
493
- models: {
494
- shape: asset.models?.shape,
495
- gsStandard: asset.models?.gs
496
- },
497
- animations: {
498
- frameIdle: asset.animations?.frameIdle,
499
- frameMono: asset.animations?.frameFallback
500
- },
501
- customAnimations: asset.animations?.customAnimations ?? [],
502
- characterSettings: {
503
- ...asset.camera ? { camera: { ...asset.camera } } : {},
504
- ...asset.transform ? { transform: { ...asset.transform } } : {}
505
- }
506
- };
507
- }
508
- /**
509
- * Get single avatar by ID from AvatarKit SDK API (v2 driven-ingress avatar API).
510
- * Domain: composed from region as api.${region}.spatius.ai
511
- * Auth: Public endpoint, no authentication required
512
- * Fetches the new `AvatarAsset` payload from `/v2/avatar/{id}` and maps it onto
513
- * the internal `CharacterMeta` shape consumed by the download / render pipeline:
514
- * - `models.gs` → `models.gsStandard`
515
- * - `animations.frameFallback` → `animations.frameMono`
516
- * - inline `camera` / `transform` → `characterSettings.{camera,transform}`
517
- * (so the renderer reads structured values directly and no camera resource is downloaded)
518
- * @internal
519
- */
520
- async getCharacterById(characterId, options) {
521
- const { signal } = options || {};
522
- const startTime = Date.now();
523
- const traceId = generateTraceId();
524
- try {
525
- if (signal?.aborted) throw new Error("Request cancelled");
526
- const response = await this.getSdkApiClient().request(`/v2/avatar/${characterId}`, {
527
- method: "GET",
528
- headers: { "x-sp-trace-id": traceId },
529
- signal
530
- });
531
- if (response?.errors && Array.isArray(response.errors) && response.errors.length > 0) {
532
- const firstError = response.errors[0];
533
- throw new AvatarError(`${firstError.code || firstError.status || "SERVER_ERROR"}: ${firstError.detail || firstError.title || firstError.message || "Unknown server error"}`, ErrorCode.failedToFetchAvatarMetadata);
534
- }
535
- logMetric("fetch_avatar_metadata_latency", Date.now() - startTime, {}, {
536
- avatar_id: characterId,
537
- trace_id: traceId
538
- });
539
- return this.mapAvatarAssetToCharacterMeta(response, characterId);
540
- } catch (error) {
541
- if (error instanceof Error && (error.name === "AbortError" || error.message === "Request cancelled")) {
542
- logEvent("fetch_avatar_metadata_cancelled", "info", {
543
- avatar_id: characterId ?? "unknown",
544
- trace_id: traceId
545
- });
546
- throw error;
547
- }
548
- logger.error("Failed to fetch character:", error);
549
- if (error instanceof AvatarError) {
550
- logEvent("fetch_avatar_metadata_failed", "error", {
551
- avatar_id: characterId ?? "unknown",
552
- description: error.message,
553
- trace_id: traceId
554
- });
555
- throw error;
556
- }
557
- const errorMessage = error && typeof error === "object" && "message" in error ? String(error.message) : "Failed to fetch character";
558
- const dataMessage = error && typeof error === "object" && "data" in error && typeof error.data === "object" && error.data?.message ? String(error.data.message) : null;
559
- logEvent("fetch_avatar_metadata_failed", "error", {
560
- avatar_id: characterId ?? "unknown",
561
- description: dataMessage || errorMessage,
562
- trace_id: traceId
563
- });
564
- throw new AvatarError("Failed to load avatar due to network issues, please check your connection and try again.", ErrorCode.failedToFetchAvatarMetadata);
565
- }
566
- }
567
- };
568
- //#endregion
569
- export { AvatarDownloader_exports as n, AvatarDownloader as t };