feat: massive front-end overhaul and initial github release

This commit is contained in:
Simeon Radivoev 2026-02-08 21:18:10 +02:00
parent a2b40e38bf
commit d5a0e70580
Signed by: simeonradivoev
GPG key ID: 7611A451D2A5D37A
303 changed files with 19840 additions and 676 deletions

38
src/bun/api/clients.ts Normal file
View file

@ -0,0 +1,38 @@
import { config } from "./settings";
import Elysia from "elysia";
export const romm = new Elysia({ prefix: "/romm" })
.all("/*", async ({ request, params, set }) =>
{
if (!config.has('rommAddress') && !config.get('rommAddress'))
{
return new Response("Romm Address Not Found", { status: 404 });
}
const rommUrl = new URL(config.get('rommAddress')!);
const url = new URL(request.url);
url.pathname = url.pathname.replace(/^\/api\/romm/, '');
url.host = rommUrl.host;
url.port = rommUrl.port;
url.protocol = rommUrl.protocol;
// Forward headers (optional: remove host if needed)
const headers = new Headers(request.headers);
headers.delete('host');
headers.set("accept-encoding", "identity");
const rommResponse = await fetch(url, {
method: request.method,
headers,
body: await request.arrayBuffer(),
redirect: 'manual', // avoid ROMM redirects
});
set.status = rommResponse.status;
rommResponse.headers.forEach((value, key) =>
{
set.headers[key] = value;
});
return new Response(rommResponse.body, { status: rommResponse.status });
});

42
src/bun/api/rpc.ts Normal file
View file

@ -0,0 +1,42 @@
import { RPC_PORT } from "../../shared/constants";
import { settings } from "./settings";
import { romm } from "./clients";
import Elysia from "elysia";
import { cors } from "@elysiajs/cors";
import { host } from "../utils";
const api = new Elysia({ prefix: "/api", serve: {} })
.use(cors())
.use(romm)
.use(settings);
export type AppType = typeof api;
export function RunAPIServer ()
{
console.log("Launching API Server on port ", RPC_PORT);
return {
apiServer: api.listen({
port: RPC_PORT,
hostname: host,
development: process.env.NODE_ENV === 'development',
fetch (req, server)
{
if (server.upgrade(req, {
data: undefined
}))
{
return;
}
return api.fetch(req);
},
websocket: {
message (ws, message)
{
},
}
})
};
}

29
src/bun/api/settings.ts Normal file
View file

@ -0,0 +1,29 @@
import z from "zod";
import { SettingsSchema, SettingsType } from "../../shared/constants";
import Conf from "conf";
import projectPackage from '../../../package.json';
import Elysia from "elysia";
export const config = new Conf<SettingsType>({
projectName: projectPackage.name,
projectSuffix: 'bun',
schema: Object.fromEntries(Object.entries(SettingsSchema.shape).map(([key, schema]) => [key, schema.toJSONSchema() as any])) as any,
defaults: SettingsSchema.parse({}),
});
console.log("Config Path Located At: ", config.path);
export const settings = new Elysia({ prefix: '/settings' })
.get("/:id", async ({ params: { id } }) =>
{
const value = config.get(id);
return { value: value };
}, {
params: z.object({ id: z.keyof(SettingsSchema) }),
}).post('/:id',
async ({ params: { id }, body: { value }, }) =>
{
config.set(id, value);
}, {
params: z.object({ id: z.keyof(SettingsSchema) }),
body: z.object({ value: z.any() })
});

View file

