import type { ConfigKeys, IConfig } from '@electron/types/runtime'; import configManager from '@electron/service/config-service'; import type { HostApiResult } from '@src/types/runtime'; import type { HostApiContext } from '../context'; import type { NormalizedHostApiRequest } from '../route-utils'; import { fail, ok, parseJsonBody } from '../route-utils'; function extractSettingKey(pathname: string): string | null { if (!pathname.startsWith('/api/settings/')) { return null; } const rawKey = pathname.slice('/api/settings/'.length).trim(); if (!rawKey) { return null; } return decodeURIComponent(rawKey); } function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function unwrapSettingValue(body: unknown): unknown { if (isPlainObject(body) && Object.prototype.hasOwnProperty.call(body, 'value')) { return body.value; } return body; } export async function handleSettingsRoutes( request: NormalizedHostApiRequest, _ctx: HostApiContext, ): Promise | null> { const { pathname, method } = request; if (pathname === '/api/settings' && method === 'GET') { try { return ok(configManager.getConfig()); } catch (error) { return fail(500, error instanceof Error ? error.message : String(error)); } } if (pathname === '/api/settings' && method === 'PUT') { try { const body = parseJsonBody(request.body); if (!isPlainObject(body)) { return fail(400, 'settings payload must be an object'); } configManager.update(body as Partial); return ok({ success: true, settings: configManager.getConfig(), }); } catch (error) { return fail(500, error instanceof Error ? error.message : String(error)); } } const key = extractSettingKey(pathname); if (pathname.startsWith('/api/settings/') && !key) { return fail(400, 'setting key is required'); } if (!key) { return null; } if (method === 'GET') { try { return ok({ value: configManager.get(key as ConfigKeys), }); } catch (error) { return fail(500, error instanceof Error ? error.message : String(error)); } } if (method === 'PUT') { try { const value = unwrapSettingValue(parseJsonBody(request.body)); configManager.set(key as ConfigKeys, value); return ok({ success: true, key, value, }); } catch (error) { return fail(500, error instanceof Error ? error.message : String(error)); } } return null; }