@spatius/avatarkit 1.3.1-beta.6 → 1.3.1

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.
Files changed (22) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/{AvatarDownloader-Dfi7wtgQ.js → AvatarDownloader-DyhenPKd.js} +98 -43
  3. package/dist/{AvatarSDK-CnZqa_X4.js → AvatarSDK-DgPvHU4L.js} +162 -2560
  4. package/dist/{OpusCodec-D9DcUV65.js → OpusCodec-CXU7ysrU.js} +43 -9
  5. package/dist/{OpusDecoderProxy-Ar_dFXRB.js → OpusDecoderProxy-Cq8Z_MZY.js} +19 -6
  6. package/dist/{OpusEncoderProxy-9YIZ7nIt.js → OpusEncoderProxy-CzY-VckE.js} +42 -7
  7. package/dist/{StreamingAudioPlayer-D4q7c1U0.js → StreamingAudioPlayer-CIJmBp3z.js} +2 -2
  8. package/dist/assets/{AvatarDownloader-D5GePpJ2.js → AvatarDownloader-G5FO1bVl.js} +96 -41
  9. package/dist/assets/{AvatarSDK-DR8dNylh.js → AvatarSDK-C_Anluwp.js} +149 -12
  10. package/dist/assets/{OpusDecoderWorker.worker-B7R93nev.js → OpusDecoderWorker.worker-C2T0afkj.js} +21 -5
  11. package/dist/assets/{OpusEncoderWorker.worker-BYWIV5xu.js → OpusEncoderWorker.worker-DLYO9vPK.js} +53 -11
  12. package/dist/assets/{logger-D8rDVim7.js → logger-YPooEAbA.js} +451 -132
  13. package/dist/core/AvatarController.d.ts +10 -0
  14. package/dist/{error-utils-CqKOrHrY.js → error-utils-BogEllAd.js} +1 -1
  15. package/dist/index.js +279 -46
  16. package/dist/internal-telemetry.d.ts +45 -20
  17. package/dist/internal-telemetry.js +27 -2
  18. package/dist/{logger-fAU8oahT.js → logger-BOpQ7u0w.js} +468 -132
  19. package/dist/otel-trace-Ct4T48nC.js +2565 -0
  20. package/dist/{pwa-cache-manager-CwXaM3xR.js → pwa-cache-manager-C7NbU52Q.js} +1 -1
  21. package/dist/types/index.d.ts +30 -4
  22. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { n as __exportAll } from "./rolldown-runtime-B-1-B7_t.js";
2
- import { $ as TraceFlags, A as ExportResultCode, B as ATTR_EXCEPTION_TYPE, C as createInstrumentationScope, D as defaultResource, E as OTLPExporterBase, F as isTimeInputHrTime, G as isTracingSuppressed, H as getNumberFromEnv, I as millisToHrTime, J as diag$1, K as suppressTracing, L as otperformance, M as hrTime, N as hrTimeDuration, O as resourceFromAttributes, P as isTimeInput, Q as INVALID_SPAN_CONTEXT, R as ATTR_EXCEPTION_MESSAGE, S as JSON_ENCODER, T as toAttributes, Tt as DrivingServiceMode, U as getStringFromEnv, V as ATTR_SERVICE_NAME, W as globalErrorHandler, X as isSpanContextValid, Y as context, Z as isValidTraceId, _ as cleanupOtelMetrics, a as clientContextFields, at as getGlobal, c as logEvent, ct as OTEL_LOGS_ENDPOINT, d as cleanupOtel, dt as OTEL_TRACES_ENDPOINT, et as ContextAPI, f as initializeOtel, ft as OTEL_TRACES_STREAM_NAME, g as fetchBootstrap, h as clockSync, ht as idManager, i as cleanupPostHog, it as DiagAPI, j as addHrTimes, k as BindOnceFuture, kt as LogLevel, lt as OTEL_PASSWORD, n as setLogLevel, nt as ROOT_CONTEXT, o as getLogsFeatureFlag, ot as registerGlobal, pt as OTEL_USERNAME, q as trace, r as logSink, rt as createContextKey, s as initializePostHog, st as unregisterGlobal, t as logger, tt as createNoopMeter, u as updatePostHogPersonPropertiesForFlags, ut as OTEL_STREAM_NAME, v as initializeOtelMetrics, w as createResource, x as createLegacyOtlpBrowserExportDelegate, z as ATTR_EXCEPTION_STACKTRACE } from "./logger-fAU8oahT.js";
2
+ import { Mt as LogLevel, Ot as DrivingServiceMode, _ as fetchBootstrap, a as clientContextFields, b as cleanupOtelMetrics, c as logEvent, d as cleanupOtel, dt as OTEL_LOGS_ENDPOINT, f as initializeOtel, ft as OTEL_PASSWORD, g as clockSync, gt as OTEL_USERNAME, i as cleanupPostHog, n as setLogLevel, o as getLogsFeatureFlag, pt as OTEL_STREAM_NAME, r as logSink, s as initializePostHog, t as logger, u as updatePostHogPersonPropertiesForFlags, vt as idManager, x as initializeOtelMetrics } from "./logger-BOpQ7u0w.js";
3
+ import { n as initializeOtelTrace, r as startInitTrace, t as cleanupOtelTrace } from "./otel-trace-Ct4T48nC.js";
3
4
  //#region node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js
4
5
  /**
5
6
  * Read a 64 bit varint as two JS numbers.
@@ -824,7 +825,7 @@ var Struct = {
824
825
  return message;
825
826
  },
826
827
  fromJSON(object) {
827
- return { fields: isObject$2(object.fields) ? globalThis.Object.entries(object.fields).reduce((acc, [key, value]) => {
828
+ return { fields: isObject$1(object.fields) ? globalThis.Object.entries(object.fields).reduce((acc, [key, value]) => {
828
829
  acc[key] = value;
829
830
  return acc;
830
831
  }, {}) : {} };
@@ -982,7 +983,7 @@ var Value = {
982
983
  numberValue: isSet$1(object.numberValue) ? globalThis.Number(object.numberValue) : isSet$1(object.number_value) ? globalThis.Number(object.number_value) : void 0,
983
984
  stringValue: isSet$1(object.stringValue) ? globalThis.String(object.stringValue) : isSet$1(object.string_value) ? globalThis.String(object.string_value) : void 0,
984
985
  boolValue: isSet$1(object.boolValue) ? globalThis.Boolean(object.boolValue) : isSet$1(object.bool_value) ? globalThis.Boolean(object.bool_value) : void 0,
985
- structValue: isObject$2(object.structValue) ? object.structValue : isObject$2(object.struct_value) ? object.struct_value : void 0,
986
+ structValue: isObject$1(object.structValue) ? object.structValue : isObject$1(object.struct_value) ? object.struct_value : void 0,
986
987
  listValue: globalThis.Array.isArray(object.listValue) ? [...object.listValue] : globalThis.Array.isArray(object.list_value) ? [...object.list_value] : void 0
987
988
  };
988
989
  },
@@ -1080,7 +1081,7 @@ var ListValue = {
1080
1081
  else return message;
1081
1082
  }
1082
1083
  };
1083
- function isObject$2(value) {
1084
+ function isObject$1(value) {
1084
1085
  return typeof value === "object" && value !== null;
1085
1086
  }
1086
1087
  function isSet$1(value) {
@@ -1291,10 +1292,10 @@ var LiveKitEgressConfig = {
1291
1292
  apiSecret: isSet(object.apiSecret) ? globalThis.String(object.apiSecret) : isSet(object.api_secret) ? globalThis.String(object.api_secret) : "",
1292
1293
  roomName: isSet(object.roomName) ? globalThis.String(object.roomName) : isSet(object.room_name) ? globalThis.String(object.room_name) : "",
1293
1294
  publisherId: isSet(object.publisherId) ? globalThis.String(object.publisherId) : isSet(object.publisher_id) ? globalThis.String(object.publisher_id) : "",
1294
- extraAttributes: isObject$1(object.extraAttributes) ? globalThis.Object.entries(object.extraAttributes).reduce((acc, [key, value]) => {
1295
+ extraAttributes: isObject(object.extraAttributes) ? globalThis.Object.entries(object.extraAttributes).reduce((acc, [key, value]) => {
1295
1296
  acc[key] = globalThis.String(value);
1296
1297
  return acc;
1297
- }, {}) : isObject$1(object.extra_attributes) ? globalThis.Object.entries(object.extra_attributes).reduce((acc, [key, value]) => {
1298
+ }, {}) : isObject(object.extra_attributes) ? globalThis.Object.entries(object.extra_attributes).reduce((acc, [key, value]) => {
1298
1299
  acc[key] = globalThis.String(value);
1299
1300
  return acc;
1300
1301
  }, {}) : {},
@@ -1525,7 +1526,7 @@ var DrivenIngressConfig = {
1525
1526
  shapeNpy: isSet(object.shapeNpy) ? bytesFromBase64(object.shapeNpy) : isSet(object.shape_npy) ? bytesFromBase64(object.shape_npy) : /* @__PURE__ */ new Uint8Array(0),
1526
1527
  styleNpy: isSet(object.styleNpy) ? bytesFromBase64(object.styleNpy) : isSet(object.style_npy) ? bytesFromBase64(object.style_npy) : /* @__PURE__ */ new Uint8Array(0),
1527
1528
  drivenServerUrl: isSet(object.drivenServerUrl) ? globalThis.String(object.drivenServerUrl) : isSet(object.driven_server_url) ? globalThis.String(object.driven_server_url) : "",
1528
- modelSettings: isObject$1(object.modelSettings) ? object.modelSettings : isObject$1(object.model_settings) ? object.model_settings : void 0,
1529
+ modelSettings: isObject(object.modelSettings) ? object.modelSettings : isObject(object.model_settings) ? object.model_settings : void 0,
1529
1530
  encoderStartFrame: isSet(object.encoderStartFrame) ? globalThis.Number(object.encoderStartFrame) : isSet(object.encoder_start_frame) ? globalThis.Number(object.encoder_start_frame) : 0
1530
1531
  };
1531
1532
  },
@@ -2321,2591 +2322,169 @@ var Message = {
2321
2322
  },