@ -1,39 +1,55 @@
import { BrowserWindow, Updater } from "electrobun/bun";
import { RunBunServer } from './server';
import { RunAPIServer } from './api/rpc';
import { spawnBrowser } from './utils/browser-spawner';
import { BuildParams } from './utils/browser-params';
const DEV_SERVER_PORT = 5173;
const DEV_SERVER_URL = `http://localhost:${DEV_SERVER_PORT}/Dashboard`;
const api = RunAPIServer();
let bunServer: { stop: () => void; url: URL; } | undefined;
// Check if Vite dev server is running for HMR
async function getMainViewUrl(): Promise<string> {
const channel = await Updater.localInfo.channel();
if (channel === "dev") {
try {
await fetch(DEV_SERVER_URL, { method: "HEAD" });
console.log(`HMR enabled: Using Vite dev server at ${DEV_SERVER_URL}`);
return DEV_SERVER_URL;
} catch {
console.log("Vite dev server not running. Run 'bun run dev:hmr' for HMR support.");
}
}
return "views://mainview/index.html";
if (!Bun.env.PUBLIC_ACCESS)
{
bunServer = RunBunServer();
}
// Create the main application window
const url = await getMainViewUrl();
function cleanup ()
{
bunServer?.stop();
api.apiServer.stop();
process.exit(0);
}
const mainWindow = new BrowserWindow({
title: "GameFlow",
url,
renderer: 'cef',
styleMask: {
Borderless: true,
},
frame: {
width: 1280,
height: 800,
x: 200,
y: 200,
},
});
try
{
const webviewWorker = new Worker(process.env.IS_BINARY ? "./webview-worker.ts" : new URL("./webview-worker", import.meta.url).href, {
smol: true,
});
webviewWorker.addEventListener('error', console.error);
await new Promise(resolve => webviewWorker.addEventListener('close', resolve));
cleanup();
}
catch (error)
{
console.error(error);
console.log("React Tailwind Vite app started!");
const browserParams = await BuildParams();
if (!browserParams)
{
console.error("Could not find valid browser");
process.exit();
}
const browser = spawnBrowser({
browser: browserParams.browser.type,
args: browserParams.args,
env: browserParams.env,
detached: true,
execPath: browserParams.browser.path,
source: browserParams.browser.source,
ipc (message)
{
console.log(message);
},
onExit: cleanup
});
}

22
src/bun/server.ts Normal file
View file

@ -0,0 +1,22 @@
import { SERVER_PORT } from "../shared/constants";
import path from 'node:path';
import { host } from "./utils";
export function RunBunServer ()
{
console.log("Launching Server on port ", SERVER_PORT);
return Bun.serve({
port: SERVER_PORT,
hostname: host,
routes: {
"/": Bun.file("./dist/index.html"),
// Serve a file by lazily loading it into memory
"/favicon.ico": Bun.file("./dist/favicon.ico"),
},
fetch: async (req) =>
{
const url = new URL(req.url);
return new Response(Bun.file(`./${path.join('dist', url.pathname)}`));
},
});
}

19
src/bun/types.d.ts vendored Normal file
View file

@ -0,0 +1,19 @@
declare const IS_BINARY: string;
declare module 'download-chromium' {
export default function download ({
platform,
revision = '499413',
log = false,
onProgress = undefined,
installPath = '{__dirname}/.local-chromium' }: {
platform?: 'linux' | 'mac' | 'win32' | 'win64',
revision?: string,
log?: boolean,
installPath?: string,
onProgress?: (percent: number, transferred: number, total: number) => void;
}): Promise<string>
{
};
}

19
src/bun/utils.ts Normal file
View file

@ -0,0 +1,19 @@
import { networkInterfaces } from 'node:os';
const localIp = Object.values(networkInterfaces())
.flat()
.find((iface) => iface?.family === 'IPv4' && !iface.internal)?.address || 'localhost';
export const host = process.env.PUBLIC_ACCESS ? localIp : 'localhost';
export function checkRunning (pid: number)
{
try
{
return process.kill(pid, 0);
} catch (error: any)
{
return error.code === 'EPERM';
}
}

View file

@ -0,0 +1,91 @@
import { SERVER_URL } from "../../shared/constants";
import os from 'node:os';
import path, { dirname } from 'node:path';
import { getBrowserPath } from "./get-browser";
import { config } from "../api/settings";
import { host } from "../utils";
export async function BuildParams ()
{
const validBrowser = await getBrowserPath({
browserOrder: ['chrome', 'chromium']
});
if (!validBrowser)
{
return undefined;
}
const args: string[] = [];
const browserEnv = {
GOOGLE_API_KEY: 'no',
GOOGLE_DEFAULT_CLIENT_ID: 'no',
GOOGLE_DEFAULT_CLIENT_SECRET: 'no',
};
if (validBrowser.type === 'chrome' || validBrowser.type === 'chromium')
{
const isEdge = validBrowser.path.toLowerCase().includes('edge') || validBrowser.path.toLowerCase().includes('msedge');
console.log(`[Browser] Detected: ${validBrowser.type} from ${validBrowser.source} - ${isEdge ? 'Edge' : 'Chrome/Chromium'}`);
args.push(`--app=${SERVER_URL(host)}`);
args.push(`--app-id=gameflow`);
args.push(`--force-app-mode`);
args.push('--no-default-browser-check');
args.push('--no-first-run');
args.push('--disable-infobars');
args.push("--disable-extensions");
args.push("--disable-plugins");
args.push(`--user-data-dir=${path.join(dirname(config.path), 'browser-data')}`);
args.push('--disable-sync'); //Disable syncing to a Google account
args.push('--disable-sync-preferences');
args.push('--disable-component-update');
args.push('--allow-insecure-localhost');
args.push('--auto-accept-camera-and-microphone-capture');
args.push(`--window-size=${config.get('windowSize.width')},${config.get('windowSize.height')}`);
args.push('--password-store=basic');
args.push('--block-new-web-contents');
args.push('--bwsi');
args.push('--ash-no-nudges');
args.push('--autoplay-policy=no-user-gesture-required'); // allow autoplay of videos
args.push('--disabled-features=WindowControlsOverlay,navigationControls,Translate,msUndersideButton');
args.push(`--profile-directory=Default`);
if (config.has('windowPosition'))
{
args.push(`--window-position=${config.get('windowPosition.x')},${config.get('windowPosition.y')}`);
}
if (isEdge)
{
// Disable Edge sync and cloud features
args.push('--disable-sync');
args.push('--disable-background-networking');
args.push('--disable-client-side-phishing-detection');
args.push('--disable-component-extensions-with-background-pages');
args.push('--disable-default-apps');
args.push('--disable-extensions-except=');
args.push('--disable-feature=TranslateUI');
args.push('--disable-background-timer-throttling');
args.push('--disable-backgrounding-occluded-windows');
args.push('--disable-breakpad');
args.push('--disable-client-side-phishing-detection');
args.push('--disable-component-update');
args.push('--disable-hang-monitor');
args.push('--disable-ipc-flooding-protection');
args.push('--disable-popup-blocking');
args.push('--disable-prompt-on-repost');
args.push('--disable-renderer-backgrounding');
args.push('--metrics-recording-only');
args.push('--no-service-autorun');
}
if (os.platform() === 'linux')
{
args.push("--disable-web-security");
args.push("--no-sandbox");
}
}
return { env: browserEnv, args, browser: validBrowser };
}

View file

@ -0,0 +1,166 @@
import { type Subprocess } from "bun";
export type RunBrowserType = "chrome" | "chromium" | "firefox" | "edge";
export type RunBrowserSource = "running" | "system" | "flatpak";
/**
* Options for spawning a browser process.
*
* @property browser - The browser type to spawn
* @property args - Optional command-line arguments to pass to the browser
* @property env - Optional environment variables to set for the browser process
* @property detached - If true, the browser process runs independently of the parent
* @property execPath - Full path to the browser executable (required)
* @property source - How the browser was discovered (running, system, or flatpak)
*/
interface SpawnBrowserOptions
{
browser: RunBrowserType;
args?: string[];
env?: Record<string, string>;
detached?: boolean;
execPath: string; // Required: browser executable path from get-browser.ts
source: RunBrowserSource; // How the browser was discovered (running, system, or flatpak)
onExit?: () => void; // Called when the browser exists duh
ipc?: (message: string) => void;
}
/**
* Spawns a browser process with proper handling for different installation types.
*
* Behavior depends on the browser source:
* - "running": Browser is already running, spawns additional instance
* - "system": Native system installation, spawned directly with execPath
* - "flatpak": Flatpak containerized browser, spawned via `flatpak run` with proper arguments
*
* For Flatpak browsers, uses Steam-style argument ordering:
* `flatpak run [OPTIONS] [APP_ID] @@u @@ [USER_ARGS]`
*
* @param options - Spawn options including browser type, path, source, and arguments
* @returns A Bun Subprocess instance
* @throws Error if execPath is not provided or if browser configuration is invalid
*
* @example
* const browser = await getBrowserPath();
* if (browser) {
* const proc = spawnBrowser({
* browser: browser.type,
* args: ["--no-sandbox", "https://example.com"],
* source: browser.source,
* execPath: browser.path,
* detached: true
* });
* }
*/
export function spawnBrowser ({
browser,
args = [],
env = {},
detached = false,
execPath,
source,
onExit,
ipc
}: SpawnBrowserOptions): Subprocess
{
// Configuration for both Flatpak and Native
// Contains Flatpak app IDs, internal container paths, and fallback binary names
const config: Record<RunBrowserType, { id: string; internalCmd: string; bin: string[]; }> = {
chrome: {
id: "com.google.Chrome",
internalCmd: "/app/bin/chrome", // Explicit command inside container
bin: ["google-chrome", "google-chrome-stable", "chrome"]
},
chromium: {
id: "org.chromium.Chromium",
internalCmd: "/app/bin/chromium",
bin: ["chromium", "chromium-browser"]
},
firefox: {
id: "org.mozilla.firefox",
internalCmd: "/app/bin/firefox",
bin: ["firefox"]
},
edge: {
id: "com.microsoft.Edge",
internalCmd: "/app/bin/edge", // Varies, but usually standard for Edge
bin: ["microsoft-edge", "microsoft-edge-stable"]
}
};
const target = config[browser];
const useFlatpak = source === "flatpak";
let cmd: string[];
let finalEnv: Record<string, string> | undefined;
if (useFlatpak)
{
// --- Flatpak Mode (Steam Style) ---
// Structure: flatpak run [ENV] [FLATPAK_OPTS] [APP_ID] @@u @@ [USER_ARGS]
// The @@u @@ syntax enables file forwarding for URL arguments
const envFlags = Object.entries(env).map(([k, v]) => `--env=${k}=${v}`);
// We explicitly set the command to ensure we don't rely on the default entrypoint failing
const flatpakOpts = [
"run",
"--branch=stable",
`--arch=${process.arch === "x64" ? "x86_64" : process.arch}`, // map node arch to flatpak arch
`--command=${target.internalCmd}`,
"--file-forwarding",
...envFlags // Inject env vars here
];
// Combine: flatpak run ... com.google.Chrome @@u @@ [USER_ARGS]
cmd = [
"flatpak",
...flatpakOpts,
target.id,
"@@u",
"@@",
...args
];
// Clear env for the spawner so it doesn't pollute the flatpak command wrapper
finalEnv = undefined;
console.log(`[Browser] Launching Flatpak: ${cmd.join(" ")}`);
} else
{
// --- Native Mode ---
// Use the provided execPath directly
cmd = [execPath, ...args];
finalEnv = { ...process.env, ...env } as Record<string, string>;
console.log(`[Browser] Launching Native: ${execPath}`);
}
const processSub = Bun.spawn(cmd, {
env: finalEnv,
stdin: "ignore",
stdout: "inherit",
stderr: "inherit",
ipc,
onExit (_proc, exitCode)
{
if (exitCode !== 0 && exitCode !== null)
{
console.error(`[Browser] Exited with code: ${exitCode}`);
}
onExit?.();
},
});
if (detached) processSub.unref();
return processSub;
}
// --- Test Run ---
// spawnBrowser({
// browser: "chrome",
// args: ["--window-size=1024,640", "--force-device-scale-factor=1.25"],
// detached: true
// });

View file

@ -0,0 +1,611 @@
import { spawnSync } from "bun";
import { platform } from "node:os";
import { RunBrowserType } from "./browser-spawner";
export type GetBrowserType = "chrome" | "chromium" | "firefox";
export type GetBrowserSource = "running" | "system" | "flatpak";
/**
* Browser discovery priority configuration
*/
interface BrowserPriorityConfig
{
/** Include currently running browser processes in search */
includeRunning?: boolean;
/** Browser types to search for, in priority order */
browserOrder?: GetBrowserType[];
/** Include system default browser on Windows */
includeSystemDefault?: boolean;
/** Include Flatpak browsers on Linux */
includeFlatpak?: boolean;
}
/**
* Browser discovery result containing the executable path, browser type, and discovery source.
*/
interface BrowserResult
{
/** Full path to the browser executable */
path: string;
/** Type of browser (chrome, chromium, or firefox) */
type: GetBrowserType;
/** Source of discovery (running process, system installation, or flatpak) */
source: GetBrowserSource;
}
/**
* Main function to find a valid browser executable.
*
* Searches for an available browser based on customizable priority configuration.
* Default priority order:
* 1. Currently running Chrome process (fastest return)
* 2. Windows: Default system browser (if on Windows)
* 3. Standard System Paths (Firefox > Chrome > Chromium by default)
* 4. Flatpak (Linux only)
*
* @param config - Optional priority configuration to customize search behavior
* @returns A promise that resolves to a BrowserResult containing the path, type, and source
* of the discovered browser, or null if no suitable browser is found.
*
* @example
* // Use default priority
* const browser = await getBrowserPath();
*
* @example
* // Prefer Chrome over Firefox, skip running processes
* const browser = await getBrowserPath({
* includeRunning: false,
* browserOrder: ['chrome', 'firefox', 'chromium']
* });
*/
export async function getBrowserPath (config?: BrowserPriorityConfig): Promise<BrowserResult | null>
{
// Default configuration
const {
includeRunning = true,
browserOrder = ["firefox", "chrome", "chromium"],
includeSystemDefault = true,
includeFlatpak = true
} = config || {};
const currentPlatform = platform();
// 1. Check for currently running browser process
if (includeRunning)
{
const runningBrowser = await getRunningBrowserPath(browserOrder, currentPlatform);
if (runningBrowser)
{
console.log(`[Found] Running ${runningBrowser.type} process: ${runningBrowser.path}`);
return { ...runningBrowser, source: "running" };
}
}
// 2. Windows: Check default system browser
if (includeSystemDefault && currentPlatform === "win32")
{
const defaultBrowser = await getWindowsDefaultBrowser(browserOrder);
if (defaultBrowser && browserOrder.includes(defaultBrowser.type))
{
console.log(`[Found] Windows default browser: ${defaultBrowser.path} (${defaultBrowser.type})`);
return { ...defaultBrowser, source: "system" };
}
}
// 3. Check standard install paths with custom priority
for (const browser of browserOrder)
{
const path = await findSystemBrowser(browser, currentPlatform);
if (path)
{
console.log(`[Found] Installed ${browser}: ${path}`);
return { path, type: browser, source: "system" };
}
}
// 4. Check Flatpaks (Linux only)
if (includeFlatpak && currentPlatform === "linux")
{
for (const browser of browserOrder)
{
const path = await findFlatpakBrowser(browser);
if (path)
{
console.log(`[Found] Flatpak ${browser}: ${path}`);
return { path, type: browser, source: "flatpak" };
}
}
}
console.error("No suitable browser found.");
return null;
}
// --- Helper: Find Running Process ---
/**
* Attempts to find the path of a currently running browser (Chrome, Chromium, or Firefox).
*
* Platform-specific implementations:
* - Windows: Uses PowerShell to query running processes
* - Linux: Uses pgrep to find the process and resolves /proc/[pid]/exe
* - macOS: Uses ps command to find Chrome or Firefox in process list
*
* @param os - The operating system ("win32", "linux", or "darwin")
* @returns An object with path and type of the running browser, or null if not found
*/
async function getRunningBrowserPath (browserOrder: GetBrowserType[], os: string): Promise<{ path: string, type: GetBrowserType; } | null>
{
try
{
if (os === "win32")
{
// PowerShell is most reliable for getting full paths on Windows
// Check for Firefox first, then Chrome
for (const processName of browserOrder)
{
const cmd = spawnSync([
"powershell",
"-NoProfile",
"-Command",
`(Get-Process ${processName} -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path)`
]);
const path = cmd.stdout.toString().trim();
if (path && await Bun.file(path).exists())
{
const browserType: GetBrowserType = processName === 'firefox' ? 'firefox' : 'chrome';
console.log(`[Browser] Found running ${browserType}: ${path}`);
return { path, type: browserType };
}
}
return null;
}
if (os === "linux")
{
const names: Record<RunBrowserType, string[]> = {
chrome: ['chrome', 'google-chrome', 'google-chrome-stable'],
chromium: ['chromium'],
firefox: ['firefox'],
edge: ['edge']
};
// Find PID of firefox or chrome, then resolve the symlink in /proc
for (const processName of browserOrder.flatMap(b => names[b]))
{
const pgrep = spawnSync(["pgrep", "-o", processName]); // -o = oldest (parent)
const pid = pgrep.stdout.toString().trim();
if (!pid) continue;
// Read the symlink for the executable path using readlink
const linkPath = `/proc/${pid}/exe`;
// Use shell readlink to resolve the symlink
const readLink = spawnSync(["readlink", "-f", linkPath]);
const finalPath = readLink.stdout.toString().trim();
if (finalPath && await Bun.file(finalPath).exists())
{
const browserType: GetBrowserType = processName === 'firefox' ? 'firefox' : 'chrome';
console.log(`[Browser] Found running ${browserType}: ${finalPath}`);
return { path: finalPath, type: browserType };
}
}
return null;
}
if (os === "darwin")
{
// macOS: ps command to list process paths
const cmd = spawnSync(["ps", "-A", "-o", "comm"]);
const output = cmd.stdout.toString();
// Check for Firefox first
const firefoxMatch = output.split('\n').find(line => line.includes("Firefox.app/Contents/MacOS/firefox"));
if (firefoxMatch)
{
console.log(`[Browser] Found running firefox: ${firefoxMatch.trim()}`);
return { path: firefoxMatch.trim(), type: 'firefox' };
}
// Check for Chrome
const chromeMatch = output.split('\n').find(line => line.includes("Google Chrome.app/Contents/MacOS/Google Chrome"));
if (chromeMatch)
{
console.log(`[Browser] Found running chrome: ${chromeMatch.trim()}`);
return { path: chromeMatch.trim(), type: 'chrome' };
}
return null;
}
} catch (e)
{
// Ignore errors checking running processes
return null;
}
return null;
}
// --- Helper: Get Windows Default Browser ---
/**
* Detects the default browser set in Windows via registry queries.
*
* Queries multiple registry locations for Windows 11+ and Windows 10 compatibility:
* - URL associations (Windows 11+)
* - File extension associations (Windows 10)
* - Classic ProgID associations
*
* Falls back through multiple methods if the primary registry keys are unavailable.
*
* @returns An object with the default browser's path and type, or null if detection fails
*/
async function getWindowsDefaultBrowser (allowed: GetBrowserType[]): Promise<{ path: string, type: GetBrowserType; } | null>
{
try
{
// Query the registry for the default browser
// Windows 10/11 store default browser association in multiple places
const registryKeys = [
// Windows 11+ (Preferred)
'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice',
// Windows 10 fallback
'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.html\\UserChoice',
// Classic method - looks at .html file association
'HKEY_CLASSES_ROOT\\.html'
];
for (const regKey of registryKeys)
{
try
{
const cmd = spawnSync(["reg", "query", regKey]);
if (cmd.success)
{
const output = cmd.stdout.toString().toLowerCase();
// Check which browser is the default
if ((output.includes('chrome') || output.includes('google')) && allowed.includes('chrome'))
{
const chromePath = await findSystemBrowser("chrome", "win32");
if (chromePath) return { path: chromePath, type: "chrome" };
}
if ((output.includes('msedge') || output.includes('edge')) && allowed.includes('chromium'))
{
const edgePath = await findSystemBrowser("chromium", "win32");
if (edgePath && edgePath.includes('msedge')) return { path: edgePath, type: "chromium" };
}
if (output.includes('firefox') && allowed.includes('firefox'))
{
const firefoxPath = await findSystemBrowser("firefox", "win32");
if (firefoxPath) return { path: firefoxPath, type: "firefox" };
}
}
} catch (e)
{
// Try next registry key
}
}
// Fallback: Try to get progId for .html files
try
{
const progIdCmd = spawnSync(["reg", "query", "HKEY_CLASSES_ROOT\\.html", "/ve"]);
if (progIdCmd.success)
{
const progId = progIdCmd.stdout.toString().match(/REG_SZ\s+(.+?)(?:\r?\n|$)/)?.[1]?.trim();
if (progId)
{
// Query the ProgID's shell\\open\\command to get the browser path
const cmdKey = `HKEY_CLASSES_ROOT\\${progId}\\shell\\open\\command`;
const openCmd = spawnSync(["reg", "query", cmdKey, "/ve"]);
if (openCmd.success)
{
const execPath = openCmd.stdout.toString().match(/REG_SZ\s+"?([^"\r\n]+\.exe)/i)?.[1];
if (execPath && await Bun.file(execPath).exists())
{
// Determine browser type
if (execPath.toLowerCase().includes('chrome') && allowed.includes('chrome'))
{
return { path: execPath, type: "chrome" };
} else if ((execPath.toLowerCase().includes('edge') || execPath.toLowerCase().includes('msedge')) && allowed.includes('chromium'))
{
return { path: execPath, type: "chromium" };
} else if (execPath.toLowerCase().includes('firefox') && allowed.includes('firefox'))
{
return { path: execPath, type: "firefox" };
}
}
}
}
}
} catch (e)
{
// Fallback failed
}
} catch (e)
{
// Default browser detection failed
}
return null;
}
// --- Helper: Find System Installed Browser ---
/**
* Searches for a browser installation in standard system locations.
*
* Platform-specific behavior:
* - Windows: Checks registry and common installation directories (Program Files, AppData, etc.)
* - macOS: Checks Applications folder
* - Linux: Uses `which` command to find binary in $PATH
*
* @param browser - The browser type to search for
* @param os - The operating system ("win32", "linux", or "darwin")
* @returns The full path to the browser executable, or null if not found
*/
async function findSystemBrowser (browser: GetBrowserType, os: string): Promise<string | null>
{
if (os === "win32")
{
// First, try registry lookup (most reliable on Windows)
const registryPath = await findBrowserViaRegistry(browser);
if (registryPath) return registryPath;
// Fallback to standard install paths
const standardPaths = getStandardWindowsPaths(browser);
for (const fullPath of standardPaths)
{
if (await Bun.file(fullPath).exists()) return fullPath;
}
return null;
}
if (os === "linux" || os === "darwin")
{
// Common binary names
const binMap: Record<string, string[]> = {
chrome: ["google-chrome", "google-chrome-stable", "chrome"],
chromium: ["chromium", "chromium-browser"],
firefox: ["firefox"]
};
if (os === "darwin")
{
// macOS standard paths
const macPaths = {
chrome: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
chromium: "/Applications/Chromium.app/Contents/MacOS/Chromium",
firefox: "/Applications/Firefox.app/Contents/MacOS/firefox"
};
if (await Bun.file(macPaths[browser]).exists()) return macPaths[browser];
return null;
}
// Linux: use `which` to find in $PATH
for (const bin of binMap[browser])
{
const cmd = spawnSync(["which", bin]);
if (cmd.success)
{
const path = cmd.stdout.toString().trim();
if (path && await Bun.file(path).exists()) return path;
}
}
}
return null;
}
// --- Helper: Windows Registry Lookup ---
/**
* Queries Windows registry for browser installation paths.
*
* Checks App Paths registry hives which are populated by browser installers:
* - HKEY_LOCAL_MACHINE (system-wide installations)
* - HKEY_LOCAL_MACHINE\WOW6432Node (32-bit applications on 64-bit systems)
* - HKEY_CURRENT_USER (user-specific installations)
*
* This is more reliable than hardcoded paths as it dynamically finds where
* the browser installer registered itself.
*
* @param browser - The browser type to search for
* @returns The full path to the browser executable from registry, or null if not found
*/
async function findBrowserViaRegistry (browser: GetBrowserType): Promise<string | null>
{
try
{
// Registry paths for browser installations
const registryPaths: Record<GetBrowserType, string[]> = {
chrome: [
// Standard Chrome registry paths
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe',
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe',
// User-specific Chrome registry
'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe'
],
chromium: [
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chromium.exe',
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chromium.exe'
],
firefox: [
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\firefox.exe',
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\firefox.exe',
// Check Mozilla Firefox registry for install location
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Mozilla\\Mozilla Firefox'
]
};
for (const regPath of registryPaths[browser])
{
try
{
const cmd = spawnSync([
"reg",
"query",
regPath,
"/ve"
]);
if (cmd.success)
{
const output = cmd.stdout.toString();
// Extract path from registry output (format: " (Default) REG_SZ C:\path\to\exe")
const match = output.match(/REG_SZ\s+(.+?)(?:\r?\n|$)/);
if (match && match[1])
{
const path = match[1].trim();
if (path && await Bun.file(path).exists())
{
return path;
}
}
}
} catch (e)
{
// Continue to next registry path
}
}
} catch (e)
{
// Registry lookup failed, will fallback to standard paths
}
return null;
}
// --- Helper: Standard Windows Browser Paths ---
/**
* Generates a list of common Windows browser installation paths to check.
*
* Includes:
* - Program Files locations (64-bit and 32-bit)
* - LocalAppData (user-specific installations)
* - Microsoft Edge paths (treated as chromium)
* - Portable installations and custom locations
*
* @param browser - The browser type to generate paths for
* @returns An array of potential browser executable paths
*/
function getStandardWindowsPaths (browser: GetBrowserType): string[]
{
const paths: string[] = [];
const prefixes = [
process.env.LOCALAPPDATA,
process.env.PROGRAMFILES,
process.env["PROGRAMFILES(X86)"]
].filter(Boolean) as string[];
// Standard installation patterns
const browserPatterns: Record<GetBrowserType, string[]> = {
chrome: [
"\\Google\\Chrome\\Application\\chrome.exe",
"\\Google\\Chrome\\chrome.exe"
],
chromium: [
"\\Chromium\\Application\\chrome.exe",
"\\Chromium\\chromium.exe"
],
firefox: [
"\\Mozilla Firefox\\firefox.exe",
"\\Mozilla\\Firefox\\firefox.exe",
"\\Firefox\\firefox.exe"
]
};
// Add standard paths
for (const prefix of prefixes)
{
for (const pattern of browserPatterns[browser])
{
paths.push(`${prefix}${pattern}`);
}
}
// Add common user-specific paths (especially for Chrome Portable or custom installations)
const userProfile = process.env.USERPROFILE;
if (userProfile)
{
if (browser === "chrome")
{
paths.push(`${userProfile}\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe`);
paths.push(`${userProfile}\\AppData\\Roaming\\Google\\Chrome\\Application\\chrome.exe`);
} else if (browser === "firefox")
{
paths.push(`${userProfile}\\AppData\\Local\\Mozilla Firefox\\firefox.exe`);
paths.push(`${userProfile}\\AppData\\Roaming\\Mozilla Firefox\\firefox.exe`);
// Also check for Program Files under user profile (some custom installs)
paths.push(`${userProfile}\\AppData\\Local\\Programs\\Firefox\\firefox.exe`);
}
}
// Add alternative common locations for Edge (treated as chromium)
if (browser === "chromium")
{
const edgePaths = [
`${process.env.PROGRAMFILES}\\Microsoft\\Edge\\Application\\msedge.exe`,
`${process.env["PROGRAMFILES(X86)"]}\\Microsoft\\Edge\\Application\\msedge.exe`,
`${userProfile}\\AppData\\Local\\Microsoft\\Edge\\Application\\msedge.exe`
].filter(p => p);
paths.push(...edgePaths);
}
return paths;
}
// --- Helper: Find Flatpak (Linux Only) ---
/**
* Searches for a Flatpak browser installation on Linux.
*
* Checks if a Flatpak is installed by querying the flatpak command,
* then looks for the exported binary in standard Flatpak export directories.
*
* Flatpak paths checked:
* - /var/lib/flatpak/exports/bin/ (system-wide)
* - ~/.local/share/flatpak/exports/bin/ (user-specific)
*
* @param browser - The browser type to search for
* @returns The path to the Flatpak browser binary, or null if not found
*/
async function findFlatpakBrowser (browser: GetBrowserType): Promise<string | null>
{
// Check if flatpak is installed first
if (spawnSync(["which", "flatpak"]).exitCode !== 0) return null;
const flatpakIds = {
chrome: "com.google.Chrome",
chromium: "org.chromium.Chromium",
firefox: "org.mozilla.firefox"
};
const appId = flatpakIds[browser];
// Check if specific flatpak is installed
const checkCmd = spawnSync(["flatpak", "info", appId]);
if (checkCmd.success)
{
// We return the flatpak run command wrapper or the path?
// Usually tools expect an executable. For flatpak, we might need a wrapper script
// or just return "flatpak" with arguments.
// However, usually tools want a single path.
// We will return the internal path if accessible, or the flatpak binary path usually isn't enough.
// OPTION A: Return the standard export path if it exists
const exportPath = `/var/lib/flatpak/exports/bin/${appId}`;
if (await Bun.file(exportPath).exists()) return exportPath;
const userExportPath = `${process.env.HOME}/.local/share/flatpak/exports/bin/${appId}`;
if (await Bun.file(userExportPath).exists()) return userExportPath;
}
return null;
}

