()
| 434 | // Lazy load Puter.js only when needed to avoid unnecessary socket.io connections |
| 435 | let puterLoadingPromise = null; |
| 436 | function isPuterJsSupportedHere() { |
| 437 | const protocol = window.location && window.location.protocol; |
| 438 | return protocol === 'http:' || protocol === 'https:'; |
| 439 | } |
| 440 | |
| 441 | async function loadPuterJS() { |
| 442 | if (!isPuterJsSupportedHere()) { |
| 443 | throw new Error('Puter.com AI is unavailable in this view (file:// protocol). Restart the desktop app or use Server Mode in a browser.'); |
| 444 | } |
| 445 | |
| 446 | // If already loaded, return immediately |
| 447 | if (typeof puter !== 'undefined' && puter && puter.ai) { |
| 448 | console.log('[Puter] Puter.js already loaded'); |
| 449 | return Promise.resolve(); |
| 450 | } |
| 451 | |
| 452 | // If already loading, return the existing promise |
| 453 | if (puterLoadingPromise) { |
| 454 | console.log('[Puter] Puter.js already loading, waiting...'); |
| 455 | return puterLoadingPromise; |
| 456 | } |
| 457 | |
| 458 | // Check if script tag already exists |
| 459 | const existingScript = document.querySelector('script[src="https://js.puter.com/v2/"]'); |
| 460 | if (existingScript) { |
| 461 | console.log('[Puter] Puter.js script tag already exists, waiting for load...'); |
| 462 | puterLoadingPromise = new Promise((resolve, reject) => { |
| 463 | let retries = 0; |
| 464 | const maxRetries = 50; // 5 seconds |
| 465 | const checkInterval = setInterval(() => { |
| 466 | retries++; |
| 467 | if (typeof puter !== 'undefined' && puter && puter.ai) { |
| 468 | clearInterval(checkInterval); |
| 469 | puterLoadingPromise = null; |
| 470 | console.log('[Puter] Puter.js loaded successfully'); |
| 471 | resolve(); |
| 472 | } else if (retries >= maxRetries) { |
| 473 | clearInterval(checkInterval); |
| 474 | puterLoadingPromise = null; |
| 475 | reject(new Error('Puter.js failed to load within timeout')); |
| 476 | } |
| 477 | }, 100); |
| 478 | }); |
| 479 | return puterLoadingPromise; |
| 480 | } |
| 481 | |
| 482 | // Load Puter.js dynamically |
| 483 | console.log('[Puter] Loading Puter.js dynamically...'); |
| 484 | puterLoadingPromise = new Promise((resolve, reject) => { |
| 485 | const script = document.createElement('script'); |
| 486 | script.src = 'https://js.puter.com/v2/'; |
| 487 | script.async = true; |
| 488 | script.onload = () => { |
| 489 | // Wait for puter object to be available |
| 490 | let retries = 0; |
| 491 | const maxRetries = 50; // 5 seconds |
| 492 | const checkInterval = setInterval(() => { |
| 493 | retries++; |
no outgoing calls
no test coverage detected