ttp-agent-sdk 2.43.0 → 2.45.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 (46) hide show
  1. package/dist/agent-widget.dev.js +5999 -2308
  2. package/dist/agent-widget.dev.js.map +1 -1
  3. package/dist/agent-widget.esm.js +1 -1
  4. package/dist/agent-widget.esm.js.map +1 -1
  5. package/dist/agent-widget.js +1 -1
  6. package/dist/agent-widget.js.map +1 -1
  7. package/dist/audio-processor.js +2 -2
  8. package/dist/demos/demo-sdk-loader.js +1 -0
  9. package/dist/demos/discovery.js +1 -0
  10. package/dist/demos/index.html +0 -13
  11. package/dist/demos/test-ecommerce.html +28 -45
  12. package/dist/demos/test-tour.html +19 -35
  13. package/dist/demos/test-widget.html +38 -18
  14. package/dist/demos/widget-customization-dev.html +15 -6
  15. package/dist/demos/widget-customization.html +14 -6
  16. package/dist/discovery.js +1 -0
  17. package/dist/examples/demo-sdk-loader.js +1 -0
  18. package/dist/examples/demo-v2.html +2 -2
  19. package/dist/examples/discovery.js +1 -0
  20. package/dist/examples/ocado-cart-network-probe.js +1 -0
  21. package/dist/examples/sobeys-cart-dispatch-probe.js +1 -0
  22. package/dist/examples/sobeys-cart-read-test.html +112 -0
  23. package/dist/examples/sobeys-cart-read-test.js +1 -0
  24. package/dist/examples/sobeys-cart-subscribe-probe.js +1 -0
  25. package/dist/examples/sobeys-cart-subscribe-test.html +168 -0
  26. package/dist/examples/sobeys-cart-subscribe-test.js +1 -0
  27. package/dist/examples/sobeys-inject-probe-min.js +1 -0
  28. package/dist/examples/sobeys-inject-probe.js +1 -0
  29. package/dist/examples/test-ecommerce.html +28 -45
  30. package/dist/examples/test-index.html +0 -13
  31. package/dist/examples/test-restaurant.html +4 -2
  32. package/dist/examples/test-tour.html +19 -35
  33. package/dist/examples/test-widget.html +38 -18
  34. package/dist/examples/widget-customization-dev.html +15 -6
  35. package/dist/examples/widget-customization.html +14 -6
  36. package/dist/hooks/noyhasade.js +1 -0
  37. package/examples/demo-sdk-loader.js +249 -0
  38. package/examples/demo-v2.html +2 -2
  39. package/examples/test-ecommerce.html +28 -45
  40. package/examples/test-index.html +0 -13
  41. package/examples/test-restaurant.html +4 -2
  42. package/examples/test-tour.html +19 -35
  43. package/examples/test-widget.html +38 -18
  44. package/examples/widget-customization-dev.html +15 -6
  45. package/examples/widget-customization.html +14 -6
  46. package/package.json +2 -2
@@ -149,8 +149,9 @@
149
149
  </label>
150
150
  <label>STT Provider
151
151
  <select id="sttSelect">
152
+ <option value="soniox" selected>Soniox (default — no override)</option>
152
153
  <option value="">Default (server)</option>
153
- <option value="azure-stt" selected>Azure STT</option>
154
+ <option value="azure-stt">Azure STT</option>
154
155
  </select>
155
156
  </label>
156
157
  </div>
@@ -201,24 +202,7 @@ window.testWidget._flavor.messageHandlers['show_items']({
201
202
  });</div>
202
203
  </div>
203
204
 
204
- <script>
205
- (function() {
206
- var isNgrok = window.location.hostname.includes('ngrok');
207
- if (isNgrok) {
208
- var s = document.createElement('script');
209
- s.type = 'text/javascript';
210
- document.head.appendChild(s);
211
- fetch('/agent-widget.js', { headers: { 'ngrok-skip-browser-warning': '1' } })
212
- .then(function(r) { return r.text(); })
213
- .then(function(code) { s.textContent = code; })
214
- .catch(function(e) { console.error('SDK fetch failed:', e); });
215
- } else {
216
- var s = document.createElement('script');
217
- s.src = '/agent-widget.js';
218
- document.head.appendChild(s);
219
- }
220
- })();
221
- </script>
205
+ <script src="demo-sdk-loader.js"></script>
222
206
 
223
207
  <script>
224
208
  let chatWidget = null;