View file

@ -0,0 +1,9 @@
import Webview from "@rcompat/webview";
import platform from "@rcompat/webview/windows-x64";
import { SERVER_URL } from "../shared/constants";
import { host } from "./utils";
console.log("Launching Webview");
const webview = new Webview({ debug: import.meta.env.NODE_ENV === 'development', platform });
webview.navigate(SERVER_URL(host));
webview.run();

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,16 @@
// This file is auto-generated by @hey-api/openapi-ts
import { type ClientOptions, type Config, createClient, createConfig } from './client';
import type { ClientOptions as ClientOptions2 } from './types.gen';
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export const client = createClient(createConfig<ClientOptions2>());

View file

@ -0,0 +1,311 @@
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from '../core/serverSentEvents.gen';
import type { HttpMethod } from '../core/types.gen';
import { getValidRequestBody } from '../core/utils.gen';
import type {
Client,
Config,
RequestOptions,
ResolvedRequestOptions,
} from './types.gen';
import {
buildUrl,
createConfig,
createInterceptors,
getParseAs,
mergeConfigs,
mergeHeaders,
setAuthParams,
} from './utils.gen';
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
body?: any;
headers: ReturnType<typeof mergeHeaders>;
};
export const createClient = (config: Config = {}): Client => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors<
Request,
Response,
unknown,
ResolvedRequestOptions
>();
const beforeRequest = async (options: RequestOptions) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
serializedBody: undefined,
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.serializedBody === '') {
opts.headers.delete('Content-Type');
}
const url = buildUrl(opts);
return { opts, url };
};
const request: Client['request'] = async (options) => {
// @ts-expect-error
const { opts, url } = await beforeRequest(options);
const requestInit: ReqInit = {
redirect: 'follow',
...opts,
body: getValidRequestBody(opts),
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch!;
let response: Response;
try {
response = await _fetch(request);
} catch (error) {
// Handle fetch exceptions (AbortError, network errors, etc.)
let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(
error,
undefined as any,
request,
opts,
)) as unknown;
}
}
finalError = finalError || ({} as unknown);
if (opts.throwOnError) {
throw finalError;
}
// Return error response
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
request,
response: undefined as any,
};
}
for (const fn of interceptors.response.fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
const parseAs =
(opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';
if (
response.status === 204 ||
response.headers.get('Content-Length') === '0'
) {
let emptyData: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'text':
emptyData = await response[parseAs]();
break;
case 'formData':
emptyData = new FormData();
break;
case 'stream':
emptyData = response.body;
break;
case 'json':
default:
emptyData = {};
break;
}
return opts.responseStyle === 'data'
? emptyData
: {
data: emptyData,
...result,
};
}
let data: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'text':
data = await response[parseAs]();
break;
case 'json': {
// Some servers return 200 with no Content-Length and empty body.
// response.json() would throw; read as text and parse if non-empty.
const text = await response.text();
data = text ? JSON.parse(text) : {};
break;
}
case 'stream':
return opts.responseStyle === 'data'
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === 'json') {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === 'data'
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError: unknown;
try {
jsonError = JSON.parse(textError);
} catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, response, request, opts)) as string;
}
}
finalError = finalError || ({} as string);
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
...result,
};
};
const makeMethodFn =
(method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
request({ ...options, method });
const makeSseFn =
(method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
return request;
},
serializedBody: getValidRequestBody(opts) as
| BodyInit
| null
| undefined,
url,
});
};
return {
buildUrl,
connect: makeMethodFn('CONNECT'),
delete: makeMethodFn('DELETE'),
get: makeMethodFn('GET'),
getConfig,
head: makeMethodFn('HEAD'),
interceptors,
options: makeMethodFn('OPTIONS'),
patch: makeMethodFn('PATCH'),
post: makeMethodFn('POST'),
put: makeMethodFn('PUT'),
request,
setConfig,
sse: {
connect: makeSseFn('CONNECT'),
delete: makeSseFn('DELETE'),
get: makeSseFn('GET'),
head: makeSseFn('HEAD'),
options: makeSseFn('OPTIONS'),
patch: makeSseFn('PATCH'),
post: makeSseFn('POST'),
put: makeSseFn('PUT'),
trace: makeSseFn('TRACE'),
},
trace: makeMethodFn('TRACE'),
} as Client;
};