2322
2323
  fromPartial(object) {
2323
2324
  const message = createBaseMessage();
2324
- message.type = object.type ?? 0;
2325
- message.clientConfigureSession = object.clientConfigureSession !== void 0 && object.clientConfigureSession !== null ? ClientConfigureSession.fromPartial(object.clientConfigureSession) : void 0;
2326
- message.serverConfirmSession = object.serverConfirmSession !== void 0 && object.serverConfirmSession !== null ? ServerConfirmSession.fromPartial(object.serverConfirmSession) : void 0;
2327
- message.clientAudioInput = object.clientAudioInput !== void 0 && object.clientAudioInput !== null ? ClientAudioInput.fromPartial(object.clientAudioInput) : void 0;
2328
- message.serverError = object.serverError !== void 0 && object.serverError !== null ? ServerError.fromPartial(object.serverError) : void 0;
2329
- message.serverResponseAnimation = object.serverResponseAnimation !== void 0 && object.serverResponseAnimation !== null ? ServerResponseAnimation.fromPartial(object.serverResponseAnimation) : void 0;
2330
- message.drivenConfig = object.drivenConfig !== void 0 && object.drivenConfig !== null ? DrivenIngressConfig.fromPartial(object.drivenConfig) : void 0;
2331
- message.clientInterrupt = object.clientInterrupt !== void 0 && object.clientInterrupt !== null ? ClientInterrupt.fromPartial(object.clientInterrupt) : void 0;
2332
- return message;
2333
- }
2334
- };
2335
- function bytesFromBase64(b64) {
2336
- const bin = globalThis.atob(b64);
2337
- const arr = new Uint8Array(bin.length);
2338
- for (let i = 0; i < bin.length; ++i) arr[i] = bin.charCodeAt(i);
2339
- return arr;
2340
- }
2341
- function base64FromBytes(arr) {
2342
- const bin = [];
2343
- arr.forEach((byte) => {
2344
- bin.push(globalThis.String.fromCharCode(byte));
2345
- });
2346
- return globalThis.btoa(bin.join(""));
2347
- }
2348
- function isObject$1(value) {
2349
- return typeof value === "object" && value !== null;
2350
- }
2351
- function isSet(value) {
2352
- return value !== null && value !== void 0;
2353
- }
2354
- //#endregion
2355
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js
2356
- var BaggageImpl = class BaggageImpl {
2357
- constructor(entries) {
2358
- this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map();
2359
- }
2360
- getEntry(key) {
2361
- const entry = this._entries.get(key);
2362
- if (!entry) return;
2363
- return Object.assign({}, entry);
2364
- }
2365
- getAllEntries() {
2366
- return Array.from(this._entries.entries());
2367
- }
2368
- setEntry(key, entry) {
2369
- const newBaggage = new BaggageImpl(this._entries);
2370
- newBaggage._entries.set(key, entry);
2371
- return newBaggage;
2372
- }
2373
- removeEntry(key) {
2374
- const newBaggage = new BaggageImpl(this._entries);
2375
- newBaggage._entries.delete(key);
2376
- return newBaggage;
2377
- }
2378
- removeEntries(...keys) {
2379
- const newBaggage = new BaggageImpl(this._entries);
2380
- for (const key of keys) newBaggage._entries.delete(key);
2381
- return newBaggage;
2382
- }
2383
- clear() {
2384
- return new BaggageImpl();
2385
- }
2386
- };
2387
- //#endregion
2388
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js
2389
- /**
2390
- * Symbol used to make BaggageEntryMetadata an opaque type
2391
- */
2392
- var baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
2393
- //#endregion
2394
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/utils.js
2395
- var diag = DiagAPI.instance();
2396
- /**
2397
- * Create a new Baggage with optional entries
2398
- *
2399
- * @param entries An array of baggage entries the new baggage should contain
2400
- */
2401
- function createBaggage(entries = {}) {
2402
- return new BaggageImpl(new Map(Object.entries(entries)));
2403
- }
2404
- /**
2405
- * Create a serializable BaggageEntryMetadata object from a string.
2406
- *
2407
- * @param str string metadata. Format is currently not defined by the spec and has no special meaning.
2408
- *
2409
- * @since 1.0.0
2410
- */
2411
- function baggageEntryMetadataFromString(str) {
2412
- if (typeof str !== "string") {
2413
- diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
2414
- str = "";
2415
- }
2416
- return {
2417
- __TYPE__: baggageEntryMetadataSymbol,
2418
- toString() {
2419
- return str;
2420
- }
2421
- };
2422
- }
2423
- //#endregion
2424
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js
2425
- /**
2426
- * @since 1.0.0
2427
- */
2428
- var defaultTextMapGetter = {
2429
- get(carrier, key) {
2430
- if (carrier == null) return;
2431
- return carrier[key];
2432
- },
2433
- keys(carrier) {
2434
- if (carrier == null) return [];
2435
- return Object.keys(carrier);
2436
- }
2437
- };
2438
- /**
2439
- * @since 1.0.0
2440
- */
2441
- var defaultTextMapSetter = { set(carrier, key, value) {
2442
- if (carrier == null) return;
2443
- carrier[key] = value;
2444
- } };
2445
- //#endregion
2446
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js
2447
- /**
2448
- * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.
2449
- * A sampling decision that determines how a {@link Span} will be recorded
2450
- * and collected.
2451
- *
2452
- * @since 1.0.0
2453
- */
2454
- var SamplingDecision$1;
2455
- (function(SamplingDecision) {
2456
- /**
2457
- * `Span.isRecording() === false`, span will not be recorded and all events
2458
- * and attributes will be dropped.
2459
- */
2460
- SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
2461
- /**
2462
- * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
2463
- * MUST NOT be set.
2464
- */
2465
- SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
2466
- /**
2467
- * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
2468
- * MUST be set.
2469
- */
2470
- SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
2471
- })(SamplingDecision$1 || (SamplingDecision$1 = {}));
2472
- //#endregion
2473
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js
2474
- /**
2475
- * @since 1.0.0
2476
- */
2477
- var SpanKind;
2478
- (function(SpanKind) {
2479
- /** Default value. Indicates that the span is used internally. */
2480
- SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL";
2481
- /**
2482
- * Indicates that the span covers server-side handling of an RPC or other
2483
- * remote request.
2484
- */
2485
- SpanKind[SpanKind["SERVER"] = 1] = "SERVER";
2486
- /**
2487
- * Indicates that the span covers the client-side wrapper around an RPC or
2488
- * other remote request.
2489
- */
2490
- SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT";
2491
- /**
2492
- * Indicates that the span describes producer sending a message to a
2493
- * broker. Unlike client and server, there is no direct critical path latency
2494
- * relationship between producer and consumer spans.
2495
- */
2496
- SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER";
2497
- /**
2498
- * Indicates that the span describes consumer receiving a message from a
2499
- * broker. Unlike client and server, there is no direct critical path latency
2500
- * relationship between producer and consumer spans.
2501
- */
2502
- SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER";
2503
- })(SpanKind || (SpanKind = {}));
2504
- //#endregion
2505
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js
2506
- /**
2507
- * An enumeration of status codes.
2508
- *
2509
- * @since 1.0.0
2510
- */
2511
- var SpanStatusCode;
2512
- (function(SpanStatusCode) {
2513
- /**
2514
- * The default status.
2515
- */
2516
- SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
2517
- /**
2518
- * The operation has been validated by an Application developer or
2519
- * Operator to have completed successfully.
2520
- */
2521
- SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
2522
- /**
2523
- * The operation contains an error.
2524
- */
2525
- SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
2526
- })(SpanStatusCode || (SpanStatusCode = {}));
2527
- //#endregion
2528
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js
2529
- /**
2530
- * No-op implementations of {@link TextMapPropagator}.
2531
- */
2532
- var NoopTextMapPropagator = class {
2533
- /** Noop inject function does nothing */
2534
- inject(_context, _carrier) {}
2535
- /** Noop extract function does nothing and returns the input context */
2536
- extract(context, _carrier) {
2537
- return context;
2538
- }
2539
- fields() {
2540
- return [];
2541
- }
2542
- };
2543
- //#endregion
2544
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js
2545
- /**
2546
- * Baggage key
2547
- */
2548
- var BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key");
2549
- /**
2550
- * Retrieve the current baggage from the given context
2551
- *
2552
- * @param {Context} Context that manage all context values
2553
- * @returns {Baggage} Extracted baggage from the context
2554
- */
2555
- function getBaggage(context) {
2556
- return context.getValue(BAGGAGE_KEY) || void 0;
2557
- }
2558
- /**
2559
- * Retrieve the current baggage from the active/current context
2560
- *
2561
- * @returns {Baggage} Extracted baggage from the context
2562
- */
2563
- function getActiveBaggage() {
2564
- return getBaggage(ContextAPI.getInstance().active());
2565
- }
2566
- /**
2567
- * Store a baggage in the given context
2568
- *
2569
- * @param {Context} Context that manage all context values
2570
- * @param {Baggage} baggage that will be set in the actual context
2571
- */
2572
- function setBaggage(context, baggage) {
2573
- return context.setValue(BAGGAGE_KEY, baggage);
2574
- }
2575
- /**
2576
- * Delete the baggage stored in the given context
2577
- *
2578
- * @param {Context} Context that manage all context values
2579
- */
2580
- function deleteBaggage(context) {
2581
- return context.deleteValue(BAGGAGE_KEY);
2582
- }
2583
- //#endregion
2584
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/propagation.js
2585
- var API_NAME = "propagation";
2586
- var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();
2587
- //#endregion
2588
- //#region node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation-api.js
2589
- /**
2590
- * Entrypoint for propagation API
2591
- *
2592
- * @since 1.0.0
2593
- */
2594
- var propagation = class PropagationAPI {
2595
- /** Empty private constructor prevents end users from constructing a new instance of the API */
2596
- constructor() {
2597
- this.createBaggage = createBaggage;
2598
- this.getBaggage = getBaggage;
2599
- this.getActiveBaggage = getActiveBaggage;
2600
- this.setBaggage = setBaggage;
2601
- this.deleteBaggage = deleteBaggage;
2602
- }
2603
- /** Get the singleton instance of the Propagator API */
2604
- static getInstance() {
2605
- if (!this._instance) this._instance = new PropagationAPI();
2606
- return this._instance;
2607
- }
2608
- /**
2609
- * Set the current propagator.
2610
- *
2611
- * @returns true if the propagator was successfully registered, else false
2612
- */
2613
- setGlobalPropagator(propagator) {
2614
- return registerGlobal(API_NAME, propagator, DiagAPI.instance());
2615
- }
2616
- /**
2617
- * Inject context into a carrier to be propagated inter-process
2618
- *
2619
- * @param context Context carrying tracing data to inject
2620
- * @param carrier carrier to inject context into
2621
- * @param setter Function used to set values on the carrier
2622
- */
2623
- inject(context, carrier, setter = defaultTextMapSetter) {
2624
- return this._getGlobalPropagator().inject(context, carrier, setter);
2625
- }
2626
- /**
2627
- * Extract context from a carrier
2628
- *
2629
- * @param context Context which the newly created context will inherit from
2630
- * @param carrier Carrier to extract context from
2631
- * @param getter Function used to extract keys from a carrier
2632
- */
2633
- extract(context, carrier, getter = defaultTextMapGetter) {
2634
- return this._getGlobalPropagator().extract(context, carrier, getter);
2635
- }
2636
- /**
2637
- * Return a list of all fields which may be used by the propagator.
2638
- */
2639
- fields() {
2640
- return this._getGlobalPropagator().fields();
2641
- }
2642
- /** Remove the global propagator */
2643
- disable() {
2644
- unregisterGlobal(API_NAME, DiagAPI.instance());
2645
- }
2646
- _getGlobalPropagator() {
2647
- return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
2648
- }
2649
- }.getInstance();
2650
- //#endregion
2651
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/constants.js
2652
- var BAGGAGE_HEADER = "baggage";
2653
- var BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;
2654
- //#endregion
2655
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/utils.js
2656
- function serializeKeyPairs(keyPairs) {
2657
- return keyPairs.reduce((hValue, current) => {
2658
- const value = `${hValue}${hValue !== "" ? "," : ""}${current}`;
2659
- return value.length > 8192 ? hValue : value;
2660
- }, "");
2661
- }
2662
- function getKeyPairs(baggage) {
2663
- return baggage.getAllEntries().map(([key, value]) => {
2664
- let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;
2665
- if (value.metadata !== void 0) entry += ";" + value.metadata.toString();
2666
- return entry;
2667
- });
2668
- }
2669
- function parsePairKeyValue(entry) {
2670
- if (!entry) return;
2671
- const metadataSeparatorIndex = entry.indexOf(";");
2672
- const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex);
2673
- const separatorIndex = keyPairPart.indexOf("=");
2674
- if (separatorIndex <= 0) return;
2675
- const rawKey = keyPairPart.substring(0, separatorIndex).trim();
2676
- const rawValue = keyPairPart.substring(separatorIndex + 1).trim();
2677
- if (!rawKey || !rawValue) return;
2678
- let key;
2679
- let value;
2680
- try {
2681
- key = decodeURIComponent(rawKey);
2682
- value = decodeURIComponent(rawValue);
2683
- } catch {
2684
- return;
2685
- }
2686
- let metadata;
2687
- if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) metadata = baggageEntryMetadataFromString(entry.substring(metadataSeparatorIndex + 1));
2688
- return {
2689
- key,
2690
- value,
2691
- metadata
2692
- };
2693
- }
2694
- //#endregion
2695
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/baggage/propagation/W3CBaggagePropagator.js
2696
- /**
2697
- * Propagates {@link Baggage} through Context format propagation.
2698
- *
2699
- * Based on the Baggage specification:
2700
- * https://w3c.github.io/baggage/
2701
- */
2702
- var W3CBaggagePropagator = class {
2703
- inject(context, carrier, setter) {
2704
- const baggage = propagation.getBaggage(context);
2705
- if (!baggage || isTracingSuppressed(context)) return;
2706
- const headerValue = serializeKeyPairs(getKeyPairs(baggage).filter((pair) => {
2707
- return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;
2708
- }).slice(0, 180));
2709
- if (headerValue.length > 0) setter.set(carrier, BAGGAGE_HEADER, headerValue);
2710
- }
2711
- extract(context, carrier, getter) {
2712
- const headerValue = getter.get(carrier, BAGGAGE_HEADER);
2713
- const baggageString = Array.isArray(headerValue) ? headerValue.join(",") : headerValue;
2714
- if (!baggageString) return context;
2715
- const baggage = {};
2716
- if (baggageString.length === 0) return context;
2717
- baggageString.split(",").forEach((entry) => {
2718
- const keyPair = parsePairKeyValue(entry);
2719
- if (keyPair) {
2720
- const baggageEntry = { value: keyPair.value };
2721
- if (keyPair.metadata) baggageEntry.metadata = keyPair.metadata;
2722
- baggage[keyPair.key] = baggageEntry;
2723
- }
2724
- });
2725
- if (Object.entries(baggage).length === 0) return context;
2726
- return propagation.setBaggage(context, propagation.createBaggage(baggage));
2727
- }
2728
- fields() {
2729
- return [BAGGAGE_HEADER];
2730
- }
2731
- };
2732
- //#endregion
2733
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/common/attributes.js
2734
- function sanitizeAttributes(attributes) {
2735
- const out = {};
2736
- if (typeof attributes !== "object" || attributes == null) return out;
2737
- for (const key in attributes) {
2738
- if (!Object.prototype.hasOwnProperty.call(attributes, key)) continue;
2739
- if (!isAttributeKey(key)) {
2740
- diag$1.warn(`Invalid attribute key: ${key}`);
2741
- continue;
2742
- }
2743
- const val = attributes[key];
2744
- if (!isAttributeValue(val)) {
2745
- diag$1.warn(`Invalid attribute value set for key: ${key}`);
2746
- continue;
2747
- }
2748
- if (Array.isArray(val)) out[key] = val.slice();
2749
- else out[key] = val;
2750
- }
2751
- return out;
2752
- }
2753
- function isAttributeKey(key) {
2754
- return typeof key === "string" && key !== "";
2755
- }
2756
- function isAttributeValue(val) {
2757
- if (val == null) return true;
2758
- if (Array.isArray(val)) return isHomogeneousAttributeValueArray(val);
2759
- return isValidPrimitiveAttributeValueType(typeof val);
2760
- }
2761
- function isHomogeneousAttributeValueArray(arr) {
2762
- let type;
2763
- for (const element of arr) {
2764
- if (element == null) continue;
2765
- const elementType = typeof element;
2766
- if (elementType === type) continue;
2767
- if (!type) {
2768
- if (isValidPrimitiveAttributeValueType(elementType)) {
2769
- type = elementType;
2770
- continue;
2771
- }
2772
- return false;
2773
- }
2774
- return false;
2775
- }
2776
- return true;
2777
- }
2778
- function isValidPrimitiveAttributeValueType(valType) {
2779
- switch (valType) {
2780
- case "number":
2781
- case "boolean":
2782
- case "string": return true;
2783
- }
2784
- return false;
2785
- }
2786
- //#endregion
2787
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/propagation/composite.js
2788
- /** Combines multiple propagators into a single propagator. */
2789
- var CompositePropagator = class {
2790
- _propagators;
2791
- _fields;
2792
- /**
2793
- * Construct a composite propagator from a list of propagators.
2794
- *
2795
- * @param [config] Configuration object for composite propagator
2796
- */
2797
- constructor(config = {}) {
2798
- this._propagators = config.propagators ?? [];
2799
- const fields = /* @__PURE__ */ new Set();
2800
- for (const propagator of this._propagators) {
2801
- const propagatorFields = typeof propagator.fields === "function" ? propagator.fields() : [];
2802
- for (const field of propagatorFields) fields.add(field);
2803
- }
2804
- this._fields = Array.from(fields);
2805
- }
2806
- /**
2807
- * Run each of the configured propagators with the given context and carrier.
2808
- * Propagators are run in the order they are configured, so if multiple
2809
- * propagators write the same carrier key, the propagator later in the list
2810
- * will "win".
2811
- *
2812
- * @param context Context to inject
2813
- * @param carrier Carrier into which context will be injected
2814
- */
2815
- inject(context, carrier, setter) {
2816
- for (const propagator of this._propagators) try {
2817
- propagator.inject(context, carrier, setter);
2818
- } catch (err) {
2819
- diag$1.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);
2820
- }
2821
- }
2822
- /**
2823
- * Run each of the configured propagators with the given context and carrier.
2824
- * Propagators are run in the order they are configured, so if multiple
2825
- * propagators write the same context key, the propagator later in the list
2826
- * will "win".
2827
- *
2828
- * @param context Context to add values to
2829
- * @param carrier Carrier from which to extract context
2830
- */
2831
- extract(context, carrier, getter) {
2832
- return this._propagators.reduce((ctx, propagator) => {
2833
- try {
2834
- return propagator.extract(ctx, carrier, getter);
2835
- } catch (err) {
2836
- diag$1.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`);
2837
- }
2838
- return ctx;
2839
- }, context);
2840
- }
2841
- fields() {
2842
- return this._fields.slice();
2843
- }
2844
- };
2845
- //#endregion
2846
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/internal/validators.js
2847
- var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
2848
- var VALID_KEY_REGEX = new RegExp(`^(?:${`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`}|${`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`})$`);
2849
- var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
2850
- var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
2851
- /**
2852
- * Key is opaque string up to 256 characters printable. It MUST begin with a
2853
- * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,
2854
- * underscores _, dashes -, asterisks *, and forward slashes /.
2855
- * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the
2856
- * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.
2857
- * see https://www.w3.org/TR/trace-context/#key
2858
- */
2859
- function validateKey(key) {
2860
- return VALID_KEY_REGEX.test(key);
2861
- }
2862
- /**
2863
- * Value is opaque string up to 256 characters printable ASCII RFC0020
2864
- * characters (i.e., the range 0x20 to 0x7E) except comma , and =.
2865
- */
2866
- function validateValue(value) {
2867
- return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
2868
- }
2869
- //#endregion
2870
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/trace/TraceState.js
2871
- var MAX_TRACE_STATE_ITEMS = 32;
2872
- var MAX_TRACE_STATE_LEN = 512;
2873
- var LIST_MEMBERS_SEPARATOR = ",";
2874
- var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
2875
- /**
2876
- * TraceState must be a class and not a simple object type because of the spec
2877
- * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).
2878
- *
2879
- * Here is the list of allowed mutations:
2880
- * - New key-value pair should be added into the beginning of the list
2881
- * - The value of any key can be updated. Modified keys MUST be moved to the
2882
- * beginning of the list.
2883
- */
2884
- var TraceState = class TraceState {
2885
- _length;
2886
- _rawTraceState;
2887
- _internalState;
2888
- constructor(rawTraceState) {
2889
- this._rawTraceState = typeof rawTraceState === "string" ? rawTraceState : "";
2890
- this._length = this._rawTraceState.length;
2891
- }
2892
- set(key, value) {
2893
- if (!validateKey(key) || !validateValue(value)) return this;
2894
- const currState = this._getState();
2895
- const currValue = currState.get(key);
2896
- let newLength = this._length;
2897
- if (typeof currValue === "string") newLength += value.length - currValue.length;
2898
- else newLength += key.length + value.length + (currState.size > 0 ? 2 : 1);
2899
- if (newLength > MAX_TRACE_STATE_LEN) return this;
2900
- const newState = new Map(currState);
2901
- newState.delete(key);
2902
- newState.set(key, value);
2903
- return this._fromState(newState, newLength);
2904
- }
2905
- unset(key) {
2906
- const currState = this._getState();
2907
- const currValue = currState.get(key);
2908
- if (typeof currValue !== "string") return this;
2909
- let newLength = this._length - (key.length + currValue.length + 1);
2910
- if (currState.size > 1) newLength = newLength - 1;
2911
- const newState = new Map(currState);
2912
- newState.delete(key);
2913
- return this._fromState(newState, newLength);
2914
- }
2915
- get(key) {
2916
- return this._getState().get(key);
2917
- }
2918
- serialize() {
2919
- let serialized = "";
2920
- let index = 0;
2921
- for (const entry of this._getState()) {
2922
- if (index > 0) serialized = LIST_MEMBERS_SEPARATOR + serialized;
2923
- serialized = `${entry[0]}${LIST_MEMBER_KEY_VALUE_SPLITTER}${entry[1]}` + serialized;
2924
- index++;
2925
- }
2926
- return serialized;
2927
- }
2928
- _getState() {
2929
- if (this._internalState) return this._internalState;
2930
- const vendorMembers = this._rawTraceState.split(LIST_MEMBERS_SEPARATOR);
2931
- const vendorEntries = /* @__PURE__ */ new Map();
2932
- let currentLength = 0;
2933
- for (const member of vendorMembers) {
2934
- const m = member.trim();
2935
- const idx = m.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
2936
- if (idx === -1) continue;
2937
- const key = m.slice(0, idx);
2938
- const value = m.slice(idx + 1);
2939
- if (!validateKey(key) || !validateValue(value)) continue;
2940
- const futureLength = currentLength + m.length + (vendorEntries.size > 0 ? 1 : 0);
2941
- if (futureLength > MAX_TRACE_STATE_LEN) continue;
2942
- vendorEntries.set(key, value);
2943
- currentLength = futureLength;
2944
- if (vendorEntries.size >= MAX_TRACE_STATE_ITEMS) break;
2945
- }
2946
- this._length = currentLength;
2947
- this._internalState = new Map(Array.from(vendorEntries.entries()).reverse());
2948
- return this._internalState;
2949
- }
2950
- _fromState(state, length) {
2951
- const traceState = Object.create(TraceState.prototype);
2952
- traceState._internalState = state;
2953
- traceState._length = length;
2954
- return traceState;
2955
- }
2956
- };
2957
- //#endregion
2958
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/trace/W3CTraceContextPropagator.js
2959
- var TRACE_PARENT_HEADER = "traceparent";
2960
- var TRACE_STATE_HEADER = "tracestate";
2961
- var VERSION$1 = "00";
2962
- var TRACE_PARENT_REGEX = new RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);
2963
- /**
2964
- * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}
2965
- * @param traceParent - A meta property that comes from server.
2966
- * It should be dynamically generated server side to have the server's request trace Id,
2967
- * a parent span Id that was set on the server's request span,
2968
- * and the trace flags to indicate the server's sampling decision
2969
- * (01 = sampled, 00 = not sampled).
2970
- * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'
2971
- * For more information see {@link https://www.w3.org/TR/trace-context/}
2972
- */
2973
- function parseTraceParent(traceParent) {
2974
- const match = TRACE_PARENT_REGEX.exec(traceParent);
2975
- if (!match) return null;
2976
- if (match[1] === "00" && match[5]) return null;
2977
- return {
2978
- traceId: match[2],
2979
- spanId: match[3],
2980
- traceFlags: parseInt(match[4], 16)
2981
- };
2982
- }
2983
- /**
2984
- * Propagates {@link SpanContext} through Trace Context format propagation.
2985
- *
2986
- * Based on the Trace Context specification:
2987
- * https://www.w3.org/TR/trace-context/
2988
- */
2989
- var W3CTraceContextPropagator = class {
2990
- inject(context, carrier, setter) {
2991
- const spanContext = trace.getSpanContext(context);
2992
- if (!spanContext || isTracingSuppressed(context) || !isSpanContextValid(spanContext)) return;
2993
- const traceParent = `${VERSION$1}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;
2994
- setter.set(carrier, TRACE_PARENT_HEADER, traceParent);
2995
- if (spanContext.traceState) setter.set(carrier, TRACE_STATE_HEADER, spanContext.traceState.serialize());
2996
- }
2997
- extract(context, carrier, getter) {
2998
- const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);
2999
- if (!traceParentHeader) return context;
3000
- const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader;
3001
- if (typeof traceParent !== "string") return context;
3002
- const spanContext = parseTraceParent(traceParent);
3003
- if (!spanContext) return context;
3004
- spanContext.isRemote = true;
3005
- const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);
3006
- if (traceStateHeader) {
3007
- const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader;
3008
- spanContext.traceState = new TraceState(typeof state === "string" ? state : void 0);
3009
- }
3010
- return trace.setSpanContext(context, spanContext);
3011
- }
3012
- fields() {
3013
- return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];
3014
- }
3015
- };
3016
- //#endregion
3017
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/utils/lodash.merge.js
3018
- /**
3019
- * based on lodash in order to support esm builds without esModuleInterop.
3020
- * lodash is using MIT License.
3021
- **/
3022
- var objectTag = "[object Object]";
3023
- var nullTag = "[object Null]";
3024
- var undefinedTag = "[object Undefined]";
3025
- var funcToString = Function.prototype.toString;
3026
- var objectCtorString = funcToString.call(Object);
3027
- var getPrototypeOf = Object.getPrototypeOf;
3028
- var objectProto = Object.prototype;
3029
- var hasOwnProperty = objectProto.hasOwnProperty;
3030
- var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
3031
- var nativeObjectToString = objectProto.toString;
3032
- /**
3033
- * Checks if `value` is a plain object, that is, an object created by the
3034
- * `Object` constructor or one with a `[[Prototype]]` of `null`.
3035
- *
3036
- * @static
3037
- * @memberOf _
3038
- * @since 0.8.0
3039
- * @category Lang
3040
- * @param {*} value The value to check.
3041
- * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
3042
- * @example
3043
- *
3044
- * function Foo() {
3045
- * this.a = 1;
3046
- * }
3047
- *
3048
- * _.isPlainObject(new Foo);
3049
- * // => false
3050
- *
3051
- * _.isPlainObject([1, 2, 3]);
3052
- * // => false
3053
- *
3054
- * _.isPlainObject({ 'x': 0, 'y': 0 });
3055
- * // => true
3056
- *
3057
- * _.isPlainObject(Object.create(null));
3058
- * // => true
3059
- */
3060
- function isPlainObject(value) {
3061
- if (!isObjectLike(value) || baseGetTag(value) !== objectTag) return false;
3062
- const proto = getPrototypeOf(value);
3063
- if (proto === null) return true;
3064
- const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
3065
- return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
3066
- }
3067
- /**
3068
- * Checks if `value` is object-like. A value is object-like if it's not `null`
3069
- * and has a `typeof` result of "object".
3070
- *
3071
- * @static
3072
- * @memberOf _
3073
- * @since 4.0.0
3074
- * @category Lang
3075
- * @param {*} value The value to check.
3076
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3077
- * @example
3078
- *
3079
- * _.isObjectLike({});
3080
- * // => true
3081
- *
3082
- * _.isObjectLike([1, 2, 3]);
3083
- * // => true
3084
- *
3085
- * _.isObjectLike(_.noop);
3086
- * // => false
3087
- *
3088
- * _.isObjectLike(null);
3089
- * // => false
3090
- */
3091
- function isObjectLike(value) {
3092
- return value != null && typeof value == "object";
3093
- }
3094
- /**
3095
- * The base implementation of `getTag` without fallbacks for buggy environments.
3096
- *
3097
- * @private
3098
- * @param {*} value The value to query.
3099
- * @returns {string} Returns the `toStringTag`.
3100
- */
3101
- function baseGetTag(value) {
3102
- if (value == null) return value === void 0 ? undefinedTag : nullTag;
3103
- return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
3104
- }
3105
- /**
3106
- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3107
- *
3108
- * @private
3109
- * @param {*} value The value to query.
3110
- * @returns {string} Returns the raw `toStringTag`.
3111
- */
3112
- function getRawTag(value) {
3113
- const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
3114
- let unmasked = false;
3115
- try {
3116
- value[symToStringTag] = void 0;
3117
- unmasked = true;
3118
- } catch {}
3119
- const result = nativeObjectToString.call(value);
3120
- if (unmasked) if (isOwn) value[symToStringTag] = tag;
3121
- else delete value[symToStringTag];
3122
- return result;
3123
- }
3124
- /**
3125
- * Converts `value` to a string using `Object.prototype.toString`.
3126
- *
3127
- * @private
3128
- * @param {*} value The value to convert.
3129
- * @returns {string} Returns the converted string.
3130
- */
3131
- function objectToString(value) {
3132
- return nativeObjectToString.call(value);
3133
- }
3134
- //#endregion
3135
- //#region node_modules/.pnpm/@opentelemetry+core@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/esm/utils/merge.js
3136
- var MAX_LEVEL = 20;
3137
- /**
3138
- * Merges objects together
3139
- * @param args - objects / values to be merged
3140
- */
3141
- function merge(...args) {
3142
- let result = args.shift();
3143
- const objects = /* @__PURE__ */ new WeakMap();
3144
- while (args.length > 0) result = mergeTwoObjects(result, args.shift(), 0, objects);
3145
- return result;
3146
- }
3147
- function takeValue(value) {
3148
- if (isArray(value)) return value.slice();
3149
- return value;
3150
- }
3151
- /**
3152
- * Merges two objects
3153
- * @param one - first object
3154
- * @param two - second object
3155
- * @param level - current deep level
3156
- * @param objects - objects holder that has been already referenced - to prevent
3157
- * cyclic dependency
3158
- */
3159
- function mergeTwoObjects(one, two, level = 0, objects) {
3160
- let result;
3161
- if (level > MAX_LEVEL) return;
3162
- level++;
3163
- if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) result = takeValue(two);
3164
- else if (isArray(one)) {
3165
- result = one.slice();
3166
- if (isArray(two)) for (let i = 0, j = two.length; i < j; i++) result.push(takeValue(two[i]));
3167
- else if (isObject(two)) {
3168
- const keys = Object.keys(two);
3169
- for (let i = 0, j = keys.length; i < j; i++) {
3170
- const key = keys[i];
3171
- if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
3172
- result[key] = takeValue(two[key]);
3173
- }
3174
- }
3175
- } else if (isObject(one)) if (isObject(two)) {
3176
- if (!shouldMerge(one, two)) return two;
3177
- result = Object.assign({}, one);
3178
- const keys = Object.keys(two);
3179
- for (let i = 0, j = keys.length; i < j; i++) {
3180
- const key = keys[i];
3181
- if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
3182
- const twoValue = two[key];
3183
- if (isPrimitive(twoValue)) if (typeof twoValue === "undefined") delete result[key];
3184
- else result[key] = twoValue;
3185
- else {
3186
- const obj1 = result[key];
3187
- const obj2 = twoValue;
3188
- if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) delete result[key];
3189
- else {
3190
- if (isObject(obj1) && isObject(obj2)) {
3191
- const arr1 = objects.get(obj1) || [];
3192
- const arr2 = objects.get(obj2) || [];
3193
- arr1.push({
3194
- obj: one,
3195
- key
3196
- });
3197
- arr2.push({
3198
- obj: two,
3199
- key
3200
- });
3201
- objects.set(obj1, arr1);
3202
- objects.set(obj2, arr2);
3203
- }
3204
- result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
3205
- }
3206
- }
3207
- }
3208
- } else result = two;
3209
- return result;
3210
- }
3211
- /**
3212
- * Function to check if object has been already reference
3213
- * @param obj
3214
- * @param key
3215
- * @param objects
3216
- */
3217
- function wasObjectReferenced(obj, key, objects) {
3218
- const arr = objects.get(obj[key]) || [];
3219
- for (let i = 0, j = arr.length; i < j; i++) {
3220
- const info = arr[i];
3221
- if (info.key === key && info.obj === obj) return true;
3222
- }
3223
- return false;
3224
- }
3225
- function isArray(value) {
3226
- return Array.isArray(value);
3227
- }
3228
- function isFunction(value) {
3229
- return typeof value === "function";
3230
- }
3231
- function isObject(value) {
3232
- return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
3233
- }
3234
- function isPrimitive(value) {
3235
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
3236
- }
3237
- function shouldMerge(one, two) {
3238
- if (!isPlainObject(one) || !isPlainObject(two)) return false;
3239
- return true;
3240
- }
3241
- //#endregion
3242
- //#region node_modules/.pnpm/@opentelemetry+otlp-transformer@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/esm/trace/internal.js
3243
- var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256;
3244
- var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512;
3245
- /**
3246
- * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags
3247
- * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.
3248
- */
3249
- function buildSpanFlagsFrom(traceFlags, isRemote) {
3250
- let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;
3251
- if (isRemote) flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;
3252
- return flags;
3253
- }
3254
- function sdkSpanToOtlpSpan(span, encoder) {
3255
- const ctx = span.spanContext();
3256
- const status = span.status;
3257
- const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
3258
- return {
3259
- traceId: encoder.encodeSpanContext(ctx.traceId),
3260
- spanId: encoder.encodeSpanContext(ctx.spanId),
3261
- parentSpanId,
3262
- traceState: ctx.traceState?.serialize(),
3263
- name: span.name,
3264
- kind: span.kind == null ? 0 : span.kind + 1,
3265
- startTimeUnixNano: encoder.encodeHrTime(span.startTime),
3266
- endTimeUnixNano: encoder.encodeHrTime(span.endTime),
3267
- attributes: toAttributes(span.attributes, encoder),
3268
- droppedAttributesCount: span.droppedAttributesCount,
3269
- events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
3270
- droppedEventsCount: span.droppedEventsCount,
3271
- status: {
3272
- code: status.code,
3273
- message: status.message
3274
- },
3275
- links: span.links.map((link) => toOtlpLink(link, encoder)),
3276
- droppedLinksCount: span.droppedLinksCount,
3277
- flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote)
3278
- };
3279
- }
3280
- function toOtlpLink(link, encoder) {
3281
- return {
3282
- attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],
3283
- spanId: encoder.encodeSpanContext(link.context.spanId),
3284
- traceId: encoder.encodeSpanContext(link.context.traceId),
3285
- traceState: link.context.traceState?.serialize(),
3286
- droppedAttributesCount: link.droppedAttributesCount || 0,
3287
- flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote)
3288
- };
3289
- }
3290
- function toOtlpSpanEvent(timedEvent, encoder) {
3291
- return {
3292
- attributes: timedEvent.attributes ? toAttributes(timedEvent.attributes, encoder) : [],
3293
- name: timedEvent.name,
3294
- timeUnixNano: encoder.encodeHrTime(timedEvent.time),
3295
- droppedAttributesCount: timedEvent.droppedAttributesCount || 0
3296
- };
3297
- }
3298
- function createExportTraceServiceRequest(spans, encoder) {
3299
- return { resourceSpans: spanRecordsToResourceSpans(spans, encoder) };
3300
- }
3301
- function createResourceMap(readableSpans) {
3302
- const resourceMap = /* @__PURE__ */ new Map();
3303
- for (const record of readableSpans) {
3304
- let ilsMap = resourceMap.get(record.resource);
3305
- if (!ilsMap) {
3306
- ilsMap = /* @__PURE__ */ new Map();
3307
- resourceMap.set(record.resource, ilsMap);
3308
- }
3309
- const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`;
3310
- let records = ilsMap.get(instrumentationScopeKey);
3311
- if (!records) {
3312
- records = [];
3313
- ilsMap.set(instrumentationScopeKey, records);
3314
- }
3315
- records.push(record);
3316
- }
3317
- return resourceMap;
3318
- }
3319
- function spanRecordsToResourceSpans(readableSpans, encoder) {
3320
- const resourceMap = createResourceMap(readableSpans);
3321
- const out = [];
3322
- const entryIterator = resourceMap.entries();
3323
- let entry = entryIterator.next();
3324
- while (!entry.done) {
3325
- const [resource, ilmMap] = entry.value;
3326
- const scopeResourceSpans = [];
3327
- const ilmIterator = ilmMap.values();
3328
- let ilmEntry = ilmIterator.next();
3329
- while (!ilmEntry.done) {
3330
- const scopeSpans = ilmEntry.value;
3331
- if (scopeSpans.length > 0) {
3332
- const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder));
3333
- scopeResourceSpans.push({
3334
- scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),
3335
- spans,
3336
- schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
3337
- });
3338
- }
3339
- ilmEntry = ilmIterator.next();
3340
- }
3341
- const processedResource = createResource(resource, encoder);
3342
- out.push({
3343
- resource: processedResource,
3344
- scopeSpans: scopeResourceSpans,
3345
- schemaUrl: processedResource.schemaUrl
3346
- });
3347
- entry = entryIterator.next();
3348
- }
3349
- return out;
3350
- }
3351
- //#endregion
3352
- //#region node_modules/.pnpm/@opentelemetry+otlp-transformer@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/esm/trace/json/trace.js
3353
- var JsonTraceSerializer = {
3354
- serializeRequest: (arg) => {
3355
- const request = createExportTraceServiceRequest(arg, JSON_ENCODER);
3356
- return new TextEncoder().encode(JSON.stringify(request));
3357
- },
3358
- deserializeResponse: (arg) => {
3359
- if (arg.length === 0) return {};
3360
- const decoder = new TextDecoder();
3361
- try {
3362
- return JSON.parse(decoder.decode(arg));
3363
- } catch (err) {
3364
- diag$1.warn(`Failed to parse trace export response: ${err.message}. Returning empty response`);
3365
- return {};
3366
- }
3367
- }
3368
- };
3369
- //#endregion
3370
- //#region core/avatarViewRegistry.ts
3371
- var AvatarViewRegistry = class {
3372
- entries = /* @__PURE__ */ new Set();
3373
- register(view) {
3374
- this.entries.add(new WeakRef(view));
3375
- }
3376
- unregister(view) {
3377
- for (const ref of this.entries) if (ref.deref() === view) {
3378
- this.entries.delete(ref);
3379
- return;
3380
- }
3381
- }
3382
- applyResolutionCapToAll() {
3383
- for (const ref of this.entries) {
3384
- const view = ref.deref();
3385
- if (view) view.applyResolutionCapFromSdk();
3386
- else this.entries.delete(ref);
3387
- }
3388
- }
3389
- };
3390
- var avatarViewRegistry = new AvatarViewRegistry();
3391
- //#endregion
3392
- //#region utils/region-resolver.ts
3393
- /**
3394
- * Region 解析(区域自动调度)
3395
- *
3396
- * - region 为 'auto':调一次 bootstrap,用后台推荐的 region.current。
3397
- * - region 为具体值(用户手动指定):直接用,跳过调度。
3398
- * - auto 但 bootstrap 失败:降级到默认 region(us-west),并上报一条 error 埋点
3399
- * (严重事件,供监控观测),不阻断初始化。
3400
- *
3401
- * 与时钟校准(clock-sync)解耦:各自独立调 bootstrap,互不影响。
3402
- * @internal
3403
- */
3404
- /** region 解析请求超时 */
3405
- var RESOLVE_TIMEOUT_MS = 5e3;
3406
- /** 缓存上次成功解析的具体 region 的 localStorage key,供后续降级复用。 */
3407
- var CACHE_KEY = "avatarkit_cached_region";
3408
- /** 写缓存:成功解析出具体 region 时存下,供以后失败时降级复用。localStorage 不可用时静默跳过。 */
3409
- function writeRegionCache(region) {
3410
- try {
3411
- if (typeof localStorage !== "undefined") localStorage.setItem(CACHE_KEY, region);
3412
- } catch {}
3413
- }
3414
- /** 读缓存:返回上次成功解析的 region,无则 null。 */
3415
- function readRegionCache() {
3416
- try {
3417
- if (typeof localStorage === "undefined") return null;
3418
- const v = localStorage.getItem(CACHE_KEY);
3419
- return v && v.length > 0 ? v : null;
3420
- } catch {
3421
- return null;
3422
- }
3423
- }
3424
- /**
3425
- * 把请求的 region 解析成实际接入 region。
3426
- * @param requestedRegion 用户传入的 region('auto' 或具体值)
3427
- * @returns 实际接入 region(always a concrete value,不会是 'auto')
3428
- * @internal
3429
- */
3430
- async function resolveRegion(opts) {
3431
- const { appId, sdkVersion, requestedRegion } = opts;
3432
- if (requestedRegion !== "auto") return requestedRegion;
3433
- const controller = new AbortController();
3434
- const timer = setTimeout(() => controller.abort(), RESOLVE_TIMEOUT_MS);
3435
- try {
3436
- const current = (await fetchBootstrap({
3437
- appId,
3438
- sdkVersion,
3439
- region: "auto"
3440
- }, controller.signal)).region?.current;
3441
- if (typeof current === "string" && current.length > 0) {
3442
- writeRegionCache(current);
3443
- logger.log(`[RegionResolver] auto → ${current}`);
3444
- return current;
3445
- }
3446
- throw new Error("bootstrap response missing region.current");
3447
- } catch (error) {
3448
- const message = error instanceof Error ? error.message : String(error);
3449
- const cached = readRegionCache();
3450
- const fallback = cached ?? "us-west";
3451
- logger.warn(`[RegionResolver] auto resolve failed, falling back to ${fallback} (from_cache=${cached !== null}): ${message}`);
3452
- logEvent("region_resolve_failed", "error", {
3453
- fallback_region: fallback,
3454
- from_cache: cached !== null,
3455
- reason: message
3456
- });
3457
- return fallback;
3458
- } finally {
3459
- clearTimeout(timer);
3460
- }
3461
- }
3462
- //#endregion
3463
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/enums.js
3464
- var ExceptionEventName = "exception";
3465
- //#endregion
3466
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Span.js
3467
- /**
3468
- * This class represents a span.
3469
- */
3470
- var SpanImpl = class {
3471
- _spanContext;
3472
- kind;
3473
- parentSpanContext;
3474
- attributes = {};
3475
- links = [];
3476
- events = [];
3477
- startTime;
3478
- resource;
3479
- instrumentationScope;
3480
- _droppedAttributesCount = 0;
3481
- _droppedEventsCount = 0;
3482
- _droppedLinksCount = 0;
3483
- _attributesCount = 0;
3484
- name;
3485
- status = { code: SpanStatusCode.UNSET };
3486
- endTime = [0, 0];
3487
- _ended = false;
3488
- _duration = [-1, -1];
3489
- _spanProcessor;
3490
- _spanLimits;
3491
- _attributeValueLengthLimit;
3492
- _recordEndMetrics;
3493
- _performanceStartTime;
3494
- _performanceOffset;
3495
- _startTimeProvided;
3496
- /**
3497
- * Constructs a new SpanImpl instance.
3498
- */
3499
- constructor(opts) {
3500
- const now = Date.now();
3501
- this._spanContext = opts.spanContext;
3502
- this._performanceStartTime = otperformance.now();
3503
- this._performanceOffset = now - (this._performanceStartTime + otperformance.timeOrigin);
3504
- this._startTimeProvided = opts.startTime != null;
3505
- this._spanLimits = opts.spanLimits;
3506
- this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0;
3507
- this._spanProcessor = opts.spanProcessor;
3508
- this.name = opts.name;
3509
- this.parentSpanContext = opts.parentSpanContext;
3510
- this.kind = opts.kind;
3511
- if (opts.links) for (const link of opts.links) this.addLink(link);
3512
- this.startTime = this._getTime(opts.startTime ?? now);
3513
- this.resource = opts.resource;
3514
- this.instrumentationScope = opts.scope;
3515
- this._recordEndMetrics = opts.recordEndMetrics;
3516
- if (opts.attributes != null) this.setAttributes(opts.attributes);
3517
- this._spanProcessor.onStart(this, opts.context);
3518
- }
3519
- spanContext() {
3520
- return this._spanContext;
3521
- }
3522
- setAttribute(key, value) {
3523
- if (value == null || this._isSpanEnded()) return this;
3524
- if (key.length === 0) {
3525
- diag$1.warn(`Invalid attribute key: ${key}`);
3526
- return this;
3527
- }
3528
- if (!isAttributeValue(value)) {
3529
- diag$1.warn(`Invalid attribute value set for key: ${key}`);
3530
- return this;
3531
- }
3532
- const { attributeCountLimit } = this._spanLimits;
3533
- const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
3534
- if (attributeCountLimit !== void 0 && this._attributesCount >= attributeCountLimit && isNewKey) {
3535
- this._droppedAttributesCount++;
3536
- return this;
3537
- }
3538
- this.attributes[key] = this._truncateToSize(value);
3539
- if (isNewKey) this._attributesCount++;
3540
- return this;
3541
- }
3542
- setAttributes(attributes) {
3543
- for (const key in attributes) if (Object.prototype.hasOwnProperty.call(attributes, key)) this.setAttribute(key, attributes[key]);
3544
- return this;
3545
- }
3546
- /**
3547
- *
3548
- * @param name Span Name
3549
- * @param [attributesOrStartTime] Span attributes or start time
3550
- * if type is {@type TimeInput} and 3rd param is undefined
3551
- * @param [timeStamp] Specified time stamp for the event
3552
- */
3553
- addEvent(name, attributesOrStartTime, timeStamp) {
3554
- if (this._isSpanEnded()) return this;
3555
- const { eventCountLimit } = this._spanLimits;
3556
- if (eventCountLimit === 0) {
3557
- diag$1.warn("No events allowed.");
3558
- this._droppedEventsCount++;
3559
- return this;
3560
- }
3561
- if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) {
3562
- if (this._droppedEventsCount === 0) diag$1.debug("Dropping extra events.");
3563
- this.events.shift();
3564
- this._droppedEventsCount++;
3565
- }
3566
- if (isTimeInput(attributesOrStartTime)) {
3567
- if (!isTimeInput(timeStamp)) timeStamp = attributesOrStartTime;
3568
- attributesOrStartTime = void 0;
3569
- }
3570
- const sanitized = sanitizeAttributes(attributesOrStartTime);
3571
- const { attributePerEventCountLimit } = this._spanLimits;
3572
- const attributes = {};
3573
- let droppedAttributesCount = 0;
3574
- let eventAttributesCount = 0;
3575
- for (const attr in sanitized) {
3576
- if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue;
3577
- const attrVal = sanitized[attr];
3578
- if (attributePerEventCountLimit !== void 0 && eventAttributesCount >= attributePerEventCountLimit) {
3579
- droppedAttributesCount++;
3580
- continue;
3581
- }
3582
- attributes[attr] = this._truncateToSize(attrVal);
3583
- eventAttributesCount++;
3584
- }
3585
- this.events.push({
3586
- name,
3587
- attributes,
3588
- time: this._getTime(timeStamp),
3589
- droppedAttributesCount
3590
- });
3591
- return this;
3592
- }
3593
- addLink(link) {
3594
- if (this._isSpanEnded()) return this;
3595
- const { linkCountLimit } = this._spanLimits;
3596
- if (linkCountLimit === 0) {
3597
- this._droppedLinksCount++;
3598
- return this;
3599
- }
3600
- if (linkCountLimit !== void 0 && this.links.length >= linkCountLimit) {
3601
- if (this._droppedLinksCount === 0) diag$1.debug("Dropping extra links.");
3602
- this.links.shift();
3603
- this._droppedLinksCount++;
3604
- }
3605
- const { attributePerLinkCountLimit } = this._spanLimits;
3606
- const sanitized = sanitizeAttributes(link.attributes);
3607
- const attributes = {};
3608
- let droppedAttributesCount = 0;
3609
- let linkAttributesCount = 0;
3610
- for (const attr in sanitized) {
3611
- if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue;
3612
- const attrVal = sanitized[attr];
3613
- if (attributePerLinkCountLimit !== void 0 && linkAttributesCount >= attributePerLinkCountLimit) {
3614
- droppedAttributesCount++;
3615
- continue;
3616
- }
3617
- attributes[attr] = this._truncateToSize(attrVal);
3618
- linkAttributesCount++;
3619
- }
3620
- const processedLink = { context: link.context };
3621
- if (linkAttributesCount > 0) processedLink.attributes = attributes;
3622
- if (droppedAttributesCount > 0) processedLink.droppedAttributesCount = droppedAttributesCount;
3623
- this.links.push(processedLink);
3624
- return this;
3625
- }
3626
- addLinks(links) {
3627
- for (const link of links) this.addLink(link);
3628
- return this;
3629
- }
3630
- setStatus(status) {
3631
- if (this._isSpanEnded()) return this;
3632
- if (status.code === SpanStatusCode.UNSET) return this;
3633
- if (this.status.code === SpanStatusCode.OK) return this;
3634
- const newStatus = { code: status.code };
3635
- if (status.code === SpanStatusCode.ERROR) {
3636
- if (typeof status.message === "string") newStatus.message = status.message;
3637
- else if (status.message != null) diag$1.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
3638
- }
3639
- this.status = newStatus;
3640
- return this;
3641
- }
3642
- updateName(name) {
3643
- if (this._isSpanEnded()) return this;
3644
- this.name = name;
3645
- return this;
3646
- }
3647
- end(endTime) {
3648
- if (this._isSpanEnded()) {
3649
- diag$1.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
3650
- return;
3651
- }
3652
- this.endTime = this._getTime(endTime);
3653
- this._duration = hrTimeDuration(this.startTime, this.endTime);
3654
- if (this._duration[0] < 0) {
3655
- diag$1.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime);
3656
- this.endTime = this.startTime.slice();
3657
- this._duration = [0, 0];
3658
- }
3659
- if (this._droppedEventsCount > 0) diag$1.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
3660
- if (this._droppedLinksCount > 0) diag$1.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
3661
- if (this._spanProcessor.onEnding) this._spanProcessor.onEnding(this);
3662
- this._recordEndMetrics?.();
3663
- this._ended = true;
3664
- this._spanProcessor.onEnd(this);
3665
- }
3666
- _getTime(inp) {
3667
- if (typeof inp === "number" && inp <= otperformance.now()) return hrTime(inp + this._performanceOffset);
3668
- if (typeof inp === "number") return millisToHrTime(inp);
3669
- if (inp instanceof Date) return millisToHrTime(inp.getTime());
3670
- if (isTimeInputHrTime(inp)) return inp;
3671
- if (this._startTimeProvided) return millisToHrTime(Date.now());
3672
- const msDuration = otperformance.now() - this._performanceStartTime;
3673
- return addHrTimes(this.startTime, millisToHrTime(msDuration));
3674
- }
3675
- isRecording() {
3676
- return this._ended === false;
3677
- }
3678
- recordException(exception, time) {
3679
- const attributes = {};
3680
- if (typeof exception === "string") attributes[ATTR_EXCEPTION_MESSAGE] = exception;
3681
- else if (exception) {
3682
- if (exception.code) attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
3683
- else if (exception.name) attributes[ATTR_EXCEPTION_TYPE] = exception.name;
3684
- if (exception.message) attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
3685
- if (exception.stack) attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
3686
- }
3687
- if (attributes["exception.type"] || attributes["exception.message"]) this.addEvent(ExceptionEventName, attributes, time);
3688
- else diag$1.warn(`Failed to record an exception ${exception}`);
3689
- }
3690
- get duration() {
3691
- return this._duration;
3692
- }
3693
- get ended() {
3694
- return this._ended;
3695
- }
3696
- get droppedAttributesCount() {
3697
- return this._droppedAttributesCount;
3698
- }
3699
- get droppedEventsCount() {
3700
- return this._droppedEventsCount;
3701
- }
3702
- get droppedLinksCount() {
3703
- return this._droppedLinksCount;
3704
- }
3705
- _isSpanEnded() {
3706
- if (this._ended) {
3707
- const error = /* @__PURE__ */ new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
3708
- diag$1.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
3709
- }
3710
- return this._ended;
3711
- }
3712
- _truncateToLimitUtil(value, limit) {
3713
- if (value.length <= limit) return value;
3714
- return value.substring(0, limit);
3715
- }
3716
- /**
3717
- * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
3718
- * return string with truncated to {@code attributeValueLengthLimit} characters
3719
- *
3720
- * If the given attribute value is array of strings then
3721
- * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
3722
- *
3723
- * Otherwise return same Attribute {@code value}
3724
- *
3725
- * @param value Attribute value
3726
- * @returns truncated attribute value if required, otherwise same value
3727
- */
3728
- _truncateToSize(value) {
3729
- const limit = this._attributeValueLengthLimit;
3730
- if (limit <= 0) {
3731
- diag$1.warn(`Attribute value limit must be positive, got ${limit}`);
3732
- return value;
3733
- }
3734
- if (typeof value === "string") return this._truncateToLimitUtil(value, limit);
3735
- if (Array.isArray(value)) return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val);
3736
- return value;
3737
- }
3738
- };
3739
- //#endregion
3740
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Sampler.js
3741
- /**
3742
- * A sampling decision that determines how a {@link Span} will be recorded
3743
- * and collected.
3744
- */
3745
- var SamplingDecision;
3746
- (function(SamplingDecision) {
3747
- /**
3748
- * `Span.isRecording() === false`, span will not be recorded and all events
3749
- * and attributes will be dropped.
3750
- */
3751
- SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
3752
- /**
3753
- * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
3754
- * MUST NOT be set.
3755
- */
3756
- SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
3757
- /**
3758
- * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
3759
- * MUST be set.
3760
- */
3761
- SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
3762
- })(SamplingDecision || (SamplingDecision = {}));
3763
- //#endregion
3764
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOffSampler.js
3765
- /** Sampler that samples no traces. */
3766
- var AlwaysOffSampler = class {
3767
- shouldSample() {
3768
- return { decision: SamplingDecision.NOT_RECORD };
3769
- }
3770
- toString() {
3771
- return "AlwaysOffSampler";
3772
- }
3773
- };
3774
- //#endregion
3775
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOnSampler.js
3776
- /** Sampler that samples all traces. */
3777
- var AlwaysOnSampler = class {
3778
- shouldSample() {
3779
- return { decision: SamplingDecision.RECORD_AND_SAMPLED };
3780
- }
3781
- toString() {
3782
- return "AlwaysOnSampler";
3783
- }
3784
- };
3785
- //#endregion
3786
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/ParentBasedSampler.js
3787
- /**
3788
- * A composite sampler that either respects the parent span's sampling decision
3789
- * or delegates to `delegateSampler` for root spans.
3790
- */
3791
- var ParentBasedSampler = class {
3792
- _root;
3793
- _remoteParentSampled;
3794
- _remoteParentNotSampled;
3795
- _localParentSampled;
3796
- _localParentNotSampled;
3797
- constructor(config) {
3798
- this._root = config.root;
3799
- if (!this._root) {
3800
- globalErrorHandler(/* @__PURE__ */ new Error("ParentBasedSampler must have a root sampler configured"));
3801
- this._root = new AlwaysOnSampler();
3802
- }
3803
- this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler();
3804
- this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler();
3805
- this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler();
3806
- this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler();
3807
- }
3808
- shouldSample(context, traceId, spanName, spanKind, attributes, links) {
3809
- const parentContext = trace.getSpanContext(context);
3810
- if (!parentContext || !isSpanContextValid(parentContext)) return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
3811
- if (parentContext.isRemote) {
3812
- if (parentContext.traceFlags & TraceFlags.SAMPLED) return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
3813
- return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
3814
- }
3815
- if (parentContext.traceFlags & TraceFlags.SAMPLED) return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
3816
- return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
3817
- }
3818
- toString() {
3819
- return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
3820
- }
3821
- };
3822
- //#endregion
3823
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/TraceIdRatioBasedSampler.js
3824
- /** Sampler that samples a given fraction of traces based of trace id deterministically. */
3825
- var TraceIdRatioBasedSampler = class {
3826
- _ratio;
3827
- _upperBound;
3828
- constructor(ratio = 0) {
3829
- this._ratio = this._normalize(ratio);
3830
- this._upperBound = Math.floor(this._ratio * 4294967295);
3831
- }
3832
- shouldSample(context, traceId) {
3833
- return { decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD };
3834
- }
3835
- toString() {
3836
- return `TraceIdRatioBased{${this._ratio}}`;
3837
- }
3838
- _normalize(ratio) {
3839
- if (typeof ratio !== "number" || isNaN(ratio)) return 0;
3840
- return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
3841
- }
3842
- _accumulate(traceId) {
3843
- let accumulation = 0;
3844
- for (let i = 0; i < 32; i += 8) {
3845
- let part = 0;
3846
- for (let j = 0; j < 8; j++) {
3847
- const c = traceId.charCodeAt(i + j);
3848
- const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;
3849
- part = part << 4 | v;
3850
- }
3851
- accumulation = (accumulation ^ part) >>> 0;
3852
- }
3853
- return accumulation;
3854
- }
3855
- };
3856
- //#endregion
3857
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/config.js
3858
- var TracesSamplerValues;
3859
- (function(TracesSamplerValues) {
3860
- TracesSamplerValues["AlwaysOff"] = "always_off";
3861
- TracesSamplerValues["AlwaysOn"] = "always_on";
3862
- TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off";
3863
- TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on";
3864
- TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio";
3865
- TracesSamplerValues["TraceIdRatio"] = "traceidratio";
3866
- })(TracesSamplerValues || (TracesSamplerValues = {}));
3867
- var DEFAULT_RATIO = 1;
3868
- /**
3869
- * Load default configuration. For fields with primitive values, any user-provided
3870
- * value will override the corresponding default value. For fields with
3871
- * non-primitive values (like `spanLimits`), the user-provided value will be
3872
- * used to extend the default value.
3873
- */
3874
- function loadDefaultConfig() {
3875
- return {
3876
- sampler: buildSamplerFromEnv(),
3877
- forceFlushTimeoutMillis: 3e4,
3878
- generalLimits: {
3879
- attributeValueLengthLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
3880
- attributeCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128
3881
- },
3882
- spanLimits: {
3883
- attributeValueLengthLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
3884
- attributeCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128,
3885
- linkCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128,
3886
- eventCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128,
3887
- attributePerEventCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128,
3888
- attributePerLinkCountLimit: /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128
3889
- }
3890
- };
3891
- }
3892
- /**
3893
- * Based on environment, builds a sampler, complies with specification.
3894
- */
3895
- function buildSamplerFromEnv() {
3896
- const sampler = /* @__PURE__ */ getStringFromEnv("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn;
3897
- switch (sampler) {
3898
- case TracesSamplerValues.AlwaysOn: return new AlwaysOnSampler();
3899
- case TracesSamplerValues.AlwaysOff: return new AlwaysOffSampler();
3900
- case TracesSamplerValues.ParentBasedAlwaysOn: return new ParentBasedSampler({ root: new AlwaysOnSampler() });
3901
- case TracesSamplerValues.ParentBasedAlwaysOff: return new ParentBasedSampler({ root: new AlwaysOffSampler() });
3902
- case TracesSamplerValues.TraceIdRatio: return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
3903
- case TracesSamplerValues.ParentBasedTraceIdRatio: return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()) });
3904
- default:
3905
- diag$1.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
3906
- return new ParentBasedSampler({ root: new AlwaysOnSampler() });
3907
- }
3908
- }
3909
- function getSamplerProbabilityFromEnv() {
3910
- const probability = /* @__PURE__ */ getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");
3911
- if (probability == null) {
3912
- diag$1.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
3913
- return DEFAULT_RATIO;
3914
- }
3915
- if (probability < 0 || probability > 1) {
3916
- diag$1.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
3917
- return DEFAULT_RATIO;
3918
- }
3919
- return probability;
3920
- }
3921
- /**
3922
- * Function to merge Default configuration (as specified in './config') with
3923
- * user provided configurations.
3924
- */
3925
- function mergeConfig(userConfig) {
3926
- const perInstanceDefaults = { sampler: buildSamplerFromEnv() };
3927
- const DEFAULT_CONFIG = loadDefaultConfig();
3928
- const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
3929
- target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
3930
- target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
3931
- return target;
3932
- }
3933
- /**
3934
- * When general limits are provided and model specific limits are not,
3935
- * configures the model specific limits by using the values from the general ones.
3936
- * @param userConfig User provided tracer configuration
3937
- */
3938
- function reconfigureLimits(userConfig) {
3939
- const spanLimits = Object.assign({}, userConfig.spanLimits);
3940
- /**
3941
- * Reassign span attribute count limit to use first non null value defined by user or use default value
3942
- */
3943
- spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128;
3944
- /**
3945
- * Reassign span attribute value length limit to use first non null value defined by user or use default value
3946
- */
3947
- spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? /* @__PURE__ */ getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? /* @__PURE__ */ getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity;
3948
- return Object.assign({}, userConfig, { spanLimits });
3949
- }
3950
- //#endregion
3951
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/export/BatchSpanProcessorBase.js
3952
- /**
3953
- * Implementation of the {@link SpanProcessor} that batches spans exported by
3954
- * the SDK then pushes them to the exporter pipeline.
3955
- */
3956
- var BatchSpanProcessorBase = class {
3957
- _maxExportBatchSize;
3958
- _maxQueueSize;
3959
- _scheduledDelayMillis;
3960
- _exportTimeoutMillis;
3961
- _exporter;
3962
- _isExporting = false;
3963
- _finishedSpans = [];
3964
- _timer;
3965
- _shutdownOnce;
3966
- _droppedSpansCount = 0;
3967
- constructor(exporter, config) {
3968
- this._exporter = exporter;
3969
- this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
3970
- this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
3971
- this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
3972
- this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : /* @__PURE__ */ getNumberFromEnv("OTEL_BSP_EXPORT_TIMEOUT") ?? 3e4;
3973
- this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
3974
- if (this._maxExportBatchSize > this._maxQueueSize) {
3975
- diag$1.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
3976
- this._maxExportBatchSize = this._maxQueueSize;
3977
- }
3978
- }
3979
- forceFlush() {
3980
- if (this._shutdownOnce.isCalled) return this._shutdownOnce.promise;
3981
- return this._flushAll();
3982
- }
3983
- onStart(_span, _parentContext) {}
3984
- onEnd(span) {
3985
- if (this._shutdownOnce.isCalled) return;
3986
- if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) return;
3987
- this._addToBuffer(span);
3988
- }
3989
- shutdown() {
3990
- return this._shutdownOnce.call();
3991
- }
3992
- _shutdown() {
3993
- return Promise.resolve().then(() => {
3994
- return this.onShutdown();
3995
- }).then(() => {
3996
- return this._flushAll();
3997
- }).then(() => {
3998
- return this._exporter.shutdown();
3999
- });
4000
- }
4001
- /** Add a span in the buffer. */
4002
- _addToBuffer(span) {
4003
- if (this._finishedSpans.length >= this._maxQueueSize) {
4004
- if (this._droppedSpansCount === 0) diag$1.debug("maxQueueSize reached, dropping spans");
4005
- this._droppedSpansCount++;
4006
- return;
4007
- }
4008
- if (this._droppedSpansCount > 0) {
4009
- diag$1.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
4010
- this._droppedSpansCount = 0;
4011
- }
4012
- this._finishedSpans.push(span);
4013
- this._maybeStartTimer();
4014
- }
4015
- /**
4016
- * Send all spans to the exporter respecting the batch size limit
4017
- * This function is used only on forceFlush or shutdown,
4018
- * for all other cases _flush should be used
4019
- * */
4020
- _flushAll() {
4021
- return new Promise((resolve, reject) => {
4022
- const promises = [];
4023
- const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
4024
- for (let i = 0, j = count; i < j; i++) promises.push(this._flushOneBatch());
4025
- Promise.all(promises).then(() => {
4026
- resolve();
4027
- }).catch(reject);
4028
- });
4029
- }
4030
- _flushOneBatch() {
4031
- this._clearTimer();
4032
- if (this._finishedSpans.length === 0) return Promise.resolve();
4033
- return new Promise((resolve, reject) => {
4034
- const timer = setTimeout(() => {
4035
- reject(/* @__PURE__ */ new Error("Timeout"));
4036
- }, this._exportTimeoutMillis);
4037
- context.with(suppressTracing(context.active()), () => {
4038
- let spans;
4039
- if (this._finishedSpans.length <= this._maxExportBatchSize) {
4040
- spans = this._finishedSpans;
4041
- this._finishedSpans = [];
4042
- } else spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
4043
- const doExport = () => this._exporter.export(spans, (result) => {
4044
- clearTimeout(timer);
4045
- if (result.code === ExportResultCode.SUCCESS) resolve();
4046
- else reject(result.error ?? /* @__PURE__ */ new Error("BatchSpanProcessor: span export failed"));
4047
- });
4048
- let pendingResources = null;
4049
- for (let i = 0, len = spans.length; i < len; i++) {
4050
- const span = spans[i];
4051
- if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
4052
- pendingResources ??= [];
4053
- pendingResources.push(span.resource.waitForAsyncAttributes());
4054
- }
4055
- }
4056
- if (pendingResources === null) doExport();
4057
- else Promise.all(pendingResources).then(doExport, (err) => {
4058
- globalErrorHandler(err);
4059
- reject(err);
4060
- });
4061
- });
4062
- });
4063
- }
4064
- _maybeStartTimer() {
4065
- if (this._isExporting) return;
4066
- const flush = () => {
4067
- this._isExporting = true;
4068
- this._flushOneBatch().finally(() => {
4069
- this._isExporting = false;
4070
- if (this._finishedSpans.length > 0) {
4071
- this._clearTimer();
4072
- this._maybeStartTimer();
4073
- }
4074
- }).catch((e) => {
4075
- this._isExporting = false;
4076
- globalErrorHandler(e);
4077
- });
4078
- };
4079
- if (this._finishedSpans.length >= this._maxExportBatchSize) return flush();
4080
- if (this._timer !== void 0) return;
4081
- this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
4082
- if (typeof this._timer !== "number") this._timer.unref();
4083
- }
4084
- _clearTimer() {
4085
- if (this._timer !== void 0) {
4086
- clearTimeout(this._timer);
4087
- this._timer = void 0;
4088
- }
4089
- }
4090
- };
4091
- //#endregion
4092
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/browser/export/BatchSpanProcessor.js
4093
- var BatchSpanProcessor = class extends BatchSpanProcessorBase {
4094
- _visibilityChangeListener;
4095
- _pageHideListener;
4096
- constructor(_exporter, config) {
4097
- super(_exporter, config);
4098
- this.onInit(config);
4099
- }
4100
- onInit(config) {
4101
- if (config?.disableAutoFlushOnDocumentHide !== true && typeof document !== "undefined") {
4102
- this._visibilityChangeListener = () => {
4103
- if (document.visibilityState === "hidden") this.forceFlush().catch((error) => {
4104
- globalErrorHandler(error);
4105
- });
4106
- };
4107
- this._pageHideListener = () => {
4108
- this.forceFlush().catch((error) => {
4109
- globalErrorHandler(error);
4110
- });
4111
- };
4112
- document.addEventListener("visibilitychange", this._visibilityChangeListener);
4113
- document.addEventListener("pagehide", this._pageHideListener);
4114
- }
4115
- }
4116
- onShutdown() {
4117
- if (typeof document !== "undefined") {
4118
- if (this._visibilityChangeListener) document.removeEventListener("visibilitychange", this._visibilityChangeListener);
4119
- if (this._pageHideListener) document.removeEventListener("pagehide", this._pageHideListener);
4120
- }
4121
- }
4122
- };
4123
- //#endregion
4124
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/browser/RandomIdGenerator.js
4125
- var TRACE_ID_BYTES = 16;
4126
- var SPAN_ID_BYTES = 8;
4127
- var TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);
4128
- var SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);
4129
- var HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
4130
- /**
4131
- * Fills buffer with random bytes, ensuring at least one is non-zero
4132
- * per W3C Trace Context spec.
4133
- */
4134
- function randomFill(buf) {
4135
- for (let i = 0; i < buf.length; i++) buf[i] = Math.random() * 256 >>> 0;
4136
- for (let i = 0; i < buf.length; i++) if (buf[i] > 0) return;
4137
- buf[buf.length - 1] = 1;
4138
- }
4139
- function toHex(buf) {
4140
- let hex = "";
4141
- for (let i = 0; i < buf.length; i++) hex += HEX[buf[i]];
4142
- return hex;
4143
- }
4144
- var RandomIdGenerator = class {
4145
- /**
4146
- * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
4147
- * characters corresponding to 128 bits.
4148
- */
4149
- generateTraceId() {
4150
- randomFill(TRACE_BUFFER);
4151
- return toHex(TRACE_BUFFER);
4152
- }
4153
- /**
4154
- * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
4155
- * characters corresponding to 64 bits.
4156
- */
4157
- generateSpanId() {
4158
- randomFill(SPAN_BUFFER);
4159
- return toHex(SPAN_BUFFER);
4160
- }
4161
- };
4162
- //#endregion
4163
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/semconv.js
4164
- /**
4165
- * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
4166
- *
4167
- * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
4168
- */
4169
- var ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin";
4170
- /**
4171
- * The result value of the sampler for this span
4172
- *
4173
- * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
4174
- */
4175
- var ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result";
4176
- /**
4177
- * The number of created spans with `recording=true` for which the end operation has not been called yet.
4178
- *
4179
- * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
4180
- */
4181
- var METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live";
4182
- /**
4183
- * The number of created spans.
4184
- *
4185
- * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
4186
- *
4187
- * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
4188
- */
4189
- var METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started";
4190
- //#endregion
4191
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/TracerMetrics.js
4192
- /**
4193
- * Generates `otel.sdk.span.*` metrics.
4194
- * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
4195
- */
4196
- var TracerMetrics = class {
4197
- startedSpans;
4198
- liveSpans;
4199
- constructor(meter) {
4200
- this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
4201
- unit: "{span}",
4202
- description: "The number of created spans."
4203
- });
4204
- this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
4205
- unit: "{span}",
4206
- description: "The number of currently live spans."
4207
- });
4208
- }
4209
- startSpan(parentSpanCtx, samplingDecision) {
4210
- const samplingDecisionStr = samplingDecisionToString(samplingDecision);
4211
- this.startedSpans.add(1, {
4212
- [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
4213
- [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
4214
- });
4215
- if (samplingDecision === SamplingDecision.NOT_RECORD) return () => {};
4216
- const liveSpanAttributes = { [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr };
4217
- this.liveSpans.add(1, liveSpanAttributes);
4218
- return () => {
4219
- this.liveSpans.add(-1, liveSpanAttributes);
4220
- };
2325
+ message.type = object.type ?? 0;
2326
+ message.clientConfigureSession = object.clientConfigureSession !== void 0 && object.clientConfigureSession !== null ? ClientConfigureSession.fromPartial(object.clientConfigureSession) : void 0;
2327
+ message.serverConfirmSession = object.serverConfirmSession !== void 0 && object.serverConfirmSession !== null ? ServerConfirmSession.fromPartial(object.serverConfirmSession) : void 0;
2328
+ message.clientAudioInput = object.clientAudioInput !== void 0 && object.clientAudioInput !== null ? ClientAudioInput.fromPartial(object.clientAudioInput) : void 0;
2329
+ message.serverError = object.serverError !== void 0 && object.serverError !== null ? ServerError.fromPartial(object.serverError) : void 0;
2330
+ message.serverResponseAnimation = object.serverResponseAnimation !== void 0 && object.serverResponseAnimation !== null ? ServerResponseAnimation.fromPartial(object.serverResponseAnimation) : void 0;
2331
+ message.drivenConfig = object.drivenConfig !== void 0 && object.drivenConfig !== null ? DrivenIngressConfig.fromPartial(object.drivenConfig) : void 0;
2332
+ message.clientInterrupt = object.clientInterrupt !== void 0 && object.clientInterrupt !== null ? ClientInterrupt.fromPartial(object.clientInterrupt) : void 0;
2333
+ return message;
4221
2334
  }
4222
2335
  };
4223
- function parentOrigin(parentSpanContext) {
4224
- if (!parentSpanContext) return "none";
4225
- if (parentSpanContext.isRemote) return "remote";
4226
- return "local";
2336
+ function bytesFromBase64(b64) {
2337
+ const bin = globalThis.atob(b64);
2338
+ const arr = new Uint8Array(bin.length);
2339
+ for (let i = 0; i < bin.length; ++i) arr[i] = bin.charCodeAt(i);
2340
+ return arr;
4227
2341
  }
4228
- function samplingDecisionToString(decision) {
4229
- switch (decision) {
4230
- case SamplingDecision.RECORD_AND_SAMPLED: return "RECORD_AND_SAMPLE";
4231
- case SamplingDecision.RECORD: return "RECORD_ONLY";
4232
- case SamplingDecision.NOT_RECORD: return "DROP";
4233
- }
2342
+ function base64FromBytes(arr) {
2343
+ const bin = [];
2344
+ arr.forEach((byte) => {
2345
+ bin.push(globalThis.String.fromCharCode(byte));
2346
+ });
2347
+ return globalThis.btoa(bin.join(""));
2348
+ }
2349
+ function isObject(value) {
2350
+ return typeof value === "object" && value !== null;
2351
+ }
2352
+ function isSet(value) {
2353
+ return value !== null && value !== void 0;
4234
2354
  }
4235
2355
  //#endregion
4236
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js
4237
- var VERSION = "2.7.1";
4238
- //#endregion
4239
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/Tracer.js
4240
- /**
4241
- * This class represents a basic tracer.
4242
- */
4243
- var Tracer = class {
4244
- _sampler;
4245
- _generalLimits;
4246
- _spanLimits;
4247
- _idGenerator;
4248
- instrumentationScope;
4249
- _resource;
4250
- _spanProcessor;
4251
- _tracerMetrics;
4252
- /**
4253
- * Constructs a new Tracer instance.
4254
- */
4255
- constructor(instrumentationScope, config, resource, spanProcessor) {
4256
- const localConfig = mergeConfig(config);
4257
- this._sampler = localConfig.sampler;
4258
- this._generalLimits = localConfig.generalLimits;
4259
- this._spanLimits = localConfig.spanLimits;
4260
- this._idGenerator = config.idGenerator || new RandomIdGenerator();
4261
- this._resource = resource;
4262
- this._spanProcessor = spanProcessor;
4263
- this.instrumentationScope = instrumentationScope;
4264
- const meter = localConfig.meterProvider ? localConfig.meterProvider.getMeter("@opentelemetry/sdk-trace", VERSION) : createNoopMeter();
4265
- this._tracerMetrics = new TracerMetrics(meter);
4266
- }
4267
- /**
4268
- * Starts a new Span or returns the default NoopSpan based on the sampling
4269
- * decision.
4270
- */
4271
- startSpan(name, options = {}, context$1 = context.active()) {
4272
- if (options.root) context$1 = trace.deleteSpan(context$1);
4273
- const parentSpan = trace.getSpan(context$1);
4274
- if (isTracingSuppressed(context$1)) {
4275
- diag$1.debug("Instrumentation suppressed, returning Noop Span");
4276
- return trace.wrapSpanContext(INVALID_SPAN_CONTEXT);
4277
- }
4278
- const parentSpanContext = parentSpan?.spanContext();
4279
- const spanId = this._idGenerator.generateSpanId();
4280
- let validParentSpanContext;
4281
- let traceId;
4282
- let traceState;
4283
- if (!parentSpanContext || !trace.isSpanContextValid(parentSpanContext)) traceId = this._idGenerator.generateTraceId();
4284
- else {
4285
- traceId = parentSpanContext.traceId;
4286
- traceState = parentSpanContext.traceState;
4287
- validParentSpanContext = parentSpanContext;
4288
- }
4289
- const spanKind = options.kind ?? SpanKind.INTERNAL;
4290
- const links = (options.links ?? []).map((link) => {
4291
- return {
4292
- context: link.context,
4293
- attributes: sanitizeAttributes(link.attributes)
4294
- };
4295
- });
4296
- const attributes = sanitizeAttributes(options.attributes);
4297
- const samplingResult = this._sampler.shouldSample(context$1, traceId, name, spanKind, attributes, links);
4298
- const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
4299
- traceState = samplingResult.traceState ?? traceState;
4300
- const spanContext = {
4301
- traceId,
4302
- spanId,
4303
- traceFlags: samplingResult.decision === SamplingDecision$1.RECORD_AND_SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE,
4304
- traceState
4305
- };
4306
- if (samplingResult.decision === SamplingDecision$1.NOT_RECORD) {
4307
- diag$1.debug("Recording is off, propagating context in a non-recording span");
4308
- return trace.wrapSpanContext(spanContext);
4309
- }
4310
- const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
4311
- return new SpanImpl({
4312
- resource: this._resource,
4313
- scope: this.instrumentationScope,
4314
- context: context$1,
4315
- spanContext,
4316
- name,
4317
- kind: spanKind,
4318
- links,
4319
- parentSpanContext: validParentSpanContext,
4320
- attributes: initAttributes,
4321
- startTime: options.startTime,
4322
- spanProcessor: this._spanProcessor,
4323
- spanLimits: this._spanLimits,
4324
- recordEndMetrics
4325
- });
2356
+ //#region core/avatarViewRegistry.ts
2357
+ var AvatarViewRegistry = class {
2358
+ entries = /* @__PURE__ */ new Set();
2359
+ register(view) {
2360
+ this.entries.add(new WeakRef(view));
4326
2361
  }
4327
- startActiveSpan(name, arg2, arg3, arg4) {
4328
- let opts;
4329
- let ctx;
4330
- let fn;
4331
- if (arguments.length < 2) return;
4332
- else if (arguments.length === 2) fn = arg2;
4333
- else if (arguments.length === 3) {
4334
- opts = arg2;
4335
- fn = arg3;
4336
- } else {
4337
- opts = arg2;
4338
- ctx = arg3;
4339
- fn = arg4;
2362
+ unregister(view) {
2363
+ for (const ref of this.entries) if (ref.deref() === view) {
2364
+ this.entries.delete(ref);
2365
+ return;
4340
2366
  }
4341
- const parentContext = ctx ?? context.active();
4342
- const span = this.startSpan(name, opts, parentContext);
4343
- const contextWithSpanSet = trace.setSpan(parentContext, span);
4344
- return context.with(contextWithSpanSet, fn, void 0, span);
4345
- }
4346
- /** Returns the active {@link GeneralLimits}. */
4347
- getGeneralLimits() {
4348
- return this._generalLimits;
4349
- }
4350
- /** Returns the active {@link SpanLimits}. */
4351
- getSpanLimits() {
4352
- return this._spanLimits;
4353
- }
4354
- };
4355
- //#endregion
4356
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/MultiSpanProcessor.js
4357
- /**
4358
- * Implementation of the {@link SpanProcessor} that simply forwards all
4359
- * received events to a list of {@link SpanProcessor}s.
4360
- */
4361
- var MultiSpanProcessor = class {
4362
- _spanProcessors;
4363
- constructor(spanProcessors) {
4364
- this._spanProcessors = spanProcessors;
4365
- }
4366
- forceFlush() {
4367
- const promises = [];
4368
- for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.forceFlush());
4369
- return new Promise((resolve) => {
4370
- Promise.all(promises).then(() => {
4371
- resolve();
4372
- }).catch((error) => {
4373
- globalErrorHandler(error || /* @__PURE__ */ new Error("MultiSpanProcessor: forceFlush failed"));
4374
- resolve();
4375
- });
4376
- });
4377
- }
4378
- onStart(span, context) {
4379
- for (const spanProcessor of this._spanProcessors) spanProcessor.onStart(span, context);
4380
- }
4381
- onEnding(span) {
4382
- for (const spanProcessor of this._spanProcessors) if (spanProcessor.onEnding) spanProcessor.onEnding(span);
4383
- }
4384
- onEnd(span) {
4385
- for (const spanProcessor of this._spanProcessors) spanProcessor.onEnd(span);
4386
2367
  }
4387
- shutdown() {
4388
- const promises = [];
4389
- for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.shutdown());
4390
- return new Promise((resolve, reject) => {
4391
- Promise.all(promises).then(() => {
4392
- resolve();
4393
- }, reject);
4394
- });
4395
- }
4396
- };
4397
- //#endregion
4398
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/esm/BasicTracerProvider.js
4399
- var ForceFlushState;
4400
- (function(ForceFlushState) {
4401
- ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
4402
- ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
4403
- ForceFlushState[ForceFlushState["error"] = 2] = "error";
4404
- ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
4405
- })(ForceFlushState || (ForceFlushState = {}));
4406
- /**
4407
- * This class represents a basic tracer provider which platform libraries can extend
4408
- */
4409
- var BasicTracerProvider = class {
4410
- _config;
4411
- _tracers = /* @__PURE__ */ new Map();
4412
- _resource;
4413
- _activeSpanProcessor;
4414
- constructor(config = {}) {
4415
- const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
4416
- this._resource = mergedConfig.resource ?? defaultResource();
4417
- this._config = Object.assign({}, mergedConfig, { resource: this._resource });
4418
- const spanProcessors = [];
4419
- if (config.spanProcessors?.length) spanProcessors.push(...config.spanProcessors);
4420
- this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
4421
- }
4422
- getTracer(name, version, options) {
4423
- const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`;
4424
- if (!this._tracers.has(key)) this._tracers.set(key, new Tracer({
4425
- name,
4426
- version,
4427
- schemaUrl: options?.schemaUrl
4428
- }, this._config, this._resource, this._activeSpanProcessor));
4429
- return this._tracers.get(key);
4430
- }
4431
- forceFlush() {
4432
- const timeout = this._config.forceFlushTimeoutMillis;
4433
- const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
4434
- return new Promise((resolve) => {
4435
- let state;
4436
- const timeoutInterval = setTimeout(() => {
4437
- resolve(/* @__PURE__ */ new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
4438
- state = ForceFlushState.timeout;
4439
- }, timeout);
4440
- spanProcessor.forceFlush().then(() => {
4441
- clearTimeout(timeoutInterval);
4442
- if (state !== ForceFlushState.timeout) {
4443
- state = ForceFlushState.resolved;
4444
- resolve(state);
4445
- }
4446
- }).catch((error) => {
4447
- clearTimeout(timeoutInterval);
4448
- state = ForceFlushState.error;
4449
- resolve(error);
4450
- });
4451
- });
4452
- });
4453
- return new Promise((resolve, reject) => {
4454
- Promise.all(promises).then((results) => {
4455
- const errors = results.filter((result) => result !== ForceFlushState.resolved);
4456
- if (errors.length > 0) reject(errors);
4457
- else resolve();
4458
- }).catch((error) => reject([error]));
4459
- });
4460
- }
4461
- shutdown() {
4462
- return this._activeSpanProcessor.shutdown();
4463
- }
4464
- };
4465
- //#endregion
4466
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-web@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-web/build/esm/StackContextManager.js
4467
- /**
4468
- * Stack Context Manager for managing the state in web
4469
- * it doesn't fully support the async calls though
4470
- */
4471
- var StackContextManager = class {
4472
- /**
4473
- * whether the context manager is enabled or not
4474
- */
4475
- _enabled = false;
4476
- /**
4477
- * Keeps the reference to current context
4478
- */
4479
- _currentContext = ROOT_CONTEXT;
4480
- /**
4481
- *
4482
- * @param context
4483
- * @param target Function to be executed within the context
4484
- */
4485
- _bindFunction(context = ROOT_CONTEXT, target) {
4486
- const manager = this;
4487
- const contextWrapper = function(...args) {
4488
- return manager.with(context, () => target.apply(this, args));
4489
- };
4490
- Object.defineProperty(contextWrapper, "length", {
4491
- enumerable: false,
4492
- configurable: true,
4493
- writable: false,
4494
- value: target.length
4495
- });
4496
- return contextWrapper;
4497
- }
4498
- /**
4499
- * Returns the active context
4500
- */
4501
- active() {
4502
- return this._currentContext;
4503
- }
4504
- /**
4505
- * Binds a the certain context or the active one to the target function and then returns the target
4506
- * @param context A context (span) to be bind to target
4507
- * @param target a function or event emitter. When target or one of its callbacks is called,
4508
- * the provided context will be used as the active context for the duration of the call.
4509
- */
4510
- bind(context, target) {
4511
- if (context === void 0) context = this.active();
4512
- if (typeof target === "function") return this._bindFunction(context, target);
4513
- return target;
4514
- }
4515
- /**
4516
- * Disable the context manager (clears the current context)
4517
- */
4518
- disable() {
4519
- this._currentContext = ROOT_CONTEXT;
4520
- this._enabled = false;
4521
- return this;
4522
- }
4523
- /**
4524
- * Enables the context manager and creates a default(root) context
4525
- */
4526
- enable() {
4527
- if (this._enabled) return this;
4528
- this._enabled = true;
4529
- this._currentContext = ROOT_CONTEXT;
4530
- return this;
4531
- }
4532
- /**
4533
- * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.
4534
- * The context will be set as active
4535
- * @param context
4536
- * @param fn Callback function
4537
- * @param thisArg optional receiver to be used for calling fn
4538
- * @param args optional arguments forwarded to fn
4539
- */
4540
- with(context, fn, thisArg, ...args) {
4541
- const previousContext = this._currentContext;
4542
- this._currentContext = context || ROOT_CONTEXT;
4543
- try {
4544
- return fn.call(thisArg, ...args);
4545
- } finally {
4546
- this._currentContext = previousContext;
2368
+ applyResolutionCapToAll() {
2369
+ for (const ref of this.entries) {
2370
+ const view = ref.deref();
2371
+ if (view) view.applyResolutionCapFromSdk();
2372
+ else this.entries.delete(ref);
4547
2373
  }
4548
2374
  }
4549
2375
  };
2376
+ var avatarViewRegistry = new AvatarViewRegistry();
4550
2377
  //#endregion
4551
- //#region node_modules/.pnpm/@opentelemetry+sdk-trace-web@2.7.1_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-web/build/esm/WebTracerProvider.js
4552
- function setupContextManager(contextManager) {
4553
- if (contextManager === null) return;
4554
- if (contextManager === void 0) {
4555
- const defaultContextManager = new StackContextManager();
4556
- defaultContextManager.enable();
4557
- context.setGlobalContextManager(defaultContextManager);
4558
- return;
4559
- }
4560
- contextManager.enable();
4561
- context.setGlobalContextManager(contextManager);
4562
- }
4563
- function setupPropagator(propagator) {
4564
- if (propagator === null) return;
4565
- if (propagator === void 0) {
4566
- propagation.setGlobalPropagator(new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }));
4567
- return;
4568
- }
4569
- propagation.setGlobalPropagator(propagator);
4570
- }
4571
- /**
4572
- * This class represents a web tracer with {@link StackContextManager}
4573
- */
4574
- var WebTracerProvider = class extends BasicTracerProvider {
4575
- /**
4576
- * Constructs a new Tracer instance.
4577
- * @param config Web Tracer config
4578
- */
4579
- constructor(config = {}) {
4580
- super(config);
4581
- }
4582
- /**
4583
- * Register this TracerProvider for use with the OpenTelemetry API.
4584
- * Undefined values may be replaced with defaults, and
4585
- * null values will be skipped.
4586
- *
4587
- * @param config Configuration object for SDK registration
4588
- */
4589
- register(config = {}) {
4590
- trace.setGlobalTracerProvider(this);
4591
- setupPropagator(config.propagator);
4592
- setupContextManager(config.contextManager);
4593
- }
4594
- };
4595
- //#endregion
4596
- //#region node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.218.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/esm/platform/browser/OTLPTraceExporter.js
4597
- /**
4598
- * Collector Trace Exporter for Web
4599
- */
4600
- var OTLPTraceExporter = class extends OTLPExporterBase {
4601
- constructor(config = {}) {
4602
- super(createLegacyOtlpBrowserExportDelegate(config, JsonTraceSerializer, "v1/traces", { "Content-Type": "application/json" }));
4603
- }
4604
- };
4605
- //#endregion
4606
- //#region utils/trace-id.ts
2378
+ //#region utils/region-resolver.ts
4607
2379
  /**
4608
- * W3C trace-id / traceparent derivation for the driving-service upstream.
2380
+ * Region 解析(区域自动调度)—— stale-while-revalidate
4609
2381
  *
4610
- * Kept apart from `otel-trace.ts` so it pulls in no `@opentelemetry` packages:
4611
- * the WebSocket client stamps a traceparent on every first audio chunk, and it
4612
- * should not drag the tracer SDK into that path (nor into the unit tests, where
4613
- * the otel-api ESM build does not resolve cleanly).
2382
+ * - region 为具体值(用户手动指定):直接用,跳过调度。
2383
+ * - region 'auto' 且**有缓存**:立即返回缓存值,bootstrap 转后台异步跑、只更新缓存。
2384
+ * - region 'auto' 且**无缓存**(首次启动):同步等 bootstrap,拿到即用并写缓存。
2385
+ * - auto 无缓存且 bootstrap 失败:降级到默认 region(us-west),并上报一条 error 埋点
2386
+ * (严重事件,供监控观测),不阻断初始化。
4614
2387
  *
4615
- * @internal
4616
- */
4617
- /**
4618
- * 把 conversation_id 确定性映射成合法的 W3C trace_id(16 字节 / 32 位十六进制)。
2388
+ * 为什么缓存优先:bootstrap 是一次网络往返,此前每次 init 都要等它(弱网下最多 5s
2389
+ * 超时)才能继续。实际上用户的接入区极少变动,用上次结果几乎总是对的。
4619
2390
  *
4620
- * W3C/OTel 规定 trace_id 必须是 32 hex,而 conversation_id(形如
4621
- * `20260718110509_4xz9iyH8F3Gi`)不是合法格式,不能直接用。这里用 FNV-1a 4 个不同
4622
- * 初始种子各算一个 32bit 哈希,拼成 128bit —— 同步、确定性(同一 conversation_id 永远
4623
- * 得同一 trace_id)、无外部依赖,后端可用同一算法复现以串成同一条 trace。
4624
- * @internal
4625
- */
4626
- /** FNV-1a 32-bit with a variable seed, so one string yields several independent hashes. */
4627
- function fnv1a(str, seed) {
4628
- let h = seed >>> 0;
4629
- for (let i = 0; i < str.length; i++) {
4630
- h ^= str.charCodeAt(i);
4631
- h = Math.imul(h, 16777619) >>> 0;
4632
- }
4633
- return h >>> 0;
4634
- }
4635
- function conversationIdToTraceId(conversationId) {
4636
- const seeds = [
4637
- 2166136261,
4638
- 16777619,
4639
- 3735928559,
4640
- 2654435769
4641
- ];
4642
- let hex = "";
4643
- for (const s of seeds) hex += fnv1a(conversationId, s).toString(16).padStart(8, "0");
4644
- return /^0+$/.test(hex) ? "0".repeat(31) + "1" : hex;
4645
- }
4646
- /**
4647
- * Derive the driven.request span_id (8 bytes / 16 hex) deterministically from
4648
- * the conversation_id.
2391
+ * **后台刷新到的新值不影响本次会话**,只写缓存、下次启动生效。会话中途换接入域名
2392
+ * 会让已建立的 WS / 下到一半的资产指向另一个接入点,风险远大于「晚一次启动才切区」。
4649
2393
  *
4650
- * The server needs traceparent's parent span_id on the FIRST ClientAudioInput —
4651
- * before the SDK has built the driven.request span, which only happens when
4652
- * playback ends and the timeline is known. Deriving it means both moments can
4653
- * compute the same span_id independently, so the traceparent the server sees and
4654
- * the span the SDK later reports carry the identical id, with no state threaded
4655
- * between "audio sent" and "playback ended". Uses seeds distinct from the
4656
- * trace_id ones so the span_id is not a slice of the trace_id.
2394
+ * 与时钟校准(clock-sync)解耦:各自独立调 bootstrap,互不影响。
4657
2395
  * @internal
4658
2396
  */
