@cuekit-ai/react 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -181,6 +181,7 @@ function onStateChange() {
181
181
  }
182
182
  }
183
183
  function getElementPath(element3) {
184
+ if (typeof window === "undefined") return "";
184
185
  if (element3.id) {
185
186
  return `id(${element3.id})`;
186
187
  }
@@ -261,6 +262,7 @@ var init_navigation = __esm({
261
262
  }
262
263
  }, 100);
263
264
  });
265
+ if (typeof window === "undefined") return;
264
266
  observer.observe(document.body, { childList: true, subtree: true });
265
267
  };
266
268
  }
@@ -271,11 +273,388 @@ var WEBRTC_BACKEND_SERVER_URL;
271
273
  var init_constants = __esm({
272
274
  "src/constants/index.ts"() {
273
275
  "use strict";
274
- WEBRTC_BACKEND_SERVER_URL = "https://api-webrtc-dev.cuekit.ai";
276
+ WEBRTC_BACKEND_SERVER_URL = "https://api-webrtc-dev.ansyr.ai";
277
+ }
278
+ });
279
+
280
+ // src/utils/jsx-encoder.ts
281
+ function generateStableDOMId(element3) {
282
+ const tagName = element3.tagName.toLowerCase();
283
+ const text7 = (element3.textContent || "").trim().substring(0, 50);
284
+ let sibling = element3.previousElementSibling;
285
+ let position3 = 1;
286
+ while (sibling) {
287
+ if (sibling.tagName === element3.tagName) {
288
+ position3++;
289
+ }
290
+ sibling = sibling.previousElementSibling;
291
+ }
292
+ const path2 = getElementPath2(element3);
293
+ const idString = `${tagName}[${position3}]_(${text7})_${path2}`;
294
+ let hash = 0;
295
+ for (let i2 = 0; i2 < idString.length; i2++) {
296
+ const char = idString.charCodeAt(i2);
297
+ hash = (hash << 5) - hash + char;
298
+ hash |= 0;
299
+ }
300
+ return hash.toString(36);
301
+ }
302
+ function getElementPath2(element3) {
303
+ if (element3.id) {
304
+ return `id(${element3.id})`;
305
+ }
306
+ if (element3.tagName.toLowerCase() === "body") {
307
+ return "/body";
308
+ }
309
+ let ix = 0;
310
+ const siblings = element3.parentNode?.children || new HTMLCollection();
311
+ for (let i2 = 0; i2 < siblings.length; i2++) {
312
+ const sibling = siblings[i2];
313
+ if (sibling === element3) {
314
+ return `${getElementPath2(element3.parentNode)}/${element3.tagName}[${ix + 1}]`;
315
+ }
316
+ if (sibling.nodeType === 1 && sibling.tagName === element3.tagName) {
317
+ ix++;
318
+ }
319
+ }
320
+ return "not_found";
321
+ }
322
+ var init_jsx_encoder = __esm({
323
+ "src/utils/jsx-encoder.ts"() {
324
+ "use strict";
325
+ }
326
+ });
327
+
328
+ // src/utils/element-service.ts
329
+ function getInteractiveElements() {
330
+ if (typeof document === "undefined") {
331
+ return new class extends Array {
332
+ }();
333
+ }
334
+ return document.querySelectorAll(INTERACTIVE_ELEMENT_SELECTOR);
335
+ }
336
+ function getImmediateText(element3) {
337
+ let text7 = "";
338
+ if (element3.childNodes) {
339
+ for (const node2 of Array.from(element3.childNodes)) {
340
+ if (node2.nodeType === 3) {
341
+ text7 += node2.textContent || "";
342
+ }
343
+ }
344
+ }
345
+ return text7.trim();
346
+ }
347
+ function captureFullDOMStructure() {
348
+ console.log("\u{1F333} Capturing full DOM structure...");
349
+ const components = [];
350
+ const interactiveElements = getInteractiveElements();
351
+ interactiveElements.forEach((element3) => {
352
+ if (element3 instanceof HTMLElement && !element3.closest("[data-cuekit-ignore]")) {
353
+ const nodeData = buildFlatDOMNode(element3);
354
+ if (nodeData) {
355
+ components.push(nodeData);
356
+ }
357
+ }
358
+ });
359
+ const result = { components };
360
+ console.log("\u{1F333} Full DOM structure captured:", result);
361
+ return result;
362
+ }
363
+ function buildFlatDOMNode(element3) {
364
+ if (element3.tagName.toLowerCase() === "script" || element3.hasAttribute("data-cuekit-ignore") || element3.style.display === "none" || element3.style.visibility === "hidden") {
365
+ return null;
366
+ }
367
+ const hash = generateStableDOMId(element3);
368
+ const text7 = getImmediateText(element3).substring(0, 100);
369
+ const isClickable = isElementClickable(element3);
370
+ const componentType = element3.tagName.toLowerCase();
371
+ return {
372
+ hash,
373
+ text: text7,
374
+ isClickable,
375
+ componentType,
376
+ children: []
377
+ // No children in a flat structure
378
+ };
379
+ }
380
+ function isElementClickable(element3) {
381
+ const interactiveSelectors = [
382
+ "button",
383
+ "a",
384
+ "input",
385
+ "select",
386
+ "textarea",
387
+ '[role="button"]',
388
+ '[role="link"]',
389
+ '[role="tab"]',
390
+ "[data-onclick-id]",
391
+ "[data-on-press-id]",
392
+ "[onclick]",
393
+ "[onmousedown]",
394
+ "[onmouseup]",
395
+ "[ontouchstart]",
396
+ "[ontouchend]",
397
+ "[onkeydown]",
398
+ "[onkeyup]",
399
+ "[onkeypress]"
400
+ ];
401
+ for (const selector of interactiveSelectors) {
402
+ if (element3.matches(selector)) {
403
+ return true;
404
+ }
405
+ }
406
+ const hasClickEvents = element3.onclick !== null || element3.getAttribute("onclick") !== null;
407
+ const hasInteractiveEvents = element3.ontouchstart !== null || element3.getAttribute("ontouchstart") !== null || element3.ontouchend !== null || element3.getAttribute("ontouchend") !== null || element3.onkeydown !== null || element3.getAttribute("onkeydown") !== null || element3.onkeyup !== null || element3.getAttribute("onkeyup") !== null || element3.onkeypress !== null || element3.getAttribute("onkeypress") !== null;
408
+ const hasPointerCursor = element3.style.cursor === "pointer" || getComputedStyle(element3).cursor === "pointer";
409
+ const hasTabIndex = element3.hasAttribute("tabindex") && parseInt(element3.getAttribute("tabindex") || "0") >= 0;
410
+ const hasInteractiveDataAttrs = element3.hasAttribute("data-clickable") || element3.hasAttribute("data-interactive") || element3.hasAttribute("data-action") || element3.hasAttribute("data-handler");
411
+ const hasInteractiveAria = element3.hasAttribute("aria-pressed") || element3.hasAttribute("aria-expanded") || element3.hasAttribute("aria-selected") || element3.hasAttribute("aria-checked");
412
+ return hasClickEvents || hasInteractiveEvents || hasPointerCursor || hasTabIndex || hasInteractiveDataAttrs || hasInteractiveAria;
413
+ }
414
+ function executeAction(action) {
415
+ console.log("\u{1F3AF} Executing element action:", action);
416
+ const { action_type, target_element, target } = action;
417
+ switch (action_type) {
418
+ case "click":
419
+ return clickElement(target_element);
420
+ case "navigate":
421
+ return navigateToElement(target_element || target);
422
+ case "input":
423
+ case "focus":
424
+ return focusElement(target_element);
425
+ case "toggle":
426
+ return toggleElement(target_element);
427
+ default:
428
+ console.warn(`\u26A0\uFE0F Unknown action type: ${action_type}`);
429
+ return false;
430
+ }
431
+ }
432
+ function getFullDOMStructure() {
433
+ console.log("\u{1F333} ElementService: Getting full DOM structure...");
434
+ return captureFullDOMStructure();
435
+ }
436
+ function clickElement(elementId) {
437
+ if (!elementId) {
438
+ console.warn("\u26A0\uFE0F No element ID provided for click action");
439
+ return false;
440
+ }
441
+ const domStructure = getFullDOMStructure();
442
+ const elementToClick = findElementById(domStructure, elementId);
443
+ if (elementToClick) {
444
+ console.log(`\u{1F3AF} Clicking element: ${elementId}`);
445
+ const domElement = findDOMElementById(elementId);
446
+ if (domElement) {
447
+ domElement.click();
448
+ return true;
449
+ }
450
+ } else {
451
+ console.warn(`\u26A0\uFE0F Element not found: ${elementId}`);
452
+ }
453
+ return false;
454
+ }
455
+ function navigateToElement(target) {
456
+ if (!target) {
457
+ console.warn("\u26A0\uFE0F No target provided for navigation action");
458
+ return false;
459
+ }
460
+ console.log(`\u{1F9ED} Navigating to: ${target}`);
461
+ if (target.includes("/") || target.startsWith("http")) {
462
+ safeNavigate(target, {});
463
+ } else {
464
+ handleNavigationAndClick(target, target);
465
+ }
466
+ return true;
467
+ }
468
+ function focusElement(elementId) {
469
+ if (!elementId) {
470
+ console.warn("\u26A0\uFE0F No element ID provided for focus action");
471
+ return false;
472
+ }
473
+ const domElement = findDOMElementById(elementId);
474
+ if (domElement instanceof HTMLInputElement || domElement instanceof HTMLTextAreaElement || domElement instanceof HTMLSelectElement) {
475
+ console.log(`\u{1F4DD} Focusing element: ${elementId}`);
476
+ domElement.focus();
477
+ return true;
478
+ } else {
479
+ console.warn(`\u26A0\uFE0F Focusable element not found: ${elementId}`);
480
+ return false;
481
+ }
482
+ }
483
+ function toggleElement(elementId) {
484
+ if (!elementId) {
485
+ console.warn("\u26A0\uFE0F No element ID provided for toggle action");
486
+ return false;
487
+ }
488
+ const domElement = findDOMElementById(elementId);
489
+ if (domElement instanceof HTMLElement) {
490
+ console.log(`\u{1F504} Toggling element: ${elementId}`);
491
+ if (domElement instanceof HTMLInputElement) {
492
+ if (domElement.type === "checkbox") {
493
+ domElement.checked = !domElement.checked;
494
+ } else if (domElement.type === "radio") {
495
+ domElement.checked = true;
496
+ }
497
+ domElement.dispatchEvent(new Event("change", { bubbles: true }));
498
+ } else {
499
+ domElement.click();
500
+ }
501
+ return true;
502
+ } else {
503
+ console.warn(`\u26A0\uFE0F Toggleable element not found: ${elementId}`);
504
+ return false;
505
+ }
506
+ }
507
+ function findElementById(domStructure, elementId) {
508
+ const searchInComponents = (components) => {
509
+ for (const component of components) {
510
+ if (component.hash === elementId) {
511
+ return component;
512
+ }
513
+ if (component.children.length > 0) {
514
+ const found = searchInComponents(component.children);
515
+ if (found) return found;
516
+ }
517
+ }
518
+ return null;
519
+ };
520
+ return searchInComponents(domStructure.components);
521
+ }
522
+ function findDOMElementById(elementId) {
523
+ const interactiveElements = getInteractiveElements();
524
+ for (const element3 of interactiveElements) {
525
+ if (element3 instanceof HTMLElement) {
526
+ console.log("\u{1F50D} Checking element:", element3);
527
+ const hash = generateStableDOMId(element3);
528
+ console.log("\u{1F50D} Generated hash:", hash);
529
+ if (hash === elementId) {
530
+ console.log("\u{1F50D} Found element:", element3);
531
+ return element3;
532
+ }
533
+ }
534
+ }
535
+ return null;
536
+ }
537
+ var INTERACTIVE_ELEMENT_SELECTOR;
538
+ var init_element_service = __esm({
539
+ "src/utils/element-service.ts"() {
540
+ "use strict";
541
+ init_jsx_encoder();
542
+ init_navigation();
543
+ INTERACTIVE_ELEMENT_SELECTOR = 'a, button, input, textarea, select, [role="button"], [onclick]';
275
544
  }
276
545
  });