@@ -244,14 +228,15 @@ window.testWidget._flavor.messageHandlers['show_items']({
244
228
  const agentId = document.getElementById('agentId').value;
245
229
  const appId = document.getElementById('appId').value;
246
230
 
247
- chatWidget = new TTPAgentSDK.TTPChatWidget({
231
+ const widgetConfig = window.TTPDemoSdkLoader.applyWebSocketUrl({
248
232
  agentId,
249
233
  appId,
250
234
  language: document.getElementById('languageSelect').value,
251
235
  agentSettingsOverride: (() => {
252
236
  const override = {};
253
237
  const stt = document.getElementById('sttSelect').value;
254
- if (stt) override.sttProvider = stt;
238
+ // Soniox is server default; only override when picking a non-default provider
239
+ if (stt && stt !== 'soniox') override.sttProvider = stt;
255
240
  return override;
256
241
  })(),
257
242
  behavior: {
@@ -272,6 +257,7 @@ window.testWidget._flavor.messageHandlers['show_items']({
272
257
  text: 'היי, אשמח אם תוכלי לעזור לי במשהו....'
273
258
  }
274
259
  });
260
+ chatWidget = new TTPAgentSDK.TTPChatWidget(widgetConfig);
275
261
 
276
262
  window.testWidget = chatWidget;
277
263
  updateStatus('TTPChatWidget created — tours flavor (mock-tour)', 'success');
@@ -352,22 +338,20 @@ window.testWidget._flavor.messageHandlers['show_items']({
352
338
  updateStatus('Booking cleared', '');
353
339
  };
354
340
 
355
- function waitForSDK() {
356
- return new Promise((resolve, reject) => {
357
- if (window.TTPAgentSDK?.TTPChatWidget) { resolve(); return; }
358
- let attempts = 0;
359
- const iv = setInterval(() => {
360
- attempts++;
361
- if (window.TTPAgentSDK?.TTPChatWidget) { clearInterval(iv); resolve(); }
362
- else if (attempts >= 150) { clearInterval(iv); reject(new Error('SDK failed to load')); }
363
- }, 100);
364
- });
341
+ function boot() {
342
+ const mode = window.TTPDemoSdkLoader?.getMode?.() || 'prod';
343
+ updateStatus('SDK loaded (' + mode + ') creating widget...', '');
344
+ createWidget();
365
345
  }
366
346
 
367
- waitForSDK().then(() => {
368
- updateStatus('SDK loaded — creating widget...', '');
369
- createWidget();
370
- }).catch(e => {
347
+ window.addEventListener('ttp-demo-sdk-ready', () => {
348
+ if (chatWidget) {
349
+ chatWidget.destroy();
350
+ chatWidget = null;
351
+ }
352
+ boot();
353
+ });
354
+ window.TTPDemoSdkLoader.waitForReady().then(boot).catch((e) => {
371
355
  updateStatus('SDK load failed: ' + e.message, 'error');
372
356
  });
373
357
  </script>
@@ -285,9 +285,11 @@
285
285
  <input type="text" id="getSessionUrl" value="" placeholder="https://your-api.com/get-session">
286
286
  </div>
287
287
 
288
- <div class="config-group">
289
- <label for="websocketUrl">WebSocket URL</label>
290
- <input type="text" id="websocketUrl" value="wss://speech.talktopc.com/ws/conv" placeholder="wss://...">
288
+ <div class="config-group" style="grid-column: 1 / -1;">
289
+ <label>WebSocket URL</label>
290
+ <p id="demoWsUrlDisplay" style="font-size: 13px; color: #4b5563; margin-top: 4px; font-family: monospace;">
291
+ Set by SDK toggle (top-right): Production → speech.talktopc.com · Development → speech.bidme.co.il
292
+ </p>
291
293
  </div>
292
294
 
293
295
  <div class="config-group">
@@ -398,16 +400,12 @@
398
400
  </div>
399
401
  </div>
400
402
 
401
- <!-- Load SDK as UMD library (script tag) -->
402
- <script src="/agent-widget.js" onload="console.log('✅ SDK script loaded, TTPAgentSDK:', typeof window.TTPAgentSDK)" onerror="console.error('❌ Failed to load SDK script')"></script>
403
+ <script src="demo-sdk-loader.js"></script>
403
404
  <script>
404
- console.log('🔵 Waiting for SDK to load...');
405
-
406
- // Wait for TTPAgentSDK to be available (UMD library loads as global)
405
+ console.log('🔵 Waiting for SDK to load (use top-right toggle for prod/dev)...');
406
+
407
407
  function initSDK() {
408
408
  if (typeof window.TTPAgentSDK === 'undefined') {
409
- console.log('⏳ TTPAgentSDK not ready yet, waiting...');
410
- setTimeout(initSDK, 100);
411
409
  return;
412
410
  }
413
411
 
@@ -427,6 +425,8 @@
427
425
 
428
426
  window.TTPChatWidget = TTPChatWidget;
429
427
  window.widgetInstance = null;
428
+ const mode = window.TTPDemoSdkLoader?.getMode?.() || '?';
429
+ console.log('✅ SDK ready:', window.TTPDemoSdkLoader?.getSrc?.(mode), '(' + mode + ')');
430
430
 
431
431
  // Define functions after module loads
432
432
  window.initializeWidget = function() {
@@ -442,7 +442,6 @@
442
442
  const agentId = document.getElementById('agentId').value;
443
443
  const appId = document.getElementById('appId').value;
444
444
  const getSessionUrl = document.getElementById('getSessionUrl').value;
445
- const websocketUrl = document.getElementById('websocketUrl').value;
446
445
  const position = document.getElementById('position').value;
447
446
  const language = document.getElementById('language').value;
448
447
  const mode = document.getElementById('mode').value;
@@ -477,9 +476,8 @@
477
476
  config.getSessionUrl = getSessionUrl;
478
477
  }
479
478
 
480
- if (websocketUrl) {
481
- config.websocketUrl = websocketUrl;
482
- }
479
+ window.TTPDemoSdkLoader.applyWebSocketUrl(config);
480
+ console.log('🔌 websocketUrl:', config.websocketUrl, '(SDK mode:', window.TTPDemoSdkLoader.getMode() + ')');
483
481
 
484
482
  // Handle position
485
483
  if (position) {
@@ -549,7 +547,6 @@
549
547
  document.getElementById('agentId').value = 'agent_e5cf06457';
550
548
  document.getElementById('appId').value = 'app_Bc01EqMQt2Euehl4qqZSi6l3FJP42Q9vJ0pC';
551
549
  document.getElementById('getSessionUrl').value = '';
552
- document.getElementById('websocketUrl').value = 'wss://speech.talktopc.com/ws/conv';
553
550
  document.getElementById('position').value = 'bottom-right';
554
551
  document.getElementById('language').value = 'en';
555
552
  document.getElementById('mode').value = 'unified';
@@ -638,9 +635,32 @@
638
635
  resetConfig: typeof window.resetConfig
639
636
  });
640
637
  }
641
-
642
- // Start initialization
643
- initSDK();
638
+
639
+ function updateWsUrlDisplay() {
640
+ const el = document.getElementById('demoWsUrlDisplay');
641
+ if (!el || !window.TTPDemoSdkLoader) return;
642
+ const mode = window.TTPDemoSdkLoader.getMode();
643
+ el.textContent = window.TTPDemoSdkLoader.getWebSocketUrl(mode) + ' (' + mode + ')';
644
+ }
645
+
646
+ window.addEventListener('ttp-demo-sdk-ready', () => {
647
+ updateWsUrlDisplay();
648
+ if (window.widgetInstance && typeof window.destroyWidget === 'function') {
649
+ window.destroyWidget();
650
+ }
651
+ initSDK();
652
+ // Re-create widget if user already initialized (so WS URL matches new SDK mode)
653
+ if (typeof window.initializeWidget === 'function' && document.getElementById('widgetStatus')?.textContent === 'Yes') {
654
+ window.initializeWidget();
655
+ }
656
+ });
657
+ window.TTPDemoSdkLoader.waitForReady().then(() => {
658
+ updateWsUrlDisplay();
659
+ initSDK();
660
+ }).catch((e) => {
661
+ console.error('❌ SDK load failed:', e);
662
+ alert('SDK load failed. Check Network for agent-widget*.js');
663
+ });
644
664
  </script>
645
665
  </body>
646
666
  </html>
@@ -1280,10 +1280,11 @@
1280
1280
  }
1281
1281
  }
1282
1282
  </style>
1283
+ <script src="demo-sdk-loader.js"></script>
1283
1284
  </head>
1284
1285
  <body>
1285
1286
  <div class="header">
1286
- <div class="dev-banner">⚠️ DEV PAGE - Using production SDK (agent-widget.js)</div>
1287
+ <div class="dev-banner">🔧 Use the SDK toggle (top-right) to switch Production ↔ Development bundles</div>
1287
1288
  <a href="test-index.html" class="back-link">← Back to Demos</a>
1288
1289
  <h1>🎨 Widget Live Customization (Dev Page)</h1>
1289
1290
  <div style="margin-top: 16px; display: flex; align-items: center; justify-content: center; gap: 24px; flex-wrap: wrap;">
@@ -4126,6 +4127,10 @@
4126
4127
  }
4127
4128
  };
4128
4129
 
4130
+ if (window.TTPDemoSdkLoader) {
4131
+ window.TTPDemoSdkLoader.applyWebSocketUrl(actualConfig);
4132
+ }
4133
+
4129
4134
  try {
4130
4135
  // Reset manual close tracking when widget is recreated (unless user manually closed it)
4131
4136
  // Don't reset if widget was manually closed and mock panel is also closed
@@ -4348,8 +4353,15 @@
4348
4353
  };
4349
4354
 
4350
4355
  // Start checking for SDK (will also be called when script loads)
4351
- window.checkAndInitWidget();
4352
-
4356
+ window.addEventListener('ttp-demo-sdk-ready', () => {
4357
+ if (actualWidgetInstance) {
4358
+ try { actualWidgetInstance.destroy(); } catch (e) { /* ignore */ }
4359
+ actualWidgetInstance = null;
4360
+ }
4361
+ window.checkAndInitWidget();
4362
+ });
4363
+ window.TTPDemoSdkLoader.waitForReady().then(() => window.checkAndInitWidget());
4364
+
4353
4365
  // Debug helper - expose widget instance globally for inspection
4354
4366
  window.debugWidget = function() {
4355
4367
  console.log('=== Widget Debug Info ===');
@@ -4376,8 +4388,5 @@
4376
4388
  };
4377
4389
  };
4378
4390
  </script>
4379
-
4380
- <!-- Load the widget SDK (production version) -->
4381
- <script src="/agent-widget.js?v=2.34.2" onload="if (typeof window.checkAndInitWidget === 'function') setTimeout(window.checkAndInitWidget, 100);" onerror="console.error('❌ Failed to load SDK script from /agent-widget.js'); alert('Failed to load SDK. Check console for details.');"></script>
4382
4391
  </body>
4383
4392
  </html>
@@ -1793,6 +1793,7 @@
1793
1793
  }
1794
1794
  }
1795
1795
  </style>
1796
+ <script src="demo-sdk-loader.js"></script>
1796
1797
  </head>
1797
1798
  <body>
1798
1799
  <div class="header">
@@ -5017,6 +5018,10 @@
5017
5018
  }
5018
5019
  };