View file

@ -0,0 +1,25 @@
// This file is auto-generated by @hey-api/openapi-ts
export type { Auth } from '../core/auth.gen';
export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
export {
formDataBodySerializer,
jsonBodySerializer,
urlSearchParamsBodySerializer,
} from '../core/bodySerializer.gen';
export { buildClientParams } from '../core/params.gen';
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
export { createClient } from './client.gen';
export type {
Client,
ClientOptions,
Config,
CreateClientConfig,
Options,
RequestOptions,
RequestResult,
ResolvedRequestOptions,
ResponseStyle,
TDataShape,
} from './types.gen';
export { createConfig, mergeHeaders } from './utils.gen';

View file

@ -0,0 +1,241 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Auth } from '../core/auth.gen';
import type {
ServerSentEventsOptions,
ServerSentEventsResult,
} from '../core/serverSentEvents.gen';
import type {
Client as CoreClient,
Config as CoreConfig,
} from '../core/types.gen';
import type { Middleware } from './utils.gen';
export type ResponseStyle = 'data' | 'fields';
export interface Config<T extends ClientOptions = ClientOptions>
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T['baseUrl'];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?:
| 'arrayBuffer'
| 'auto'
| 'blob'
| 'formData'
| 'json'
| 'stream'
| 'text';
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T['throwOnError'];
}
export interface RequestOptions<
TData = unknown,
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}>,
Pick<
ServerSentEventsOptions<TData>,
| 'onSseError'
| 'onSseEvent'
| 'sseDefaultRetryDelay'
| 'sseMaxRetryAttempts'
| 'sseMaxRetryDelay'
> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export interface ResolvedRequestOptions<
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
serializedBody?: string;
}
export type RequestResult<
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = 'fields',
> = ThrowOnError extends true
? Promise<
TResponseStyle extends 'data'
? TData extends Record<string, unknown>
? TData[keyof TData]
: TData
: {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
request: Request;
response: Response;
}
>
: Promise<
TResponseStyle extends 'data'
?
| (TData extends Record<string, unknown>
? TData[keyof TData]
: TData)
| undefined
: (
| {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
error: undefined;
}
| {
data: undefined;
error: TError extends Record<string, unknown>
? TError[keyof TError]
: TError;
}
) & {
request: Request;
response: Response;
}
>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type SseFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
) => Promise<ServerSentEventsResult<TData, TError>>;
type RequestFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
Pick<
Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>,
'method'
>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <
TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
},
>(
options: TData & Options<TData>,
) => string;
export type Client = CoreClient<
RequestFn,
Config,
MethodFn,
BuildUrlFn,
SseFn
> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
TResponse = unknown,
TResponseStyle extends ResponseStyle = 'fields',
> = OmitKeys<
RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
'body' | 'path' | 'query' | 'url'
> &
([TData] extends [never] ? unknown : Omit<TData, 'url'>);