277
546
 
278
547
  // node_modules/livekit-client/dist/livekit-client.esm.mjs
548
+ var livekit_client_esm_exports = {};
549
+ __export(livekit_client_esm_exports, {
550
+ AudioPresets: () => AudioPresets,
551
+ BackupCodecPolicy: () => BackupCodecPolicy,
552
+ BaseKeyProvider: () => BaseKeyProvider,
553
+ CheckStatus: () => CheckStatus,
554
+ Checker: () => Checker,
555
+ ConnectionCheck: () => ConnectionCheck,
556
+ ConnectionError: () => ConnectionError,
557
+ ConnectionErrorReason: () => ConnectionErrorReason,
558
+ ConnectionQuality: () => ConnectionQuality,
559
+ ConnectionState: () => ConnectionState,
560
+ CriticalTimers: () => CriticalTimers,
561
+ CryptorError: () => CryptorError,
562
+ CryptorErrorReason: () => CryptorErrorReason,
563
+ CryptorEvent: () => CryptorEvent,
564
+ DataPacket_Kind: () => DataPacket_Kind,
565
+ DefaultReconnectPolicy: () => DefaultReconnectPolicy,
566
+ DeviceUnsupportedError: () => DeviceUnsupportedError,
567
+ DisconnectReason: () => DisconnectReason,
568
+ EncryptionEvent: () => EncryptionEvent,
569
+ EngineEvent: () => EngineEvent,
570
+ ExternalE2EEKeyProvider: () => ExternalE2EEKeyProvider,
571
+ KeyHandlerEvent: () => KeyHandlerEvent,
572
+ KeyProviderEvent: () => KeyProviderEvent,
573
+ LivekitError: () => LivekitError,
574
+ LocalAudioTrack: () => LocalAudioTrack,
575
+ LocalParticipant: () => LocalParticipant,
576
+ LocalTrack: () => LocalTrack,
577
+ LocalTrackPublication: () => LocalTrackPublication,
578
+ LocalTrackRecorder: () => LocalTrackRecorder,
579
+ LocalVideoTrack: () => LocalVideoTrack,
580
+ LogLevel: () => LogLevel,
581
+ LoggerNames: () => LoggerNames,
582
+ MediaDeviceFailure: () => MediaDeviceFailure,
583
+ Mutex: () => _,
584
+ NegotiationError: () => NegotiationError,
585
+ Participant: () => Participant,
586
+ ParticipantEvent: () => ParticipantEvent,
587
+ ParticipantKind: () => ParticipantInfo_Kind,
588
+ PublishDataError: () => PublishDataError,
589
+ PublishTrackError: () => PublishTrackError,
590
+ RemoteAudioTrack: () => RemoteAudioTrack,
591
+ RemoteParticipant: () => RemoteParticipant,
592
+ RemoteTrack: () => RemoteTrack,
593
+ RemoteTrackPublication: () => RemoteTrackPublication,
594
+ RemoteVideoTrack: () => RemoteVideoTrack,
595
+ Room: () => Room,
596
+ RoomEvent: () => RoomEvent,
597
+ RpcError: () => RpcError,
598
+ ScreenSharePresets: () => ScreenSharePresets,
599
+ SignalRequestError: () => SignalRequestError,
600
+ SubscriptionError: () => SubscriptionError,
601
+ Track: () => Track,
602
+ TrackEvent: () => TrackEvent,
603
+ TrackInvalidError: () => TrackInvalidError,
604
+ TrackPublication: () => TrackPublication,
605
+ TrackType: () => TrackType,
606
+ UnexpectedConnectionState: () => UnexpectedConnectionState,
607
+ UnsupportedServer: () => UnsupportedServer,
608
+ VideoPreset: () => VideoPreset,
609
+ VideoPresets: () => VideoPresets,
610
+ VideoPresets43: () => VideoPresets43,
611
+ VideoQuality: () => VideoQuality,
612
+ attachToElement: () => attachToElement,
613
+ attributes: () => attributeTypings,
614
+ compareVersions: () => compareVersions,
615
+ createAudioAnalyser: () => createAudioAnalyser,
616
+ createE2EEKey: () => createE2EEKey,
617
+ createKeyMaterialFromBuffer: () => createKeyMaterialFromBuffer,
618
+ createKeyMaterialFromString: () => createKeyMaterialFromString,
619
+ createLocalAudioTrack: () => createLocalAudioTrack,
620
+ createLocalScreenTracks: () => createLocalScreenTracks,
621
+ createLocalTracks: () => createLocalTracks,
622
+ createLocalVideoTrack: () => createLocalVideoTrack,
623
+ deriveKeys: () => deriveKeys,
624
+ detachTrack: () => detachTrack,
625
+ facingModeFromDeviceLabel: () => facingModeFromDeviceLabel,
626
+ facingModeFromLocalTrack: () => facingModeFromLocalTrack,
627
+ getBrowser: () => getBrowser,
628
+ getEmptyAudioStreamTrack: () => getEmptyAudioStreamTrack,
629
+ getEmptyVideoStreamTrack: () => getEmptyVideoStreamTrack,
630
+ getLogger: () => getLogger,
631
+ importKey: () => importKey,
632
+ isAudioTrack: () => isAudioTrack,
633
+ isBackupCodec: () => isBackupCodec,
634
+ isBrowserSupported: () => isBrowserSupported,
635
+ isE2EESupported: () => isE2EESupported,
636
+ isInsertableStreamSupported: () => isInsertableStreamSupported,
637
+ isLocalParticipant: () => isLocalParticipant,
638
+ isLocalTrack: () => isLocalTrack,
639
+ isRemoteParticipant: () => isRemoteParticipant,
640
+ isRemoteTrack: () => isRemoteTrack,
641
+ isScriptTransformSupported: () => isScriptTransformSupported,
642
+ isVideoFrame: () => isVideoFrame,
643
+ isVideoTrack: () => isVideoTrack,
644
+ needsRbspUnescaping: () => needsRbspUnescaping,
645
+ parseRbsp: () => parseRbsp,
646
+ protocolVersion: () => protocolVersion,
647
+ ratchet: () => ratchet,
648
+ setLogExtension: () => setLogExtension,
649
+ setLogLevel: () => setLogLevel,
650
+ supportsAV1: () => supportsAV1,
651
+ supportsAdaptiveStream: () => supportsAdaptiveStream,
652
+ supportsDynacast: () => supportsDynacast,
653
+ supportsVP9: () => supportsVP9,
654
+ version: () => version,
655
+ videoCodecs: () => videoCodecs,
656
+ writeRbsp: () => writeRbsp
657
+ });
279
658
  function _mergeNamespaces(n, m) {
280
659
  m.forEach(function(e3) {
281
660
  e3 && typeof e3 !== "string" && !Array.isArray(e3) && Object.keys(e3).forEach(function(k2) {
@@ -2300,6 +2679,34 @@ function getLogger(name2) {
2300
2679
  logger.setDefaultLevel(livekitLogger.getLevel());
2301
2680
  return logger;
2302
2681
  }
2682
+ function setLogLevel(level, loggerName) {
2683
+ if (loggerName) {
2684
+ loglevelExports.getLogger(loggerName).setLevel(level);
2685
+ } else {
2686
+ for (const logger of livekitLoggers) {
2687
+ logger.setLevel(level);
2688
+ }
2689
+ }
2690
+ }
2691
+ function setLogExtension(extension2, logger) {
2692
+ const loggers = logger ? [logger] : livekitLoggers;
2693
+ loggers.forEach((logR) => {
2694
+ const originalFactory = logR.methodFactory;
2695
+ logR.methodFactory = (methodName, configLevel, loggerName) => {
2696
+ const rawMethod = originalFactory(methodName, configLevel, loggerName);
2697
+ const logLevel = LogLevel[methodName];
2698
+ const needLog = logLevel >= configLevel && logLevel < LogLevel.silent;
2699
+ return (msg, context) => {
2700
+ if (context) rawMethod(msg, context);
2701
+ else rawMethod(msg);
2702
+ if (needLog) {
2703
+ extension2(logLevel, msg, context);
2704
+ }
2705
+ };
2706
+ };
2707
+ logR.setLevel(logR.getLevel());
2708
+ });
2709
+ }
2303
2710
  function __rest(s, e3) {
2304
2711
  var t = {};
2305
2712
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e3.indexOf(p) < 0)
@@ -5192,6 +5599,118 @@ function isInsertableStreamSupported() {
5192
5599
  return typeof window.RTCRtpSender !== "undefined" && // @ts-ignore
5193
5600
  typeof window.RTCRtpSender.prototype.createEncodedStreams !== "undefined";
5194
5601
  }
5602
+ function isVideoFrame(frame) {
5603
+ return "type" in frame;
5604
+ }
5605
+ function importKey(keyBytes_1) {
5606
+ return __awaiter(this, arguments, void 0, function(keyBytes) {
5607
+ let algorithm = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
5608
+ name: ENCRYPTION_ALGORITHM
5609
+ };
5610
+ let usage = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "encrypt";
5611
+ return function* () {
5612
+ return crypto.subtle.importKey("raw", keyBytes, algorithm, false, usage === "derive" ? ["deriveBits", "deriveKey"] : ["encrypt", "decrypt"]);
5613
+ }();
5614
+ });
5615
+ }
5616
+ function createKeyMaterialFromString(password) {
5617
+ return __awaiter(this, void 0, void 0, function* () {
5618
+ let enc = new TextEncoder();
5619
+ const keyMaterial = yield crypto.subtle.importKey("raw", enc.encode(password), {
5620
+ name: "PBKDF2"
5621
+ }, false, ["deriveBits", "deriveKey"]);
5622
+ return keyMaterial;
5623
+ });
5624
+ }
5625
+ function createKeyMaterialFromBuffer(cryptoBuffer) {
5626
+ return __awaiter(this, void 0, void 0, function* () {
5627
+ const keyMaterial = yield crypto.subtle.importKey("raw", cryptoBuffer, "HKDF", false, ["deriveBits", "deriveKey"]);
5628
+ return keyMaterial;
5629
+ });
5630
+ }
5631
+ function getAlgoOptions(algorithmName, salt) {
5632
+ const textEncoder = new TextEncoder();
5633
+ const encodedSalt = textEncoder.encode(salt);
5634
+ switch (algorithmName) {
5635
+ case "HKDF":
5636
+ return {
5637
+ name: "HKDF",
5638
+ salt: encodedSalt,
5639
+ hash: "SHA-256",
5640
+ info: new ArrayBuffer(128)
5641
+ };
5642
+ case "PBKDF2": {
5643
+ return {
5644
+ name: "PBKDF2",
5645
+ salt: encodedSalt,
5646
+ hash: "SHA-256",
5647
+ iterations: 1e5
5648
+ };
5649
+ }
5650
+ default:
5651
+ throw new Error("algorithm ".concat(algorithmName, " is currently unsupported"));
5652
+ }
5653
+ }
5654
+ function deriveKeys(material, salt) {
5655
+ return __awaiter(this, void 0, void 0, function* () {
5656
+ const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);
5657
+ const encryptionKey = yield crypto.subtle.deriveKey(algorithmOptions, material, {
5658
+ name: ENCRYPTION_ALGORITHM,
5659
+ length: 128
5660
+ }, false, ["encrypt", "decrypt"]);
5661
+ return {
5662
+ material,
5663
+ encryptionKey
5664
+ };
5665
+ });
5666
+ }
5667
+ function createE2EEKey() {
5668
+ return window.crypto.getRandomValues(new Uint8Array(32));
5669
+ }
5670
+ function ratchet(material, salt) {
5671
+ return __awaiter(this, void 0, void 0, function* () {
5672
+ const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);
5673
+ return crypto.subtle.deriveBits(algorithmOptions, material, 256);
5674
+ });
5675
+ }
5676
+ function needsRbspUnescaping(frameData) {
5677
+ for (var i2 = 0; i2 < frameData.length - 3; i2++) {
5678
+ if (frameData[i2] == 0 && frameData[i2 + 1] == 0 && frameData[i2 + 2] == 3) return true;
5679
+ }
5680
+ return false;
5681
+ }
5682
+ function parseRbsp(stream) {
5683
+ const dataOut = [];
5684
+ var length = stream.length;
5685
+ for (var i2 = 0; i2 < stream.length; ) {
5686
+ if (length - i2 >= 3 && !stream[i2] && !stream[i2 + 1] && stream[i2 + 2] == 3) {
5687
+ dataOut.push(stream[i2++]);
5688
+ dataOut.push(stream[i2++]);
5689
+ i2++;
5690
+ } else {
5691
+ dataOut.push(stream[i2++]);
5692
+ }
5693
+ }
5694
+ return new Uint8Array(dataOut);
5695
+ }
5696
+ function writeRbsp(data_in) {
5697
+ const dataOut = [];
5698
+ var numConsecutiveZeros = 0;
5699
+ for (var i2 = 0; i2 < data_in.length; ++i2) {
5700
+ var byte = data_in[i2];
5701
+ if (byte <= kEmulationByte && numConsecutiveZeros >= kZerosInStartSequence) {
5702
+ dataOut.push(kEmulationByte);
5703
+ numConsecutiveZeros = 0;
5704
+ }
5705
+ dataOut.push(byte);
5706
+ if (byte == 0) {
5707
+ ++numConsecutiveZeros;
5708
+ } else {
5709
+ numConsecutiveZeros = 0;
5710
+ }
5711
+ }
5712
+ return new Uint8Array(dataOut);
5713
+ }
5195
5714
  function cloneDeep(value) {
5196
5715
  if (typeof value === "undefined") {
5197
5716
  return value;
@@ -5299,6 +5818,12 @@ function supportsTransceiver() {
5299
5818
  function supportsAddTrack() {
5300
5819
  return "addTrack" in RTCPeerConnection.prototype;
5301
5820
  }
5821
+ function supportsAdaptiveStream() {
5822
+ return typeof ResizeObserver !== void 0 && typeof IntersectionObserver !== void 0;
5823
+ }
5824
+ function supportsDynacast() {
5825
+ return supportsTransceiver();
5826
+ }
5302
5827
  function supportsAV1() {
5303
5828
  if (!("getCapabilities" in RTCRtpSender)) {
5304
5829
  return false;
@@ -5486,6 +6011,12 @@ function getClientInfo() {
5486
6011
  }
5487
6012
  return info;
5488
6013
  }
6014
+ function getEmptyVideoStreamTrack() {
6015
+ if (!emptyVideoStreamTrack) {
6016
+ emptyVideoStreamTrack = createDummyVideoStreamTrack();
6017
+ }
6018
+ return emptyVideoStreamTrack.clone();
6019
+ }
5489
6020
  function createDummyVideoStreamTrack() {
5490
6021
  let width = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 16;
5491
6022
  let height = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 16;
@@ -5698,6 +6229,9 @@ function isRemoteVideoTrack(track) {
5698
6229
  function isLocalParticipant(p) {
5699
6230
  return p.isLocal;
5700
6231
  }
6232
+ function isRemoteParticipant(p) {
6233
+ return !p.isLocal;
6234
+ }
5701
6235
  function splitUtf8(s, n) {
5702
6236
  const result = [];
5703
6237
  let encoded = new TextEncoder().encode(s);
@@ -7494,6 +8028,34 @@ function createLocalAudioTrack(options) {
7494
8028
  return tracks[0];
7495
8029
  });
7496
8030
  }
8031
+ function createLocalScreenTracks(options) {
8032
+ return __awaiter(this, void 0, void 0, function* () {
8033
+ if (options === void 0) {
8034
+ options = {};
8035
+ }
8036
+ if (options.resolution === void 0 && !isSafari17Based()) {
8037
+ options.resolution = ScreenSharePresets.h1080fps30.resolution;
8038
+ }
8039
+ if (navigator.mediaDevices.getDisplayMedia === void 0) {
8040
+ throw new DeviceUnsupportedError("getDisplayMedia not supported");
8041
+ }
8042
+ const constraints = screenCaptureToDisplayMediaStreamOptions(options);
8043
+ const stream = yield navigator.mediaDevices.getDisplayMedia(constraints);
8044
+ const tracks = stream.getVideoTracks();
8045
+ if (tracks.length === 0) {
8046
+ throw new TrackInvalidError("no video track found");
8047
+ }
8048
+ const screenVideo = new LocalVideoTrack(tracks[0], void 0, false);
8049
+ screenVideo.source = Track.Source.ScreenShare;
8050
+ const localTracks = [screenVideo];
8051
+ if (stream.getAudioTracks().length > 0) {
8052
+ const screenAudio = new LocalAudioTrack(stream.getAudioTracks()[0], void 0, false);
8053
+ screenAudio.source = Track.Source.ScreenShareAudio;
8054
+ localTracks.push(screenAudio);
8055
+ }
8056
+ return localTracks;
8057
+ });
8058
+ }
7497
8059
  function qualityFromProto(q2) {
7498
8060
  switch (q2) {
7499
8061
  case ConnectionQuality$1.EXCELLENT:
@@ -7550,7 +8112,55 @@ function isIPPrivate(address) {
7550
8112
  }
7551
8113
  return false;
7552
8114
  }
7553
- var e, h, o, _, FLOAT32_MAX, FLOAT32_MIN, UINT32_MAX, INT32_MAX, INT32_MIN, enumTypeSymbol, Message, TWO_PWR_32_DBL, decimalFrom1e7WithLeadingZeros, protoInt64, ScalarType, LongType, WireType, BinaryWriter, BinaryReader, encTable, decTable, protoBase64, jsonReadDefaults, jsonWriteDefaults, tokenNull, tokenIgnoredUnknownEnum, unknownFieldsSymbol, readDefaults, writeDefaults, InternalFieldList, fieldJsonName, reservedObjectProperties, reservedMessageProperties, fallback, safeMessageProperty, safeObjectProperty, InternalOneofInfo, proto3, Timestamp, MetricsBatch, TimeSeriesMetric, MetricSample, EventMetric, BackupCodecPolicy$1, TrackType, TrackSource, VideoQuality$1, ConnectionQuality$1, ClientConfigSetting, DisconnectReason, ReconnectReason, SubscriptionError, AudioTrackFeature, Room$1, Codec, ParticipantPermission, ParticipantInfo, ParticipantInfo_State, ParticipantInfo_Kind, ParticipantInfo_KindDetail, Encryption_Type, SimulcastCodecInfo, TrackInfo, VideoLayer, DataPacket, DataPacket_Kind, ActiveSpeakerUpdate, SpeakerInfo, UserPacket, SipDTMF, Transcription, TranscriptionSegment, ChatMessage, RpcRequest, RpcAck, RpcResponse, RpcError$1, ParticipantTracks, ServerInfo, ServerInfo_Edition, ClientInfo, ClientInfo_SDK, ClientConfiguration, VideoConfiguration, DisabledCodecs, TimedVersion, DataStream_OperationType, DataStream_TextHeader, DataStream_ByteHeader, DataStream_Header, DataStream_Chunk, DataStream_Trailer, SignalTarget, StreamState, CandidateProtocol, SignalRequest, SignalResponse, SimulcastCodec, AddTrackRequest, TrickleRequest, MuteTrackRequest, JoinResponse, ReconnectResponse, TrackPublishedResponse, TrackUnpublishedResponse, SessionDescription, ParticipantUpdate, UpdateSubscription, UpdateTrackSettings, UpdateLocalAudioTrack, UpdateLocalVideoTrack, LeaveRequest, LeaveRequest_Action, UpdateVideoLayers, UpdateParticipantMetadata, ICEServer, SpeakersChanged, RoomUpdate, ConnectionQualityInfo, ConnectionQualityUpdate, StreamStateInfo, StreamStateUpdate, SubscribedQuality, SubscribedCodec, SubscribedQualityUpdate, TrackPermission, SubscriptionPermission, SubscriptionPermissionUpdate, RoomMovedResponse, SyncState, DataChannelReceiveState, DataChannelInfo, SimulateScenario, Ping, Pong, RegionSettings, RegionInfo, SubscriptionResponse, RequestResponse, RequestResponse_Reason, TrackSubscribed, loglevel$1, loglevel, hasRequiredLoglevel, loglevelExports, LogLevel, LoggerNames, livekitLogger, livekitLoggers, workerLogger, maxRetryDelay, DEFAULT_RETRY_DELAYS_IN_MS, DefaultReconnectPolicy, events, hasRequiredEvents, eventsExports, logDisabled_, deprecationWarnings_, logging, chromeShim, firefoxShim, safariShim, sdp$1, hasRequiredSdp, sdpExports, SDPUtils, sdp, commonShim, DECRYPTION_FAILURE_TOLERANCE, E2EE_FLAG, SALT, KEY_PROVIDER_DEFAULTS, KeyProviderEvent, KeyHandlerEvent, EncryptionEvent, CryptorEvent, BaseKeyProvider, LivekitError, ConnectionErrorReason, ConnectionError, DeviceUnsupportedError, TrackInvalidError, UnsupportedServer, UnexpectedConnectionState, NegotiationError, PublishTrackError, SignalRequestError, MediaDeviceFailure, CryptorErrorReason, RoomEvent, ParticipantEvent, EngineEvent, TrackEvent, commonVersionIdentifier, browserDetails, browsersList, version$1, version, protocolVersion, CriticalTimers, BACKGROUND_REACTION_DELAY, recycledElements, VideoQuality, Track, VideoPreset, backupCodecs, videoCodecs, BackupCodecPolicy, AudioPresets, VideoPresets, VideoPresets43, ScreenSharePresets, separator, ddExtensionURI, resizeObserver, getResizeObserver, intersectionObserver, getIntersectionObserver, emptyAudioStreamTrack, Future, E2EEManager, defaultId, DeviceManager, QueueTaskStatus, AsyncQueue, passThroughQueueSignals, SignalConnectionState, SignalClient, DataPacketBuffer, TTLMap, lib, parser, grammar, hasRequiredGrammar, hasRequiredParser, writer, hasRequiredWriter, hasRequiredLib, libExports, startBitrateForSVC, debounceInterval, PCEvents, PCTransport, defaultVideoCodec, publishDefaults, audioDefaults, videoDefaults, roomOptionDefaults, roomConnectOptionDefaults, PCTransportState, PCTransportManager, RpcError, MAX_PAYLOAD_BYTES, monitorFrequency, isMediaRecorderAvailable, FallbackRecorder, RecorderBase, LocalTrackRecorder, DEFAULT_DIMENSIONS_TIMEOUT, PRE_CONNECT_BUFFER_TIMEOUT, LocalTrack, LocalAudioTrack, presets169, presets43, presetsScreenShare, defaultSimulcastPresets169, defaultSimulcastPresets43, computeDefaultScreenShareSimulcastPresets, videoRids, ScalabilityMode, refreshSubscribedCodecAfterNewCodec, LocalVideoTrack, lossyDataChannel, reliableDataChannel, minReconnectWait, leaveReconnect, reliabeReceiveStateTTL, PCState, RTCEngine, SignalReconnectError, RegionUrlProvider, BaseStreamReader, ByteStreamReader, TextStreamReader, BaseStreamWriter, TextStreamWriter, ByteStreamWriter, RemoteTrack, RemoteAudioTrack, REACTION_DELAY, RemoteVideoTrack, HTMLElementInfo, TrackPublication, LocalTrackPublication, ConnectionQuality, Participant, STREAM_CHUNK_SIZE, LocalParticipant, RemoteTrackPublication, RemoteParticipant, ConnectionState, connectionReconcileFrequency, Room, CheckStatus, Checker, CloudRegionCheck, TEST_DURATION, ConnectionProtocolCheck, PublishAudioCheck, PublishVideoCheck, ReconnectCheck, TURNCheck, WebRTCCheck, WebSocketCheck, ConnectionCheck;
8115
+ function facingModeFromLocalTrack(localTrack) {
8116
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
8117
+ var _a;
8118
+ const track = isLocalTrack(localTrack) ? localTrack.mediaStreamTrack : localTrack;
8119
+ const trackSettings = track.getSettings();
8120
+ let result = {
8121
+ facingMode: (_a = options.defaultFacingMode) !== null && _a !== void 0 ? _a : "user",
8122
+ confidence: "low"
8123
+ };
8124
+ if ("facingMode" in trackSettings) {
8125
+ const rawFacingMode = trackSettings.facingMode;
8126
+ livekitLogger.trace("rawFacingMode", {
8127
+ rawFacingMode
8128
+ });
8129
+ if (rawFacingMode && typeof rawFacingMode === "string" && isFacingModeValue(rawFacingMode)) {
8130
+ result = {
8131
+ facingMode: rawFacingMode,
8132
+ confidence: "high"
8133
+ };
8134
+ }
8135
+ }
8136
+ if (["low", "medium"].includes(result.confidence)) {
8137
+ livekitLogger.trace("Try to get facing mode from device label: (".concat(track.label, ")"));
8138
+ const labelAnalysisResult = facingModeFromDeviceLabel(track.label);
8139
+ if (labelAnalysisResult !== void 0) {
8140
+ result = labelAnalysisResult;
8141
+ }
8142
+ }
8143
+ return result;
8144
+ }
8145
+ function facingModeFromDeviceLabel(deviceLabel) {
8146
+ var _a;
8147
+ const label = deviceLabel.trim().toLowerCase();
8148
+ if (label === "") {
8149
+ return void 0;
8150
+ }
8151
+ if (knownDeviceLabels.has(label)) {
8152
+ return knownDeviceLabels.get(label);
8153
+ }
8154
+ return (_a = Array.from(knownDeviceLabelSections.entries()).find((_ref) => {
8155
+ let [section] = _ref;
8156
+ return label.includes(section);
8157
+ })) === null || _a === void 0 ? void 0 : _a[1];
8158
+ }
8159
+ function isFacingModeValue(item) {
8160
+ const allowedValues = ["user", "environment", "left", "right"];
8161
+ return item === void 0 || allowedValues.includes(item);
8162
+ }
8163
+ var e, h, o, _, FLOAT32_MAX, FLOAT32_MIN, UINT32_MAX, INT32_MAX, INT32_MIN, enumTypeSymbol, Message, TWO_PWR_32_DBL, decimalFrom1e7WithLeadingZeros, protoInt64, ScalarType, LongType, WireType, BinaryWriter, BinaryReader, encTable, decTable, protoBase64, jsonReadDefaults, jsonWriteDefaults, tokenNull, tokenIgnoredUnknownEnum, unknownFieldsSymbol, readDefaults, writeDefaults, InternalFieldList, fieldJsonName, reservedObjectProperties, reservedMessageProperties, fallback, safeMessageProperty, safeObjectProperty, InternalOneofInfo, proto3, Timestamp, MetricsBatch, TimeSeriesMetric, MetricSample, EventMetric, BackupCodecPolicy$1, TrackType, TrackSource, VideoQuality$1, ConnectionQuality$1, ClientConfigSetting, DisconnectReason, ReconnectReason, SubscriptionError, AudioTrackFeature, Room$1, Codec, ParticipantPermission, ParticipantInfo, ParticipantInfo_State, ParticipantInfo_Kind, ParticipantInfo_KindDetail, Encryption_Type, SimulcastCodecInfo, TrackInfo, VideoLayer, DataPacket, DataPacket_Kind, ActiveSpeakerUpdate, SpeakerInfo, UserPacket, SipDTMF, Transcription, TranscriptionSegment, ChatMessage, RpcRequest, RpcAck, RpcResponse, RpcError$1, ParticipantTracks, ServerInfo, ServerInfo_Edition, ClientInfo, ClientInfo_SDK, ClientConfiguration, VideoConfiguration, DisabledCodecs, TimedVersion, DataStream_OperationType, DataStream_TextHeader, DataStream_ByteHeader, DataStream_Header, DataStream_Chunk, DataStream_Trailer, SignalTarget, StreamState, CandidateProtocol, SignalRequest, SignalResponse, SimulcastCodec, AddTrackRequest, TrickleRequest, MuteTrackRequest, JoinResponse, ReconnectResponse, TrackPublishedResponse, TrackUnpublishedResponse, SessionDescription, ParticipantUpdate, UpdateSubscription, UpdateTrackSettings, UpdateLocalAudioTrack, UpdateLocalVideoTrack, LeaveRequest, LeaveRequest_Action, UpdateVideoLayers, UpdateParticipantMetadata, ICEServer, SpeakersChanged, RoomUpdate, ConnectionQualityInfo, ConnectionQualityUpdate, StreamStateInfo, StreamStateUpdate, SubscribedQuality, SubscribedCodec, SubscribedQualityUpdate, TrackPermission, SubscriptionPermission, SubscriptionPermissionUpdate, RoomMovedResponse, SyncState, DataChannelReceiveState, DataChannelInfo, SimulateScenario, Ping, Pong, RegionSettings, RegionInfo, SubscriptionResponse, RequestResponse, RequestResponse_Reason, TrackSubscribed, loglevel$1, loglevel, hasRequiredLoglevel, loglevelExports, LogLevel, LoggerNames, livekitLogger, livekitLoggers, workerLogger, maxRetryDelay, DEFAULT_RETRY_DELAYS_IN_MS, DefaultReconnectPolicy, events, hasRequiredEvents, eventsExports, logDisabled_, deprecationWarnings_, logging, chromeShim, firefoxShim, safariShim, sdp$1, hasRequiredSdp, sdpExports, SDPUtils, sdp, commonShim, ENCRYPTION_ALGORITHM, DECRYPTION_FAILURE_TOLERANCE, E2EE_FLAG, SALT, KEY_PROVIDER_DEFAULTS, KeyProviderEvent, KeyHandlerEvent, EncryptionEvent, CryptorEvent, kZerosInStartSequence, kEmulationByte, BaseKeyProvider, ExternalE2EEKeyProvider, LivekitError, ConnectionErrorReason, ConnectionError, DeviceUnsupportedError, TrackInvalidError, UnsupportedServer, UnexpectedConnectionState, NegotiationError, PublishDataError, PublishTrackError, SignalRequestError, MediaDeviceFailure, CryptorErrorReason, CryptorError, RoomEvent, ParticipantEvent, EngineEvent, TrackEvent, commonVersionIdentifier, browserDetails, browsersList, version$1, version, protocolVersion, CriticalTimers, BACKGROUND_REACTION_DELAY, recycledElements, VideoQuality, Track, VideoPreset, backupCodecs, videoCodecs, BackupCodecPolicy, AudioPresets, VideoPresets, VideoPresets43, ScreenSharePresets, separator, ddExtensionURI, resizeObserver, getResizeObserver, intersectionObserver, getIntersectionObserver, emptyVideoStreamTrack, emptyAudioStreamTrack, Future, E2EEManager, defaultId, DeviceManager, QueueTaskStatus, AsyncQueue, passThroughQueueSignals, SignalConnectionState, SignalClient, DataPacketBuffer, TTLMap, lib, parser, grammar, hasRequiredGrammar, hasRequiredParser, writer, hasRequiredWriter, hasRequiredLib, libExports, startBitrateForSVC, debounceInterval, PCEvents, PCTransport, defaultVideoCodec, publishDefaults, audioDefaults, videoDefaults, roomOptionDefaults, roomConnectOptionDefaults, PCTransportState, PCTransportManager, RpcError, MAX_PAYLOAD_BYTES, monitorFrequency, isMediaRecorderAvailable, FallbackRecorder, RecorderBase, LocalTrackRecorder, DEFAULT_DIMENSIONS_TIMEOUT, PRE_CONNECT_BUFFER_TIMEOUT, LocalTrack, LocalAudioTrack, presets169, presets43, presetsScreenShare, defaultSimulcastPresets169, defaultSimulcastPresets43, computeDefaultScreenShareSimulcastPresets, videoRids, ScalabilityMode, refreshSubscribedCodecAfterNewCodec, LocalVideoTrack, lossyDataChannel, reliableDataChannel, minReconnectWait, leaveReconnect, reliabeReceiveStateTTL, PCState, RTCEngine, SignalReconnectError, RegionUrlProvider, BaseStreamReader, ByteStreamReader, TextStreamReader, BaseStreamWriter, TextStreamWriter, ByteStreamWriter, RemoteTrack, RemoteAudioTrack, REACTION_DELAY, RemoteVideoTrack, HTMLElementInfo, TrackPublication, LocalTrackPublication, ConnectionQuality, Participant, STREAM_CHUNK_SIZE, LocalParticipant, RemoteTrackPublication, RemoteParticipant, ConnectionState, connectionReconcileFrequency, Room, Convert, attributeTypings, CheckStatus, Checker, CloudRegionCheck, TEST_DURATION, ConnectionProtocolCheck, PublishAudioCheck, PublishVideoCheck, ReconnectCheck, TURNCheck, WebRTCCheck, WebSocketCheck, ConnectionCheck, knownDeviceLabels, knownDeviceLabelSections;
7554
8164
  var init_livekit_client_esm = __esm({
7555
8165
  "node_modules/livekit-client/dist/livekit-client.esm.mjs"() {
7556
8166
  "use strict";
@@ -11289,6 +11899,7 @@ var init_livekit_client_esm = __esm({
11289
11899
  adapterFactory({
11290
11900
  window: typeof window === "undefined" ? void 0 : window
11291
11901
  });
11902
+ ENCRYPTION_ALGORITHM = "AES-GCM";
11292
11903
  DECRYPTION_FAILURE_TOLERANCE = 10;
11293
11904
  E2EE_FLAG = "lk_e2ee";
11294
11905
  SALT = "LKFrameEncryptionKey";
@@ -11314,6 +11925,8 @@ var init_livekit_client_esm = __esm({
11314
11925
  (function(CryptorEvent2) {
11315
11926
  CryptorEvent2["Error"] = "cryptorError";
11316
11927
  })(CryptorEvent || (CryptorEvent = {}));
11928
+ kZerosInStartSequence = 2;
11929
+ kEmulationByte = 3;
11317
11930
  BaseKeyProvider = class extends eventsExports.EventEmitter {
11318
11931
  constructor() {
11319
11932
  let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
@@ -11357,6 +11970,32 @@ var init_livekit_client_esm = __esm({
11357
11970
  this.emit(KeyProviderEvent.RatchetRequest, participantIdentity, keyIndex);
11358
11971
  }
11359
11972
  };
11973
+ ExternalE2EEKeyProvider = class extends BaseKeyProvider {
11974
+ constructor() {
11975
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
11976
+ const opts = Object.assign(Object.assign({}, options), {
11977
+ sharedKey: true,
11978
+ // for a shared key provider failing to decrypt for a specific participant
11979
+ // should not mark the key as invalid, so we accept wrong keys forever
11980
+ // and won't try to auto-ratchet
11981
+ ratchetWindowSize: 0,
11982
+ failureTolerance: -1
11983
+ });
11984
+ super(opts);
11985
+ }
11986
+ /**
11987
+ * Accepts a passphrase that's used to create the crypto keys.
11988
+ * When passing in a string, PBKDF2 is used.
11989
+ * When passing in an Array buffer of cryptographically random numbers, HKDF is being used. (recommended)
11990
+ * @param key
11991
+ */
11992
+ setKey(key) {
11993
+ return __awaiter(this, void 0, void 0, function* () {
11994
+ const derivedKey = typeof key === "string" ? yield createKeyMaterialFromString(key) : yield createKeyMaterialFromBuffer(key);
11995
+ this.onSetEncryptionKey(derivedKey);
11996
+ });
11997
+ }
11998
+ };
11360
11999
  LivekitError = class extends Error {
11361
12000
  constructor(code4, message) {
11362
12001
  super(message || "an error has occured");
@@ -11412,6 +12051,12 @@ var init_livekit_client_esm = __esm({
11412
12051
  this.name = "NegotiationError";
11413
12052
  }
11414
12053
  };
12054
+ PublishDataError = class extends LivekitError {
12055
+ constructor(message) {
12056
+ super(14, message !== null && message !== void 0 ? message : "unable to publish data");
12057
+ this.name = "PublishDataError";
12058
+ }
12059
+ };
11415
12060
  PublishTrackError = class extends LivekitError {
11416
12061
  constructor(message, status) {
11417
12062
  super(15, message);
@@ -11454,6 +12099,15 @@ var init_livekit_client_esm = __esm({
11454
12099
  CryptorErrorReason2[CryptorErrorReason2["MissingKey"] = 1] = "MissingKey";
11455
12100
  CryptorErrorReason2[CryptorErrorReason2["InternalError"] = 2] = "InternalError";
11456
12101
  })(CryptorErrorReason || (CryptorErrorReason = {}));
12102
+ CryptorError = class extends LivekitError {
12103
+ constructor(message) {
12104
+ let reason = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : CryptorErrorReason.InternalError;
12105
+ let participantIdentity = arguments.length > 2 ? arguments[2] : void 0;
12106
+ super(40, message);
12107
+ this.reason = reason;
12108
+ this.participantIdentity = participantIdentity;
12109
+ }
12110
+ };
11457
12111
  (function(RoomEvent2) {
11458
12112
  RoomEvent2["Connected"] = "connected";
11459
12113
  RoomEvent2["Reconnecting"] = "reconnecting";
@@ -22182,6 +22836,24 @@ var init_livekit_client_esm = __esm({
22182
22836
  Room.cleanupRegistry = typeof FinalizationRegistry !== "undefined" && new FinalizationRegistry((cleanup) => {
22183
22837
  cleanup();
22184
22838
  });
22839
+ Convert = class {
22840
+ static toAgentAttributes(json) {
22841
+ return JSON.parse(json);
22842
+ }
22843
+ static agentAttributesToJson(value) {
22844
+ return JSON.stringify(value);
22845
+ }
22846
+ static toTranscriptionAttributes(json) {
22847
+ return JSON.parse(json);
22848
+ }
22849
+ static transcriptionAttributesToJson(value) {
22850
+ return JSON.stringify(value);
22851
+ }
22852
+ };
22853
+ attributeTypings = /* @__PURE__ */ Object.freeze({
22854
+ __proto__: null,
22855
+ Convert
22856
+ });
22185
22857
  (function(CheckStatus2) {
22186
22858
  CheckStatus2[CheckStatus2["IDLE"] = 0] = "IDLE";
22187
22859
  CheckStatus2[CheckStatus2["RUNNING"] = 1] = "RUNNING";
@@ -22865,142 +23537,17 @@ var init_livekit_client_esm = __esm({
22865
23537
  });
22866
23538
  }
22867
23539
  };
22868
- }
22869
- });
22870
-
22871
- // src/utils/jsx-encoder.ts
22872
- function generateStableDOMId(element3) {
22873
- const tagName = element3.tagName.toLowerCase();
22874
- const text7 = (element3.textContent || "").trim().substring(0, 50);
22875
- let sibling = element3.previousElementSibling;
22876
- let position3 = 1;
22877
- while (sibling) {
22878
- if (sibling.tagName === element3.tagName) {
22879
- position3++;
22880
- }
22881
- sibling = sibling.previousElementSibling;
22882
- }
22883
- const path2 = getElementPath2(element3);
22884
- const idString = `${tagName}[${position3}]_(${text7})_${path2}`;
22885
- let hash = 0;
22886
- for (let i2 = 0; i2 < idString.length; i2++) {
22887
- const char = idString.charCodeAt(i2);
22888
- hash = (hash << 5) - hash + char;
22889
- hash |= 0;
22890
- }
22891
- return hash.toString(36);
22892
- }
22893
- function getElementPath2(element3) {
22894
- if (element3.id) {
22895
- return `id(${element3.id})`;
22896
- }
22897
- if (element3.tagName.toLowerCase() === "body") {
22898
- return "/body";
22899
- }
22900
- let ix = 0;
22901
- const siblings = element3.parentNode?.children || new HTMLCollection();
22902
- for (let i2 = 0; i2 < siblings.length; i2++) {
22903
- const sibling = siblings[i2];
22904
- if (sibling === element3) {
22905
- return `${getElementPath2(element3.parentNode)}/${element3.tagName}[${ix + 1}]`;
22906
- }
22907
- if (sibling.nodeType === 1 && sibling.tagName === element3.tagName) {
22908
- ix++;
22909
- }
22910
- }
22911
- return "not_found";
22912
- }
22913
- var init_jsx_encoder = __esm({
22914
- "src/utils/jsx-encoder.ts"() {
22915
- "use strict";
22916
- }
22917
- });
22918
-
22919
- // src/utils/patch-react.ts
22920
- function getImmediateText(element3) {
22921
- let text7 = "";
22922
- if (element3.childNodes) {
22923
- for (const node2 of Array.from(element3.childNodes)) {
22924
- if (node2.nodeType === 3) {
22925
- text7 += node2.textContent || "";
22926
- }
22927
- }
22928
- }
22929
- return text7.trim();
22930
- }
22931
- function captureFullDOMStructure() {
22932
- console.log("\u{1F333} Capturing full DOM structure...");
22933
- const components = [];
22934
- const interactiveElements = document.querySelectorAll(
22935
- 'a, button, input, textarea, select, [role="button"], [onclick]'
22936
- );
22937
- interactiveElements.forEach((element3) => {
22938
- if (element3 instanceof HTMLElement && !element3.closest("[data-cuekit-ignore]")) {
22939
- const nodeData = buildFlatDOMNode(element3);
22940
- if (nodeData) {
22941
- components.push(nodeData);
22942
- }
22943
- }
22944
- });
22945
- const result = { components };
22946
- console.log("\u{1F333} Full DOM structure captured:", result);
22947
- return result;
22948
- }
22949
- function buildFlatDOMNode(element3) {
22950
- if (element3.tagName.toLowerCase() === "script" || element3.hasAttribute("data-cuekit-ignore") || element3.style.display === "none" || element3.style.visibility === "hidden") {
22951
- return null;
22952
- }
22953
- const hash = generateStableDOMId(element3);
22954
- const text7 = getImmediateText(element3).substring(0, 100);
22955
- const isClickable = isElementClickable(element3);
22956
- const componentType = element3.tagName.toLowerCase();
22957
- return {
22958
- hash,
22959
- text: text7,
22960
- isClickable,
22961
- componentType,
22962
- children: []
22963
- // No children in a flat structure
22964
- };
22965
- }
22966
- function isElementClickable(element3) {
22967
- const interactiveSelectors = [
22968
- "button",
22969
- "a",
22970
- "input",
22971
- "select",
22972
- "textarea",
22973
- '[role="button"]',
22974
- '[role="link"]',
22975
- '[role="tab"]',
22976
- "[data-onclick-id]",
22977
- "[data-on-press-id]",
22978
- "[onclick]",
22979
- "[onmousedown]",
22980
- "[onmouseup]",
22981
- "[ontouchstart]",
22982
- "[ontouchend]",
22983
- "[onkeydown]",
22984
- "[onkeyup]",
22985
- "[onkeypress]"
22986
- ];
22987
- for (const selector of interactiveSelectors) {
22988
- if (element3.matches(selector)) {
22989
- return true;
22990
- }
22991
- }
22992
- const hasClickEvents = element3.onclick !== null || element3.getAttribute("onclick") !== null;
22993
- const hasInteractiveEvents = element3.ontouchstart !== null || element3.getAttribute("ontouchstart") !== null || element3.ontouchend !== null || element3.getAttribute("ontouchend") !== null || element3.onkeydown !== null || element3.getAttribute("onkeydown") !== null || element3.onkeyup !== null || element3.getAttribute("onkeyup") !== null || element3.onkeypress !== null || element3.getAttribute("onkeypress") !== null;
22994
- const hasPointerCursor = element3.style.cursor === "pointer" || getComputedStyle(element3).cursor === "pointer";
22995
- const hasTabIndex = element3.hasAttribute("tabindex") && parseInt(element3.getAttribute("tabindex") || "0") >= 0;
22996
- const hasInteractiveDataAttrs = element3.hasAttribute("data-clickable") || element3.hasAttribute("data-interactive") || element3.hasAttribute("data-action") || element3.hasAttribute("data-handler");
22997
- const hasInteractiveAria = element3.hasAttribute("aria-pressed") || element3.hasAttribute("aria-expanded") || element3.hasAttribute("aria-selected") || element3.hasAttribute("aria-checked");
22998
- return hasClickEvents || hasInteractiveEvents || hasPointerCursor || hasTabIndex || hasInteractiveDataAttrs || hasInteractiveAria;
22999
- }
23000
- var init_patch_react = __esm({
23001
- "src/utils/patch-react.ts"() {
23002
- "use strict";
23003
- init_jsx_encoder();
23540
+ knownDeviceLabels = /* @__PURE__ */ new Map([["obs virtual camera", {
23541
+ facingMode: "environment",
23542
+ confidence: "medium"
23543
+ }]]);
23544
+ knownDeviceLabelSections = /* @__PURE__ */ new Map([["iphone", {
23545
+ facingMode: "environment",
23546
+ confidence: "medium"
23547
+ }], ["ipad", {
23548
+ facingMode: "environment",
23549
+ confidence: "medium"
23550
+ }]]);
23004
23551
  }
23005
23552
  });
23006
23553
 
@@ -23023,6 +23570,12 @@ __export(webrtc_service_exports, {
23023
23570
  setServerUrl: () => setServerUrl,
23024
23571
  setWebRTCCallbacks: () => setWebRTCCallbacks
23025
23572
  });
23573
+ async function getLiveKitClient() {
23574
+ if (!livekitClient) {
23575
+ livekitClient = await Promise.resolve().then(() => (init_livekit_client_esm(), livekit_client_esm_exports));
23576
+ }
23577
+ return livekitClient;
23578
+ }
23026
23579
  function setServerUrl(url) {
23027
23580
  serverUrl = url;
23028
23581
  }
@@ -23071,16 +23624,17 @@ async function connectToRoom(newLivekitUrl, newToken) {
23071
23624
  console.log("\u{1F3A4} WebRTCService: Connecting to room...", { url, hasToken: !!authToken });
23072
23625
  try {
23073
23626
  setWebRTCConnectionState({ isConnected: false, isConnecting: true });
23074
- room = new Room({
23627
+ const { Room: Room3 } = await getLiveKitClient();
23628
+ room = new Room3({
23075
23629
  adaptiveStream: true,
23076
23630
  dynacast: true
23077
23631
  });
23078
- setupEventListeners();
23079
- await room.connect(url, authToken);
23080
- console.log("\u{1F3A4} WebRTCService: Successfully connected to room:", room.name);
23632
+ await setupEventListeners();
23633
+ await room?.connect(url, authToken);
23634
+ console.log("\u{1F3A4} WebRTCService: Successfully connected to room:", room?.name);
23081
23635
  setWebRTCConnectionState({ isConnected: true, isConnecting: false });
23082
23636
  try {
23083
- await room.localParticipant.setMicrophoneEnabled(true);
23637
+ await room?.localParticipant.setMicrophoneEnabled(true);
23084
23638
  console.log("\u{1F3A4} WebRTCService: Microphone enabled");
23085
23639
  } catch (micError) {
23086
23640
  console.warn("\u{1F3A4} WebRTCService: Failed to enable microphone:", micError);
@@ -23092,57 +23646,63 @@ async function connectToRoom(newLivekitUrl, newToken) {
23092
23646
  throw error;
23093
23647
  }
23094
23648
  }
23095
- function setupEventListeners() {
23649
+ async function setupEventListeners() {
23096
23650
  if (!room) return;
23097
- room.on(RoomEvent.ConnectionStateChanged, (state) => {
23651
+ const { RoomEvent: RoomEvent2, ConnectionState: ConnectionState2, Track: Track2 } = await getLiveKitClient();
23652
+ room.on(RoomEvent2.ConnectionStateChanged, (state) => {
23098
23653
  console.log("\u{1F3A4} WebRTCService: Connection state changed:", state);
23099
23654
  callbacks.onConnectionStateChange?.(state);
23100
- if (state === ConnectionState.Connected) {
23655
+ if (state === ConnectionState2.Connected) {
23101
23656
  console.log("\u{1F3A4} WebRTCService: Successfully connected to room");
23102
23657
  setWebRTCConnectionState({ isConnected: true, isConnecting: false });
23103
- } else if (state === ConnectionState.Disconnected) {
23658
+ } else if (state === ConnectionState2.Disconnected) {
23104
23659
  console.log("\u{1F3A4} WebRTCService: Disconnected from room");
23105
23660
  setWebRTCConnectionState({ isConnected: false, isConnecting: false });
23106
- } else if (state === ConnectionState.Connecting) {
23661
+ } else if (state === ConnectionState2.Connecting) {
23107
23662
  console.log("\u{1F3A4} WebRTCService: Connecting to room...");
23108
23663
  setWebRTCConnectionState({ isConnected: false, isConnecting: true });
23109
23664
  }
23110
- }).on(RoomEvent.ParticipantConnected, (participant) => {
23665
+ }).on(RoomEvent2.ParticipantConnected, (participant) => {
23111
23666
  console.log("\u{1F3A4} WebRTCService: Participant connected:", participant.identity);
23112
23667
  updateParticipantsList();
23113
- }).on(RoomEvent.ParticipantDisconnected, (participant) => {
23668
+ }).on(RoomEvent2.ParticipantDisconnected, (participant) => {
23114
23669
  console.log("\u{1F3A4} WebRTCService: Participant disconnected:", participant.identity);
23115
23670
  updateParticipantsList();
23116
- }).on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
23117
- if (track.kind === Track.Kind.Audio && !participant.isLocal) {
23118
- const isAIParticipant = participant.identity.toLowerCase().includes("ai") || participant.identity.toLowerCase().includes("bot") || !participant.identity.startsWith("user_");
23119
- if (isAIParticipant) {
23120
- const element3 = track.attach();
23121
- if (audioContainerRef?.current) {
23122
- audioContainerRef.current.appendChild(element3);
23123
- if (element3 instanceof HTMLAudioElement) {
23124
- const trackId = track.sid || `track_${Date.now()}_${Math.random()}`;
23125
- callbacks.onAISpeechStart?.(trackId);
23126
- element3.play().catch(
23127
- (error) => console.warn("\u{1F3A4} WebRTCService: Failed to auto-play audio:", error)
23128
- );
23129
- element3.addEventListener("ended", () => callbacks.onAISpeechEnd?.(trackId));
23130
- element3.addEventListener("pause", () => callbacks.onAISpeechEnd?.(trackId));
23131
- }
23132
- }
23133
- }
23134
- }
23135
- }).on(RoomEvent.TrackUnsubscribed, (track) => {
23671
+ }).on(
23672
+ RoomEvent2.TrackSubscribed,
23673
+ (track, publication, participant) => {
23674
+ if (track.kind === Track2.Kind.Audio && !participant.isLocal) {
23675
+ const isAIParticipant = participant.identity.toLowerCase().includes("ai") || participant.identity.toLowerCase().includes("bot") || !participant.identity.startsWith("user_");
23676
+ if (isAIParticipant) {
23677
+ const element3 = track.attach();
23678
+ if (audioContainerRef?.current) {
23679
+ audioContainerRef.current.appendChild(element3);
23680
+ if (element3 instanceof HTMLAudioElement) {
23681
+ const trackId = track.sid || `track_${Date.now()}_${Math.random()}`;
23682
+ callbacks.onAISpeechStart?.(trackId);
23683
+ element3.play().catch(
23684
+ (error) => console.warn("\u{1F3A4} WebRTCService: Failed to auto-play audio:", error)
23685
+ );
23686
+ element3.addEventListener("ended", () => callbacks.onAISpeechEnd?.(trackId));
23687
+ element3.addEventListener("pause", () => callbacks.onAISpeechEnd?.(trackId));
23688
+ }
23689
+ }
23690
+ }
23691
+ }
23692
+ }
23693
+ ).on(RoomEvent2.TrackUnsubscribed, (track) => {
23136
23694
  track.detach().forEach((element3) => element3.remove());
23137
- }).on(RoomEvent.DataReceived, (payload, participant) => {
23695
+ }).on(RoomEvent2.DataReceived, (payload, participant) => {
23696
+ console.log("\u{1F4E1} LiveKit data received:", new TextDecoder().decode(payload));
23138
23697
  try {
23139
23698
  const message = JSON.parse(new TextDecoder().decode(payload));
23699
+ console.log("\u{1F4E1} LiveKit data received:", message);
23140
23700
  callbacks.onNavigationCommand?.(message);
23141
23701
  } catch (error) {
23142
23702
  const message = new TextDecoder().decode(payload);
23143
23703
  callbacks.onNavigationCommand?.({ type: "raw_text", data: message });
23144
23704
  }
23145
- }).on(RoomEvent.Disconnected, () => {
23705
+ }).on(RoomEvent2.Disconnected, () => {
23146
23706
  setWebRTCConnectionState({ isConnected: false, isConnecting: false });
23147
23707
  });
23148
23708
  }
@@ -23158,14 +23718,14 @@ function updateParticipantsList() {
23158
23718
  async function sendData(data, reliable = true) {
23159
23719
  if (!room) throw new Error("Not connected to room");
23160
23720
  try {
23721
+ console.log("\u{1F4E1} LiveKit data sending:", data);
23161
23722
  const encoder = new TextEncoder();
23162
23723
  const encodedData = encoder.encode(data);
23163
23724
  await room.localParticipant.publishData(encodedData, {
23164
23725
  reliable
23165
23726
  });
23166
23727
  } catch (error) {
23167
- console.error("Error sending data:", error);
23168
- throw error;
23728
+ console.error("\u274C Failed to send data:", error);
23169
23729
  }
23170
23730
  }
23171
23731
  async function sendScreenStatus(screenData) {
@@ -23180,8 +23740,10 @@ async function sendScreenStatus(screenData) {
23180
23740
  throw error;
23181
23741
  }
23182
23742
  }
23183
- function isConnected() {
23184
- return room?.state === ConnectionState.Connected;
23743
+ async function isConnected() {
23744
+ if (!room) return false;
23745
+ const { ConnectionState: ConnectionState2 } = await getLiveKitClient();
23746
+ return room?.state === ConnectionState2.Connected;
23185
23747
  }
23186
23748
  function getRoomName() {
23187
23749
  return roomName;
@@ -23191,6 +23753,7 @@ function getParticipants() {
23191
23753
  }
23192
23754
  async function sendUserCommand(command) {
23193
23755
  if (!room) return;
23756
+ console.log(`\u{1F4AC} Sending user command: "${command}"`);
23194
23757
  await sendData(command);
23195
23758
  }
23196
23759
  async function sendRuntimeData() {
@@ -23208,6 +23771,7 @@ async function sendRuntimeData() {
23208
23771
  current_screen: screenName
23209
23772
  }
23210
23773
  };
23774
+ console.log("\u{1F4E6} Sending runtime data response");
23211
23775
  await sendData(JSON.stringify(response));
23212
23776
  console.log("\u{1F4E6} Runtime data sent successfully");
23213
23777
  } catch (error) {
@@ -23256,14 +23820,13 @@ async function disconnectFromRoom() {
23256
23820
  function getRoom() {
23257
23821
  return room;
23258
23822
  }
23259
- var room, reconnectTimeout, serverUrl, callbacks, audioContainerRef, livekitUrl, token, roomName;
23823
+ var room, reconnectTimeout, serverUrl, callbacks, audioContainerRef, livekitUrl, token, roomName, livekitClient;
23260
23824
  var init_webrtc_service = __esm({
23261
23825
  "src/utils/webrtc-service.ts"() {
23262
23826
  "use strict";
23263
- init_livekit_client_esm();
23264
23827
  init_globals();
23265
23828
  init_constants();
23266
- init_patch_react();
23829
+ init_element_service();
23267
23830
  init_navigation();
23268
23831
  room = null;
23269
23832
  reconnectTimeout = null;
@@ -23273,6 +23836,7 @@ var init_webrtc_service = __esm({
23273
23836
  livekitUrl = null;
23274
23837
  token = null;
23275
23838
  roomName = null;
23839
+ livekitClient = null;
23276
23840
  }
23277
23841
  });
23278
23842
 
@@ -23877,11 +24441,10 @@ var import_react3 = require("react");
23877
24441
 
23878
24442
  // src/hooks/use-webrtc.ts
23879
24443
  var import_react2 = require("react");
23880
- init_livekit_client_esm();
23881
24444
  init_webrtc_service();
23882
24445
  init_globals();
23883
24446
  var useWebRTC = (options) => {
23884
- const [isConnected3, setIsConnected] = (0, import_react2.useState)(false);
24447
+ const [isConnected2, setIsConnected] = (0, import_react2.useState)(false);
23885
24448
  const [isConnecting, setIsConnecting] = (0, import_react2.useState)(false);
23886
24449
  const [connectionState, setConnectionState] = (0, import_react2.useState)(null);
23887
24450
  const [participants, setParticipants] = (0, import_react2.useState)([]);
@@ -23892,9 +24455,10 @@ var useWebRTC = (options) => {
23892
24455
  setAudioContainer(audioContainerRef2);
23893
24456
  }, []);
23894
24457
  (0, import_react2.useEffect)(() => {
23895
- const handleConnectionStateChange = (state) => {
23896
- setIsConnected(state === ConnectionState.Connected);
23897
- setIsConnecting(state === ConnectionState.Connecting);
24458
+ const handleConnectionStateChange = async (state) => {
24459
+ const { ConnectionState: ConnectionState2 } = await Promise.resolve().then(() => (init_livekit_client_esm(), livekit_client_esm_exports));
24460
+ setIsConnected(state === ConnectionState2.Connected);
24461
+ setIsConnecting(state === ConnectionState2.Connecting);
23898
24462
  setConnectionState(state);
23899
24463
  options?.onConnectionStateChange?.(state);
23900
24464
  };
@@ -23941,11 +24505,20 @@ var useWebRTC = (options) => {
23941
24505
  setIsConnected(false);
23942
24506
  setRoom(null);
23943
24507
  }, []);
24508
+ (0, import_react2.useEffect)(() => {
24509
+ const checkConnection = async () => {
24510
+ const connected = await isConnected();
24511
+ setIsConnected(connected);
24512
+ };
24513
+ checkConnection();
24514
+ const interval = setInterval(checkConnection, 5e3);
24515
+ return () => clearInterval(interval);
24516
+ }, []);
23944
24517
  const memoizedParticipants = (0, import_react2.useMemo)(() => {
23945
24518
  return getParticipants().map((p) => p.identity);
23946
24519
  }, [participants]);
23947
24520
  return {
23948
- isConnected: isConnected3,
24521
+ isConnected: isConnected2,
23949
24522
  isConnecting,
23950
24523
  connectionState,
23951
24524
  room: room2,
@@ -23964,144 +24537,7 @@ var useWebRTC = (options) => {
23964
24537
 
23965
24538
  // src/hooks/use-cuekit.ts
23966
24539
  init_webrtc_service();
23967
-
23968
- // src/utils/element-service.ts
23969
- init_patch_react();
23970
- init_navigation();
23971
- function executeAction(action) {
23972
- console.log("\u{1F3AF} Executing element action:", action);
23973
- const { action_type, target_element, target } = action;
23974
- switch (action_type) {
23975
- case "click":
23976
- return clickElement(target_element);
23977
- case "navigate":
23978
- return navigateToElement(target_element || target);
23979
- case "input":
23980
- case "focus":
23981
- return focusElement(target_element);
23982
- case "toggle":
23983
- return toggleElement(target_element);
23984
- default:
23985
- console.warn(`\u26A0\uFE0F Unknown action type: ${action_type}`);
23986
- return false;
23987
- }
23988
- }
23989
- function getFullDOMStructure() {
23990
- console.log("\u{1F333} ElementService: Getting full DOM structure...");
23991
- return captureFullDOMStructure();
23992
- }
23993
- function clickElement(elementId) {
23994
- if (!elementId) {
23995
- console.warn("\u26A0\uFE0F No element ID provided for click action");
23996
- return false;
23997
- }
23998
- const domStructure = getFullDOMStructure();
23999
- const elementToClick = findElementById(domStructure, elementId);
24000
- if (elementToClick) {
24001
- console.log(`\u{1F3AF} Clicking element: ${elementId}`);
24002
- const domElement = findDOMElementById(elementId);
24003
- if (domElement) {
24004
- domElement.click();
24005
- return true;
24006
- }
24007
- } else {
24008
- console.warn(`\u26A0\uFE0F Element not found: ${elementId}`);
24009
- }
24010
- return false;
24011
- }
24012
- function navigateToElement(target) {
24013
- if (!target) {
24014
- console.warn("\u26A0\uFE0F No target provided for navigation action");
24015
- return false;
24016
- }
24017
- console.log(`\u{1F9ED} Navigating to: ${target}`);
24018
- if (target.includes("/") || target.startsWith("http")) {
24019
- safeNavigate(target, {});
24020
- } else {
24021
- handleNavigationAndClick(target, target);
24022
- }
24023
- return true;
24024
- }
24025
- function focusElement(elementId) {
24026
- if (!elementId) {
24027
- console.warn("\u26A0\uFE0F No element ID provided for focus action");
24028
- return false;
24029
- }
24030
- const domElement = findDOMElementById(elementId);
24031
- if (domElement instanceof HTMLInputElement || domElement instanceof HTMLTextAreaElement || domElement instanceof HTMLSelectElement) {
24032
- console.log(`\u{1F4DD} Focusing element: ${elementId}`);
24033
- domElement.focus();
24034
- return true;
24035
- } else {
24036
- console.warn(`\u26A0\uFE0F Focusable element not found: ${elementId}`);
24037
- return false;
24038
- }
24039
- }
24040
- function toggleElement(elementId) {
24041
- if (!elementId) {
24042
- console.warn("\u26A0\uFE0F No element ID provided for toggle action");
24043
- return false;
24044
- }
24045
- const domElement = findDOMElementById(elementId);
24046
- if (domElement instanceof HTMLElement) {
24047
- console.log(`\u{1F504} Toggling element: ${elementId}`);
24048
- if (domElement instanceof HTMLInputElement) {
24049
- if (domElement.type === "checkbox") {
24050
- domElement.checked = !domElement.checked;
24051
- } else if (domElement.type === "radio") {
24052
- domElement.checked = true;
24053
- }
24054
- domElement.dispatchEvent(new Event("change", { bubbles: true }));
24055
- } else {
24056
- domElement.click();
24057
- }
24058
- return true;
24059
- } else {
24060
- console.warn(`\u26A0\uFE0F Toggleable element not found: ${elementId}`);
24061
- return false;
24062
- }
24063
- }
24064
- function findElementById(domStructure, elementId) {
24065
- const searchInComponents = (components) => {
24066
- for (const component of components) {
24067
- if (component.hash === elementId) {
24068
- return component;
24069
- }
24070
- if (component.children.length > 0) {
24071
- const found = searchInComponents(component.children);
24072
- if (found) return found;
24073
- }
24074
- }
24075
- return null;
24076
- };
24077
- return searchInComponents(domStructure.components);
24078
- }
24079
- function findDOMElementById(elementId) {
24080
- const allElements = document.querySelectorAll("*");
24081
- for (const element3 of allElements) {
24082
- if (element3 instanceof HTMLElement) {
24083
- const hash = generateHash(element3);
24084
- if (hash === elementId) {
24085
- return element3;
24086
- }
24087
- }
24088
- }
24089
- return null;
24090
- }
24091
- function generateHash(element3) {
24092
- const tagName = element3.tagName.toLowerCase();
24093
- const text7 = (element3.textContent || "").trim().substring(0, 50);
24094
- const idString = `${tagName}_${text7}_${element3.tagName}`;
24095
- let hash = 0;
24096
- for (let i2 = 0; i2 < idString.length; i2++) {
24097
- const char = idString.charCodeAt(i2);
24098
- hash = (hash << 5) - hash + char;
24099
- hash |= 0;
24100
- }
24101
- return hash.toString(36);
24102
- }
24103
-
24104
- // src/hooks/use-cuekit.ts
24540
+ init_element_service();
24105
24541
  var useCuekit = (options) => {
24106
24542
  const [messages, setMessages] = (0, import_react3.useState)([]);
24107
24543
  const currentUserMessageRef = (0, import_react3.useRef)(null);
@@ -24153,6 +24589,7 @@ var useCuekit = (options) => {
24153
24589
  const [micState, setMicState] = (0, import_react3.useState)("idle");
24154
24590
  const [status, setStatus] = (0, import_react3.useState)("");
24155
24591
  const handleNavigationCommand = (event) => {
24592
+ console.log(`\u{1F9E0} Processing event in useCuekit: ${event.type}`, event);
24156
24593
  switch (event.type) {
24157
24594
  case "user_speech_chunk":
24158
24595
  case "ai_speech_chunk": {
@@ -24203,6 +24640,7 @@ var useCuekit = (options) => {
24203
24640
  break;
24204
24641
  }
24205
24642
  case "request_runtime_data": {
24643
+ console.log("\u{1F9E0} Requesting runtime data");
24206
24644
  sendRuntimeData();
24207
24645
  break;
24208
24646
  }
@@ -37033,7 +37471,7 @@ var ChatPopup = ({
37033
37471
  onSendText,
37034
37472
  onEndCall,
37035
37473
  messages,
37036
- isConnected: isConnected3,
37474
+ isConnected: isConnected2,
37037
37475
  micState,
37038
37476
  error,
37039
37477
  currentTheme = "dark",
@@ -37620,7 +38058,7 @@ var ChatPopup = ({
37620
38058
  }
37621
38059
  }
37622
38060
  ),
37623
- isConnected3 && onEndCall && /* @__PURE__ */ import_react9.default.createElement(
38061
+ isConnected2 && onEndCall && /* @__PURE__ */ import_react9.default.createElement(
37624
38062
  "button",
37625
38063
  {
37626
38064
  type: "submit",
@@ -39819,7 +40257,7 @@ var MicButton = ({
39819
40257
  const aiSpeechTimeoutRef = (0, import_react15.useRef)(null);
39820
40258
  const activeAITracksRef = (0, import_react15.useRef)(/* @__PURE__ */ new Set());
39821
40259
  const {
39822
- isConnected: isConnected3,
40260
+ isConnected: isConnected2,
39823
40261
  isConnecting,
39824
40262
  error: voiceError,
39825
40263
  connect: voiceConnect,
@@ -39849,6 +40287,7 @@ var MicButton = ({
39849
40287
  console.log("\u{1F3A4} MicButton received messages:", JSON.stringify(messageManagerMessages, null, 2));
39850
40288
  }, [messageManagerMessages]);
39851
40289
  (0, import_react15.useEffect)(() => {
40290
+ if (typeof window === "undefined") return;
39852
40291
  const checkTheme = () => {
39853
40292
  if (typeof document !== "undefined") {
39854
40293
  let newTheme;
@@ -39862,6 +40301,7 @@ var MicButton = ({
39862
40301
  }
39863
40302
  };
39864
40303
  checkTheme();
40304
+ if (typeof window === "undefined") return;
39865
40305
  if (defaultTheme === "system") {
39866
40306
  const observer = new MutationObserver(checkTheme);
39867
40307
  observer.observe(document.documentElement, {
@@ -39904,8 +40344,8 @@ var MicButton = ({
39904
40344
  console.log("\u{1F3A4} MicButton: Current active AI tracks:", Array.from(activeAITracksRef.current));
39905
40345
  console.log("\u{1F3A4} MicButton: Current status:", status);
39906
40346
  console.log("\u{1F3A4} MicButton: Current mic state:", micState);
39907
- console.log("\u{1F3A4} MicButton: Is listening:", isConnected3);
39908
- console.log("\u{1F3A4} MicButton: Is connected:", isConnected3);
40347
+ console.log("\u{1F3A4} MicButton: Is listening:", isConnected2);
40348
+ console.log("\u{1F3A4} MicButton: Is connected:", isConnected2);
39909
40349
  if (isSpeaking && trackId) {
39910
40350
  console.log("\u{1F3A4} MicButton: ===== AI SPEECH START =====");
39911
40351
  console.log("\u{1F3A4} MicButton: Adding track to active set:", trackId);
@@ -39960,7 +40400,7 @@ var MicButton = ({
39960
40400
  console.log("\u{1F3A4} MicButton: - Status:", status);
39961
40401
  console.log("\u{1F3A4} MicButton: ================================");
39962
40402
  },
39963
- [status, micState, isConnected3]
40403
+ [status, micState, isConnected2]
39964
40404
  );
39965
40405
  (0, import_react15.useEffect)(() => {
39966
40406
  if (audioContainerRef2.current) {
@@ -39973,9 +40413,9 @@ var MicButton = ({
39973
40413
  }
39974
40414
  };
39975
40415
  }, [handleAISpeech]);
39976
- const isListening = isConnected3;
39977
- const getUserFriendlyStatus = (micState2, isConnected4) => {
39978
- if (!isConnected4) {
40416
+ const isListening = isConnected2;
40417
+ const getUserFriendlyStatus = (micState2, isConnected3) => {
40418
+ if (!isConnected3) {
39979
40419
  return "Connecting...";
39980
40420
  }
39981
40421
  if (status && !status.includes("error") && !status.includes("failed") && !status.includes("Connection error") && !status.includes("Unable to")) {
@@ -39985,28 +40425,28 @@ var MicButton = ({
39985
40425
  if (micState2 === "thinking") return "Thinking...";
39986
40426
  if (micState2 === "replying") return "Responding...";
39987
40427
  if (micState2 === "idle") {
39988
- if (isConnected4) return "Listening...";
40428
+ if (isConnected3) return "Listening...";
39989
40429
  return "Connecting...";
39990
40430
  }
39991
- return isConnected4 ? "Ready" : "Connecting...";
40431
+ return isConnected3 ? "Ready" : "Connecting...";
39992
40432
  };
39993
40433
  (0, import_react15.useEffect)(() => {
39994
- if (isConnected3) {
40434
+ if (isConnected2) {
39995
40435
  console.log("\u{1F3A4} MicButton: WebRTC and SSE connections established - ready for commands");
39996
40436
  } else {
39997
40437
  console.log("\u{1F3A4} MicButton: WebRTC not yet connected - ignoring speech");
39998
40438
  }
39999
- }, [isConnected3]);
40439
+ }, [isConnected2]);
40000
40440
  (0, import_react15.useEffect)(() => {
40001
40441
  console.log("\u{1F3A4} MicButton: Auto-open check:", {
40002
- isConnected: isConnected3,
40442
+ isConnected: isConnected2,
40003
40443
  chatIsOpen: isChatOpen
40004
40444
  });
40005
- if (isConnected3 && !isChatOpen) {
40445
+ if (isConnected2 && !isChatOpen) {
40006
40446
  console.log("\u{1F3A4} MicButton: Auto-opening chat popup");
40007
40447
  openChat();
40008
40448
  }
40009
- }, [isConnected3, isChatOpen, openChat]);
40449
+ }, [isConnected2, isChatOpen, openChat]);
40010
40450
  (0, import_react15.useEffect)(() => {
40011
40451
  if (messageManagerMessages.length > 0 && !isChatOpen) {
40012
40452
  console.log("\u{1F3A4} MicButton: Auto-opening chat popup due to messages");
@@ -40014,7 +40454,7 @@ var MicButton = ({
40014
40454
  }
40015
40455
  }, [messageManagerMessages.length, isChatOpen, openChat]);
40016
40456
  const handleMicClick = (0, import_react15.useCallback)(() => {
40017
- const shouldStop = micState === "listening" && isConnected3;
40457
+ const shouldStop = micState === "listening" && isConnected2;
40018
40458
  if (shouldStop) {
40019
40459
  console.log("\u{1F3A4} MicButton: User wants to stop - closing everything");
40020
40460
  voiceDisconnect().then(() => {
@@ -40039,7 +40479,7 @@ var MicButton = ({
40039
40479
  }
40040
40480
  }, [
40041
40481
  micState,
40042
- isConnected3,
40482
+ isConnected2,
40043
40483
  voiceDisconnect,
40044
40484
  voiceConnect,
40045
40485
  apiKey,
@@ -40054,7 +40494,7 @@ var MicButton = ({
40054
40494
  if (!isChatOpen) {
40055
40495
  openChat();
40056
40496
  }
40057
- if (isConnected3) {
40497
+ if (isConnected2) {
40058
40498
  console.log("\u{1F3A4} MicButton: Sending via WebRTC");
40059
40499
  try {
40060
40500
  await sendUserCommand2(textToSend);
@@ -40251,13 +40691,13 @@ var MicButton = ({
40251
40691
  text: msg.text,
40252
40692
  sender: msg.role === "ai" ? "assistant" : "user"
40253
40693
  })),
40254
- isConnected: isConnected3 ?? false,
40694
+ isConnected: isConnected2 ?? false,
40255
40695
  micState,
40256
40696
  participants,
40257
40697
  error: voiceError,
40258
40698
  currentTheme,
40259
40699
  onThemeToggle: setCurrentTheme,
40260
- status: getUserFriendlyStatus(micState, isConnected3 ?? false),
40700
+ status: getUserFriendlyStatus(micState, isConnected2 ?? false),
40261
40701
  anchor: { position: screenPosition, bottom: bottomSpace, size: buttonSize }
40262
40702
  }
40263
40703
  ), isChatOpen && isChatMinimized && /* @__PURE__ */ import_react15.default.createElement(
@@ -40286,4 +40726,5 @@ var MicButton = ({
40286
40726
  };
40287
40727
 
40288
40728
  // src/index.ts
40289
- init_patch_react();
40729
+ init_element_service();
40730
+ init_element_service();