5019
5020
 
5021
+ if (window.TTPDemoSdkLoader) {
5022
+ window.TTPDemoSdkLoader.applyWebSocketUrl(actualConfig);
5023
+ }
5024
+
5020
5025
  try {
5021
5026
  // Reset manual close tracking when widget is recreated (unless user manually closed it)
5022
5027
  // Don't reset if widget was manually closed and mock panel is also closed
@@ -5450,9 +5455,15 @@
5450
5455
  }
5451
5456
  };
5452
5457
 
5453
- // Start checking for SDK (will also be called when script loads)
5454
- window.checkAndInitWidget();
5455
-
5458
+ window.addEventListener('ttp-demo-sdk-ready', () => {
5459
+ if (actualWidgetInstance) {
5460
+ try { actualWidgetInstance.destroy(); } catch (e) { /* ignore */ }
5461
+ actualWidgetInstance = null;
5462
+ }
5463
+ window.checkAndInitWidget();
5464
+ });
5465
+ window.TTPDemoSdkLoader.waitForReady().then(() => window.checkAndInitWidget());
5466
+
5456
5467
  // Debug helper - expose widget instance globally for inspection
5457
5468
  window.debugWidget = function() {
5458
5469
  console.log('=== Widget Debug Info ===');
@@ -5479,8 +5490,5 @@
5479
5490
  };
5480
5491
  };
5481
5492
  </script>
5482
-
5483
- <!-- Load the widget SDK -->
5484
- <script src="/agent-widget.js" onload="if (typeof window.checkAndInitWidget === 'function') setTimeout(window.checkAndInitWidget, 100);" onerror="console.error('❌ Failed to load SDK script from /agent-widget.js'); alert('Failed to load SDK. Check console for details.');"></script>
5485
5493
  </body>
5486
5494
  </html>