View file

@ -0,0 +1,332 @@
// This file is auto-generated by @hey-api/openapi-ts
import { getAuthToken } from '../core/auth.gen';
import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
import { jsonBodySerializer } from '../core/bodySerializer.gen';
import {
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from '../core/pathSerializer.gen';
import { getUrl } from '../core/utils.gen';
import type { Client, ClientOptions, Config, RequestOptions } from './types.gen';
export const createQuerySerializer = <T = unknown>({
parameters = {},
...args
}: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
const search: string[] = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
const options = parameters[name] || args;
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: 'form',
value,
...options.array,
});
if (serializedArray) search.push(serializedArray);
} else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: 'deepObject',
value: value as Record<string, unknown>,
...options.object,
});
if (serializedObject) search.push(serializedObject);
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved: options.allowReserved,
name,
value: value as string,
});
if (serializedPrimitive) search.push(serializedPrimitive);
}
}
}
return search.join('&');
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (
contentType: string | null,
): Exclude<Config['parseAs'], 'auto'> => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return 'stream';
}
const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
return;
}
if (
cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')
) {
return 'json';
}
if (cleanContent === 'multipart/form-data') {
return 'formData';
}
if (
['application/', 'audio/', 'image/', 'video/'].some((type) =>
cleanContent.startsWith(type),
)
) {
return 'blob';
}
if (cleanContent.startsWith('text/')) {
return 'text';
}
return;
};
const checkForExistence = (
options: Pick<RequestOptions, 'auth' | 'query'> & {
headers: Headers;
},
name?: string,
): boolean => {
if (!name) {
return false;
}
if (
options.headers.has(name) ||
options.query?.[name] ||
options.headers.get('Cookie')?.includes(`${name}=`)
) {
return true;
}
return false;
};
export const setAuthParams = async ({
security,
...options
}: Pick<Required<RequestOptions>, 'security'> &
Pick<RequestOptions, 'auth' | 'query'> & {
headers: Headers;
}) => {
for (const auth of security) {
if (checkForExistence(options, auth.name)) {
continue;
}
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case 'cookie':
options.headers.append('Cookie', `${name}=${token}`);
break;
case 'header':
default:
options.headers.set(name, token);
break;
}
}
};
export const buildUrl: Client['buildUrl'] = (options) =>
getUrl({
baseUrl: options.baseUrl as string,
path: options.path,
query: options.query,
querySerializer:
typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
export const mergeConfigs = (a: Config, b: Config): Config => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
const headersEntries = (headers: Headers): Array<[string, string]> => {
const entries: Array<[string, string]> = [];
headers.forEach((value, key) => {
entries.push([key, value]);
});
return entries;
};
export const mergeHeaders = (
...headers: Array<Required<Config>['headers'] | undefined>
): Headers => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header) {
continue;
}
const iterator =
header instanceof Headers
? headersEntries(header)
: Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
} else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v as string);
}
} else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(
key,
typeof value === 'object' ? JSON.stringify(value) : (value as string),
);
}
}
}
return mergedHeaders;
};
type ErrInterceptor<Err, Res, Req, Options> = (
error: Err,
response: Res,
request: Req,
options: Options,
) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (
request: Req,
options: Options,
) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (
response: Res,
request: Req,
options: Options,
) => Res | Promise<Res>;
class Interceptors<Interceptor> {
fns: Array<Interceptor | null> = [];
clear(): void {
this.fns = [];
}
eject(id: number | Interceptor): void {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = null;
}
}
exists(id: number | Interceptor): boolean {
const index = this.getInterceptorIndex(id);
return Boolean(this.fns[index]);
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === 'number') {
return this.fns[id] ? id : -1;
}
return this.fns.indexOf(id);
}
update(
id: number | Interceptor,
fn: Interceptor,
): number | Interceptor | false {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = fn;
return id;
}
return false;
}
use(fn: Interceptor): number {
this.fns.push(fn);
return this.fns.length - 1;
}
}
export interface Middleware<Req, Res, Err, Options> {
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
request: Interceptors<ReqInterceptor<Req, Options>>;
response: Interceptors<ResInterceptor<Res, Req, Options>>;
}
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
Req,
Res,
Err,
Options
> => ({
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
request: new Interceptors<ReqInterceptor<Req, Options>>(),
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: 'form',
},
object: {
explode: true,
style: 'deepObject',
},
});
const defaultHeaders = {
'Content-Type': 'application/json',
};
export const createConfig = <T extends ClientOptions = ClientOptions>(
override: Config<Omit<ClientOptions, keyof T> & T> = {},
): Config<Omit<ClientOptions, keyof T> & T> => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
...override,
});

