/** * Keyboard command handler — routing for summon-autofill: * 1. Restricted URL (non-http/https) → open popup * 2. Ping content script (150ms timeout) → if alive, send SUMMON_AUTOFILL * (content script opens the same unified inline selector used for field focus) * 3. Content script not ready / no login form detected → open popup fallback */ const PING_TIMEOUT_MS = 150; async function pingContentScript(tabId: number): Promise { return new Promise((resolve) => { const timer = setTimeout(() => resolve(false), PING_TIMEOUT_MS); try { chrome.tabs.sendMessage(tabId, { type: "PING" }, (response) => { clearTimeout(timer); if (chrome.runtime.lastError) { resolve(false); } else { resolve(response?.ok === true); } }); } catch { clearTimeout(timer); resolve(false); } }); } async function openPopup(): Promise { try { // chrome.action.openPopup() requires Chrome 127+ and user gesture context; // it may throw — that's acceptable, we degrade gracefully. await (chrome.action as { openPopup?: () => Promise }).openPopup?.(); } catch { // Silently ignore — user can click the toolbar icon instead } } export function setupCommands(): void { chrome.commands.onCommand.addListener(async (command) => { if (command !== "summon-autofill") return; const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab?.id || !tab.url) return; // ── Step 1: restricted URL? ─────────────────────────────────── if (!/^https?:\/\//i.test(tab.url)) { await openPopup(); return; } const tabId = tab.id; // ── Step 2: ping existing content script ───────────────────── const alive = await pingContentScript(tabId); if (alive) { // Content script handles SUMMON_AUTOFILL by opening the unified inline // selector. It returns ok: true only when it found a login/signup form. // If ok: false (no form on page), fall through to open the popup. const response = await new Promise<{ ok?: boolean }>((resolve) => { try { chrome.tabs.sendMessage(tabId, { type: "SUMMON_AUTOFILL" }, (r) => { resolve((r as { ok?: boolean }) ?? {}); }); } catch { resolve({}); } }); if (response?.ok) return; } // ── Step 3: content script unavailable or no login form ────── // Open the popup as a universal fallback. await openPopup(); }); }