@@ -0,0 +1 @@
1
+ function noyhasadeDataProductId(t){if(null==t||""===t)return"";const o=String(t);return o.startsWith("product#")?"search-product#"+o.slice(8):(o.startsWith("search-product#"),o)}function ensureCatGrid(){let t=document.querySelector(".cat-grid");if(t)return t;const o=document.querySelector("main")||document.querySelector(".site-content")||document.body;return t=document.createElement("div"),t.className="cat-grid",o.prepend(t),t}function findCardByDataId(t){if(null==t||""===t)return null;const o=String(t),e=[o];o.startsWith("api-")||e.push("api-"+o);for(const t of e)for(const o of document.querySelectorAll("[data-product-id]"))if(o.getAttribute("data-product-id")===t)return o;return null}function findCartLineMeta(t,o){if(void 0===window.NoyCart||"function"!=typeof window.NoyCart.getAll)return null;try{const e=window.NoyCart.getAll()||[],n=Array.isArray(e)?e:Object.values(e),r=t=>{const o=String(t||"").match(/#(\d+)/);return o?o[1]:""},a=r(o)||r(t)||r(noyhasadeDataProductId(t));if(!a)return null;for(const t of n)if(t&&String(t.id||"").includes("#"+a))return t}catch(t){console.warn("[NoyHasade] findCartLineMeta:",t)}return null}function truthyFlag(t){return!0===t||"true"===t||1===t||"1"===t}function escapeHtml(t){return String(null==t?"":t).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function cartSummaryForLog(t){return t&&t.length?t.map(t=>`${t.id||"?"}×${t.qty??"?"}`).join(" | "):"(empty)"}function openNoyCart(){if(void 0!==window.NoyCartUI&&"function"==typeof window.NoyCartUI.open)return window.NoyCartUI.open(),!0;const t=document.getElementById("headCart");return!!t&&(t.click(),!0)}function closeNoyCart(){if(void 0!==window.NoyCartUI&&"function"==typeof window.NoyCartUI.close)try{return window.NoyCartUI.close(),!0}catch(t){console.warn("[NoyHasade] NoyCartUI.close failed:",t)}const t=document.getElementById("headCart");if(t&&"true"===t.getAttribute("aria-expanded"))return t.click(),!0;try{document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0,cancelable:!0}))}catch(t){console.warn("[NoyHasade] closeNoyCart Escape fallback failed:",t)}return!1}function noyCategoryPathForSlug(t){const o=String(t||"").trim();if(!o)return"";const e=o.split("/").map(t=>t.trim()).filter(Boolean);return e.length?"/product-category/"+e.map(t=>encodeURIComponent(t)).join("/")+"/":""}function noyFindCategoryNavLink(t){const o=String(t||"").trim();if(!o)return null;const e=noyCategoryPathForSlug(o);let n=e;try{n=decodeURIComponent(e)}catch(t){}for(const t of document.querySelectorAll("[data-api-category-slug]")){if((t.getAttribute("data-api-category-slug")||"").trim()!==o)continue;const e=t.closest("a");if(e&&e.href)return e}for(const t of document.querySelectorAll('a[href*="product-category"]')){const r=t.getAttribute("href")||"";if(!r)continue;let a="";try{a=new URL(r,location.origin).pathname}catch(t){continue}try{const r=decodeURIComponent(a);if(a===new URL(e,location.origin).pathname||r===n||r.includes("/"+o+"/")||r.endsWith("/"+o))return t}catch(e){if(a.includes(encodeURIComponent(o))||a.includes(o))return t}}return null}function noyOpenCategory(t){const o=String(t||"").trim();if(!o)return;try{sessionStorage.setItem(STORAGE_SCROLL_CATEGORY_KEY,o)}catch(t){}const e=noyCategoryPathForSlug(o);if(!e)return;let n=location.pathname;try{n=decodeURIComponent(location.pathname)}catch(t){}const r=new URL(e,location.origin);try{if(location.pathname===r.pathname||n===decodeURIComponent(r.pathname))return void[350,900,1800].forEach(t=>window.setTimeout(noyTryScrollToCategoryProducts,t))}catch(t){}const a=noyFindCategoryNavLink(o);if(a)try{return a.click(),console.log("[NoyHasade] open_category via native nav link",e),void[350,900,1800].forEach(t=>window.setTimeout(noyTryScrollToCategoryProducts,t))}catch(t){console.warn("[NoyHasade] nav link click failed:",t)}if("function"==typeof window.NoyNavigateToCategory)try{return window.NoyNavigateToCategory(o),console.log("[NoyHasade] open_category via NoyNavigateToCategory",o),void[350,900,1800].forEach(t=>window.setTimeout(noyTryScrollToCategoryProducts,t))}catch(t){console.warn("[NoyHasade] NoyNavigateToCategory failed:",t)}try{history.pushState(null,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:null})),console.log("[NoyHasade] open_category via pushState+popstate",e)}catch(t){return console.warn("[NoyHasade] pushState failed, assigning location:",t),void location.assign(e)}[350,900,1800].forEach(t=>window.setTimeout(noyTryScrollToCategoryProducts,t))}let _shoppingListAddQueue=Promise.resolve();const SHOPPING_LIST_REVEAL_MS=380,SHOPPING_LIST_FLY_PAD_MS=820,OPEN_CATEGORY_AFTER_CART_CLOSE_MS=260,STORAGE_SCROLL_CATEGORY_KEY="ttpNoyCatScrollSlug";function noyScrollDebugEnabled(){try{if("undefined"!=typeof window&&!0===window.__TTP_NOY_SCROLL_DEBUG__)return!0;if("undefined"!=typeof localStorage&&"1"===localStorage.getItem("ttpNoyScrollDebug"))return!0}catch(t){}return!1}function noyScrollLog(...t){noyScrollDebugEnabled()&&console.log("[NoyHasade scroll]",...t)}const CATEGORY_SCROLL_EXTRA_DRASTIC_PX=1e3,CATEGORY_SCROLL_SLOW_EXTRA_PX=2e3,CATEGORY_SCROLL_LOOP_PX_PER_SEC=2600,CATEGORY_SCROLL_LOOP_MIN_STEP_PX=28,CATEGORY_SCROLL_LOOP_MAX_STEP_PX=220,CATEGORY_SCROLL_LOOP_STUCK_FRAMES=5,CATEGORY_SCROLL_LOOP_MAX_MS=25e3,CATEGORY_SCROLL_TARGET_OFFSET_PX=3e3,CATEGORY_SCROLL_AFTER_SMOOTH_INTO_VIEW_MS=600,CATEGORY_SCROLL_POST_LOAD_MS=3e3,CATEGORY_SCROLL_POST_LOAD_MS_FAST=400,CATEGORY_SCROLL_LOAD_FALLBACK_MS=15e3;function noyRunAfterPageLoaded(t,o){const e="number"==typeof o?o:CATEGORY_SCROLL_POST_LOAD_MS;let n=!1;const r=()=>{n||(n=!0,window.setTimeout(t,e))};"complete"!==document.readyState?(window.addEventListener("load",r,{once:!0}),window.setTimeout(r,15e3)):r()}function noyFindInnerScrollContainer(){let t=null,o=0;const e=document.body;if(!e)return null;const n=e.querySelectorAll("*");for(let e=0;e<n.length;e++){const r=n[e],a=r.tagName;if("SCRIPT"===a||"STYLE"===a||"SVG"===a||"IFRAME"===a)continue;let c;try{c=getComputedStyle(r)}catch(t){continue}if(!/(auto|scroll|overlay)/.test(c.overflowY))continue;const i=r.scrollHeight-r.clientHeight;i>o&&i>48&&(o=i,t=r)}return t}function noyResolveScrollTarget(){const t=document.documentElement,o=Math.max(0,t.scrollHeight-window.innerHeight),e=noyFindInnerScrollContainer(),n=e?Math.max(0,e.scrollHeight-e.clientHeight):0;let r=!1;try{const o=document.body?getComputedStyle(document.body):{},e=getComputedStyle(t);r=/hidden|clip/.test(o.overflowY||"")||/hidden|clip/.test(e.overflowY||"")||/hidden|clip/.test(o.overflow||"")||/hidden|clip/.test(e.overflow||"")}catch(t){}return noyScrollLog("noyResolveScrollTarget",{winMax:o,innerMax:n,bodyLocksVertical:r,inner:e?e.tagName+"."+(e.className||""):null}),e&&n>64&&(r||n+8>=o)?{mode:"element",el:e}:{mode:"window",el:null}}function noyWithInstantScroll(t,o){const e=[],n=t=>{t&&1===t.nodeType&&e.push(t)};n(document.documentElement),n(document.body),n(t);const r=e.map(t=>t.style.scrollBehavior);e.forEach(t=>{try{t.style.scrollBehavior="auto"}catch(t){}});try{o()}finally{e.forEach((t,o)=>{try{t.style.scrollBehavior=r[o]||""}catch(t){}})}}function noyCategoryScrollLoopToOffset(t){if(t<1)return;let o=noyResolveScrollTarget();const e=performance.now();let n=e,r=0,a=t;const c=()=>{if("element"===o.mode&&o.el){const t=o.el,e=Math.max(0,t.scrollHeight-t.clientHeight);return{el:t,max:e,get:()=>t.scrollTop,kind:"element"}}return{el:null,max:Math.max(0,document.documentElement.scrollHeight-window.innerHeight),get:()=>window.scrollY??window.pageYOffset??0,kind:"window"}},i=c();noyScrollLog("noyCategoryScrollLoopToOffset",{mode:o.mode,totalOffsetPx:t,start:i.get(),scrollMax:i.max,pxPerSec:2600}),i.max-i.get()<2?noyScrollLog("scroll loop: no room at start"):requestAnimationFrame(function t(i){if(a<=2)return void noyScrollLog("scroll loop: done (budget spent)");if(i-e>25e3)return void noyScrollLog("scroll loop: timeout",{remaining:a});const l=c();if(l.get()>=l.max-2)return void noyScrollLog("scroll loop: hit scroll max",{remaining:a});const d=Math.min(.1,Math.max(0,(i-n)/1e3));n=i;let s=Math.ceil(2600*d);s=Math.max(28,Math.min(220,s));const u=function(t){const o=c(),e=o.get(),n=Math.max(0,o.max-e),r=Math.min(t,n,a);if(r<1)return 0;if("element"===o.kind&&o.el){const t=o.el;return noyWithInstantScroll(t,()=>{try{t.scrollBy({top:r,left:0,behavior:"auto"})}catch(o){t.scrollTop+=r}t.scrollTop<=e+.5&&(t.scrollTop=Math.min(e+r,o.max))}),Math.max(0,t.scrollTop-e)}return noyWithInstantScroll(null,()=>{try{window.scrollBy({top:r,left:0,behavior:"auto"})}catch(t){window.scrollTo(window.scrollX,e+r)}}),Math.max(0,(window.scrollY??window.pageYOffset??0)-e)}(s);if(a=Math.max(0,a-u),u<1){if(r+=1,r>=5){r=0;const t=noyResolveScrollTarget();t.mode===o.mode&&t.el===o.el||noyScrollLog("scroll loop: re-resolve target",{was:o.mode,now:t.mode}),o=t}}else r=0;requestAnimationFrame(t)})}function noyCategoryScrollSequence(t){if(t&&t.isConnected){noyScrollLog("noyCategoryScrollSequence: start",t.tagName,t.className);try{t.scrollIntoView({behavior:"instant",block:"start"})}catch(t){}window.setTimeout(()=>{noyCategoryScrollLoopToOffset(3e3)},600)}else noyScrollLog("noyCategoryScrollSequence: anchor not connected, skipping",t)}function noyStripHebrewNiqqud(t){return String(t||"").replace(/[\u0591-\u05C7]/g,"")}function noyCategoryScrollWindowOnly(){noyScrollLog("noyCategoryScrollWindowOnly: no product anchor, scrolling window or inner panel"),window.setTimeout(()=>{noyCategoryScrollLoopToOffset(3e3)},600)}function findFirstCategoryProductRow(){const t=document.querySelector(".cat-grid");if(t){const o=t.querySelector('.cat-card, article[class*="product"], li.product');if(o)return o}const o=document.querySelector("ul.products");if(o){const t=o.querySelector("li.product");if(t)return t}const e=document.querySelector(".woocommerce .products .product");if(e)return e;const n=["main",".site-content","#siteMain","#content",".page-content","article.page"];for(const t of n)for(const o of[`${t} [data-product-id]`,`${t} .product`,`${t} [class*="product-card"]`,`${t} .cat-card`])try{const t=document.querySelector(o);if(t)return t}catch(t){}for(const t of[".category-products [data-product-id]",".category-products .product","[data-category-products] [data-product-id]","section.products [data-product-id]"])try{const o=document.querySelector(t);if(o)return o}catch(t){}return document.querySelector("[data-product-id]")||null}const NOY_CATEGORY_SCROLL_EXTRA_PATH_TESTS={המזווה:t=>/category-pantry/i.test(t),מזווה:t=>/category-pantry/i.test(t),pantry:t=>/category-pantry/i.test(t)};function noyPathMatchesCategorySlug(t,o){const e=String(o||"").trim();if(!e)return!1;const n="/product-category/"+e+"/";if(t.includes(n))return!0;try{const o="/product-category/"+encodeURIComponent(e)+"/";if(t.includes(o))return!0}catch(t){}const r=NOY_CATEGORY_SCROLL_EXTRA_PATH_TESTS[e];if("function"==typeof r&&r(t))return!0;const a=noyStripHebrewNiqqud(e);for(const o of Object.keys(NOY_CATEGORY_SCROLL_EXTRA_PATH_TESTS))if(noyStripHebrewNiqqud(o)===a){const e=NOY_CATEGORY_SCROLL_EXTRA_PATH_TESTS[o];if("function"==typeof e&&e(t))return!0}return!!(/category-pantry/i.test(t)&&a.length>0)}function noyRunCategoryScrollWhenReady(){let t=0;const o=()=>{t+=1;const e=findFirstCategoryProductRow();if(!e||!e.isConnected)return t>=80?(noyScrollLog("give up: no product row after",t,"tries; window-only scroll"),void noyCategoryScrollWindowOnly()):void window.setTimeout(o,120);noyCategoryScrollSequence(e)};o()}function noyTryScrollToCategoryProducts(){let t=null;try{t=sessionStorage.getItem(STORAGE_SCROLL_CATEGORY_KEY)}catch(t){return}if(!t)return void(/category-pantry/i.test(location.pathname)&&noyScrollDebugEnabled()&&console.warn("[NoyHasade scroll] sessionStorage missing",STORAGE_SCROLL_CATEGORY_KEY,"— open_category must run before navigating here, or scroll will not run."));let o="";try{o=decodeURIComponent(location.pathname)}catch(t){o=location.pathname}if(!noyPathMatchesCategorySlug(o,t))return void noyScrollLog("path/slug mismatch — skip scroll",{path:o,wanted:t,pathname:location.pathname});const e=/category-pantry/i.test(o)||/category-pantry/i.test(location.pathname)?CATEGORY_SCROLL_POST_LOAD_MS_FAST:CATEGORY_SCROLL_POST_LOAD_MS;let n=0;const r=()=>{if(n+=1,findFirstCategoryProductRow()){try{sessionStorage.removeItem(STORAGE_SCROLL_CATEGORY_KEY)}catch(t){}return noyScrollLog("product row found, scheduling post-load scroll"),void noyRunAfterPageLoaded(()=>{noyRunCategoryScrollWhenReady()},e)}if(n>=120){try{sessionStorage.removeItem(STORAGE_SCROLL_CATEGORY_KEY)}catch(t){}return noyScrollLog("no product node in time — post-load window-only scroll"),void noyRunAfterPageLoaded(()=>{noyRunCategoryScrollWhenReady()},e)}setTimeout(r,100)};r()}function noyDefaultFlyPadMs(){return void 0!==window.NoyCart&&"number"==typeof window.NoyCart.flyAnimationMs?window.NoyCart.flyAnimationMs:820}window.__TTP_HOOKS__={addToCart(t){const o=async()=>{const{productId:o,quantity:e,productName:n,price:r,currency:a,imageUrl:c,sellBy:i,openCart:l}=t||{},d="[NoyHasade addToCart]";let s=!1;const u=truthyFlag(t?.showOnPage),y=truthyFlag(t?.last),g=u?y:!1!==l;if(void 0===window.NoyCart||"function"!=typeof window.NoyCart.setQtyFromCard){console.error(`${d} NoyCart missing or setQtyFromCard unavailable`);const t=Number(e),r=Number.isFinite(t)&&t<=0,a=!r||0!==t&&-1!==t?r?Math.abs(t):0:1;return{productName:n||o,quantity:r?-a:Number.isFinite(t)&&t>0?t:1}}const p=noyhasadeDataProductId(o);let f=null;if(u){const t=ensureCatGrid(),e=p||String(o||""),l=null!=r&&""!==r?String(r):"",d=c?[c]:[],s="weight"===i?'/ לק"ג':"/ יחידה";"function"==typeof window.NoyAppendProductCard?f=window.NoyAppendProductCard(t,{id:e,name:n||"",images:d,price:l,showPriceBy:s,isIsraeli:!0}):(window.__TTP_HOOKS__._showProductOnPage({productId:o,productName:n,price:r,currency:a,imageUrl:c,dataId:p,sellBy:i}),"function"==typeof window.NoyEnhanceCategoryCards&&window.NoyEnhanceCategoryCards(t)),f||(f=findCardByDataId(e)||findCardByDataId(p))}f||(f=findCardByDataId(p));const m=!!f;if(!f){const t=findCartLineMeta(o,p),e=c||t?.imageSrc||t?.image||"",l=n||t?.name||"",u=null!=r&&""!==r?r:t?.unitPrice,y=null!=u&&""!==u?`${u} ${a||"₪"}`:"",g="weight"===i?'לק"ג':"quantity"===i?"ליח'":t?.meta&&/לק|ק"ג/.test(String(t.meta))?'לק"ג':"ליח'";f=document.createElement("div"),f.setAttribute("data-product-id",t&&t.id?t.id:p||o);const m=escapeHtml(l);f.innerHTML=`\n <span class="cat-card__title">${m}</span>\n <span class="cat-card__price">${escapeHtml(y)}</span>\n <span class="cat-card__unit">${escapeHtml(g)}</span>\n <div class="cat-card__img"><img src="${escapeHtml(e)}" alt="${m}"></div>\n `,console.log(`${d} fake card pidAttr=${f.getAttribute("data-product-id")} enriched=${!!t}`);const w=ensureCatGrid();f.classList.add("cat-card"),w.appendChild(f),s=!0}let w=[];if("function"==typeof window.NoyCart.getAll)try{const t=window.NoyCart.getAll()||[];w=Array.isArray(t)?t:Object.values(t)}catch(t){console.error(`${d} getAll before op failed:`,t)}const C=Number(e),S=Number.isFinite(C)&&C<=0;console.log(`${d} start`,{productId:o,quantity:C,mode:S?"subtract":"add",dataId:p,card:m?"dom":"fake",cartLines:w.length,cart:cartSummaryForLog(w)});const _="function"==typeof window.NoyCart.getQtyStepForCard?window.NoyCart.getQtyStepForCard(f):1,h=!S||0!==C&&-1!==C?S?Math.abs(C):0:1,T="function"==typeof window.NoyCart.getProductId?window.NoyCart.getProductId(f):"",O=T&&"function"==typeof window.NoyCart.getQty?window.NoyCart.getQty(T):0;let L;if(S&&0===O&&console.warn(`${d} SUBTRACT no-op: cart has qty 0 for resolved pid="${T}" (productId=${o}). Wrong SKU vs cart, or line not in cart — backend should match get_site_cart.`),S){const t=Math.max(0,O-h);L="function"==typeof window.NoyCart.normalizeQty?window.NoyCart.normalizeQty(t,_):t}else{const t=Number.isFinite(C)&&C>0?C:1;if(u){const o=O+t;L="function"==typeof window.NoyCart.normalizeQty?window.NoyCart.normalizeQty(o,_):o}else L="function"==typeof window.NoyCart.normalizeQty?window.NoyCart.normalizeQty(t,_):t}if(!S&&f&&f.isConnected&&"function"==typeof f.scrollIntoView&&(u||s)){try{f.scrollIntoView({behavior:"smooth",block:"nearest"})}catch(t){}await new Promise(t=>setTimeout(t,380))}console.log(`${d} setQty`,{pid:T,prevQty:O,targetQty:L,step:_,subtractUnits:S?h:void 0});try{S?window.NoyCart.setQtyFromCard(f,L,{fly:!1}):window.NoyCart.setQtyFromCard(f,L,{fly:!0})}catch(t){console.error(`${d} setQtyFromCard failed:`,t)}if(S||await new Promise(t=>setTimeout(t,noyDefaultFlyPadMs())),s){try{f.remove()}catch(t){}s=!1}const N=T&&"function"==typeof window.NoyCart.getQty?window.NoyCart.getQty(T):void 0;S&&O>0&&N===O&&L!==O&&console.warn(`${d} SUBTRACT: qty unchanged after setQty (still ${O}); target was ${L}`);let A=[];if("function"==typeof window.NoyCart.getAll)try{const t=window.NoyCart.getAll()||[];A=Array.isArray(t)?t:Object.values(t)}catch(t){console.error(`${d} getAll after op failed:`,t)}const R=t=>{const o={};return t.forEach(t=>{t&&t.id&&(o[t.id]=t.qty)}),o},E=R(w),v=R(A),P=Object.keys({...E,...v}).some(t=>E[t]!==v[t]);S&&O>0&&!P&&console.warn(`${d} subtract did not change any cart line`,{pid:T,prevQty:O,targetQty:L,cart:cartSummaryForLog(A)}),console.log(`${d} done`,{cart:cartSummaryForLog(A),cartChanged:P,pid:T,qtyAfter:N}),g&&(openNoyCart()||console.warn(`${d} could not open cart drawer`));const b=A.length,I=A.reduce((t,o)=>t+(o.unitPrice??o.price??0)*(o.qty||0),0);return{productName:n||o,quantity:S?-h:Number.isFinite(C)&&C>0?C:1,cartItemCount:b,cartTotal:I,currency:a||"ILS"}};if(truthyFlag(t?.showOnPage)){const t=_shoppingListAddQueue.then(o,o);return _shoppingListAddQueue=t.catch(()=>{}),t}return o()},getCart(){if(void 0!==window.NoyCart&&"function"==typeof window.NoyCart.getAll){const t=window.NoyCart.getAll(),o=Array.isArray(t)?t:Object.values(t||{}),e=o.reduce((t,o)=>t+(o.unitPrice??o.price??0)*(o.qty||o.quantity||0),0);return console.log("[NoyHasade getCart]",{lines:o.length,cart:cartSummaryForLog(o),total_price:e}),{items:o.map(t=>({title:t.name||t.title,quantity:t.qty||t.quantity,price:t.unitPrice??t.price})),item_count:o.length,total_price:e}}return console.warn("[NoyHasade getCart] NoyCart.getAll not available"),{items:[],item_count:0,total_price:0}},async simulateSearch({query:t}){closeNoyCart(),void 0!==window.NoyDevSearch&&"function"==typeof window.NoyDevSearch.run?await window.NoyDevSearch.run(t):console.warn("[NoyHasade Hooks] NoyDevSearch.run not available")},clear_products(){const t=ensureCatGrid();t.innerHTML="",t.scrollIntoView({behavior:"smooth",block:"start"}),console.log("[NoyHasade Hooks] Cleared product grid (.cat-grid)")},open_category(t){closeNoyCart();const o=t?.slug??t?.category_slug;window.setTimeout(()=>{noyOpenCategory(o),console.log("[NoyHasade Hooks] open_category",o||"(empty)")},260)},_showProductOnPage({productId:t,productName:o,price:e,currency:n,imageUrl:r,dataId:a,sellBy:c}){const i=ensureCatGrid(),l=a||noyhasadeDataProductId(t),d=e?`${e}&nbsp;₪`:"",s="weight"===c?'/ לק"ג':"/ יחידה",u=escapeHtml(o||""),y='<article class="cat-card" data-product-id="'+l+'"><div class="cat-card__media"><div class="cat-card__img"><img src="'+escapeHtml(r||"")+'" alt="'+u+'" loading="lazy" width="600" height="600"/></div></div><div class="cat-card__body"><h3 class="cat-card__title">'+u+'</h3><div class="cat-card__price-row"><span class="cat-card__price">'+d+'</span><span class="cat-card__unit">'+s+'</span></div><div class="cat-card__actions"><button type="button" class="cat-card__plus" aria-label="הוסף לעגלה">+</button></div></div></article>';i.insertAdjacentHTML("beforeend",y),"function"==typeof window.NoyEnhanceCategoryCards&&window.NoyEnhanceCategoryCards(i),console.log(`[NoyHasade Hooks] Added product card to page: ${o} (${l})`)}},window.__TTP_NOY_CATEGORY_SCROLL_INIT__||(window.__TTP_NOY_CATEGORY_SCROLL_INIT__=!0,window.addEventListener("pageshow",()=>noyTryScrollToCategoryProducts()),window.addEventListener("popstate",()=>window.setTimeout(noyTryScrollToCategoryProducts,50))),noyTryScrollToCategoryProducts();
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Demo pages: toggle Production vs Development SDK bundle.
3
+ * Persists choice in localStorage; dispatches `ttp-demo-sdk-ready` after each load.
4
+ */
5
+ (function (global) {
6
+ const STORAGE_KEY = 'ttp-demo-sdk-mode';
7
+ const PROD_SRC = '/agent-widget.js';
8
+ const DEV_SRC = '/agent-widget.dev.js';
9
+ const PROD_WS_URL = 'wss://speech.talktopc.com/ws/conv';
10
+ const DEV_WS_URL = 'wss://speech.bidme.co.il/ws/conv';
11
+
12
+ let loadPromise = null;
13
+ let currentMode = null;
14
+
15
+ function getMode() {
16
+ return global.localStorage.getItem(STORAGE_KEY) === 'dev' ? 'dev' : 'prod';
17
+ }
18
+
19
+ function getSrc(mode) {
20
+ return mode === 'dev' ? DEV_SRC : PROD_SRC;
21
+ }
22
+
23
+ function getLabel(mode) {
24
+ return mode === 'dev' ? 'Development' : 'Production';
25
+ }
26
+
27
+ /** WebSocket URL for widget config — tied to SDK mode, not user-editable. */
28
+ function getWebSocketUrl(mode) {
29
+ return (mode === 'dev' ? DEV_WS_URL : PROD_WS_URL);
30
+ }
31
+
32
+ function applyWebSocketUrl(config, mode) {
33
+ const next = config && typeof config === 'object' ? config : {};
34
+ const resolvedMode = mode === 'dev' || mode === 'prod' ? mode : getMode();
35
+ next.websocketUrl = getWebSocketUrl(resolvedMode);
36
+ return next;
37
+ }
38
+
39
+ function destroyWidgetInstances() {
40
+ const destroy = (w) => {
41
+ try {
42
+ w?.destroy?.();
43
+ } catch (e) {
44
+ console.warn('[TTPDemoSdk] destroy failed', e);
45
+ }
46
+ };
47
+ destroy(global.widgetInstance);
48
+ destroy(global.chatWidget);
49
+ destroy(global.testWidget);
50
+ if (typeof global.actualWidgetInstance !== 'undefined') {
51
+ destroy(global.actualWidgetInstance);
52
+ global.actualWidgetInstance = null;
53
+ }
54
+ global.widgetInstance = null;
55
+ global.chatWidget = null;
56
+ global.testWidget = null;
57
+ }
58
+
59
+ function removeSdkScripts() {
60
+ document.querySelectorAll('script[src*="agent-widget"]').forEach((s) => s.remove());
61
+ delete global.TTPAgentSDK;
62
+ delete global.TTPChatWidget;
63
+ }
64
+
65
+ function loadSdkViaScriptTag(mode) {
66
+ return new Promise((resolve, reject) => {
67
+ removeSdkScripts();
68
+ const script = document.createElement('script');
69
+ script.src = getSrc(mode) + '?t=' + Date.now();
70
+ script.onload = () => {
71
+ currentMode = mode;
72
+ const detail = { mode, src: script.src, label: getLabel(mode) };
73
+ global.dispatchEvent(new CustomEvent('ttp-demo-sdk-ready', { detail }));
74
+ resolve(global.TTPAgentSDK);
75
+ };
76
+ script.onerror = () => reject(new Error('Failed to load SDK: ' + script.src));
77
+ document.head.appendChild(script);
78
+ });
79
+ }
80
+
81
+ function loadSdkViaNgrokFetch(mode) {
82
+ return fetch(getSrc(mode), { headers: { 'ngrok-skip-browser-warning': '1' } })
83
+ .then((r) => {
84
+ if (!r.ok) throw new Error('SDK fetch HTTP ' + r.status);
85
+ return r.text();
86
+ })
87
+ .then((code) => {
88
+ removeSdkScripts();
89
+ const script = document.createElement('script');
90
+ script.type = 'text/javascript';
91
+ script.textContent = code;
92
+ document.head.appendChild(script);
93
+ currentMode = mode;
94
+ const detail = { mode, src: getSrc(mode), label: getLabel(mode), ngrok: true };
95
+ global.dispatchEvent(new CustomEvent('ttp-demo-sdk-ready', { detail }));
96
+ return global.TTPAgentSDK;
97
+ });
98
+ }
99
+
100
+ function loadSdk(mode) {
101
+ mode = mode === 'dev' || mode === 'prod' ? mode : getMode();
102
+ global.localStorage.setItem(STORAGE_KEY, mode);
103
+ updateToggleUI(mode);
104
+
105
+ loadPromise = global.location.hostname.includes('ngrok')
106
+ ? loadSdkViaNgrokFetch(mode)
107
+ : loadSdkViaScriptTag(mode);
108
+
109
+ return loadPromise.catch((err) => {
110
+ console.error('[TTPDemoSdk]', err);
111
+ throw err;
112
+ });
113
+ }
114
+
115
+ function setMode(mode) {
116
+ if (mode !== 'dev' && mode !== 'prod') return loadSdk(getMode());
117
+ destroyWidgetInstances();
118
+ return loadSdk(mode);
119
+ }
120
+
121
+ function waitForReady() {
122
+ if (global.TTPAgentSDK?.TTPChatWidget && loadPromise) {
123
+ return Promise.resolve(global.TTPAgentSDK);
124
+ }
125
+ return loadPromise || loadSdk(getMode());
126
+ }
127
+
128
+ function injectStyles() {
129
+ if (document.getElementById('ttp-demo-sdk-toggle-styles')) return;
130
+ const style = document.createElement('style');
131
+ style.id = 'ttp-demo-sdk-toggle-styles';
132
+ style.textContent = `
133
+ #ttp-demo-sdk-toggle {
134
+ position: fixed;
135
+ top: 12px;
136
+ right: 12px;
137
+ z-index: 2147483646;
138
+ display: flex;
139
+ align-items: center;
140
+ gap: 8px;
141
+ padding: 8px 12px;
142
+ background: #111827;
143
+ color: #f9fafb;
144
+ font: 13px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
145
+ border-radius: 10px;
146
+ box-shadow: 0 4px 14px rgba(0,0,0,.25);
147
+ }
148
+ #ttp-demo-sdk-toggle .ttp-demo-sdk-label { opacity: .85; margin-right: 4px; }
149
+ #ttp-demo-sdk-toggle button {
150
+ border: none;
151
+ cursor: pointer;
152
+ padding: 6px 12px;
153
+ border-radius: 6px;
154
+ font-size: 12px;
155
+ font-weight: 600;
156
+ background: #374151;
157
+ color: #e5e7eb;
158
+ }
159
+ #ttp-demo-sdk-toggle button:hover { background: #4b5563; }
160
+ #ttp-demo-sdk-toggle button.active {
161
+ background: #4f46e5;
162
+ color: #fff;
163
+ }
164
+ #ttp-demo-sdk-toggle button.active-dev {
165
+ background: #d97706;
166
+ color: #fff;
167
+ }
168
+ #ttp-demo-sdk-toggle .ttp-demo-sdk-file {
169
+ font-size: 11px;
170
+ opacity: .7;
171
+ max-width: 140px;
172
+ overflow: hidden;
173
+ text-overflow: ellipsis;
174
+ white-space: nowrap;
175
+ }
176
+ `;
177
+ document.head.appendChild(style);
178
+ }
179
+
180
+ function updateToggleUI(mode) {
181
+ const root = document.getElementById('ttp-demo-sdk-toggle');
182
+ if (!root) return;
183
+ const prodBtn = root.querySelector('[data-mode="prod"]');
184
+ const devBtn = root.querySelector('[data-mode="dev"]');
185
+ const fileEl = root.querySelector('.ttp-demo-sdk-file');
186
+ if (prodBtn) {
187
+ prodBtn.classList.toggle('active', mode === 'prod');
188
+ prodBtn.classList.toggle('active-dev', false);
189
+ }
190
+ if (devBtn) {
191
+ devBtn.classList.toggle('active', mode === 'dev');
192
+ devBtn.classList.toggle('active-dev', mode === 'dev');
193
+ }
194
+ if (fileEl) {
195
+ fileEl.title = getWebSocketUrl(mode);
196
+ fileEl.textContent = mode === 'dev' ? 'dev.js · speech.bidme' : 'prod.js · talktopc';
197
+ }
198
+ }
199
+
200
+ function injectToggle() {
201
+ if (document.getElementById('ttp-demo-sdk-toggle')) return;
202
+ injectStyles();
203
+ const root = document.createElement('div');
204
+ root.id = 'ttp-demo-sdk-toggle';
205
+ root.setAttribute('role', 'group');
206
+ root.setAttribute('aria-label', 'SDK bundle');
207
+ root.innerHTML =
208
+ '<span class="ttp-demo-sdk-label">SDK</span>' +
209
+ '<button type="button" data-mode="prod" title="Production minified bundle">Production</button>' +
210
+ '<button type="button" data-mode="dev" title="Development bundle with source maps">Development</button>' +
211
+ '<span class="ttp-demo-sdk-file"></span>';
212
+ root.querySelector('[data-mode="prod"]').addEventListener('click', () => {
213
+ if (getMode() !== 'prod') setMode('prod');
214
+ });
215
+ root.querySelector('[data-mode="dev"]').addEventListener('click', () => {
216
+ if (getMode() !== 'dev') setMode('dev');
217
+ });
218
+ document.body.appendChild(root);
219
+ updateToggleUI(getMode());
220
+ }
221
+
222
+ function init() {
223
+ injectToggle();
224
+ return loadSdk(getMode());
225
+ }
226
+
227
+ global.TTPDemoSdkLoader = {
228
+ STORAGE_KEY,
229
+ PROD_SRC,
230
+ DEV_SRC,
231
+ PROD_WS_URL,
232
+ DEV_WS_URL,
233
+ getMode,
234
+ getSrc,
235
+ getLabel,
236
+ getWebSocketUrl,
237
+ applyWebSocketUrl,
238
+ loadSdk,
239
+ setMode,
240
+ waitForReady,
241
+ destroyWidgetInstances,
242
+ };
243
+
244
+ if (document.readyState === 'loading') {
245
+ document.addEventListener('DOMContentLoaded', init);
246
+ } else {
247
+ init();
248
+ }
249
+ })(window);
@@ -721,9 +721,9 @@
721
721
 
722
722
  <option value="22050">22.05 kHz</option>
723
723
 
724
- <option value="24000">24 kHz</option>
724
+ <option value="24000" selected>24 kHz</option>
725
725
 
726
- <option value="44100" selected>44.1 kHz (CD Quality)</option>
726
+ <option value="44100">44.1 kHz (CD Quality)</option>
727
727
 
728
728
  <option value="48000">48 kHz (Pro)</option>
729
729