View file

@ -0,0 +1,42 @@
// This file is auto-generated by @hey-api/openapi-ts
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: 'header' | 'query' | 'cookie';
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: 'basic' | 'bearer';
type: 'apiKey' | 'http';
}
export const getAuthToken = async (
auth: Auth,
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
): Promise<string | undefined> => {
const token =
typeof callback === 'function' ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === 'bearer') {
return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
return `Basic ${btoa(token)}`;
}
return token;
};

View file

@ -0,0 +1,100 @@
// This file is auto-generated by @hey-api/openapi-ts
import type {
ArrayStyle,
ObjectStyle,
SerializerOptions,
} from './pathSerializer.gen';
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
type QuerySerializerOptionsObject = {
allowReserved?: boolean;
array?: Partial<SerializerOptions<ArrayStyle>>;
object?: Partial<SerializerOptions<ObjectStyle>>;
};
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
/**
* Per-parameter serialization overrides. When provided, these settings
* override the global array/object settings for specific parameter names.
*/
parameters?: Record<string, QuerySerializerOptionsObject>;
};
const serializeFormDataPair = (
data: FormData,
key: string,
value: unknown,
): void => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
} else if (value instanceof Date) {
data.append(key, value.toISOString());
} else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
value: unknown,
): void => {
if (typeof value === 'string') {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): FormData => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: <T>(body: T): string =>
JSON.stringify(body, (_key, value) =>
typeof value === 'bigint' ? value.toString() : value,
),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): string => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
} else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};

