import { execFileSync } from "node:child_process"; import { existsSync } from "node:fs"; import path from "node:path"; /** Map the debug app's loopback API to the development machine, without exposing it on the LAN. */ export function forwardAndroidApi({ env = process.env, run = execFileSync, } = {}) { if (env.TAURI_ENV_PLATFORM !== "android") return; const endpoint = new URL(env.ALTITUDE_API_URL || "http://127.0.0.1:8080/api"); if (!["http:", "https:"].includes(endpoint.protocol)) throw new Error("ALTITUDE_API_URL must be an HTTP or HTTPS URL."); if (!["127.0.0.1", "localhost", "[::1]"].includes(endpoint.hostname)) return; const port = endpoint.port || (endpoint.protocol === "https:" ? "443" : "80"); const sdk = env.ANDROID_HOME || env.ANDROID_SDK_ROOT; const executable = process.platform === "win32" ? "adb.exe" : "adb"; const candidate = sdk && path.join(sdk, "platform-tools", executable); const adb = candidate && existsSync(candidate) ? candidate : executable; const options = { encoding: "utf8", timeout: 10000 }; const devices = run(adb, ["devices"], options) .split(/\r?\n/) .map((line) => line.trim().split(/\s+/)) .filter(([, state]) => state === "device") .map(([serial]) => serial); let serial = env.ANDROID_SERIAL; if (serial && !devices.includes(serial)) throw new Error( "The selected Android device is not ready. Unlock it and allow USB debugging.", ); if (!serial) { if (!devices.length) throw new Error( "Connect and authorize your Android device to forward the local API.", ); if (devices.length > 1) throw new Error( "Multiple Android devices are connected. Set ANDROID_SERIAL to the device you are developing on.", ); serial = devices[0]; } run(adb, ["-s", serial, "reverse", `tcp:${port}`, `tcp:${port}`], options); console.log(`Android API forwarding ready on port ${port}.`); }