4659
- function conversationIdToDrivenSpanId(conversationId) {
4660
- const hex = fnv1a(conversationId, 3421674724).toString(16).padStart(8, "0") + fnv1a(conversationId, 4294967297).toString(16).padStart(8, "0");
4661
- return /^0+$/.test(hex) ? "0".repeat(15) + "1" : hex;
4662
- }
4663
- /**
4664
- * Monotonic counter mixed into every generated id. performance.now() barely moves
4665
- * between spans built in the same millisecond, so on its own it produced COLLIDING
4666
- * span ids (several recv spans shared one id, breaking the trace tree). The counter
4667
- * guarantees a distinct seed per call and per hex chunk.
4668
- */
4669
- var idCounter = 0;
4670
- /** A random lowercase-hex string of `len` chars, non-zero. Not for ids that must be reproducible. */
4671
- function randomHex(len) {
4672
- let out = "";
4673
- while (out.length < len) {
4674
- idCounter = idCounter + 1 >>> 0;
4675
- const seed = ((performance.now() * 1e6 | 0) ^ Math.imul(idCounter, 2654435769)) >>> 0;
4676
- const n = Math.imul(seed, 2246822507) >>> 0;
4677
- out += n.toString(16).padStart(8, "0");
4678
- }
4679
- const hex = out.slice(0, len);
4680
- return /^0+$/.test(hex) ? "0".repeat(len - 1) + "1" : hex;
2397
+ /** region 解析请求超时 */
2398
+ var RESOLVE_TIMEOUT_MS = 5e3;
2399
+ /** 缓存上次成功解析的具体 region localStorage key,供后续降级复用。 */
2400
+ var CACHE_KEY = "avatarkit_cached_region";
2401
+ /** 写缓存:成功解析出具体 region 时存下,供以后失败时降级复用。localStorage 不可用时静默跳过。 */
2402
+ function writeRegionCache(region) {
2403
+ try {
2404
+ if (typeof localStorage !== "undefined") localStorage.setItem(CACHE_KEY, region);
2405
+ } catch {}
4681
2406
  }
4682
- /**
4683
- * OTel IdGenerator that lets one span be given a specific id — the officially
4684
- * supported way to control a span_id, versus reaching into span internals.
4685
- *
4686
- * driven.request must carry the exact span_id already placed in the first
4687
- * ClientAudioInput's traceparent, so the server's audio.process (parent = that
4688
- * id) hangs under the SDK's real span. Set `nextSpanId` right before startSpan;
4689
- * the generator hands it out once, then falls back to random for every other
4690
- * span (whose ids need not be predictable).
4691
- *
4692
- * Deliberately dependency-free (no `implements IdGenerator`) so this module pulls
4693
- * in no @opentelemetry package; it duck-types the two-method interface.
4694
- * @internal
4695
- */
4696
- var PinnableIdGenerator = class {
4697
- nextSpanId = null;
4698
- generateTraceId() {
4699
- return randomHex(32);
4700
- }
4701
- generateSpanId() {
4702
- if (this.nextSpanId) {
4703
- const id = this.nextSpanId;
4704
- this.nextSpanId = null;
4705
- return id;
4706
- }
4707
- return randomHex(16);
2407
+ /** 读缓存:返回上次成功解析的 region,无则 null。 */
2408
+ function readRegionCache() {
2409
+ try {
2410
+ if (typeof localStorage === "undefined") return null;
2411
+ const v = localStorage.getItem(CACHE_KEY);
2412
+ return v && v.length > 0 ? v : null;
2413
+ } catch {
2414
+ return null;
4708
2415
  }
4709
- };
4710
- /**
4711
- * Build the W3C `traceparent` for a conversation's upstream audio, to hand the
4712
- * driving service on the first ClientAudioInput of each req_id so its trace
4713
- * continues this SDK's rather than starting a fresh root.
4714
- *
4715
- * Both ids are DERIVED from the conversation_id, matching what the playback
4716
- * trace builds when it ends: the trace_id so the server's trace and the SDK's
4717
- * spans share one trace, and the span_id so it equals the driven.request span's
4718
- * id — which the server hangs audio.process under. Deriving both means the
4719
- * traceparent sent now and the span reported later carry the identical ids with
4720
- * no state threaded between them.
4721
- *
4722
- * Returns null when tracing is disabled or filtered, so callers simply omit the
4723
- * field — matching the proto's "absent → server starts a new root" contract.
4724
- *
4725
- * @internal
4726
- */
4727
- function buildTraceparent(conversationId) {
4728
- if (!conversationId) return null;
4729
- return `00-${conversationIdToTraceId(conversationId)}-${conversationIdToDrivenSpanId(conversationId)}-01`;
4730
2416
  }
4731
- //#endregion
4732
- //#region utils/otel-trace.ts
4733
2417
  /**
4734
- * OpenTelemetry Trace Tracker (Browser Version)
2418
+ * 后台刷新 region 缓存:缓存命中时发起,**结果只写缓存、不影响本次会话**(见文件头)。
4735
2419
  *
4736
- * 独立于 logs / metrics 的第三条 OTel 通道——**Trace 信号**(OTLP `/v1/traces`),
4737
- * 目标后端 OpenObserve。与另两条通道分离:各自 provider、各自 exporter、各自清理。
4738
- *
4739
- * 用途:一轮播放 = 一条 trace。root span 覆盖整轮,子 span 标记关键时刻
4740
- * (首包音频到达 / 首组动画到达 / 播放结束)。trace_id 由 conversation_id 确定性
4741
- * 派生(见 conversationIdToTraceId),使 SDK 与后端能以同一 conversation_id 关联/串联。
4742
- * @internal
4743
- */
4744
- var OTEL_TRACER_NAME = "spatius-avatarkit";
4745
- var sdkVersion = "1.0.0";
4746
- var isInitialized = false;
4747
- var tracerProvider = null;
4748
- var tracer = null;
4749
- var idGenerator = new PinnableIdGenerator();
4750
- function buildBasicAuthHeader() {
4751
- const credentials = `${OTEL_USERNAME}:${OTEL_PASSWORD}`;
4752
- return `Basic ${btoa(credentials)}`;
4753
- }
4754
- /**
4755
- * Initialize OTel TracerProvider.
4756
- * 与 logs / metrics 平行:同一份 resource 语义、同一套门禁与鉴权。
2420
+ * 失败一律静默:本次会话已经拿着缓存值正常跑了,这条刷新失败不构成用户可见问题,
2421
+ * error 埋点只会污染 `region_resolve_failed` 的告警语义(那条是「真的没 region 可用」)。
4757
2422
  * @internal
4758
2423
  */
4759
- function initializeOtelTrace(version, resourceAttrs) {
4760
- if (isInitialized) {
4761
- logger.log("[OTel-Trace] Already initialized, skipping");
4762
- return;
4763
- }
4764
- if ("wangruizhen@spatialwalk.net".startsWith("<TODO"), "spatialwalk".startsWith("<TODO"));
4765
- sdkVersion = version;
2424
+ async function refreshRegionCache(opts) {
2425
+ const controller = new AbortController();
2426
+ const timer = setTimeout(() => controller.abort(), RESOLVE_TIMEOUT_MS);
4766
2427
  try {
4767
- tracerProvider = new WebTracerProvider({
4768
- resource: resourceFromAttributes({
4769
- [ATTR_SERVICE_NAME]: "avatarkit",
4770
- "sdk.version": sdkVersion,
4771
- "sdk.platform": "web",
4772
- "sdk.package": "spatius-web-sdk",
4773
- "app_id": resourceAttrs.appId || "",
4774
- "region": resourceAttrs.region,
4775
- "dsm": resourceAttrs.dsm,
4776
- ...clientContextFields()
4777
- }),
4778
- spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({
4779
- url: OTEL_TRACES_ENDPOINT,
4780
- headers: {
4781
- "Authorization": buildBasicAuthHeader(),
4782
- "stream-name": OTEL_TRACES_STREAM_NAME
4783
- }
4784
- }))],
4785
- idGenerator
4786
- });
4787
- trace.setGlobalTracerProvider(tracerProvider);
4788
- tracer = trace.getTracer(OTEL_TRACER_NAME, sdkVersion);
4789
- isInitialized = true;
4790
- logger.log(`[OTel-Trace] Initialized - endpoint: ${OTEL_TRACES_ENDPOINT}, stream: ${OTEL_TRACES_STREAM_NAME}`);
2428
+ const current = (await fetchBootstrap({
2429
+ appId: opts.appId,
2430
+ sdkVersion: opts.sdkVersion,
2431
+ region: "auto"
2432
+ }, controller.signal)).region?.current;
2433
+ if (typeof current === "string" && current.length > 0) {
2434
+ writeRegionCache(current);
2435
+ logger.log(`[RegionResolver] background refresh → ${current} (applies next launch)`);
2436
+ }
4791
2437
  } catch (error) {
4792
- logger.warn("[OTel-Trace] Failed to initialize:", error instanceof Error ? error.message : String(error));
2438
+ logger.log(`[RegionResolver] background refresh failed (cached value stays): ${error instanceof Error ? error.message : String(error)}`);
2439
+ } finally {
2440
+ clearTimeout(timer);
4793
2441
  }
4794
2442
  }
4795
- /** 空实现:未初始化 / 被门禁拦截时返回,调用方无需判空。 */
4796
- var NOOP_GROUP = {
4797
- span: () => {},
4798
- end: () => {}
4799
- };
4800
- var NOOP_TRACE = {
4801
- span: () => {},
4802
- group: () => NOOP_GROUP,
4803
- end: () => {}
4804
- };
4805
2443
  /**
4806
- * 开一条播放 trace。root span 名 `playback`,trace_id 由 conversation_id 确定性派生,
4807
- * conversation_id 同时作为 span 属性(无论是否与后端串成一条 trace,都能按它关联查询)。
4808
- * @param startTimeMs root span 起点(首包音频 tap_0 的真实时刻,epoch ms);省略则用当前时刻。
2444
+ * 把请求的 region 解析成实际接入 region。
2445
+ * @param requestedRegion 用户传入的 region('auto' 或具体值)
2446
+ * @returns 实际接入 region(always a concrete value,不会是 'auto')
4809
2447
  * @internal
4810
2448
  */
4811
- function startPlaybackTrace(conversationId, startTimeMs, attrs = {}) {
4812
- if (!tracer || !tracerProvider) return NOOP_TRACE;
4813
- if (!conversationId) return NOOP_TRACE;
4814
- try {
4815
- const traceId = conversationIdToTraceId(conversationId);
4816
- const drivenSpanId = conversationIdToDrivenSpanId(conversationId);
4817
- const traceRootCtx = trace.setSpanContext(ROOT_CONTEXT, {
4818
- traceId,
4819
- spanId: randomHex(16),
4820
- traceFlags: 1,
4821
- isRemote: true
2449
+ async function resolveRegion(opts) {
2450
+ const { appId, sdkVersion, requestedRegion } = opts;
2451
+ if (requestedRegion !== "auto") return requestedRegion;
2452
+ const cachedRegion = readRegionCache();
2453
+ if (cachedRegion !== null) {
2454
+ logger.log(`[RegionResolver] auto ${cachedRegion} (cached, refreshing in background)`);
2455
+ refreshRegionCache({
2456
+ appId,
2457
+ sdkVersion
4822
2458
  });
4823
- idGenerator.nextSpanId = drivenSpanId;
4824
- const drivenRequest = tracer.startSpan("driven.request", {
4825
- attributes: {
4826
- conversation_id: conversationId,
4827
- ...attrs
4828
- },
4829
- ...typeof startTimeMs === "number" ? { startTime: startTimeMs } : {}
4830
- }, traceRootCtx);
4831
- const drivenCtx = trace.setSpan(traceRootCtx, drivenRequest);
4832
- const root = tracer.startSpan("playback", {
4833
- attributes: {
4834
- conversation_id: conversationId,
4835
- ...attrs
4836
- },
4837
- ...typeof startTimeMs === "number" ? { startTime: startTimeMs } : {}
4838
- }, drivenCtx);
4839
- const rootCtx = trace.setSpan(drivenCtx, root);
4840
- const emitSpan = (ctx, name, startMs, endMs, attrs, isError = false) => {
4841
- try {
4842
- const s = tracer.startSpan(name, {
4843
- attributes: attrs,
4844
- startTime: startMs
4845
- }, ctx);
4846
- if (isError) s.setStatus({ code: SpanStatusCode.ERROR });
4847
- s.end(endMs);
4848
- } catch {}
4849
- };
4850
- return {
4851
- span(name, startMs, endMs, spanAttrs = {}, isError = false) {
4852
- emitSpan(rootCtx, name, startMs, endMs, spanAttrs, isError);
4853
- },
4854
- group(name, startMs, groupAttrs = {}) {
4855
- try {
4856
- const container = tracer.startSpan(name, {
4857
- attributes: groupAttrs,
4858
- startTime: startMs
4859
- }, rootCtx);
4860
- const groupCtx = trace.setSpan(rootCtx, container);
4861
- return {
4862
- span(spanName, s, e, attrs = {}, isError = false) {
4863
- emitSpan(groupCtx, spanName, s, e, attrs, isError);
4864
- },
4865
- end(endMs) {
4866
- try {
4867
- container.end(endMs);
4868
- } catch {}
4869
- }
4870
- };
4871
- } catch {
4872
- return NOOP_GROUP;
4873
- }
4874
- },
4875
- end(ok = true, endTimeMs, endAttrs = {}) {
4876
- try {
4877
- for (const [k, v] of Object.entries(endAttrs)) root.setAttribute(k, v);
4878
- const status = { code: ok ? SpanStatusCode.OK : SpanStatusCode.ERROR };
4879
- root.setStatus(status);
4880
- root.end(endTimeMs);
4881
- drivenRequest.setStatus(status);
4882
- drivenRequest.end(endTimeMs);
4883
- tracerProvider?.forceFlush().catch(() => {});
4884
- } catch {}
4885
- }
4886
- };
4887
- } catch (error) {
4888
- logger.warn("[OTel-Trace] Failed to start playback trace:", error instanceof Error ? error.message : String(error));
4889
- return NOOP_TRACE;
2459
+ return cachedRegion;
4890
2460
  }
4891
- }
4892
- /**
4893
- * Cleanup:flush 剩余 span 并关闭 provider。
4894
- * @internal
4895
- */
4896
- function cleanupOtelTrace() {
4897
- if (!isInitialized || !tracerProvider) return;
2461
+ const controller = new AbortController();
2462
+ const timer = setTimeout(() => controller.abort(), RESOLVE_TIMEOUT_MS);
4898
2463
  try {
4899
- tracerProvider.forceFlush().catch(() => {});
4900
- tracerProvider.shutdown().catch((error) => {
4901
- logger.warn("[OTel-Trace] Shutdown error:", error instanceof Error ? error.message : String(error));
4902
- });
2464
+ const current = (await fetchBootstrap({
2465
+ appId,
2466
+ sdkVersion,
2467
+ region: "auto"
2468
+ }, controller.signal)).region?.current;
2469
+ if (typeof current === "string" && current.length > 0) {
2470
+ writeRegionCache(current);
2471
+ logger.log(`[RegionResolver] auto → ${current}`);
2472
+ return current;
2473
+ }
2474
+ throw new Error("bootstrap response missing region.current");
4903
2475
  } catch (error) {
4904
- logger.warn("[OTel-Trace] Failed to cleanup:", error instanceof Error ? error.message : String(error));
2476
+ const message = error instanceof Error ? error.message : String(error);
2477
+ const cached = readRegionCache();
2478
+ const fallback = cached ?? "us-west";
2479
+ logger.warn(`[RegionResolver] auto resolve failed, falling back to ${fallback} (from_cache=${cached !== null}): ${message}`);
2480
+ logEvent("region_resolve_failed", "error", {
2481
+ fallback_region: fallback,
2482
+ from_cache: cached !== null,
2483
+ reason: message
2484
+ });
2485
+ return fallback;
4905
2486
  } finally {
4906
- isInitialized = false;
4907
- tracerProvider = null;
4908
- tracer = null;
2487
+ clearTimeout(timer);
4909
2488
  }
4910
2489
  }
4911
2490
  //#endregion
@@ -6321,7 +3900,7 @@ var AvatarSDK = class {
6321
3900
  static _initializationState = "uninitialized";
6322
3901
  static _initializingPromise = null;
6323
3902
  static _configuration = null;
6324
- static _version = "1.3.1-beta.6";
3903
+ static _version = "1.3.1";
6325
3904
  static _avatarCore = null;
6326
3905
  static _cachedDeviceScore = null;
6327
3906
  static _rendererBackend = null;
@@ -6369,8 +3948,9 @@ var AvatarSDK = class {
6369
3948
  return this._initializingPromise;
6370
3949
  }
6371
3950
  static async _initializeInternal(appId, configuration) {
3951
+ const initStart = Date.now();
3952
+ const requestedRegion = configuration.region || "auto";
6372
3953
  try {
6373
- const requestedRegion = configuration.region || "auto";
6374
3954
  logger.log(`[AvatarSDK] Initializing with appId: ${appId}, region: ${requestedRegion}`);
6375
3955
  resetDeprecationWarnings();
6376
3956
  setLogLevel(configuration.logLevel ?? LogLevel.off);
@@ -6378,6 +3958,7 @@ var AvatarSDK = class {
6378
3958
  logger.log(`[AvatarSDK] Client ID: ${idManager.getClientId()}`);
6379
3959
  const dsm = configuration.drivingServiceMode || DrivingServiceMode.direct;
6380
3960
  const appIdValue = idManager.getAppId() || "";
3961
+ const regionStart = Date.now();
6381
3962
  const region = await resolveRegion({
6382
3963
  appId: appIdValue,
6383
3964
  sdkVersion: this._version,
@@ -6388,8 +3969,8 @@ var AvatarSDK = class {
6388
3969
  region
6389
3970
  };
6390
3971
  const af = this._configuration.audioFormat;
6391
- if (af?.opusUplinkEnabled === true && af.inputAudioFormat !== "opus" && !OPUS_UPLINK_SAMPLE_RATES.includes(af.sampleRate)) {
6392
- logger.warn(`[AvatarSDK] opusUplinkEnabled=true but sampleRate=${af.sampleRate} is not Opus-compatible (supported: ${OPUS_UPLINK_SAMPLE_RATES}); disabling Opus uplink, sending raw PCM.`);
3972
+ if (af && af.opusUplinkEnabled !== false && af.inputAudioFormat !== "opus" && !OPUS_UPLINK_SAMPLE_RATES.includes(af.sampleRate)) {
3973
+ logger.warn(`[AvatarSDK] Opus uplink is on but sampleRate=${af.sampleRate} is not Opus-compatible (supported: ${OPUS_UPLINK_SAMPLE_RATES}); disabling Opus uplink, sending raw PCM.`);
6393
3974
  this._configuration = {
6394
3975
  ...this._configuration,
6395
3976
  audioFormat: {
@@ -6402,6 +3983,7 @@ var AvatarSDK = class {
6402
3983
  supported_rates: OPUS_UPLINK_SAMPLE_RATES.join(",")
6403
3984
  });
6404
3985
  }
3986
+ const regionEnd = Date.now();
6405
3987
  initializePostHog(this._version, {
6406
3988
  region,
6407
3989
  dsm
@@ -6425,9 +4007,22 @@ var AvatarSDK = class {
6425
4007
  appId: appIdValue,
6426
4008
  sdkVersion: this._version
6427
4009
  });
4010
+ const wasmStart = Date.now();
6428
4011
  await this.initializeWASMModule();
4012
+ const templateStart = Date.now();
6429
4013
  await this.initializeTemplateResources();
6430
4014
  this._initializationState = "initialized";
4015
+ const initEnd = Date.now();
4016
+ const initTrace = startInitTrace(idManager.getSessionId(), initStart, {
4017
+ region,
4018
+ dsm
4019
+ });
4020
+ initTrace.span("prepare", initStart, regionStart);
4021
+ initTrace.span("resolve_region", regionStart, regionEnd);
4022
+ initTrace.span("init_telemetry", regionEnd, wasmStart);
4023
+ initTrace.span("init_wasm", wasmStart, templateStart);
4024
+ initTrace.span("load_template", templateStart, initEnd);
4025
+ initTrace.end(true, initEnd);
6431
4026
  logEvent("sdk_initialized", "info", {});
6432
4027
  logger.log(`[AvatarSDK] Successfully initialized`);
6433
4028
  this._ensureDeviceScoreCached();
@@ -6436,6 +4031,13 @@ var AvatarSDK = class {
6436
4031
  }, 0);
6437
4032
  } catch (error) {
6438
4033
  const errorMessage = error instanceof Error ? error.message : String(error);
4034
+ try {
4035
+ const failEnd = Date.now();
4036
+ startInitTrace(idManager.getSessionId(), initStart, {
4037
+ region: requestedRegion,
4038
+ dsm: configuration.drivingServiceMode || DrivingServiceMode.direct
4039
+ }).end(false, failEnd, { error: errorMessage });
4040
+ } catch {}
6439
4041
  logger.error("Failed to initialize AvatarSDK:", errorMessage);
6440
4042
  logEvent("sdk_startup", "error", { reason: errorMessage });
6441
4043
  this._initializationState = "uninitialized";
@@ -6487,7 +4089,7 @@ var AvatarSDK = class {
6487
4089
  logger.log("[AvatarSDK] Loading template resources...");
6488
4090
  logEvent("template_init_start", "info", { stage: "sdk_init" });
6489
4091
  try {
6490
- const { AvatarDownloader } = await import("./AvatarDownloader-Dfi7wtgQ.js").then((n) => n.n);
4092
+ const { AvatarDownloader } = await import("./AvatarDownloader-DyhenPKd.js").then((n) => n.n);
6491
4093
  const templateResources = await new AvatarDownloader().loadUnifiedTemplate();
6492
4094
  if (await this._avatarCore.loadTemplateResourcesFromBuffers(templateResources)) logger.log("[AvatarSDK] Template resources initialized successfully");
6493
4095
  else logger.log("[AvatarSDK] Template resources already initialized, skipping...");
@@ -6795,4 +4397,4 @@ var AvatarSDK = class {
6795
4397
  }
6796
4398
  };
6797
4399
  //#endregion
6798
- export { avatarViewRegistry as a, Message as c, BinaryReader as d, BinaryWriter as f, buildTraceparent as i, MessageType as l, AvatarSDK_exports as n, AudioFormat as o, startPlaybackTrace as r, EgressType as s, AvatarSDK as t, TransportCompression as u };
4400
+ export { EgressType as a, TransportCompression as c, AudioFormat as i, BinaryReader as l, AvatarSDK_exports as n, Message as o, avatarViewRegistry as r, MessageType as s, AvatarSDK as t, BinaryWriter as u };