View file

@ -0,0 +1,176 @@
// This file is auto-generated by @hey-api/openapi-ts
type Slot = 'body' | 'headers' | 'path' | 'query';
export type Field =
| {
in: Exclude<Slot, 'body'>;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
}
| {
in: Extract<Slot, 'body'>;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
}
| {
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If `in` is omitted, `map` aliases `key` to the transport layer.
*/
map: Slot;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
const extraPrefixesMap: Record<string, Slot> = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
$query_: 'query',
};
const extraPrefixes = Object.entries(extraPrefixesMap);
type KeyMap = Map<
string,
| {
in: Slot;
map?: string;
}
| {
in?: never;
map: Slot;
}
>;
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ('in' in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
} else if ('key' in config) {
map.set(config.key, {
map: config.map,
});
} else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
const stripEmptySlots = (params: Params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
delete params[slot as Slot];
}
}
};
export const buildClientParams = (
args: ReadonlyArray<unknown>,
fields: FieldsConfig,
) => {
const params: Params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config: FieldsConfig[number] | undefined;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ('in' in config) {
if (config.key) {
const field = map.get(config.key)!;
const name = field.map || config.key;
if (field.in) {
(params[field.in] as Record<string, unknown>)[name] = arg;
}
} else {
params.body = arg;
}
} else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
if (field.in) {
const name = field.map || key;
(params[field.in] as Record<string, unknown>)[name] = value;
} else {
params[field.map] = value;
}
} else {
const extra = extraPrefixes.find(([prefix]) =>
key.startsWith(prefix),
);
if (extra) {
const [prefix, slot] = extra;
(params[slot] as Record<string, unknown>)[
key.slice(prefix.length)
] = value;
} else if ('allowExtra' in config && config.allowExtra) {
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
if (allowed) {
(params[slot as Slot] as Record<string, unknown>)[key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};

View file

@ -0,0 +1,181 @@
// This file is auto-generated by @hey-api/openapi-ts
interface SerializeOptions<T>
extends SerializePrimitiveOptions,
SerializerOptions<T> {}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = 'label' | 'matrix' | 'simple';
export type ObjectStyle = 'form' | 'deepObject';
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'form':
return ',';
case 'pipeDelimited':
return '|';
case 'spaceDelimited':
return '%20';
default:
return ',';
}
};
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const serializeArrayParam = ({
allowReserved,
explode,
name,
style,
value,
}: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => {
if (!explode) {
const joinedValues = (
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
case 'simple':
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
return allowReserved ? v : encodeURIComponent(v as string);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v as string,
});
})
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({
allowReserved,
name,
value,
}: SerializePrimitiveParam) => {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
throw new Error(
'Deeply-nested arrays/objects arent supported. Provide your own `querySerializer()` to handle these.',
);
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({
allowReserved,
explode,
name,
style,
value,
valueOnly,
}: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
let values: string[] = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? (v as string) : encodeURIComponent(v as string),
];
});
const joinedValues = values.join(',');
switch (style) {
case 'form':
return `${name}=${joinedValues}`;
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) =>
serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
value: v as string,
}),
)
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};

View file

@ -0,0 +1,136 @@
// This file is auto-generated by @hey-api/openapi-ts
/**
* JSON-friendly union that mirrors what Pinia Colada can hash.
*/
export type JsonValue =
| null
| string
| number
| boolean
| JsonValue[]
| { [key: string]: JsonValue };
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
if (
value === undefined ||
typeof value === 'function' ||
typeof value === 'symbol'
) {
return undefined;
}
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
return value;
};
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
try {
const json = JSON.stringify(input, queryKeyJsonReplacer);
if (json === undefined) {
return undefined;
}
return JSON.parse(json) as JsonValue;
} catch {
return undefined;
}
};
/**
* Detects plain objects (including objects with a null prototype).
*/
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
if (value === null || typeof value !== 'object') {
return false;
}
const prototype = Object.getPrototypeOf(value as object);
return prototype === Object.prototype || prototype === null;
};
/**
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
*/
const serializeSearchParams = (params: URLSearchParams): JsonValue => {
const entries = Array.from(params.entries()).sort(([a], [b]) =>
a.localeCompare(b),
);
const result: Record<string, JsonValue> = {};
for (const [key, value] of entries) {
const existing = result[key];
if (existing === undefined) {
result[key] = value;
continue;
}
if (Array.isArray(existing)) {
(existing as string[]).push(value);
} else {
result[key] = [existing, value];
}
}
return result;
};
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export const serializeQueryKeyValue = (
value: unknown,
): JsonValue | undefined => {
if (value === null) {
return null;
}
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return value;
}
if (
value === undefined ||
typeof value === 'function' ||
typeof value === 'symbol'
) {
return undefined;
}
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return stringifyToJsonValue(value);
}
if (
typeof URLSearchParams !== 'undefined' &&
value instanceof URLSearchParams
) {
return serializeSearchParams(value);
}
if (isPlainObject(value)) {
return stringifyToJsonValue(value);
}
return undefined;
};

View file

