ttp-agent-sdk 2.44.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 (34) hide show
  1. package/dist/agent-widget.dev.js +2131 -646
  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/demos/demo-sdk-loader.js +1 -0
  8. package/dist/demos/test-ecommerce.html +23 -42
  9. package/dist/demos/test-tour.html +15 -33
  10. package/dist/demos/test-widget.html +38 -18
  11. package/dist/demos/widget-customization-dev.html +15 -6
  12. package/dist/demos/widget-customization.html +14 -6
  13. package/dist/examples/demo-sdk-loader.js +1 -0
  14. package/dist/examples/ocado-cart-network-probe.js +1 -0
  15. package/dist/examples/sobeys-cart-dispatch-probe.js +1 -0
  16. package/dist/examples/sobeys-cart-read-test.html +112 -0
  17. package/dist/examples/sobeys-cart-read-test.js +1 -0
  18. package/dist/examples/sobeys-cart-subscribe-probe.js +1 -0
  19. package/dist/examples/sobeys-cart-subscribe-test.html +168 -0
  20. package/dist/examples/sobeys-cart-subscribe-test.js +1 -0
  21. package/dist/examples/sobeys-inject-probe-min.js +1 -0
  22. package/dist/examples/sobeys-inject-probe.js +1 -0
  23. package/dist/examples/test-ecommerce.html +23 -42
  24. package/dist/examples/test-tour.html +15 -33
  25. package/dist/examples/test-widget.html +38 -18
  26. package/dist/examples/widget-customization-dev.html +15 -6
  27. package/dist/examples/widget-customization.html +14 -6
  28. package/examples/demo-sdk-loader.js +249 -0
  29. package/examples/test-ecommerce.html +23 -42
  30. package/examples/test-tour.html +15 -33
  31. package/examples/test-widget.html +38 -18
  32. package/examples/widget-customization-dev.html +15 -6
  33. package/examples/widget-customization.html +14 -6
  34. package/package.json +2 -1
