/** * Phoenix App - Advanced Bulk API Tester * Version: 2.0 (Agentic Edition) */ const App = { _stateData: { spaces: [], activeSpaceId: null, activeCollectionId: 'default', outputFolderPath: '', gridMaximized: false, resultsPanelHeight: 300, sidebarWidth: 270, searchQuery: '' }, tabs: [], activeTabIndex: 0, get state() { if (!this._proxyState) { const props = ['name', 'method', 'url', 'params', 'headers', 'auth', 'bodyType', 'bodyData', 'jsonBody', 'response', 'bulk', 'activeTab', 'responseTab', 'activeRequestId', 'isPreview', 'activeCollectionId']; this._proxyState = new Proxy(this._stateData, { get(target, prop) { if (props.includes(prop)) { if (App.tabs && App.tabs[App.activeTabIndex]) { return App.tabs[App.activeTabIndex][prop]; } } return target[prop]; }, set(target, prop, value) { if (props.includes(prop)) { if (App.tabs && App.tabs[App.activeTabIndex]) { App.tabs[App.activeTabIndex][prop] = value; if (prop !== 'activeTab' && prop !== 'responseTab' && prop !== 'activeRequestId') { App.tabs[App.activeTabIndex].isPreview = false; } // Auto-save to localStorage only (no server call on every keypress) return true; } } target[prop] = value; return true; } }); } return this._proxyState; }, debouncedSaveToCollection() { if (this._autoSaveTimeout) clearTimeout(this._autoSaveTimeout); this._autoSaveTimeout = setTimeout(() => { this.saveToCollection(); }, 500); }, createNewTab(reqData, isPreview = false) { return { id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9), name: reqData ? reqData.name : 'Untitled Request', method: reqData ? reqData.method : 'POST', url: reqData ? reqData.url : '', params: reqData ? JSON.parse(JSON.stringify(reqData.params || [])) : [], headers: reqData ? JSON.parse(JSON.stringify(reqData.headers || [])) : [], auth: reqData ? JSON.parse(JSON.stringify(reqData.auth || {type:'none'})) : {type:'none'}, bodyType: reqData ? reqData.bodyType : 'none', bodyData: reqData ? JSON.parse(JSON.stringify(reqData.bodyData || [])) : [], jsonBody: reqData ? reqData.jsonBody : '', response: null, bulk: reqData && reqData.bulk ? JSON.parse(JSON.stringify(reqData.bulk)) : { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, delay: 0, repetitions: 10, results: [] }, activeTab: 'params', responseTab: 'response', activeRequestId: reqData ? reqData.id : null, activeCollectionId: reqData ? reqData.activeCollectionId : 'default', isPreview: isPreview }; }, fileStore: new Map(), // id -> FileList dom: {}, async init() { this.loadState(); this.cacheDOM(); this.bindEvents(); // Ensure active tab has at least one param and header row if (!this.state.params || this.state.params.length === 0) this.addParam('params'); if (!this.state.headers || this.state.headers.length === 0) this.addParam('headers'); // Load spaces from the server to keep them synced await this.loadSpacesFromServer(); // Apply saved sidebar width const sidebarEl = document.getElementById('sidebar'); if (sidebarEl && this._stateData.sidebarWidth) { sidebarEl.style.width = `${this._stateData.sidebarWidth}px`; } // Attach event listener for horizontal sidebar dragging const handle = document.getElementById('sidebar-resize-handle'); if (handle) { handle.addEventListener('mousedown', (e) => this.startSidebarResize(e)); } this.render(); // Remove loader const loader = document.getElementById('loading-overlay'); if (loader) loader.remove(); document.getElementById('app-root').style.visibility = 'visible'; }, // --- Tab Management --- openNewTab() { const newTab = this.createNewTab(); this.tabs.push(newTab); this.activeTabIndex = this.tabs.length - 1; if (!this.state.params || this.state.params.length === 0) this.addParam('params'); if (!this.state.headers || this.state.headers.length === 0) this.addParam('headers'); this.saveState(); this.render(); }, switchTab(index) { if (index < 0 || index >= this.tabs.length) return; this.activeTabIndex = index; this.saveState(); this.render(); }, closeTab(index) { if (this.tabs.length <= 1) { // Can't close last tab; just reset it this.tabs[0] = this.createNewTab(); this.activeTabIndex = 0; this.saveState(); this.render(); return; } this.tabs.splice(index, 1); if (this.activeTabIndex >= this.tabs.length) { this.activeTabIndex = this.tabs.length - 1; } this.saveState(); this.render(); }, cacheDOM() { this.dom = { mainPanel: document.getElementById('main-panel'), sidebar: document.getElementById('sidebar'), toast: document.getElementById('toast-container') }; if (!this.dom.sidebar || !this.dom.mainPanel) { console.error('Critical: DOM elements not found', this.dom); alert('Critical Error: Application DOM structure is missing. Please refresh.'); } }, // --- State Management --- loadState() { try { const raw = localStorage.getItem('phoenix-state-v2'); if (raw) { const data = JSON.parse(raw); // Restore _stateData (global state) if (data.spaces !== undefined) this._stateData.spaces = data.spaces; if (data.activeSpaceId !== undefined) this._stateData.activeSpaceId = data.activeSpaceId; if (data.activeCollectionId !== undefined) this._stateData.activeCollectionId = data.activeCollectionId; if (data.outputFolderPath !== undefined) this._stateData.outputFolderPath = data.outputFolderPath; if (data.gridMaximized !== undefined) this._stateData.gridMaximized = data.gridMaximized; if (data.resultsPanelHeight !== undefined) this._stateData.resultsPanelHeight = data.resultsPanelHeight; if (data.sidebarWidth !== undefined) this._stateData.sidebarWidth = data.sidebarWidth; if (data.searchQuery !== undefined) this._stateData.searchQuery = data.searchQuery; // Restore tabs if (data.tabs && data.tabs.length > 0) { this.tabs = data.tabs.map(t => ({ ...t, bulk: { ...(t.bulk || {}), running: false, results: [] }, response: null })); this.activeTabIndex = Math.min(data.activeTabIndex || 0, this.tabs.length - 1); } else { // No saved tabs, create a blank one this.tabs = [this.createNewTab()]; this.activeTabIndex = 0; } } else { // Fresh start this.tabs = [this.createNewTab()]; this.activeTabIndex = 0; } } catch (e) { console.warn('Failed to load state', e); this.tabs = [this.createNewTab()]; this.activeTabIndex = 0; } }, saveState() { // Skip expensive localStorage serialization while bulk is actively running. if (this.state.bulk && this.state.bulk.running) return; if (this._saveStateTimeout) clearTimeout(this._saveStateTimeout); this._saveStateTimeout = setTimeout(() => { try { const serializedTabs = this.tabs.map(t => ({ ...t, bulk: { ...t.bulk, running: false, results: [] }, response: null })); const persistentState = { spaces: this._stateData.spaces, activeSpaceId: this._stateData.activeSpaceId, activeCollectionId: this._stateData.activeCollectionId, outputFolderPath: this._stateData.outputFolderPath, gridMaximized: this._stateData.gridMaximized, resultsPanelHeight: this._stateData.resultsPanelHeight, sidebarWidth: this._stateData.sidebarWidth, searchQuery: this._stateData.searchQuery, tabs: serializedTabs, activeTabIndex: this.activeTabIndex }; localStorage.setItem('phoenix-state-v2', JSON.stringify(persistentState)); } catch (e) { console.warn('Failed to save state', e); } }, 300); }, async loadLastRunFromServer() { // Persistence disabled for performance — results are session-only. }, async saveLastRunToServer() { // Persistence disabled for performance — results are session-only. }, saveLastRunToServerThrottled() { if (this._saveThrottleTimeout) return; this._saveThrottleTimeout = setTimeout(async () => { this._saveThrottleTimeout = null; await this.saveLastRunToServer(); }, 1000); }, get collections() { if (!this.state.activeSpaceId) return []; const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId); return space ? space.collections : []; }, set collections(val) { if (!this.state.activeSpaceId) return; const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (space) { space.collections = val; } }, get notifications() { if (!this.state.activeSpaceId) return []; const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId); return space ? (space.notifications || []) : []; }, set notifications(val) { if (!this.state.activeSpaceId) return; const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (space) { space.notifications = val; } }, async loadSpacesFromServer() { try { const res = await fetch('/api/spaces'); const data = await res.json(); if (Array.isArray(data)) { // Check if server returned empty or only the default empty spaces const serverIsEmpty = data.length === 0 || ( data.length === 2 && data[0].id === 'personal' && data[0].collections.length === 1 && (!data[0].collections[0].requests || data[0].collections[0].requests.length === 0) && data[1].id === 'team' && data[1].collections.length === 1 && (!data[1].collections[0].requests || data[1].collections[0].requests.length === 0) ); // Check if client had non-empty legacy collections in localStorage const clientHasLegacyCollections = this.state.collections && ( this.state.collections.length > 1 || (this.state.collections[0] && this.state.collections[0].requests && this.state.collections[0].requests.length > 0) ); if (serverIsEmpty && clientHasLegacyCollections) { console.log('Migrating local client collections to spaces...'); this.state.spaces = [ { id: 'personal', name: 'Personal Space', collections: JSON.parse(JSON.stringify(this.state.collections)) }, { id: 'team', name: 'Team Space', collections: JSON.parse(JSON.stringify(this.state.collections)) } ]; delete this.state.collections; await this._debouncedSaveSpaces(); } else if (data.length === 0 && this.state.spaces && this.state.spaces.length > 0) { await this._debouncedSaveSpaces(); } else if (data.length > 0) { this.state.spaces = data; } // Validate activeSpaceId if (this.state.activeSpaceId) { const spaceExists = this.state.spaces.some(s => s.id === this.state.activeSpaceId); if (!spaceExists) { this.state.activeSpaceId = null; this.state.activeCollectionId = 'default'; this.state.activeRequestId = null; } } } } catch (e) { console.error('Failed to load spaces from server:', e); } }, async saveSpacesToServer() { try { await fetch('/api/spaces', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.state.spaces) }); } catch (e) { console.error('Failed to sync spaces with server:', e); } }, openSpace(spaceId) { this.state.activeSpaceId = spaceId; this.state.activeCollectionId = 'default'; this.state.activeRequestId = null; this.saveState(); this.render(); }, showSpacesDashboard() { this.state.activeSpaceId = null; this.state.activeCollectionId = 'default'; this.state.activeRequestId = null; this.saveState(); this.render(); }, async createSpace() { const name = prompt("Enter space name:"); if (name && name.trim()) { const id = 'space_' + Date.now(); this.state.spaces.push({ id: id, name: name.trim(), collections: [{ id: 'default', name: 'My Requests', requests: [] }] }); this.state.activeSpaceId = id; this.saveState(); await this._debouncedSaveSpaces(); this.render(); } }, async deleteSpace(spaceId) { if (this.state.spaces.length <= 1) { return this.toast("Cannot delete the last remaining space", "error"); } if (confirm("Are you sure you want to delete this space? All collections and requests inside it will be permanently lost.")) { this.state.spaces = this.state.spaces.filter(s => s.id !== spaceId); if (this.state.activeSpaceId === spaceId) { this.state.activeSpaceId = null; this.state.activeCollectionId = 'default'; this.state.activeRequestId = null; } this.saveState(); await this._debouncedSaveSpaces(); this.render(); } }, renameSpace(spaceId) { const space = this.state.spaces.find(s => s.id === spaceId); if (!space) return; const newName = prompt("Enter new workspace name:", space.name); if (newName && newName.trim()) { space.name = newName.trim(); this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, async setSpaceTheme(themeId) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (activeSpace) { activeSpace.theme = themeId; this.saveState(); await this._debouncedSaveSpaces(); this.render(); this.toast(`Applied ${themeId} theme to ${activeSpace.name}`); } }, async shareCollection(colId) { const otherSpaces = this.state.spaces.filter(s => s.id !== this.state.activeSpaceId); if (otherSpaces.length === 0) { return this.toast("No other spaces to share with", "warning"); } const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); const collection = this.collections.find(c => c.id === colId); if (!collection) return; const spacesList = otherSpaces.map((s, idx) => `${idx + 1}. ${s.name}`).join('\n'); const choice = prompt(`Select workspace to share "${collection.name}" with (enter number):\n${spacesList}`); if (choice) { const idx = parseInt(choice) - 1; if (idx >= 0 && idx < otherSpaces.length) { const targetSpace = otherSpaces[idx]; targetSpace.notifications = targetSpace.notifications || []; const alreadyShared = targetSpace.notifications.some(n => n.collection.id === colId && n.fromSpaceId === this.state.activeSpaceId); if (alreadyShared) { return this.toast("Already shared with this space, pending approval", "warning"); } targetSpace.notifications.push({ id: 'share_' + Date.now(), fromSpaceId: this.state.activeSpaceId, fromSpaceName: activeSpace ? activeSpace.name : 'Unknown Space', collection: JSON.parse(JSON.stringify(collection)) }); this.saveState(); await this._debouncedSaveSpaces(); this.toast(`Shared collection with ${targetSpace.name}!`); this.render(); } else { this.toast("Invalid selection", "error"); } } }, openNotificationsModal() { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (!activeSpace || !activeSpace.notifications || activeSpace.notifications.length === 0) return; const modal = document.createElement('div'); modal.className = 'premium-modal-overlay'; modal.id = 'notifications-modal'; const listHTML = activeSpace.notifications.map(n => `
${this.escapeHTML(n.fromSpaceName)} shared collection:
${this.escapeHTML(n.collection.name)}
${n.collection.requests ? n.collection.requests.length : 0} Requests
`).join(''); modal.innerHTML = `

Share Requests

${listHTML}
`; document.body.appendChild(modal); modal.onclick = (e) => { if (e.target === modal) modal.remove(); }; }, async approveShare(notifId) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (!activeSpace || !activeSpace.notifications) return; const idx = activeSpace.notifications.findIndex(n => n.id === notifId); if (idx >= 0) { const notif = activeSpace.notifications[idx]; const collection = notif.collection; let newName = collection.name; let counter = 1; while (activeSpace.collections.some(c => c.name === newName)) { newName = `${collection.name} (${counter++})`; } collection.name = newName; collection.id = 'col_' + Date.now(); activeSpace.collections.push(collection); activeSpace.notifications.splice(idx, 1); this.saveState(); await this._debouncedSaveSpaces(); this.toast("Collection approved and added!"); this.render(); } }, async rejectShare(notifId) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); if (!activeSpace || !activeSpace.notifications) return; const idx = activeSpace.notifications.findIndex(n => n.id === notifId); if (idx >= 0) { activeSpace.notifications.splice(idx, 1); this.saveState(); await this._debouncedSaveSpaces(); this.toast("Share request rejected"); this.render(); } }, startSidebarResize(e) { e.preventDefault(); document.body.classList.add('resizing'); const startX = e.clientX; const startWidth = this.state.sidebarWidth || 270; const handle = document.getElementById('sidebar-resize-handle'); if (handle) handle.classList.add('active'); const doDrag = (moveEvent) => { const deltaX = moveEvent.clientX - startX; const newWidth = Math.max(180, Math.min(600, startWidth + deltaX)); this.state.sidebarWidth = newWidth; const sidebarEl = document.getElementById('sidebar'); if (sidebarEl) { sidebarEl.style.width = `${newWidth}px`; } }; const stopDrag = () => { document.body.classList.remove('resizing'); document.removeEventListener('mousemove', doDrag); document.removeEventListener('mouseup', stopDrag); if (handle) handle.classList.remove('active'); this.saveState(); }; document.addEventListener('mousemove', doDrag); document.addEventListener('mouseup', stopDrag); }, replaceResultCardInDOM(result) { const newEl = this._buildCardElement(result); document.querySelectorAll(`.result-card[data-index="${result.index}"]`).forEach(card => { card.replaceWith(newEl.cloneNode(true)); }); }, async resendBulkRequest(resultIndex) { const index = resultIndex - 1; // 0-based index const bulk = this.state.bulk; const resultItem = bulk.results.find(r => r.index === resultIndex); if (!resultItem) return; this.toast(`Re-sending request #${resultIndex}...`, 'info'); // Recalculate maxFiles and maxList to determine fileIndex and listIndex 1-to-1 let maxFiles = 0; let maxList = 0; const folders = [ ...this.state.params.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()), ...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()) : []) ]; if (folders.length > 0) { for (const f of folders) { const files = this.fileStore.get(f.id); if (files && files.length > maxFiles) maxFiles = files.length; } } const allLists = [ ...this.state.params.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()), ...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()) : []), ...this.state.headers.filter(h => h.type === 'list' && h.enabled && h.key && h.key.trim()) ]; if (allLists.length > 0) { for (const listParam of allLists) { const val = listParam.value || ''; const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > maxList) maxList = arr.length; } } let fileIndex = index; let listIndex = index; if (bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) { fileIndex = Math.floor(index / maxList); listIndex = index % maxList; } try { const res = await this.executeRequest(index, fileIndex, listIndex); const isSuccess = res.status_code >= 200 && res.status_code < 300; // Adjust stats counters const wasSuccess = resultItem.status >= 200 && resultItem.status < 300; if (wasSuccess && !isSuccess) { bulk.success--; bulk.error++; } else if (!wasSuccess && isSuccess) { bulk.success++; bulk.error--; } // Update item details resultItem.status = res.status_code; resultItem.latency = res.latency || 0; resultItem.data = res.content ? res.content.substring(0, 100) : (res.binary_data ? '[Binary]' : ''); resultItem.fullContent = res.content; resultItem.binaryData = res.binary_data; resultItem.contentType = res.content_type; resultItem.headers = res.headers; if (resultItem.blobUrl && resultItem.blobUrl !== res.blobUrl) { URL.revokeObjectURL(resultItem.blobUrl); } resultItem.blobUrl = res.blobUrl; this.toast(`Request #${resultIndex} completed: ${res.status_code}`, isSuccess ? 'info' : 'error'); this.updateBulkProgressUI(); this.replaceResultCardInDOM(resultItem); await this.saveLastRunToServer(); } catch (e) { const wasSuccess = resultItem.status >= 200 && resultItem.status < 300; if (wasSuccess) { bulk.success--; bulk.error++; } resultItem.status = 'ERR'; resultItem.latency = 0; resultItem.data = e.message; this.toast(`Request #${resultIndex} failed: ${e.message}`, 'error'); this.updateBulkProgressUI(); this.replaceResultCardInDOM(resultItem); await this.saveLastRunToServer(); } }, startResultsResize(e) { e.preventDefault(); document.body.classList.add('resizing'); const startY = e.clientY; const startHeight = this.state.resultsPanelHeight || 300; const doDrag = (moveEvent) => { const deltaY = startY - moveEvent.clientY; const newHeight = Math.max(120, Math.min(800, startHeight + deltaY)); this.state.resultsPanelHeight = newHeight; const panel = document.querySelector('.bottom-results-panel'); if (panel) { panel.style.height = `${newHeight}px`; } }; const stopDrag = () => { document.body.classList.remove('resizing'); document.removeEventListener('mousemove', doDrag); document.removeEventListener('mouseup', stopDrag); this.saveState(); }; document.addEventListener('mousemove', doDrag); document.addEventListener('mouseup', stopDrag); }, _buildCardElement(result) { const tmp = document.createElement('template'); tmp.innerHTML = this.renderResultCard(result).trim(); return tmp.content.firstElementChild; }, appendResultCardToDOM(result) { const newElement = this._buildCardElement(result); const appendToGrid = (grid) => { if (!grid) return; const spinner = grid.querySelector('div[style*="fa-spinner"]'); if (spinner) spinner.remove(); grid.appendChild(newElement.cloneNode(true)); // Virtual DOM cap: keep only the most recent 200 cards in the DOM. // Older results remain accessible in this.state.bulk.results but not rendered. while (grid.children.length > 200) { grid.removeChild(grid.firstElementChild); } }; appendToGrid(document.getElementById('main-results-grid')); appendToGrid(document.querySelector('.fullscreen-results-grid')); }, updateBulkProgressUI() { if (this._rafPending) return; this._rafPending = true; requestAnimationFrame(() => { this._rafPending = false; const bulk = this.state.bulk; const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0; const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)'; document.querySelectorAll('#progress-bar-fill, .progress-fill').forEach(bar => { bar.style.width = `${pct}%`; bar.style.background = statusColor; }); document.querySelectorAll('#progress-text').forEach(el => el.innerText = `${bulk.completed} / ${bulk.total} Completed`); document.querySelectorAll('.stat-capsule').forEach(el => { if (el.classList.contains('success')) { el.innerText = `${bulk.success} Success`; } else if (el.classList.contains('error')) { el.innerText = `${bulk.error} Failed`; } else if (el.innerText.includes('Completed')) { el.innerText = `${bulk.completed} / ${bulk.total} Completed`; } }); // Intentionally NOT calling saveLastRunToServer here to prevent massive JSON stringify lag during execution! }); }, openFullscreenResults() { const bulk = this.state.bulk; if (bulk.results.length === 0 && !bulk.running) { return this.toast("No results to view in fullscreen", "warning"); } let modal = document.getElementById('fullscreen-results-overlay'); const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0; const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)'; const folderPath = this.state.outputFolderPath || 'None selected'; const contentHTML = `

Fullscreen Batch Processing Grid

Real-time execution monitoring and visual results

${bulk.completed} / ${bulk.total} Completed ${bulk.success} Success ${bulk.error} Failed
${folderPath}
`; if (!modal) { modal = document.createElement('div'); modal.className = 'fullscreen-results-overlay'; modal.id = 'fullscreen-results-overlay'; modal.innerHTML = contentHTML; document.body.appendChild(modal); } else { modal.innerHTML = contentHTML; } // Populate the fullscreen grid via DocumentFragment (no re-render of cards) const fsGrid = document.getElementById('fullscreen-results-inner'); if (fsGrid) { const frag = document.createDocumentFragment(); const shown = bulk.results.slice(-200); if (shown.length === 0 && bulk.running) { const ph = document.createElement('div'); ph.style.cssText = 'grid-column:1/-1;text-align:center;color:var(--text-muted);padding:80px;font-style:italic;'; ph.innerHTML = 'Running…'; frag.appendChild(ph); } else { shown.forEach(r => frag.appendChild(this._buildCardElement(r))); } fsGrid.appendChild(frag); } }, closeFullscreenResults() { const modal = document.getElementById('fullscreen-results-overlay'); if (modal) { modal.remove(); } }, async browseServerFolder() { try { const res = await fetch('/api/browse_folder', { method: 'POST' }); const data = await res.json(); if (data.success) { this.state.outputFolderPath = data.path; this.saveState(); this.render(); this.toast(`Folder selected: ${data.path}`); } else { this.toast(data.error || 'Failed to browse folder', 'error'); } } catch (e) { this.toast(`Error browsing folder: ${e.message}`, 'error'); } }, async saveToServerFolder() { if (!this.state.bulk.results.length) return this.toast('No results to save', 'error'); if (!this.state.outputFolderPath) { this.toast('Please select an output folder first', 'error'); await this.browseServerFolder(); if (!this.state.outputFolderPath) return; } try { this.toast('Saving files to server folder...', 'info'); // Build file list from current in-memory blobUrls const fileItems = []; for (const r of this.state.bulk.results) { const filename = this.getFinalFilename(r); if (r.blobUrl) { try { const blob = await fetch(r.blobUrl).then(res => res.blob()); const ab = await blob.arrayBuffer(); const b64 = btoa(String.fromCharCode(...new Uint8Array(ab))); fileItems.push({ filename, is_binary: true, binary_data: b64 }); } catch (e) { console.warn('blob fetch failed', r.index, e); } } else if (r.fullContent) { fileItems.push({ filename, is_binary: false, content: r.fullContent }); } } if (!fileItems.length) return this.toast('No data available to save', 'error'); const res = await fetch('/api/save_folder', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: this.state.outputFolderPath, results: fileItems }) }); const data = await res.json(); if (data.success) { const errMsg = data.errors && data.errors.length > 0 ? ` (${data.errors.length} errors)` : ''; this.toast(`Saved ${data.count} files to ${this.state.outputFolderPath}${errMsg}`); } else { this.toast(`Failed to save: ${data.error}`, 'error'); } } catch (e) { this.toast(`Error saving to folder: ${e.message}`, 'error'); } }, async saveIndividualToServerFolder(index) { const result = this.state.bulk.results.find(r => r.index === index); if (!result) return; if (!this.state.outputFolderPath) { this.toast('Please select an output folder first', 'error'); await this.browseServerFolder(); if (!this.state.outputFolderPath) return; } try { const filename = this.getFinalFilename(result); let fileItem = null; if (result.blobUrl) { const blob = await fetch(result.blobUrl).then(r => r.blob()); const ab = await blob.arrayBuffer(); const b64 = btoa(String.fromCharCode(...new Uint8Array(ab))); fileItem = { filename, is_binary: true, binary_data: b64 }; } else if (result.fullContent) { fileItem = { filename, is_binary: false, content: result.fullContent }; } if (!fileItem) return this.toast('No data for this result', 'error'); const res = await fetch('/api/save_folder', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: this.state.outputFolderPath, results: [fileItem] }) }); const data = await res.json(); if (data.success && data.count > 0) { this.toast(`Saved file #${index} to server folder`); } else { this.toast(`Failed to save: ${data.error || (data.errors && data.errors[0]) || 'Unknown error'}`, 'error'); } } catch (e) { this.toast(`Error saving file: ${e.message}`, 'error'); } }, downloadIndividualResult(index) { const result = this.state.bulk.results.find(r => r.index === index); if (!result) return; try { const finalFilename = this.getFinalFilename(result); let url; let needsRevoke = false; if (result.blobUrl) { url = result.blobUrl; } else if (result.fullContent) { const blob = new Blob([result.fullContent], { type: result.contentType || 'text/plain' }); url = URL.createObjectURL(blob); needsRevoke = true; } else { return this.toast('No content to download', 'error'); } const a = document.createElement('a'); a.href = url; a.download = finalFilename; document.body.appendChild(a); a.click(); document.body.removeChild(a); if (needsRevoke) { URL.revokeObjectURL(url); } this.toast(`Downloaded "${finalFilename}"`); } catch (e) { this.toast(`Download failed: ${e.message}`, 'error'); } }, clearBulkResults() { if (confirm("Are you sure you want to clear all batch results?")) { // Revoke all blob URLs before clearing to free memory this.state.bulk.results.forEach(r => { if (r.blobUrl) URL.revokeObjectURL(r.blobUrl); }); this.state.bulk.results = []; this.state.bulk.completed = 0; this.state.bulk.success = 0; this.state.bulk.error = 0; this.state.bulk.total = 0; this.state.bulk.running = false; this.saveState(); this.saveLastRunToServer(); this.render(); } }, toggleGridMaximized() { this.state.gridMaximized = !this.state.gridMaximized; this.render(); }, // --- Actions --- addParam(section) { const item = { id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true }; if (section === 'params') this.state.params.push(item); if (section === 'headers') this.state.headers.push(item); if (section === 'body') this.state.bodyData.push(item); this.render(); this.saveState(); }, removeParam(section, id) { if (section === 'params') this.state.params = this.state.params.filter(p => p.id !== id); if (section === 'headers') this.state.headers = this.state.headers.filter(p => p.id !== id); if (section === 'body') this.state.bodyData = this.state.bodyData.filter(p => p.id !== id); this.render(); this.saveState(); }, updateParam(section, id, field, value) { const list = section === 'params' ? this.state.params : (section === 'headers' ? this.state.headers : this.state.bodyData); const item = list.find(p => p.id === id); if (item) { item[field] = value; this.saveState(); // Re-render if type changes to show/hide file input if (field === 'type' || field === 'enabled') this.scheduleRender(); } }, // --- Request Execution --- async sendRequest() { if (!this.state.url) return this.toast('URL is required', 'error'); // Reset bulk results upon sending another single request this.state.bulk.results = []; this.state.bulk.completed = 0; this.state.bulk.success = 0; this.state.bulk.error = 0; this.state.bulk.total = 0; this.state.response = { status: 'Sending...', headers: {} }; this.state.responseTab = 'response'; // Switch view this.render(); this.saveLastRunToServerThrottled(); try { const start = Date.now(); const res = await this.executeRequest(0); const latency = Date.now() - start; res.latency = latency; this.state.response = res; if (res.blobUrl) this.state.response.blobUrl = res.blobUrl; this.saveToCollection(res.status_code || 500); } catch (e) { this.state.response = { error: e.message }; } this.render(); this.saveState(); await this.saveLastRunToServer(); }, // --- Bulk Execution --- async runBulk() { if (!this.state.url) return this.toast('URL is required', 'error'); // Calculate total items based on folders or lists let maxFiles = 0; let maxList = 0; const currentRunId = Date.now(); this.state.bulk.currentRunId = currentRunId; // Check folders first - only those that will actually be used const folders = [ ...this.state.params.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()), ...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()) : []) ]; if (folders.length > 0) { // Find max file count for (const f of folders) { const files = this.fileStore.get(f.id); if (files && files.length > maxFiles) maxFiles = files.length; } } // Check lists (params, body, headers) - only those with keys const allLists = [ ...this.state.params.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()), ...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()) : []), ...this.state.headers.filter(h => h.type === 'list' && h.enabled && h.key && h.key.trim()) ]; if (allLists.length > 0) { // Find the longest list for (const listParam of allLists) { const val = listParam.value || ''; const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > maxList) maxList = arr.length; } } let total = 0; if (this.state.bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) { total = maxFiles * maxList; } else { total = Math.max(maxFiles, maxList); } // If still no total, use the saved repetitions setting if (total === 0) { total = Math.max(1, parseInt(this.state.bulk.repetitions) || 10); } if (total <= 0) return this.toast('Invalid bulk count', 'error'); // Init Bulk State if (!this.state.bulk.paused) { this.state.bulk.total = total; this.state.bulk.completed = 0; this.state.bulk.success = 0; this.state.bulk.error = 0; this.state.bulk.results = []; this.state.bulk.nextIndex = 0; this.state.responseTab = 'results'; } else { this.state.bulk.total = total; } this.state.bulk.running = true; this.state.bulk.paused = false; this.saveToCollection('BULK'); this.render(); // Execution Queue const concurrency = Math.max(1, Math.min(20, this.state.bulk.concurrency || 1)); let active = 0; const worker = async () => { while (this.state.bulk.nextIndex < this.state.bulk.total && this.state.bulk.running && this.state.bulk.currentRunId === currentRunId) { const index = this.state.bulk.nextIndex++; active++; let fileIndex = index; let listIndex = index; if (this.state.bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) { fileIndex = Math.floor(index / maxList); listIndex = index % maxList; } const inputFilename = this.getInputFilename(index, fileIndex, listIndex); try { const res = await this.executeRequest(index, fileIndex, listIndex); if (this.state.bulk.currentRunId !== currentRunId) return; const isSuccess = res.status_code >= 200 && res.status_code < 300; if (isSuccess) this.state.bulk.success++; else this.state.bulk.error++; this.state.bulk.results.push({ index: index + 1, status: res.status_code, latency: res.latency || 0, data: res.content ? res.content.substring(0, 100) : (res.binary_data ? '[Binary]' : ''), // Strip heavy data immediately — blobUrl is a cheap pointer // fullContent and binaryData are NOT stored to avoid heap bloat fullContent: null, binaryData: null, blobUrl: res.blobUrl, contentType: res.content_type, headers: res.headers, inputFilename: inputFilename }); const newResult = this.state.bulk.results[this.state.bulk.results.length - 1]; this.appendResultCardToDOM(newResult); // Cap result memory: revoke blob URL of oldest item when trimming if (this.state.bulk.results.length > 300) { const dropped = this.state.bulk.results.shift(); if (dropped && dropped.blobUrl) URL.revokeObjectURL(dropped.blobUrl); } } catch (e) { if (this.state.bulk.currentRunId !== currentRunId) return; this.state.bulk.error++; this.state.bulk.results.push({ index: index + 1, status: 'ERR', latency: 0, data: e.message, inputFilename: inputFilename }); const errResult = this.state.bulk.results[this.state.bulk.results.length - 1]; this.appendResultCardToDOM(errResult); } finally { active--; this.state.bulk.completed++; if (this.state.bulk.currentRunId === currentRunId) { this.updateBulkProgressUI(); } } // Apply inter-request delay (only when concurrency = 1 or after each request) const delayMs = parseInt(this.state.bulk.delay) || 0; if (delayMs > 0 && this.state.bulk.running && this.state.bulk.currentRunId === currentRunId) { await new Promise(r => setTimeout(r, delayMs)); } } if (active === 0 && this.state.bulk.nextIndex >= this.state.bulk.total && this.state.bulk.currentRunId === currentRunId) { this.state.bulk.running = false; this.state.bulk.paused = false; // Sort final results by index before final render this.state.bulk.results.sort((a, b) => a.index - b.index); this.render(); this.toast('Bulk Operation Completed'); await this.saveLastRunToServer(); } }; // Spawn workers for (let i = 0; i < concurrency; i++) { worker(); } }, stopBulk() { this.state.bulk.running = false; this.state.bulk.paused = false; this.scheduleRender(); }, pauseBulk() { if (this.state.bulk.running) { this.state.bulk.running = false; this.state.bulk.paused = true; this.scheduleRender(); this.toast('Bulk Operation Paused', 'warning'); } }, resumeBulk() { if (this.state.bulk.paused) { this.runBulk(); } }, async getImageDimensions(file) { return new Promise((resolve) => { if (!file || !file.type.startsWith('image/')) return resolve({width: 0, height: 0}); const img = new Image(); const url = URL.createObjectURL(file); img.onload = () => { resolve({width: img.width, height: img.height}); URL.revokeObjectURL(url); }; img.onerror = () => { resolve({width: 0, height: 0}); URL.revokeObjectURL(url); }; img.src = url; }); }, async executeRequest(index, fileIndex = index, listIndex = index) { const start = Date.now(); // Headers const headers = {}; this.state.headers.filter(h => h.enabled && h.key && h.key.trim()).forEach(h => { // Handle list replacement in headers too let val = h.value; if (h.type === 'list') { const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > 0) val = arr[listIndex % arr.length]; } headers[h.key.trim()] = val; }); // Auth const auth = this.state.auth; if (auth.type === 'bearer') headers['Authorization'] = `Bearer ${auth.token}`; else if (auth.type === 'basic') headers['Authorization'] = 'Basic ' + btoa(`${auth.username}:${auth.password}`); else if (auth.type === 'apikey') headers[auth.key] = auth.value; // URL Params const urlObj = new URL(this.state.url); this.state.params.filter(p => p.enabled && p.key && p.key.trim()).forEach(p => { let val = p.value; // List handling if (p.type === 'list') { // Try splitting by newline first if present, else comma const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > 0) val = arr[listIndex % arr.length]; } // File logic not applicable for URL params usually, skipping urlObj.searchParams.append(p.key, val); }); // Payload Construction const finalData = new FormData(); finalData.append('method', this.state.method); finalData.append('url', urlObj.toString()); finalData.append('headers', JSON.stringify(headers)); // Add auth config for server-side handling if needed (e.g. Basic Auth via requests arg) if (auth.type === 'basic') finalData.append('auth', JSON.stringify({ type: 'basic', username: auth.username, password: auth.password })); // Body if (this.state.bodyType === 'json') { finalData.append('body_type', 'json'); finalData.append('body', this.state.jsonBody); } else if (this.state.bodyType === 'form-data') { finalData.append('body_type', 'form-data'); let currentImageFile = null; const folderParam = this.state.bodyData.find(p => p.enabled && p.type === 'folder'); if (folderParam) { const files = this.fileStore.get(folderParam.id); if (files && files.length > 0) currentImageFile = files[fileIndex % files.length]; } if (!currentImageFile) { const fileParam = this.state.bodyData.find(p => p.enabled && p.type === 'file'); if (fileParam) { const files = this.fileStore.get(fileParam.id); if (files && files.length > 0) currentImageFile = files[0]; } } let imgDims = null; const bodyParams = this.state.bodyData.filter(p => p.enabled && (p.type === 'file' || p.type === 'folder' || p.type === 'auto_width' || p.type === 'auto_height' || (p.key && p.key.trim()))); for (const p of bodyParams) { if (p.type === 'file' || p.type === 'folder') { const files = this.fileStore.get(p.id); if (files && files.length > 0) { if (p.type === 'folder') { finalData.append(p.key, files[fileIndex % files.length]); } else { for (let f of files) finalData.append(p.key, f); } } } else if (p.type === 'auto_width' || p.type === 'auto_height') { if (!imgDims) imgDims = await this.getImageDimensions(currentImageFile); finalData.append(p.key, p.type === 'auto_width' ? imgDims.width : imgDims.height); } else { let val = p.value; if (p.type === 'list') { const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > 0) val = arr[listIndex % arr.length]; } finalData.append(p.key, val); } } } const res = await fetch('/api/proxy-request', { method: 'POST', body: finalData }); const data = await res.json(); if (data.binary_data) { data.blobUrl = await this.base64ToBlobUrlAsync(data.binary_data, data.content_type); // Immediately null out raw data to free the large string from JS heap. // The blobUrl is a tiny reference to browser-managed memory. data.binary_data = null; } data.latency = Date.now() - start; return data; }, saveToCollection(lastStatus) { if (!this.state.url) return; let targetColId = this.state.activeCollectionId || 'default'; let col = this.collections.find(c => c.id === targetColId); if (!col) { col = this.collections.find(c => c.id === 'default'); if(!col) { col = { id: 'default', name: 'My Requests', requests: [] }; this.collections.push(col); } targetColId = col.id; } const existingIdx = col.requests.findIndex(r => r.id === this.state.activeRequestId || (r.url === this.state.url && r.method === this.state.method)); let existingReq = existingIdx >= 0 ? col.requests[existingIdx] : null; const reqData = { id: this.state.activeRequestId || Date.now().toString(), name: (existingReq && existingReq.name) ? existingReq.name : (this.state.url.split('?')[0].split('/').pop() || 'Root URL'), method: this.state.method, url: this.state.url, params: JSON.parse(JSON.stringify(this.state.params)), headers: JSON.parse(JSON.stringify(this.state.headers)), auth: JSON.parse(JSON.stringify(this.state.auth)), bodyType: this.state.bodyType, bodyData: JSON.parse(JSON.stringify(this.state.bodyData)), jsonBody: this.state.jsonBody, lastStatus: lastStatus !== undefined ? lastStatus : (existingReq ? existingReq.lastStatus : null), lastTime: new Date().toLocaleTimeString(), activeCollectionId: targetColId }; if (existingIdx >= 0) { // Update existing reqData.id = existingReq.id; // preserve ID col.requests[existingIdx] = reqData; } else { // Add new col.requests.unshift(reqData); } this.state.activeRequestId = reqData.id; this.saveState(); this._debouncedSaveSpaces(); }, _debouncedSaveSpaces() { if (this._saveSpacesTimer) clearTimeout(this._saveSpacesTimer); this._saveSpacesTimer = setTimeout(() => this._debouncedSaveSpaces(), 3000); }, loadRequest(colId, reqId) { const col = this.collections.find(c => c.id === colId); if(!col) return; const req = col.requests.find(r => r.id === reqId); if(!req) return; // Check if this request is already open in any tab const existingTabIdx = this.tabs.findIndex(t => t.activeRequestId === reqId); if (existingTabIdx >= 0) { // Just switch to that tab this.activeTabIndex = existingTabIdx; this.saveState(); this.render(); return; } // Postman behavior: if the current tab is a "preview" tab (untouched/empty), reuse it; // otherwise open a new tab const currTab = this.tabs[this.activeTabIndex]; const isUntouched = currTab && ( (!currTab.url || currTab.url === '') && (!currTab.activeRequestId) && (!currTab.response) && (currTab.name === 'Untitled Request' || !currTab.name) ); const reqTabData = { id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9), name: req.name || (req.url ? req.url.split('/').pop() || req.url : 'Request'), method: req.method || 'GET', url: req.url || '', params: JSON.parse(JSON.stringify(req.params || [{ id: Date.now().toString(), key: '', value: '', type: 'text', enabled: true }])), headers: JSON.parse(JSON.stringify(req.headers || [{ id: (Date.now()+1).toString(), key: '', value: '', type: 'text', enabled: true }])), auth: JSON.parse(JSON.stringify(req.auth || {type:'none'})), bodyType: req.bodyType || 'none', bodyData: JSON.parse(JSON.stringify(req.bodyData || [])), jsonBody: req.jsonBody || '', response: null, bulk: { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, results: [] }, activeTab: 'params', responseTab: 'response', activeRequestId: reqId, activeCollectionId: colId, isPreview: false }; if (isUntouched) { // Replace current blank tab this.tabs[this.activeTabIndex] = reqTabData; } else { // Open brand new tab this.tabs.push(reqTabData); this.activeTabIndex = this.tabs.length - 1; } this.saveState(); this.render(); }, deleteRequest(colId, reqId) { const col = this.collections.find(c => c.id === colId); if(col) col.requests = col.requests.filter(r => r.id !== reqId); if(this.state.activeRequestId === reqId) this.state.activeRequestId = null; this.saveState(); this._debouncedSaveSpaces(); this.render(); }, createCollection() { const name = prompt("Collection Name:"); if(name) { const id = 'col_' + Date.now(); this.collections.push({ id, name, requests: [] }); this.state.activeCollectionId = id; this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, renameCollection(colId) { const col = this.collections.find(c => c.id === colId); if(!col) return; const newName = prompt("Enter new collection name:", col.name); if(newName && newName.trim()) { col.name = newName.trim(); this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, renameRequest(colId, reqId) { const col = this.collections.find(c => c.id === colId); if(!col) return; const req = col.requests.find(r => r.id === reqId); if(!req) return; const newName = prompt("Enter new request name:", req.name); if(newName && newName.trim()) { req.name = newName.trim(); this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, deleteCollection(colId) { if(confirm("Delete this collection and all its requests? This cannot be undone.")) { this.collections = this.collections.filter(c => c.id !== colId); // Always keep at least one collection if (this.collections.length === 0) { this.collections = [{ id: 'default', name: 'My Requests', requests: [] }]; } // If deleted collection was active, switch to first remaining const stillExists = this.collections.some(c => c.id === this.state.activeCollectionId); if (!stillExists) { this.state.activeCollectionId = this.collections[0].id; this.state.activeRequestId = null; } this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, addRequestToCollection(colId) { const col = this.collections.find(c => c.id === colId); if (!col) return; const reqId = 'req_' + Date.now(); const newReq = { id: reqId, name: 'New Request', method: 'GET', url: '', description: '', params: [{ id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true }], headers: [{ id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true }], auth: { type: 'none' }, bodyType: 'none', bodyData: [], jsonBody: '' }; col.requests.push(newReq); // Open this new request in a new tab const reqTabData = { id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9), name: 'New Request', method: 'GET', url: '', params: JSON.parse(JSON.stringify(newReq.params)), headers: JSON.parse(JSON.stringify(newReq.headers)), auth: { type: 'none' }, bodyType: 'none', bodyData: [], jsonBody: '', response: null, bulk: { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, results: [] }, activeTab: 'params', responseTab: 'response', activeRequestId: reqId, activeCollectionId: colId, isPreview: false }; this.tabs.push(reqTabData); this.activeTabIndex = this.tabs.length - 1; this.saveState(); this._debouncedSaveSpaces(); this.render(); this.toast("Added new request to collection"); }, updateActiveRequestName(name) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null; const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null; if (activeReq) { activeReq.name = name.trim() || 'Untitled Request'; this.saveState(); this._debouncedSaveSpaces(); this.render(); } }, updateActiveRequestDescription(desc) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null; const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null; if (activeReq) { activeReq.description = desc; this.saveState(); this._debouncedSaveSpaces(); } }, downloadHistory() { if (!this.state.bulk.results.length) return; const csvContent = "data:text/csv;charset=utf-8," + "Index,Status,Latency (ms),Snippet\n" + this.state.bulk.results.map(r => `${r.index},${r.status},${r.latency},"${(r.data || '').replace(/"/g, '""').replace(/\n/g, ' ')}"`).join("\n"); const encodedUri = encodeURI(csvContent); const link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", `bulk_results_${new Date().toISOString()}.csv`); document.body.appendChild(link); link.click(); document.body.removeChild(link); }, // Get the input filename for a given bulk index getInputFilename(index, fileIndex = index, listIndex = index) { // Build list of active params that could provide a name const activeParams = [ ...this.state.params.filter(p => p.enabled && p.key && p.key.trim()), ...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.enabled && p.key && p.key.trim()) : []) ]; let folderName = null; // Priority 1: Folder type (usually high-intent for naming) const folderParam = activeParams.find(p => p.type === 'folder'); if (folderParam) { const files = this.fileStore.get(folderParam.id); if (files && files.length > 0) { const file = files[fileIndex % files.length]; folderName = file.webkitRelativePath || file.name; } } let listName = null; // Priority 2: List in Body (user's specific request context) if (this.state.bodyType === 'form-data') { const bodyList = this.state.bodyData.find(p => p.type === 'list' && p.enabled && p.key && p.key.trim()); if (bodyList) { const arr = bodyList.value.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > 0) listName = arr[listIndex % arr.length]; } } // Priority 3: Any other list if (!listName) { const listParam = activeParams.find(p => p.type === 'list'); if (listParam) { const val = listParam.value || ''; const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s); if (arr.length > 0) listName = arr[listIndex % arr.length]; } } if (folderName && listName) { // Strip extension from folderName, add listName, re-add extension let base = folderName; let ext = ''; const lastDot = folderName.lastIndexOf('.'); if (lastDot !== -1 && lastDot > 0 && folderName.length - lastDot <= 6) { base = folderName.substring(0, lastDot); ext = folderName.substring(lastDot); } // Replace any invalid characters in listName just in case, though usually fine const safeListName = listName.replace(/[\/\\]/g, '_'); return `${base}_${safeListName}${ext}`; } else if (folderName) { return folderName; } else if (listName) { return listName; } return `result_${index + 1}`; }, // Get the final filename with appropriate extension if missing getFinalFilename(result) { let name = result.inputFilename || `result_${result.index}`; let originalExt = ''; // Extract existing extension if present const lastDot = name.lastIndexOf('.'); if (lastDot > 0 && (name.length - lastDot) <= 6) { originalExt = name.substring(lastDot); name = name.substring(0, lastDot); } // Map common content types const ct = (result.contentType || '').toLowerCase(); if (ct.includes('image/png')) return name + '.png'; if (ct.includes('image/jpeg') || ct.includes('image/jpg')) return name + '.jpg'; if (ct.includes('image/gif')) return name + '.gif'; if (ct.includes('image/webp')) return name + '.webp'; if (ct.includes('image/svg')) return name + '.svg'; if (ct.includes('application/pdf')) return name + '.pdf'; if (ct.includes('application/json')) return name + '.json'; if (ct.includes('application/xml') || ct.includes('text/xml')) return name + '.xml'; if (ct.includes('text/html')) return name + '.html'; if (ct.includes('text/csv')) return name + '.csv'; if (ct.includes('text/css')) return name + '.css'; if (ct.includes('text/plain')) return name + '.txt'; if (ct.includes('application/zip')) return name + '.zip'; // Fallback for other binary types: try to extract subtype if (result.binaryData && ct.includes('/')) { const subtype = ct.split('/')[1].split(';')[0]; // handle "type/subtype;charset=..." if (subtype && subtype.length <= 4 && /^[a-z0-9]+$/.test(subtype)) { return name + '.' + subtype; } } // Content sniffing for JSON if content type is missing or incorrect if (!result.binaryData && result.fullContent) { const trimmed = result.fullContent.trim(); if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) { try { JSON.parse(trimmed); // Quick validation return name + '.json'; } catch(e) {} } } // If we still don't know the type, fallback to original extension if it existed if (originalExt) return name + originalExt; // Otherwise default based on data format return result.binaryData ? name + '.bin' : name + '.txt'; }, async saveAsFolder() { if (!this.state.bulk.results.length) return this.toast('No results to save', 'error'); try { if (!window.showDirectoryPicker) { return this.toast('Your browser does not support native folder saving. Please use the ZIP button instead.', 'error'); } this.toast('Select a folder to save files...', 'info'); const dirHandle = await window.showDirectoryPicker({ mode: 'readwrite' }); let savedCount = 0; let errors = 0; const usedNames = new Set(); for (const r of this.state.bulk.results) { try { let filename = this.getFinalFilename(r); let base = filename; let ext = ''; const lastDot = filename.lastIndexOf('.'); if (lastDot !== -1 && lastDot > 0) { base = filename.substring(0, lastDot); ext = filename.substring(lastDot); } let counter = 1; while (usedNames.has(filename)) { filename = `${base}_${counter}${ext}`; counter++; } usedNames.add(filename); // Get the content — prefer blobUrl, fallback to fullContent let data; if (r.blobUrl) { const blob = await fetch(r.blobUrl).then(res => res.blob()); data = await blob.arrayBuffer(); } else if (r.fullContent) { data = r.fullContent; } else { continue; // Skip empty results } // Create file and write content const fileHandle = await dirHandle.getFileHandle(filename, { create: true }); const writable = await fileHandle.createWritable(); await writable.write(data); await writable.close(); savedCount++; } catch (e) { console.error('Error saving file', r.index, e); errors++; } } if (errors > 0) { this.toast(`Saved ${savedCount} files. Failed to save ${errors} files.`, 'warning'); } else { this.toast(`Successfully saved ${savedCount} files to the selected folder.`); } } catch (e) { console.error(e); if (e.name === 'AbortError') { this.toast('Folder selection cancelled.', 'info'); } else { this.toast('Failed to save to folder: ' + e.message, 'error'); } } }, async saveAllResults() { if (!this.state.bulk.results.length) return this.toast('No results to save', 'error'); if (typeof JSZip === 'undefined') return this.toast('JSZip library not loaded. Please refresh.', 'error'); this.toast('Building ZIP file...', 'info'); const zip = new JSZip(); let savedCount = 0; const usedNames = new Set(); for (const result of this.state.bulk.results) { try { // Use the tracked input filename + auto extension let filename = this.getFinalFilename(result); let base = filename; let ext = ''; const lastDot = filename.lastIndexOf('.'); if (lastDot !== -1 && lastDot > 0) { base = filename.substring(0, lastDot); ext = filename.substring(lastDot); } let counter = 1; while (usedNames.has(filename)) { filename = `${base}_${counter}${ext}`; counter++; } usedNames.add(filename); // Get the content — prefer blobUrl (memory efficient), fallback to fullContent let data; if (result.blobUrl) { const blob = await fetch(result.blobUrl).then(r => r.blob()); data = await blob.arrayBuffer(); zip.file(filename, data, { binary: true }); } else if (result.fullContent) { data = result.fullContent; zip.file(filename, data, { binary: false }); } else { continue; // Skip empty results } savedCount++; } catch (e) { console.error('Error adding result to ZIP', result.index, e); } } if (savedCount === 0) return this.toast('No valid results to save', 'error'); // Generate and download ZIP try { this.toast('Generating ZIP, please wait...', 'info'); const blob = await zip.generateAsync({ type: 'blob' }); const url = URL.createObjectURL(blob); const modal = document.createElement('div'); modal.className = 'premium-modal-overlay'; modal.style.zIndex = '9999'; modal.innerHTML = `

ZIP Ready!

Successfully bundled ${savedCount} files.

Click to Download ZIP
`; document.body.appendChild(modal); // Note: intentionally not revoking the URL immediately so the manual click works! } catch (e) { this.toast('Error generating ZIP: ' + e.message, 'error'); } }, // --- Rendering --- // Debounced render — coalesces rapid successive calls (e.g., keystrokes) // into a single animation frame to prevent jank. scheduleRender() { if (this._renderScheduled) return; this._renderScheduled = true; requestAnimationFrame(() => { this._renderScheduled = false; this.render(); }); }, render() { const root = document.getElementById('app-root'); if (root) { // Reset base class first to prevent layout/theme clashing root.className = 'workspace'; if (this.state.bulk.results.length > 0 || this.state.bulk.running) { root.classList.add('bulk-active'); } if (this.state.gridMaximized || !this.state.activeSpaceId) { root.classList.add('grid-maximized'); } // Add theme class for active space if (this.state.activeSpaceId) { const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); const theme = activeSpace && activeSpace.theme ? activeSpace.theme : 'violet'; root.classList.add(`theme-${theme}`); } } this.renderSidebar(); this.renderMain(); this.renderResponse(); }, renderProgress() { // Optimized partial render for progress bar const bar = document.getElementById('progress-bar-fill'); const text = document.getElementById('progress-text'); if (bar && text) { const pct = (this.state.bulk.completed / this.state.bulk.total) * 100; bar.style.width = `${pct}%`; text.innerText = `${this.state.bulk.completed} / ${this.state.bulk.total}`; } }, getCollectionsHTML() { const query = (this.state.searchQuery || '').toLowerCase().trim(); let collectionsHTML = ''; this.collections.forEach(col => { const isColActive = this.state.activeCollectionId === col.id; // Filter requests const filteredRequests = col.requests.filter(r => { if (!query) return true; return ( (r.name || '').toLowerCase().includes(query) || (r.url || '').toLowerCase().includes(query) || (r.description || '').toLowerCase().includes(query) ); }); // Decide if the collection itself matches const colMatches = (col.name || '').toLowerCase().includes(query); // If neither collection matches nor has matching requests, skip rendering it if (query && !colMatches && filteredRequests.length === 0) { return; } // If there's a query and we have matches, auto-expand the collection const isExpanded = query ? true : isColActive; const reqsHTML = (query && colMatches ? col.requests : filteredRequests).map(r => `
${r.method}
${this.escapeHTML(r.name || '')}
${this.escapeHTML(r.url || 'No URL')}
`).join(''); collectionsHTML += `
${this.escapeHTML(col.name)}
${isExpanded ? `
${reqsHTML || '
Empty Collection
'}
` : ''}
`; }); return collectionsHTML; }, filterSidebarCollections(query) { this.state.searchQuery = query; const listEl = document.getElementById('sidebar-collections-list'); if (listEl) { listEl.innerHTML = this.getCollectionsHTML(); } // Also update clear button visibility const clearBtn = document.getElementById('search-clear-btn'); if (clearBtn) { clearBtn.style.display = query ? 'block' : 'none'; } }, renderSidebar() { const collectionsHTML = this.getCollectionsHTML(); const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); let notificationsBannerHTML = ''; if (activeSpace && activeSpace.notifications && activeSpace.notifications.length > 0) { notificationsBannerHTML = `
${activeSpace.notifications.length} pending share request${activeSpace.notifications.length > 1 ? 's' : ''}
`; } const spaceOptionsHTML = ` ${this.state.spaces.map(s => ` `).join('')} `; this.dom.sidebar.innerHTML = ` ${activeSpace ? ` ${notificationsBannerHTML} ` : `
Select a workspace
from the dashboard
`}
`; }, renderMain() { if (!this.state.activeSpaceId) { // Render Spaces Dashboard Grid View const spacesCardsHTML = this.state.spaces.map(s => { const count = s.collections ? s.collections.length : 0; const notifCount = s.notifications ? s.notifications.length : 0; const theme = s.theme || 'violet'; return `
${notifCount > 0 ? `${notifCount}` : ''}

${this.escapeHTML(s.name)}

${count} Collections
${this.state.spaces.length > 1 ? ` ` : ''}
`; }).join(''); const dashboardHTML = `

Workspaces

Select a workspace to access its collections, endpoints, and history.

${spacesCardsHTML}

Create New Space

Add a clean workspace
`; const headerHTML = `
PHOENIX
Workspace Dashboard
`; this.dom.mainPanel.innerHTML = headerHTML + dashboardHTML; return; } const isBulkStart = this.checkBulkStart(); const bulk = this.state.bulk; const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId); // Tab Strip (Postman-like) const tabStripHTML = `
${this.tabs.map((tab, i) => { const isActive = i === this.activeTabIndex; const tabName = tab.name || (tab.url ? tab.url.split('/').pop() || 'Request' : 'Untitled'); const displayName = tabName.length > 20 ? tabName.substring(0, 20) + '…' : tabName; const method = tab.method || 'GET'; const mc = { GET:'var(--m-get)', POST:'var(--m-post)', PUT:'var(--m-put)', DELETE:'var(--m-delete)', PATCH:'var(--m-patch)' }[method] || 'var(--text-3)'; return `
${method} ${this.escapeHTML(displayName)}
`; }).join('')}
`; // Header with Active Space name/switcher const headerHTML = `
PHOENIX
${this.escapeHTML(activeSpace ? activeSpace.name : '')}
${bulk.running ? ` ` : bulk.paused ? ` ` : `` }
${tabStripHTML} `; // Request Name & Description Section const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null; const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null; const requestMetaHTML = activeReq ? `
Name
Description
` : ''; // Tabs bar (PARAMS / HEADERS / BODY / AUTH + Bulk controls) const inputStyle = 'background:var(--bg-input);border:1px solid var(--border-2);border-radius:var(--r-xs);color:var(--text-1);padding:3px 6px;font-size:11px;text-align:center;font-family:var(--font-ui);'; const tabsHTML = `
${['params', 'headers', 'body', 'auth'].map(t => `
${t.toUpperCase()}
`).join('')}
${isBulkStart ? `
Strategy
` : ''}
Repeat
Delay ms
Workers
`; // Content let contentHTML = ''; if (this.state.activeTab === 'params') contentHTML = this.renderTable(this.state.params, 'params'); else if (this.state.activeTab === 'headers') contentHTML = this.renderTable(this.state.headers, 'headers'); else if (this.state.activeTab === 'body') contentHTML = this.renderBodyTab(); else if (this.state.activeTab === 'auth') contentHTML = this.renderAuthTab(); // Bottom Results & Response Panel (Always Rendered) const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0; const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)'; const folderPath = this.state.outputFolderPath || 'None selected'; const activeBottomTab = this.state.responseTab || 'response'; let bottomTabContentHTML = ''; if (activeBottomTab === 'response') { const resp = this.state.response; if (!resp) { bottomTabContentHTML = `
Ready to send request. Click SEND to execute a single request, or RUN BATCH for bulk.
`; } else if (resp.status === 'Sending...') { bottomTabContentHTML = `
Sending request...
`; } else if (resp.error) { bottomTabContentHTML = `
Error: ${resp.error}
`; } else { let content = resp.content; try { if (content && !resp.binary_data && content.trim().startsWith('{')) { content = JSON.stringify(JSON.parse(content), null, 2); } } catch(e){} bottomTabContentHTML = `
${resp.status_code} ${resp.latency ? resp.latency + ' ms' : ''} ${resp.content_type || 'Unknown Type'}
${resp.binary_data ? `
Binary Content
` : `
${this.escapeHTML(content)}
` }
`; } } else { if (bulk.results.length === 0) { bottomTabContentHTML = `
No batch results yet. Run a batch to see results in a grid.
`; } else { bottomTabContentHTML = `
`; } } bottomPanelHTML = `
${bulk.results.length > 0 ? `
${bulk.completed}/${bulk.total} ${bulk.success} ✓ ${bulk.error} ✗ ` : ''}
${activeBottomTab === 'results' && bulk.results.length > 0 ? `
${folderPath}
` : ''}
${bottomTabContentHTML}
`; this.dom.mainPanel.innerHTML = headerHTML + requestMetaHTML + tabsHTML + `
${contentHTML}
` + bottomPanelHTML; // After writing the skeleton, repopulate the results grid from our cached fragment // This avoids re-rendering 200+ cards on every render() call. this._repopulateResultsGrid(); }, _repopulateResultsGrid() { const grid = document.getElementById('main-results-grid'); if (!grid || !this.state.bulk.results.length) return; // Idempotent: only add cards that aren't already rendered. // This prevents rebuilding 200+ cards on every render(). const existing = grid.querySelectorAll('.result-card'); const renderedIndices = new Set(); existing.forEach(el => { const i = parseInt(el.dataset.index); if (!isNaN(i)) renderedIndices.add(i); }); const shown = this.state.bulk.results.slice(-200); // Only append cards that are missing from the DOM const missing = shown.filter(r => !renderedIndices.has(r.index)); if (!missing.length) return; const frag = document.createDocumentFragment(); missing.forEach(result => { const el = this._buildCardElement(result); frag.appendChild(el); }); grid.appendChild(frag); }, renderResultCard(result) { const isImage = (result.contentType || '').toLowerCase().includes('image') && (result.blobUrl || result.binaryData); const isSuccess = result.status >= 200 && result.status < 300; const statusClass = isSuccess ? 'status-success' : 'status-error'; const filename = result.inputFilename || `result_${result.index}`; const finalFilename = this.getFinalFilename(result); let previewHTML = ''; if (isImage) { try { previewHTML = `${filename}`; } catch (e) { previewHTML = `
Decode error
`; } } else { let icon = 'fa-file-lines'; let typeLabel = 'TXT'; const ct = (result.contentType || '').toLowerCase(); if (ct.includes('application/json')) { icon = 'fa-file-code'; typeLabel = 'JSON'; } else if (ct.includes('text/html')) { icon = 'fa-file-code'; typeLabel = 'HTML'; } else if (result.status === 'ERR') { icon = 'fa-circle-xmark'; typeLabel = 'ERROR'; } previewHTML = `
${typeLabel}

${this.escapeHTML(result.data || '')}

`; } const footerHTML = isImage ? `` : `
#${result.index} ${result.status} ${result.latency}ms
${finalFilename}
`; return `
${previewHTML}
${!isImage ? ` ` : ''}
${footerHTML}
`; }, renderResponse() { // No-op: Single response and bulk results have been consolidated into renderMain()'s bottom panel. }, renderTable(items, section) { return ` ${items.map(item => ` `).join('')}
KeyValue
${this.renderValueInput(item, section)}
`; }, renderValueInput(item, section) { if (item.type === 'file' || item.type === 'folder') { const files = this.fileStore.get(item.id); const label = files ? (item.type === 'folder' ? `${files.length} Files Selected` : `${files.length} Files`) : 'Select...'; return `
`; } if (item.type === 'auto_width' || item.type === 'auto_height') { return ``; } return ``; }, renderBodyTab() { return `
${this.state.bodyType === 'form-data' ? this.renderTable(this.state.bodyData, 'body') : ''} ${this.state.bodyType === 'json' ? `` : ''}
`; }, renderAuthTab() { const auth = this.state.auth; const inStyle = 'width:100%;padding:10px 12px;background:var(--bg-input);border:1px solid var(--border-2);border-radius:var(--r-md);color:var(--text-1);font-family:var(--font-mono);font-size:12px;transition:border-color 0.15s,box-shadow 0.15s;'; const labelStyle = 'display:block;margin-bottom:6px;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:0.07em;color:var(--text-3);'; return `
${auth.type === 'bearer' ? `
` : ''} ${auth.type === 'basic' ? `
` : ''} ${auth.type === 'apikey' ? `
` : ''}
`; }, // --- Helpers --- handleFileSelect(input, section, id) { if (input.files.length > 0) { // Convert FileList to Array and sort by path to ensure strict processing sequence (natural sorting) let filesArr = Array.from(input.files); filesArr.sort((a, b) => { const pA = a.webkitRelativePath || a.name; const pB = b.webkitRelativePath || b.name; return pA.localeCompare(pB, undefined, { numeric: true, sensitivity: 'base' }); }); this.fileStore.set(id, filesArr); this.render(); // update label } }, checkBulkStart() { const hasKeyedFolder = this.state.params.some(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()) || (this.state.bodyType === 'form-data' && this.state.bodyData.some(p => p.type === 'folder' && p.enabled && p.key && p.key.trim())); const hasKeyedList = this.state.params.some(p => p.type === 'list' && p.enabled && p.key && p.key.trim()) || (this.state.bodyType === 'form-data' && this.state.bodyData.some(p => p.type === 'list' && p.enabled && p.key && p.key.trim())) || this.state.headers.some(h => h.type === 'list' && h.enabled && h.key && h.key.trim()); return hasKeyedFolder || hasKeyedList; }, getStatusColor(code) { if (code >= 200 && code < 300) return 'var(--success)'; if (code >= 300 && code < 400) return 'var(--warning)'; if (code >= 400 || code === 'ERR') return 'var(--danger)'; return 'var(--text-muted)'; }, toast(msg, type = 'info') { const icons = { info: 'fa-circle-info', success: 'fa-circle-check', error: 'fa-circle-xmark', warning: 'fa-triangle-exclamation' }; const iconColors = { info: '#5ba0f5', success: '#0fcea0', error: '#ff4569', warning: '#f5a623' }; const icon = icons[type] || icons.info; const color = iconColors[type] || iconColors.info; const t = document.createElement('div'); t.className = `ph-toast-${type}`; t.innerHTML = `${this.escapeHTML(msg)}`; Object.assign(t.style, { display: 'flex', alignItems: 'center', gap: '10px', padding: '12px 16px', borderRadius: '10px', marginTop: '6px', fontSize: '13px', fontFamily: 'var(--font-ui)', fontWeight: '500', animation: 'toastSlideIn 0.32s cubic-bezier(0.34,1.56,0.64,1) both', }); this.dom.toast.appendChild(t); const removeDelay = type === 'error' ? 4500 : 3000; setTimeout(() => { t.style.animation = 'toastFadeOut 0.2s ease forwards'; setTimeout(() => t.remove(), 200); }, removeDelay); }, escapeHTML(str) { if (!str) return ''; if (typeof str !== 'string') return String(str); return str.replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }, base64ToUint8Array(base64Data) { if (!base64Data) return new Uint8Array(0); try { const byteCharacters = atob(base64Data); const data = new Uint8Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { data[i] = byteCharacters.charCodeAt(i); } return data; } catch (e) { console.error("Base64 to Uint8Array error", e); return new Uint8Array(0); } }, async base64ToBlobUrlAsync(base64Data, contentType) { if (!base64Data) return ''; try { const res = await fetch(`data:${contentType || 'application/octet-stream'};base64,${base64Data}`); const blob = await res.blob(); return URL.createObjectURL(blob); } catch (e) { console.error("Async Base64 decode error", e); return ''; } }, base64ToBlobUrl(base64Data, contentType) { if (!base64Data) return ''; try { const byteCharacters = atob(base64Data); const byteArrays = []; const sliceSize = 512; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return URL.createObjectURL(blob); } catch (e) { console.error("Base64 decode error", e); return ''; } }, bindEvents() { // Most events are inline (onclick, onchange) for simplicity in this structure }, // Preview a result previewResult(index) { const result = this.state.bulk.results.find(r => r.index === index); if (!result) return; const isImage = (result.contentType || '').toLowerCase().includes('image') && (result.blobUrl || result.binaryData); const finalFilename = this.getFinalFilename(result); let contentHTML = ''; if (isImage) { try { contentHTML = `${finalFilename}`; } catch (e) { contentHTML = ``; } } else { let prettyContent = result.fullContent || ''; try { if (prettyContent.trim().startsWith('{')) { prettyContent = JSON.stringify(JSON.parse(prettyContent), null, 2); } } catch(e) {} contentHTML = ``; } const modal = document.createElement('div'); modal.className = 'premium-modal-overlay'; modal.innerHTML = `
${finalFilename} Result #${result.index}
${result.status} ${result.latency}ms
${contentHTML}
`; document.body.appendChild(modal); modal.onclick = () => modal.remove(); }, // For manual clicking from history loadHistoryItem(id) { const item = this.state.history.find(h => h.id === id); if (item) { this.state.method = item.method; this.state.url = item.url; this.saveState(); this.render(); } } }; document.addEventListener('DOMContentLoaded', () => App.init());