@ -0,0 +1,266 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Config } from './types.gen';
export type ServerSentEventsOptions<TData = unknown> = Omit<
RequestInit,
'method'
> &
Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Implementing clients can call request interceptors inside this hook.
*/
onRequest?: (url: string, init: RequestInit) => Promise<Request>;
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param error The error that occurred.
*/
onSseError?: (error: unknown) => void;
/**
* Callback invoked when an event is streamed from the server.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param event Event streamed from the server.
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void;
serializedBody?: RequestInit['body'];
/**
* Default retry delay in milliseconds.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 3000
*/
sseDefaultRetryDelay?: number;
/**
* Maximum number of retry attempts before giving up.
*/
sseMaxRetryAttempts?: number;
/**
* Maximum retry delay in milliseconds.
*
* Applies only when exponential backoff is used.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 30000
*/
sseMaxRetryDelay?: number;
/**
* Optional sleep function for retry backoff.
*
* Defaults to using `setTimeout`.
*/
sseSleepFn?: (ms: number) => Promise<void>;
url: string;
};
export interface StreamEvent<TData = unknown> {
data: TData;
event?: string;
id?: string;
retry?: number;
}
export type ServerSentEventsResult<
TData = unknown,
TReturn = void,
TNext = unknown,
> = {
stream: AsyncGenerator<
TData extends Record<string, unknown> ? TData[keyof TData] : TData,
TReturn,
TNext
>;
};
export const createSseClient = <TData = unknown>({
onRequest,
onSseError,
onSseEvent,
responseTransformer,
responseValidator,
sseDefaultRetryDelay,
sseMaxRetryAttempts,
sseMaxRetryDelay,
sseSleepFn,
url,
...options
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
let lastEventId: string | undefined;
const sleep =
sseSleepFn ??
((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
const createStream = async function* () {
let retryDelay: number = sseDefaultRetryDelay ?? 3000;
let attempt = 0;
const signal = options.signal ?? new AbortController().signal;
while (true) {
if (signal.aborted) break;
attempt++;
const headers =
options.headers instanceof Headers
? options.headers
: new Headers(options.headers as Record<string, string> | undefined);
if (lastEventId !== undefined) {
headers.set('Last-Event-ID', lastEventId);
}
try {
const requestInit: RequestInit = {
redirect: 'follow',
...options,
body: options.serializedBody,
headers,
signal,
};
let request = new Request(url, requestInit);
if (onRequest) {
request = await onRequest(url, requestInit);
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = options.fetch ?? globalThis.fetch;
const response = await _fetch(request);
if (!response.ok)
throw new Error(
`SSE failed: ${response.status} ${response.statusText}`,
);
if (!response.body) throw new Error('No body in SSE response');
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
let buffer = '';
const abortHandler = () => {
try {
reader.cancel();
} catch {
// noop
}
};
signal.addEventListener('abort', abortHandler);
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
// Normalize line endings: CRLF -> LF, then CR -> LF
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const chunks = buffer.split('\n\n');
buffer = chunks.pop() ?? '';
for (const chunk of chunks) {
const lines = chunk.split('\n');
const dataLines: Array<string> = [];
let eventName: string | undefined;
for (const line of lines) {
if (line.startsWith('data:')) {
dataLines.push(line.replace(/^data:\s*/, ''));
} else if (line.startsWith('event:')) {
eventName = line.replace(/^event:\s*/, '');
} else if (line.startsWith('id:')) {
lastEventId = line.replace(/^id:\s*/, '');
} else if (line.startsWith('retry:')) {
const parsed = Number.parseInt(
line.replace(/^retry:\s*/, ''),
10,
);
if (!Number.isNaN(parsed)) {
retryDelay = parsed;
}
}
}
let data: unknown;
let parsedJson = false;
if (dataLines.length) {
const rawData = dataLines.join('\n');
try {
data = JSON.parse(rawData);
parsedJson = true;
} catch {
data = rawData;
}
}
if (parsedJson) {
if (responseValidator) {
await responseValidator(data);
}
if (responseTransformer) {
data = await responseTransformer(data);
}
}
onSseEvent?.({
data,
event: eventName,
id: lastEventId,
retry: retryDelay,
});
if (dataLines.length) {
yield data as any;
}
}
}
} finally {
signal.removeEventListener('abort', abortHandler);
reader.releaseLock();
}
break; // exit loop on normal completion
} catch (error) {
// connection failed or aborted; retry after delay
onSseError?.(error);
if (
sseMaxRetryAttempts !== undefined &&
attempt >= sseMaxRetryAttempts
) {
break; // stop after firing error
}
// exponential backoff: double retry each attempt, cap at 30s
const backoff = Math.min(
retryDelay * 2 ** (attempt - 1),
sseMaxRetryDelay ?? 30000,
);
await sleep(backoff);
}
}
};
const stream = createStream();
return { stream };
};

View file

@ -0,0 +1,118 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Auth, AuthToken } from './auth.gen';
import type {
BodySerializer,
QuerySerializer,
QuerySerializerOptions,
} from './bodySerializer.gen';
export type HttpMethod =
| 'connect'
| 'delete'
| 'get'
| 'head'
| 'options'
| 'patch'
| 'post'
| 'put'
| 'trace';
export type Client<
RequestFn = never,
Config = unknown,
MethodFn = never,
BuildUrlFn = never,
SseFn = never,
> = {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
getConfig: () => Config;
request: RequestFn;
setConfig: (config: Config) => Config;
} & {
[K in HttpMethod]: MethodFn;
} & ([SseFn] extends [never]
? { sse?: never }
: { sse: { [K in HttpMethod]: SseFn } });
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?:
| RequestInit['headers']
| Record<
string,
| string
| number
| boolean
| (string | number | boolean)[]
| null
| undefined
| unknown
>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: Uppercase<HttpMethod>;
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
? true
: [T] extends [never | undefined]
? [undefined] extends [T]
? false
: true
: false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
? never
: K]: T[K];
};

View file

@ -0,0 +1,143 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { BodySerializer, QuerySerializer } from './bodySerializer.gen';
import {
type ArraySeparatorStyle,
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from './pathSerializer.gen';
export interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
export const PATH_PARAM_RE = /\{[^{}]+\}/g;
export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style: ArraySeparatorStyle = 'simple';
if (name.endsWith('*')) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith('.')) {
name = name.substring(1);
style = 'label';
} else if (name.startsWith(';')) {
name = name.substring(1);
style = 'matrix';
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(
match,
serializeArrayParam({ explode, name, style, value }),
);
continue;
}
if (typeof value === 'object') {
url = url.replace(
match,
serializeObjectParam({
explode,
name,
style,
value: value as Record<string, unknown>,
valueOnly: true,
}),
);
continue;
}
if (style === 'matrix') {
url = url.replace(
match,
`;${serializePrimitiveParam({
name,
value: value as string,
})}`,
);
continue;
}
const replaceValue = encodeURIComponent(
style === 'label' ? `.${value as string}` : (value as string),
);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const getUrl = ({
baseUrl,
path,
query,
querySerializer,
url: _url,
}: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => {
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
let url = (baseUrl ?? '') + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : '';
if (search.startsWith('?')) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export function getValidRequestBody(options: {
body?: unknown;
bodySerializer?: BodySerializer | null;
serializedBody?: unknown;
}) {
const hasBody = options.body !== undefined;
const isSerializedBody = hasBody && options.bodySerializer;
if (isSerializedBody) {
if ('serializedBody' in options) {
const hasSerializedBody =
options.serializedBody !== undefined && options.serializedBody !== '';
return hasSerializedBody ? options.serializedBody : null;
}
// not all clients implement a serializedBody property (i.e. client-axios)
return options.body !== '' ? options.body : null;
}
// plain/text body
if (hasBody) {
return options.body;
}
// no body was provided
return undefined;
}

File diff suppressed because one or more lines are too long

1519
src/clients/romm/sdk.gen.ts Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

BIN
src/mainview/assets/favicon.ico (Stored with Git LFS) Normal file

Binary file not shown.

View file

@ -0,0 +1,28 @@
Input Prompts (1.4.1)
Created/distributed by Kenney (www.kenney.nl)
Creation date: 22-11-2025
------------------------------
License: (Creative Commons Zero, CC0)
http://creativecommons.org/publicdomain/zero/1.0/
You can use this content for personal, educational, and commercial purposes.
Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement)
------------------------------
• Website : www.kenney.nl
• Donate : www.kenney.nl/donate
• Patreon : patreon.com/kenney
Follow on social media for updates:
• Twitter: twitter.com/KenneyNL
• Instagram: instagram.com/kenney_nl
• Mastodon: mastodon.gamedev.place/@kenney

BIN
src/mainview/assets/icons/controller_steamdeck.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/controller_xbox360.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/controller_xbox_adaptive.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/controller_xboxone.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/controller_xboxseries.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_a.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_a_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_b.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_b_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_guide.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_guide_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l1.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l1_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l2.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l2_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l4.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l4_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l5.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_l5_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_options.svg (Stored with Git LFS) Normal file

Binary file not shown.

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_quickaccess.svg (Stored with Git LFS) Normal file

Binary file not shown.

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r1.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r1_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r2.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r2_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r4.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r4_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r5.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_r5_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_view.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_view_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_x.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_x_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_y.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_button_y_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_all.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_down.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_down_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_horizontal.svg (Stored with Git LFS) Normal file

Binary file not shown.

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_left.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_left_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_none.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_right.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_right_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_up.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_up_outline.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_dpad_vertical.svg (Stored with Git LFS) Normal file

Binary file not shown.

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_down.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_horizontal.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_left.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_press.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_right.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_up.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_l_vertical.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_down.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_horizontal.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_left.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_press.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_right.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_up.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_r_vertical.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_side_l.svg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
src/mainview/assets/icons/steamdeck_stick_side_r.svg (Stored with Git LFS) Normal file

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more