@@ -0,0 +1 @@
1
+ !function(e){const t="ttp-demo-sdk-mode",n="/agent-widget.js",o="/agent-widget.dev.js",d="wss://speech.talktopc.com/ws/conv",r="wss://speech.bidme.co.il/ws/conv";let c=null,s=null;function a(){return"dev"===e.localStorage.getItem(t)?"dev":"prod"}function i(e){return"dev"===e?o:n}function l(e){return"dev"===e?"Development":"Production"}function p(e){return"dev"===e?r:d}function u(){const t=e=>{try{e?.destroy?.()}catch(e){console.warn("[TTPDemoSdk] destroy failed",e)}};t(e.widgetInstance),t(e.chatWidget),t(e.testWidget),void 0!==e.actualWidgetInstance&&(t(e.actualWidgetInstance),e.actualWidgetInstance=null),e.widgetInstance=null,e.chatWidget=null,e.testWidget=null}function g(){document.querySelectorAll('script[src*="agent-widget"]').forEach(e=>e.remove()),delete e.TTPAgentSDK,delete e.TTPChatWidget}function m(n){return n="dev"===n||"prod"===n?n:a(),e.localStorage.setItem(t,n),v(n),c=e.location.hostname.includes("ngrok")?function(t){return fetch(i(t),{headers:{"ngrok-skip-browser-warning":"1"}}).then(e=>{if(!e.ok)throw new Error("SDK fetch HTTP "+e.status);return e.text()}).then(n=>{g();const o=document.createElement("script");o.type="text/javascript",o.textContent=n,document.head.appendChild(o),s=t;const d={mode:t,src:i(t),label:l(t),ngrok:!0};return e.dispatchEvent(new CustomEvent("ttp-demo-sdk-ready",{detail:d})),e.TTPAgentSDK})}(n):function(t){return new Promise((n,o)=>{g();const d=document.createElement("script");d.src=i(t)+"?t="+Date.now(),d.onload=()=>{s=t;const o={mode:t,src:d.src,label:l(t)};e.dispatchEvent(new CustomEvent("ttp-demo-sdk-ready",{detail:o})),n(e.TTPAgentSDK)},d.onerror=()=>o(new Error("Failed to load SDK: "+d.src)),document.head.appendChild(d)})}(n),c.catch(e=>{throw console.error("[TTPDemoSdk]",e),e})}function f(e){return"dev"!==e&&"prod"!==e?m(a()):(u(),m(e))}function v(e){const t=document.getElementById("ttp-demo-sdk-toggle");if(!t)return;const n=t.querySelector('[data-mode="prod"]'),o=t.querySelector('[data-mode="dev"]'),d=t.querySelector(".ttp-demo-sdk-file");n&&(n.classList.toggle("active","prod"===e),n.classList.toggle("active-dev",!1)),o&&(o.classList.toggle("active","dev"===e),o.classList.toggle("active-dev","dev"===e)),d&&(d.title=p(e),d.textContent="dev"===e?"dev.js · speech.bidme":"prod.js · talktopc")}function b(){return function(){if(document.getElementById("ttp-demo-sdk-toggle"))return;!function(){if(document.getElementById("ttp-demo-sdk-toggle-styles"))return;const e=document.createElement("style");e.id="ttp-demo-sdk-toggle-styles",e.textContent="\n #ttp-demo-sdk-toggle {\n position: fixed;\n top: 12px;\n right: 12px;\n z-index: 2147483646;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: #111827;\n color: #f9fafb;\n font: 13px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n border-radius: 10px;\n box-shadow: 0 4px 14px rgba(0,0,0,.25);\n }\n #ttp-demo-sdk-toggle .ttp-demo-sdk-label { opacity: .85; margin-right: 4px; }\n #ttp-demo-sdk-toggle button {\n border: none;\n cursor: pointer;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 600;\n background: #374151;\n color: #e5e7eb;\n }\n #ttp-demo-sdk-toggle button:hover { background: #4b5563; }\n #ttp-demo-sdk-toggle button.active {\n background: #4f46e5;\n color: #fff;\n }\n #ttp-demo-sdk-toggle button.active-dev {\n background: #d97706;\n color: #fff;\n }\n #ttp-demo-sdk-toggle .ttp-demo-sdk-file {\n font-size: 11px;\n opacity: .7;\n max-width: 140px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n ",document.head.appendChild(e)}();const e=document.createElement("div");e.id="ttp-demo-sdk-toggle",e.setAttribute("role","group"),e.setAttribute("aria-label","SDK bundle"),e.innerHTML='<span class="ttp-demo-sdk-label">SDK</span><button type="button" data-mode="prod" title="Production minified bundle">Production</button><button type="button" data-mode="dev" title="Development bundle with source maps">Development</button><span class="ttp-demo-sdk-file"></span>',e.querySelector('[data-mode="prod"]').addEventListener("click",()=>{"prod"!==a()&&f("prod")}),e.querySelector('[data-mode="dev"]').addEventListener("click",()=>{"dev"!==a()&&f("dev")}),document.body.appendChild(e),v(a())}(),m(a())}e.TTPDemoSdkLoader={STORAGE_KEY:t,PROD_SRC:n,DEV_SRC:o,PROD_WS_URL:d,DEV_WS_URL:r,getMode:a,getSrc:i,getLabel:l,getWebSocketUrl:p,applyWebSocketUrl:function(e,t){const n=e&&"object"==typeof e?e:{},o="dev"===t||"prod"===t?t:a();return n.websocketUrl=p(o),n},loadSdk:m,setMode:f,waitForReady:function(){return e.TTPAgentSDK?.TTPChatWidget&&c?Promise.resolve(e.TTPAgentSDK):c||m(a())},destroyWidgetInstances:u},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",b):b()}(window);
@@ -119,16 +119,14 @@
119
119
  </head>
120
120
  <body>
121
121
  <div class="container">
122
- <h1>TTP Hotels Flavor Test</h1>
122
+ <h1>TTP Flavor Test (Ecommerce / Hotels / …)</h1>
123
123
 
124
124
  <div class="info">
125
125
  <strong>How it works:</strong>
126
126
  <ul>
127
- <li>Uses the standard <code>TTPChatWidget</code> with <code>flavor: { type: 'hotels', partnerId: 'mock-hotel' }</code></li>
128
- <li>The backend injects hotel tools (<code>search_rooms</code>, <code>select_room</code>, <code>add_extra</code>, <code>get_booking</code>)</li>
129
- <li>Room cards display when the agent sends <code>show_items</code> messages</li>
130
- <li>Booking summary updates on <code>booking_updated</code> messages</li>
131
- <li>Gallery (<code>show_media</code>) opens fullscreen with widget minimized</li>
127
+ <li>Pick an <strong>Agent</strong> below — the demo passes <code>flavor: { type, partnerId, callView: 'minimized' }</code> for every vertical.</li>
128
+ <li>On <strong>desktop</strong> (&gt;768px), <strong><code>callView: 'minimized'</code></strong> uses the bottom voice strip when a call is active (in-panel active call UI is hidden). Mobile keeps the existing minimized bar behavior.</li>
129
+ <li>Each vertical wires WebSocket handlers (e.g. hotels: <code>show_items</code> rooms, <code>booking_updated</code>, <code>show_media</code>).</li>
132
130
  </ul>
133
131
  </div>
134
132
 
@@ -138,8 +136,8 @@
138
136
  <div class="settings-grid">
139
137
  <label>Agent
140
138
  <select id="agentSelect" onchange="handleAgentChange()">
141
- <option value="agent_ed18369b3|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|ecommerce|mock-store">Ecommerce Demo (agent_ed18369b3)</option>
142
- <option value="agent_d0774f1af|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|hotels|mock-hotel" selected>Hotels Demo (agent_d0774f1af)</option>
139
+ <option value="agent_ed18369b3|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|ecommerce|mock-store" selected>Ecommerce Demo (agent_ed18369b3)</option>
140
+ <option value="agent_d0774f1af|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|hotels|mock-hotel">Hotels Demo (agent_d0774f1af)</option>
143
141
  <option value="agent_PHARMA_ID|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|pharma|mock-pharm">Pharma Demo (update agent ID)</option>
144
142
  <option value="agent_RESTAURANT_ID|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|restaurants|mock-restaurant">Restaurant Demo (update agent ID)</option>
145
143
  <option value="agent_TOUR_ID|app_wNGQKiMUfUT5JdVIaxzXOJfdcgBegxGY5hZo|tours|mock-tour">Tour Demo (update agent ID)</option>
@@ -233,24 +231,7 @@ window.testWidget._flavor.messageHandlers['show_media']({
233
231
  });</div>
234
232
  </div>
235
233
 
236
- <script>
237
- (function() {
238
- var isNgrok = window.location.hostname.includes('ngrok');
239
- if (isNgrok) {
240
- var s = document.createElement('script');
241
- s.type = 'text/javascript';
242
- document.head.appendChild(s);
243
- fetch('/agent-widget.js', { headers: { 'ngrok-skip-browser-warning': '1' } })
244
- .then(function(r) { return r.text(); })
245
- .then(function(code) { s.textContent = code; })
246
- .catch(function(e) { console.error('SDK fetch failed:', e); });
247
- } else {
248
- var s = document.createElement('script');
249
- s.src = '/agent-widget.js';
250
- document.head.appendChild(s);
251
- }
252
- })();
253
- </script>
234
+ <script src="demo-sdk-loader.js"></script>
254
235
 
255
236
  <script>
256
237
  let chatWidget = null;
@@ -296,7 +277,7 @@ window.testWidget._flavor.messageHandlers['show_media']({
296
277
 
297
278
  const agent = getAgentConfig();
298
279
 
299
- chatWidget = new TTPAgentSDK.TTPChatWidget({
280
+ const widgetConfig = window.TTPDemoSdkLoader.applyWebSocketUrl({
300
281
  agentId: agent.agentId,
301
282
  appId: agent.appId,
302
283
  language: document.getElementById('languageSelect').value,
@@ -313,7 +294,8 @@ window.testWidget._flavor.messageHandlers['show_media']({
313
294
  },
314
295
  flavor: {
315
296
  type: agent.flavorType,
316
- partnerId: agent.partnerId
297
+ partnerId: agent.partnerId,
298
+ callView: 'minimized',
317
299
  },
318
300
  icon: {
319
301
  type: 'custom',
@@ -326,6 +308,7 @@ window.testWidget._flavor.messageHandlers['show_media']({
326
308
  text: 'היי, אשמח אם תוכלי לעזור לי '
327
309
  }
328
310
  });
311
+ chatWidget = new TTPAgentSDK.TTPChatWidget(widgetConfig);
329
312
 
330
313
  window.testWidget = chatWidget;
331
314
  const sttLabel = document.getElementById('sttSelect').selectedOptions[0].text;
@@ -416,22 +399,20 @@ window.testWidget._flavor.messageHandlers['show_media']({
416
399
  };
417
400
 
418
401
  // Wait for SDK and auto-create
419
- function waitForSDK() {
420
- return new Promise((resolve, reject) => {
421
- if (window.TTPAgentSDK?.TTPChatWidget) { resolve(); return; }
422
- let attempts = 0;
423
- const iv = setInterval(() => {
424
- attempts++;
425
- if (window.TTPAgentSDK?.TTPChatWidget) { clearInterval(iv); resolve(); }
426
- else if (attempts >= 150) { clearInterval(iv); reject(new Error('SDK failed to load')); }
427
- }, 100);
428
- });
402
+ function boot() {
403
+ const mode = window.TTPDemoSdkLoader?.getMode?.() || 'prod';
404
+ updateStatus('SDK loaded (' + mode + ') click Create Widget or wait...', '');
405
+ createWidget();
429
406
  }
430
407
 
431
- waitForSDK().then(() => {
432
- updateStatus('SDK loaded — creating widget...', '');
433
- createWidget();
434
- }).catch(e => {
408
+ window.addEventListener('ttp-demo-sdk-ready', () => {
409
+ if (chatWidget) {
410
+ chatWidget.destroy();
411
+ chatWidget = null;
412
+ }
413
+ boot();
414
+ });
415
+ window.TTPDemoSdkLoader.waitForReady().then(boot).catch((e) => {
435
416
  updateStatus('SDK load failed: ' + e.message, 'error');
436
417
  });
437
418
  </script>
@@ -202,24 +202,7 @@ window.testWidget._flavor.messageHandlers['show_items']({
202
202
  });</div>
203
203
  </div>
204
204
 
205
- <script>
206
- (function() {
207
- var isNgrok = window.location.hostname.includes('ngrok');
208
- if (isNgrok) {
209
- var s = document.createElement('script');
210
- s.type = 'text/javascript';
211
- document.head.appendChild(s);
212
- fetch('/agent-widget.js', { headers: { 'ngrok-skip-browser-warning': '1' } })
213
- .then(function(r) { return r.text(); })
214
- .then(function(code) { s.textContent = code; })
215
- .catch(function(e) { console.error('SDK fetch failed:', e); });
216
- } else {
217
- var s = document.createElement('script');
218
- s.src = '/agent-widget.js';
219
- document.head.appendChild(s);
220
- }
221
- })();
222
- </script>
205
+ <script src="demo-sdk-loader.js"></script>
223
206
 
224
207
  <script>
225
208
  let chatWidget = null;
@@ -245,7 +228,7 @@ window.testWidget._flavor.messageHandlers['show_items']({
245
228
  const agentId = document.getElementById('agentId').value;
246
229
  const appId = document.getElementById('appId').value;
247
230
 
248
- chatWidget = new TTPAgentSDK.TTPChatWidget({
231
+ const widgetConfig = window.TTPDemoSdkLoader.applyWebSocketUrl({
249
232
  agentId,
250
233
  appId,
251
234
  language: document.getElementById('languageSelect').value,
@@ -274,6 +257,7 @@ window.testWidget._flavor.messageHandlers['show_items']({
274
257
  text: 'היי, אשמח אם תוכלי לעזור לי במשהו....'
275
258
  }
276
259
  });
260
+ chatWidget = new TTPAgentSDK.TTPChatWidget(widgetConfig);
277
261
 
278
262
  window.testWidget = chatWidget;
279
263
  updateStatus('TTPChatWidget created — tours flavor (mock-tour)', 'success');
@@ -354,22 +338,20 @@ window.testWidget._flavor.messageHandlers['show_items']({
354
338
  updateStatus('Booking cleared', '');
355
339
  };
356
340
 
357
- function waitForSDK() {
358
- return new Promise((resolve, reject) => {
359
- if (window.TTPAgentSDK?.TTPChatWidget) { resolve(); return; }
360
- let attempts = 0;
361
- const iv = setInterval(() => {
362
- attempts++;
363
- if (window.TTPAgentSDK?.TTPChatWidget) { clearInterval(iv); resolve(); }
364
- else if (attempts >= 150) { clearInterval(iv); reject(new Error('SDK failed to load')); }
365
- }, 100);
366
- });
341
+ function boot() {
342
+ const mode = window.TTPDemoSdkLoader?.getMode?.() || 'prod';
343
+ updateStatus('SDK loaded (' + mode + ') creating widget...', '');
344
+ createWidget();
367
345
  }
368
346
 
369
- waitForSDK().then(() => {
370
- updateStatus('SDK loaded — creating widget...', '');
371
- createWidget();
372
- }).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) => {
373
355
  updateStatus('SDK load failed: ' + e.message, 'error');
374
356
  });
375
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(e){const t="ttp-demo-sdk-mode",n="/agent-widget.js",o="/agent-widget.dev.js",d="wss://speech.talktopc.com/ws/conv",r="wss://speech.bidme.co.il/ws/conv";let c=null,s=null;function a(){return"dev"===e.localStorage.getItem(t)?"dev":"prod"}function i(e){return"dev"===e?o:n}function l(e){return"dev"===e?"Development":"Production"}function p(e){return"dev"===e?r:d}function u(){const t=e=>{try{e?.destroy?.()}catch(e){console.warn("[TTPDemoSdk] destroy failed",e)}};t(e.widgetInstance),t(e.chatWidget),t(e.testWidget),void 0!==e.actualWidgetInstance&&(t(e.actualWidgetInstance),e.actualWidgetInstance=null),e.widgetInstance=null,e.chatWidget=null,e.testWidget=null}function g(){document.querySelectorAll('script[src*="agent-widget"]').forEach(e=>e.remove()),delete e.TTPAgentSDK,delete e.TTPChatWidget}function m(n){return n="dev"===n||"prod"===n?n:a(),e.localStorage.setItem(t,n),v(n),c=e.location.hostname.includes("ngrok")?function(t){return fetch(i(t),{headers:{"ngrok-skip-browser-warning":"1"}}).then(e=>{if(!e.ok)throw new Error("SDK fetch HTTP "+e.status);return e.text()}).then(n=>{g();const o=document.createElement("script");o.type="text/javascript",o.textContent=n,document.head.appendChild(o),s=t;const d={mode:t,src:i(t),label:l(t),ngrok:!0};return e.dispatchEvent(new CustomEvent("ttp-demo-sdk-ready",{detail:d})),e.TTPAgentSDK})}(n):function(t){return new Promise((n,o)=>{g();const d=document.createElement("script");d.src=i(t)+"?t="+Date.now(),d.onload=()=>{s=t;const o={mode:t,src:d.src,label:l(t)};e.dispatchEvent(new CustomEvent("ttp-demo-sdk-ready",{detail:o})),n(e.TTPAgentSDK)},d.onerror=()=>o(new Error("Failed to load SDK: "+d.src)),document.head.appendChild(d)})}(n),c.catch(e=>{throw console.error("[TTPDemoSdk]",e),e})}function f(e){return"dev"!==e&&"prod"!==e?m(a()):(u(),m(e))}function v(e){const t=document.getElementById("ttp-demo-sdk-toggle");if(!t)return;const n=t.querySelector('[data-mode="prod"]'),o=t.querySelector('[data-mode="dev"]'),d=t.querySelector(".ttp-demo-sdk-file");n&&(n.classList.toggle("active","prod"===e),n.classList.toggle("active-dev",!1)),o&&(o.classList.toggle("active","dev"===e),o.classList.toggle("active-dev","dev"===e)),d&&(d.title=p(e),d.textContent="dev"===e?"dev.js · speech.bidme":"prod.js · talktopc")}function b(){return function(){if(document.getElementById("ttp-demo-sdk-toggle"))return;!function(){if(document.getElementById("ttp-demo-sdk-toggle-styles"))return;const e=document.createElement("style");e.id="ttp-demo-sdk-toggle-styles",e.textContent="\n #ttp-demo-sdk-toggle {\n position: fixed;\n top: 12px;\n right: 12px;\n z-index: 2147483646;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: #111827;\n color: #f9fafb;\n font: 13px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n border-radius: 10px;\n box-shadow: 0 4px 14px rgba(0,0,0,.25);\n }\n #ttp-demo-sdk-toggle .ttp-demo-sdk-label { opacity: .85; margin-right: 4px; }\n #ttp-demo-sdk-toggle button {\n border: none;\n cursor: pointer;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 600;\n background: #374151;\n color: #e5e7eb;\n }\n #ttp-demo-sdk-toggle button:hover { background: #4b5563; }\n #ttp-demo-sdk-toggle button.active {\n background: #4f46e5;\n color: #fff;\n }\n #ttp-demo-sdk-toggle button.active-dev {\n background: #d97706;\n color: #fff;\n }\n #ttp-demo-sdk-toggle .ttp-demo-sdk-file {\n font-size: 11px;\n opacity: .7;\n max-width: 140px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n ",document.head.appendChild(e)}();const e=document.createElement("div");e.id="ttp-demo-sdk-toggle",e.setAttribute("role","group"),e.setAttribute("aria-label","SDK bundle"),e.innerHTML='<span class="ttp-demo-sdk-label">SDK</span><button type="button" data-mode="prod" title="Production minified bundle">Production</button><button type="button" data-mode="dev" title="Development bundle with source maps">Development</button><span class="ttp-demo-sdk-file"></span>',e.querySelector('[data-mode="prod"]').addEventListener("click",()=>{"prod"!==a()&&f("prod")}),e.querySelector('[data-mode="dev"]').addEventListener("click",()=>{"dev"!==a()&&f("dev")}),document.body.appendChild(e),v(a())}(),m(a())}e.TTPDemoSdkLoader={STORAGE_KEY:t,PROD_SRC:n,DEV_SRC:o,PROD_WS_URL:d,DEV_WS_URL:r,getMode:a,getSrc:i,getLabel:l,getWebSocketUrl:p,applyWebSocketUrl:function(e,t){const n=e&&"object"==typeof e?e:{},o="dev"===t||"prod"===t?t:a();return n.websocketUrl=p(o),n},loadSdk:m,setMode:f,waitForReady:function(){return e.TTPAgentSDK?.TTPChatWidget&&c?Promise.resolve(e.TTPAgentSDK):c||m(a())},destroyWidgetInstances:u},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",b):b()}(window);
@@ -0,0 +1 @@
1
+ !function(){"use strict";if(window.__ttpCartProbeInstalled)return console.warn("[TTP-CART-PROBE] already installed — run __ttpCartProbeReport() or __ttpCartProbeUninstall()"),window.__ttpCartProbeHits;const t=[];function e(t){return"string"==typeof t&&/\/api\/cart\//i.test(t)}function o(e,o,n){const r={at:(new Date).toISOString(),kind:e,url:String(o),extra:n||null};t.push(r),console.log("[TTP-CART-PROBE]",e,r.url,n||"")}window.__ttpCartProbeHits=t;const n=window.fetch;window.__ttpCartProbeNativeFetch=n,window.fetch=function(t,r){const s="string"==typeof t?t:t&&t.url||"",i=n.apply(this,arguments);return e(s)&&(o("fetch-start",s,{method:r&&r.method||"GET"}),i.then(function(t){o("fetch-end",s,{status:t.status,ok:t.ok})}).catch(function(t){o("fetch-error",s,{message:String(t&&t.message||t)})})),i};const r=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,e){return this.__ttpProbeMethod=t,this.__ttpProbeUrl="string"==typeof e?e:String(e||""),r.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){const n=this.__ttpProbeUrl||"",r=this.__ttpProbeMethod||"GET";if(e(n)){const t=this;o("xhr-start",n,{method:r}),t.addEventListener("loadend",function(){o("xhr-end",n,{method:r,status:t.status})})}return s.apply(this,arguments)},window.__ttpCartProbeReport=function(){const e={hostname:location.hostname,fetchPatched:window.fetch!==n,hitCount:t.length,hits:t.slice(),hint:0===t.length?"No /api/cart/ via fetch or XHR. Open Network tab, add to cart, note the real request URL.":"Hooks see cart traffic — cart.subscribe should be able to listen here."};return console.table(t),console.log("[TTP-CART-PROBE] report",e),e},window.__ttpCartProbeUninstall=function(){window.__ttpCartProbeNativeFetch&&(window.fetch=window.__ttpCartProbeNativeFetch),XMLHttpRequest.prototype.open=r,XMLHttpRequest.prototype.send=s,delete window.__ttpCartProbeInstalled,delete window.__ttpCartProbeHits,delete window.__ttpCartProbeReport,delete window.__ttpCartProbeUninstall,delete window.__ttpCartProbeNativeFetch,console.log("[TTP-CART-PROBE] uninstalled")},window.__ttpCartProbeInstalled=!0,console.log("[TTP-CART-PROBE] installed on",location.hostname,"— manually add to cart, then __ttpCartProbeReport()")}();
@@ -0,0 +1 @@
1
+ !function(){"use strict";if(window.__ttpSobeysDispatchProbeInstalled)return console.warn("[SOBEYS-PROBE] already installed"),window.__ttpSobeysDispatchProbeReport();const t=[];function e(){if(window.__reduxStore&&"function"==typeof window.__reduxStore.dispatch)return window.__reduxStore;function t(t,e){const o=[t];for(;o.length&&e-- >0;){const t=o.shift();if(!t)continue;const e=t.memoizedProps?.store||t.memoizedState?.store||t.pendingProps?.store||t.stateNode?.store;if(e&&"function"==typeof e.dispatch)return e;t.child&&o.push(t.child),t.sibling&&o.push(t.sibling),t.return&&o.push(t.return)}return null}function e(e){if(!e)return null;const o=Object.keys(e).filter(t=>t.startsWith("__reactFiber")||t.startsWith("__reactContainer")||t.startsWith("__reactInternalInstance"));for(const n of o){const o=t(e[n]?.current||e[n],800);if(o)return o}return null}const o=[document.getElementById("root"),document.getElementById("app"),document.getElementById("__next"),document.body,document.body?.firstElementChild].filter(Boolean);for(const t of o){const o=e(t);if(o)return o}for(const t of document.querySelectorAll("body *")){const o=e(t);if(o)return o}return null}function o(t){try{const e=t?.getState?.()||{},o=e.shoppingListSlice?.shoppingListProducts?.products;if(Array.isArray(o))return{source:"redux",products:o}}catch(t){}return n(t)}function n(t){try{const e=t?.getState?.()||{};if(e.manageListSlice)return{source:"redux",data:e.manageListSlice}}catch(t){}try{const t=sessionStorage.getItem("persist:root");if(!t)return{source:"none",data:null};const e=JSON.parse(t);return{source:"persist:root",data:e.manageListSlice?JSON.parse(e.manageListSlice):null,persistKeys:Object.keys(e)}}catch(t){return{source:"error",error:String(t.message||t)}}}function r(t,e){if(!t||!e)return 0;const o=t.products||t.items||t.listItems||t.data;if(Array.isArray(o)){const t=o.find(t=>t&&(t.item_id===e||t.objectID===e||t.objectId===e||t.id===e||t.productId===e));return Number(t?.quantity??t?.qty??t?.count??0)||0}if(o&&"object"==typeof o){const t=o[e];return Number(t?.quantity??t?.qty??t??0)||0}return 0}window.__ttpSobeysDispatchProbeHits=t;const i=e();if(window.__ttpSobeysReduxStore=i,i){const e=i.dispatch.bind(i);i.dispatch=function(o){try{const e=String(("string"==typeof o?o:o?.type)||"");if(/list|cart|add|item|manage|persist|favour|favorite|product|algolia/i.test(e)){const n={at:(new Date).toISOString(),type:e,payload:o?.payload,meta:o?.meta};t.push(n),console.log("[SOBEYS-PROBE] dispatch",n)}}catch(t){console.warn("[SOBEYS-PROBE] log error",t)}return e.apply(i,arguments)}}else console.warn("[SOBEYS-PROBE] Redux store not found yet — will retry on report/click");window.__ttpSobeysDispatchProbeReport=function(){const r=window.__ttpSobeysReduxStore||e();window.__ttpSobeysReduxStore=r;const i=o(r),s=Array.from(document.querySelectorAll('[id^="ObjectID-"]')).slice(0,8).map(t=>({tileId:t.id,addBtn:!!t.querySelector('#add_to_cart_product button, button[aria-label*="Add to list" i]')})),c={hostname:location.hostname,storeFound:!!r,stateKeys:r?Object.keys(r.getState()||{}):[],shoppingList:i,manageList:n(r),hitCount:t.length,hits:t.slice(),objectTiles:s,hint:0===t.length?"Click Add to list on a product tile, then run report again.":"Use hits[].type + hits[].payload to implement cart.add dispatch."};return console.table(t),console.log("[SOBEYS-PROBE] report",c),c},window.__ttpSobeysDispatchAdd=function(t,n){const i=window.__ttpSobeysReduxStore||e();if(!i)return{ok:!1,reason:"redux_store_not_found"};const s=Number(n);if(!Number.isFinite(s)||s<0)return{ok:!1,reason:"invalid_qty",quantity:n};const c=r(o(i),t);i.dispatch({type:"shoppingListSlice/setItemListData",payload:{items:[{item_id:String(t),product_type:"Product",quantity:s}]}});const a=r(o(i),t);return{ok:a===s||0===s&&0===a,objectId:t,previousQty:c,newQty:a,action:0===s?"remove":0===c?"add":"update"}},window.__ttpSobeysTryAddByObjectId=function(t,e){e=null==e?1:e;const n=document.getElementById("ObjectID-"+t+" OfferType-"+e);if(!n)return console.warn("[SOBEYS-PROBE] tile not found for",t,e),{ok:!1,reason:"tile_not_found"};const i=n.querySelector("#add_to_cart_product button")||n.querySelector('button[aria-label*="Add to list" i]')||Array.from(n.querySelectorAll("button")).find(t=>/add to list/i.test(t.textContent||t.getAttribute("aria-label")||""));if(!i)return{ok:!1,reason:"add_button_not_found",tileId:n.id};const s=r(o(window.__ttpSobeysReduxStore).data,t);return i.click(),{ok:!0,clicked:!0,tileId:n.id,prevQty:s,note:"Wait ~1s then __ttpSobeysDispatchProbeReport()"}},window.__ttpSobeysDispatchProbeUninstall=function(){console.log("[SOBEYS-PROBE] uninstall not fully implemented — refresh page to reset dispatch wrapper")},window.__ttpSobeysDispatchProbeInstalled=!0,console.log("[SOBEYS-PROBE] installed — click Add to list or __ttpSobeysTryAddByObjectId(objectId, offerType)"),window.__ttpSobeysDispatchProbeReport()}();
@@ -0,0 +1,112 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <title>Sobeys cart.read adapter test (mock Redux)</title>
6
+ <style>
7
+ body { font-family: system-ui, sans-serif; margin: 24px; max-width: 960px; }
8
+ pre { background: #111; color: #0f0; padding: 16px; overflow: auto; font-size: 13px; }
9
+ .pass { color: #0a0; font-weight: bold; }
10
+ .fail { color: #c00; font-weight: bold; }
11
+ button { padding: 8px 16px; margin-right: 8px; cursor: pointer; }
12
+ </style>
13
+ </head>
14
+ <body>
15
+ <h1>Sobeys <code>cart.read</code> adapter test</h1>
16
+ <p>Mocks <code>shoppingListSlice</code> on <code>window.__reduxStore</code> (same path the live adapter uses).</p>
17
+ <button id="run">Run test</button>
18
+ <button id="seed">Seed cart item</button>
19
+ <button id="clear">Clear cart</button>
20
+ <div id="status"></div>
21
+ <pre id="out">Click Run test…</pre>
22
+
23
+ <script>
24
+ window.__TTP_SOBEYS_TEST__ = true;
25
+ // Mock Sobeys Redux store
26
+ (function initMockStore() {
27
+ const state = {
28
+ shoppingListSlice: {
29
+ listId: 'mock-list-42',
30
+ listName: 'My List',
31
+ shoppingListProducts: {
32
+ products: [
33
+ {
34
+ item_id: '577689_EA_0320',
35
+ product_type: 'Product',
36
+ quantity: 2,
37
+ name: 'Neilson 2% Milk',
38
+ brand: 'Neilson',
39
+ price: 5.49,
40
+ unit: '2 L',
41
+ },
42
+ {
43
+ item_id: '123456_KG_0320',
44
+ product_type: 'Product',
45
+ quantity: 1,
46
+ name: 'Bananas',
47
+ price: 1.99,
48
+ },
49
+ ],
50
+ },
51
+ taxSummary: { subtotal: 12.97, grandTotal: 14.65 },
52
+ },
53
+ productsSlice: { products: [] },
54
+ };
55
+
56
+ window.__reduxStore = {
57
+ getState: () => state,
58
+ dispatch: (action) => {
59
+ if (action.type === 'shoppingListSlice/setItemListData' && action.payload && action.payload.items) {
60
+ const map = {};
61
+ state.shoppingListSlice.shoppingListProducts.products.forEach((p) => {
62
+ map[p.item_id] = { ...p };
63
+ });
64
+ action.payload.items.forEach((item) => {
65
+ if (!item.item_id) return;
66
+ const qty = Number(item.quantity) || 0;
67
+ if (qty <= 0) delete map[item.item_id];
68
+ else map[item.item_id] = { ...map[item.item_id], ...item, quantity: qty };
69
+ });
70
+ state.shoppingListSlice.shoppingListProducts.products = Object.values(map);
71
+ }
72
+ return action;
73
+ },
74
+ };
75
+ })();
76
+
77
+ </script>
78
+ <script src="sobeys-cart-read-test.js"></script>
79
+ <script>
80
+ const out = document.getElementById('out');
81
+ const status = document.getElementById('status');
82
+
83
+ async function runTest() {
84
+ status.textContent = 'Running…';
85
+ const report = await window.__ttpSobeysCartReadTestReport();
86
+ out.textContent = JSON.stringify(report, null, 2);
87
+ status.innerHTML = report.pass
88
+ ? '<span class="pass">PASS</span> — cart.read returned items'
89
+ : '<span class="fail">FAIL</span> — see JSON below';
90
+ return report;
91
+ }
92
+
93
+ document.getElementById('run').onclick = runTest;
94
+ document.getElementById('seed').onclick = async () => {
95
+ window.__reduxStore.dispatch({
96
+ type: 'shoppingListSlice/setItemListData',
97
+ payload: { items: [{ item_id: '247400_EA_0320', product_type: 'Product', quantity: 1, name: 'Bread' }] },
98
+ });
99
+ await runTest();
100
+ };
101
+ document.getElementById('clear').onclick = async () => {
102
+ window.__reduxStore.dispatch({
103
+ type: 'shoppingListSlice/setItemListData',
104
+ payload: { items: [{ item_id: '577689_EA_0320', quantity: 0 }, { item_id: '123456_KG_0320', quantity: 0 }] },
105
+ });
106
+ await runTest();
107
+ };
108
+
109
+ runTest();
110
+ </script>
111
+ </body>
112
+ </html>
@@ -0,0 +1 @@
1
+ !function(){"use strict";async function t(t){if(!window.__TTP_SOBEYS_TEST__&&!/(^|\.)sobeys\.com$/.test(location.hostname))return{ok:!1,success:!1,reason:"cross_origin_widget",host:location.hostname};function e(t){try{return t.getState().shoppingListSlice||{}}catch(t){return{}}}function n(t,e,n){const r={productName:"",brand:"",price:0,imageUrl:"",unit:""};if(!e||!n)return r;r.productName=String(e.name||e.product_name||e.productName||e.title||"").trim(),r.brand=String(e.brand||"").trim(),r.unit=String(e.unit||e.uom||e.packSize||"").trim(),r.imageUrl=String(e.imageUrl||e.image_url||e.image||"").trim();const i=Number(null!=e.price?e.price:e.unit_price);if(Number.isFinite(i)&&i>0&&(r.price=i),r.productName)return r;try{const e=t.getState(),i=[e.cartProductSlice,e.productsSlice,e.getShoppingListDataSlice,e.getProductDetailsDataSlice];for(let t=0;t<i.length;t++){const e=i[t];if(!e)continue;const o=Array.isArray(e)?e:e.products||e.items||e.data;if(Array.isArray(o))for(let t=0;t<o.length;t++){const e=o[t];if(!e)continue;if(String(e.item_id||e.objectID||e.id||e.productId||"")!==n)continue;r.productName=String(e.name||e.product_name||e.productName||"").trim();const i=Number(null!=e.price?e.price:e.unit_price);if(!r.price&&Number.isFinite(i)&&i>0&&(r.price=i),r.productName)return r}}}catch(t){}try{const t=document.querySelectorAll('[id^="ObjectID-'+n+'"]');for(let e=0;e<t.length;e++){const n=t[e].querySelector("a[title], a[aria-label]");if(!n)continue;const i=String(n.getAttribute("title")||n.getAttribute("aria-label")||"").trim();if(0===i.indexOf("Click here to go to")?r.productName=i.replace(/^Click here to go to\s+/i,"").replace(/\s+product detail page$/i,""):i&&(r.productName=i),r.productName)break}}catch(t){}return r}function r(t,e){return"KG"===(String(t||"").split("_")[1]||"")||e&&"weight"===String(e.product_type||"").toLowerCase()?"weight":"quantity"}const i=function(){if(window.__reduxStore&&"function"==typeof window.__reduxStore.dispatch)return window.__reduxStore;function t(t,e){const n=[t];for(;n.length&&e-- >0;){const t=n.shift();if(!t)continue;const e=t.memoizedProps&&t.memoizedProps.store||t.memoizedState&&t.memoizedState.store||t.pendingProps&&t.pendingProps.store||t.stateNode&&t.stateNode.store;if(e&&"function"==typeof e.dispatch)return e;t.child&&n.push(t.child),t.sibling&&n.push(t.sibling),t.return&&n.push(t.return)}return null}function e(e){if(!e)return null;const n=Object.keys(e).filter(function(t){return 0===t.indexOf("__reactFiber")||0===t.indexOf("__reactContainer")||0===t.indexOf("__reactInternalInstance")});for(let r=0;r<n.length;r++){const i=t(e[n[r]]&&(e[n[r]].current||e[n[r]])||null,800);if(i)return i}return null}const n=[document.getElementById("root"),document.getElementById("app"),document.body,document.body&&document.body.firstElementChild].filter(Boolean);for(let t=0;t<n.length;t++){const r=e(n[t]);if(r)return r}const r=document.querySelectorAll("body *");for(let t=0;t<r.length;t++){const n=e(r[t]);if(n)return n}return null}();if(!i)return{ok:!1,success:!1,reason:"redux_store_not_found"};const o=e(i),c=function(t){const n=e(t),r=n.shoppingListProducts&&n.shoppingListProducts.products;return Array.isArray(r)?r:[]}(i),u=o.taxSummary||{};if(0===c.length)return{ok:!0,success:!0,items:[],itemCount:0,total:Number(null!=u.grandTotal?u.grandTotal:u.subtotal)||0,currency:"CAD",checkoutUrl:"",listId:o.listId||"",cartId:o.listId||null};const s=[];let a=0,d=0,l=0;for(let t=0;t<c.length;t++){const e=c[t];if(!e||!e.item_id)continue;const o=String(e.item_id),u=Number(e.quantity)||0;if(u<=0)continue;const m=n(i,e,o);m.productName||l++;const p=m.price||0,f=p>0?+(p*u).toFixed(2):0;f>0&&(d+=f),a+=u,s.push({productId:o,productName:m.productName,brand:m.brand,unit:m.unit,imageUrl:m.imageUrl,quantity:u,price:p,subtotal:f,sellBy:r(o,e),product_type:e.product_type||"Product"})}const m=Number(null!=u.grandTotal?u.grandTotal:u.subtotal),p={ok:!0,success:!0,items:s,itemCount:a,total:Number.isFinite(m)&&m>0?m:d>0?+d.toFixed(2):0,currency:"CAD",checkoutUrl:"",listId:o.listId||"",cartId:o.listId||null,listName:o.listName||""};return l>0&&l===s.length?p.degraded="no_product_names":l>0&&(p.degraded="partial_product_names"),p}window.__ttpSobeysCartRead=t,window.__ttpSobeysCartReadTestReport=async function(){window.fetch.bind(window),console.log.bind(console,"[adapter:cart.read]");const e=await t();let n=null;if(0===(e.items||[]).length){const t=function(){const t=Array.from(document.querySelectorAll('[id^="ObjectID-"]')).find(function(t){return-1===t.id.indexOf("undefined")&&t.querySelector('button[aria-label="Add to list"]')});if(!t)return null;const e=t.id.match(/^ObjectID-(.+?) OfferType-/);return e?e[1]:null}()||"247400_EA_0320",e=function(){const t=document.getElementById("root")||document.body.firstElementChild;if(!t)return null;const e=Object.keys(t).find(function(t){return 0===t.indexOf("__reactFiber")||0===t.indexOf("__reactContainer")});return e?function(t,e){const n=[t];for(;n.length&&e-- >0;){const t=n.shift();if(!t)continue;const e=t.memoizedProps&&t.memoizedProps.store||t.memoizedState&&t.memoizedState.store||t.pendingProps&&t.pendingProps.store;if(e&&"function"==typeof e.dispatch)return e;t.child&&n.push(t.child),t.sibling&&n.push(t.sibling),t.return&&n.push(t.return)}return null}(t[e].current||t[e],800):null}();e&&(e.dispatch({type:"shoppingListSlice/setItemListData",payload:{items:[{item_id:t,product_type:"Product",quantity:1}]}}),await new Promise(function(t){setTimeout(t,500)}),n={objectId:t,via:"redux_dispatch"})}const r=await t(),i={hostname:location.hostname,emptyCartRead:e,seeded:n,cartRead:r,pass:!!(r.ok&&r.success&&(r.itemCount||0)>0&&(r.items||[]).length>0)};return console.log("[SOBEYS-CART-READ-TEST]",i),i},window.__ttpSobeysCartReadTestReport()}();
@@ -0,0 +1 @@
1
+ !function(){"use strict";async function t(){const t={hostname:location.hostname,hostOk:/(^|\.)sobeys\.com$/.test(location.hostname),subscribeInstalled:!!window.__ttpSobeysCartSubscribeInstalled,scheduleRefresh:"function"==typeof window.__ttpSobeysCartScheduleRefresh,dispatchPatched:!1,persistPoll:!!window.__ttpSobeysPersistPollId,suppressedCount:window.__ttpSobeysSuppressedIds?window.__ttpSobeysSuppressedIds.size:0,prevMapSize:window.__ttpSobeysPrevItemMap?window.__ttpSobeysPrevItemMap.size:null,ecommerce:void 0!==window.__TTP_ECOMMERCE__,bundleActions:window.__TTP_ECOMMERCE__&&window.__TTP_ECOMMERCE__.runner?[...window.__TTP_ECOMMERCE__.runner.adapters?.keys?.()||[]]:[],persistFingerprint:"",reduxLines:[]},e=function(){if(window.__reduxStore)return window.__reduxStore;const t=document.getElementById("root")||document.body.firstElementChild;if(!t)return null;const e=Object.keys(t).find(function(t){return 0===t.indexOf("__reactFiber")||0===t.indexOf("__reactContainer")});if(!e)return null;const n=[t[e].current||t[e]];let i=400;for(;n.length&&i-- >0;){const t=n.shift();if(!t)continue;const e=t.memoizedProps&&t.memoizedProps.store||t.memoizedState&&t.memoizedState.store;if(e&&"function"==typeof e.dispatch)return e;t.child&&n.push(t.child),t.sibling&&n.push(t.sibling)}return null}();if(e){t.dispatchPatched=!!e.__ttpSobeysDispatchPatched;try{const n=e.getState().shoppingListSlice?.shoppingListProducts?.products||[];t.reduxLines=n.map(function(t){return{item_id:t.item_id,quantity:t.quantity}})}catch(e){t.reduxError=String(e.message||e)}}else t.reduxStore="not_found";try{const e=sessionStorage.getItem("persist:root");if(e){const n=JSON.parse(e),i=JSON.parse(n.shoppingListSlice||"{}"),s=i.shoppingListProducts?.products||[];t.persistFingerprint=s.map(function(t){return t.item_id+":"+t.quantity}).join("|")}}catch(e){t.persistError=String(e.message||e)}return window.__TTP_ECOMMERCE__&&window.__TTP_ECOMMERCE__.runAdapter&&(t.manualSubscribe=await window.__TTP_ECOMMERCE__.runAdapter("cart.subscribe",{}),t.cartRead=await window.__TTP_ECOMMERCE__.runAdapter("cart.read",{})),console.log("[SOBEYS-CART-SUBSCRIBE-PROBE]",t),t}window.__ttpSobeysCartSubscribeProbe=t,t()}();