Files
planet/client/src/main/config.ts
T

262 lines
8.1 KiB
TypeScript

import fs from 'node:fs'
import path from 'node:path'
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
export interface ServerEndpoints {
backendUrl: string
adminUrl: string
motionWsUrl: string
}
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
splashTheme?: SplashTheme
}
export interface DesktopLaunchFlags {
fullscreen: boolean
kiosk: boolean
forceShowFps: boolean
devtools: boolean
headlessSmoke: boolean
smokeOutputPath: string | null
deepLinkUrl: string | null
splashThemeOverride?: SplashTheme
}
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
wsUrl: string
splashTheme: SplashTheme
}
const VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([
'singularity',
'constellation',
'horizon',
'off',
])
export function normalizeSplashTheme(
raw: unknown,
fallback: SplashTheme = 'singularity',
): SplashTheme {
if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase() as SplashTheme
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
}
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
backendUrl: 'https://rclaw.top',
adminUrl: 'https://admin.rclaw.top',
motionWsUrl: 'ws://127.0.0.1:8765/ws/gestures',
}
export function normalizeHttpUrl(raw: string | undefined | null, fallback: string): string {
if (!raw || typeof raw !== 'string') return fallback
const trimmed = raw.trim().replace(/\/+$/, '')
if (!trimmed) return fallback
try {
const parsed = new URL(trimmed)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return fallback
}
return parsed.origin + parsed.pathname.replace(/\/+$/, '')
} catch {
return fallback
}
}
export function normalizeWsUrl(raw: string | undefined | null, fallback: string): string {
if (!raw || typeof raw !== 'string') return fallback
const trimmed = raw.trim()
if (!trimmed) return fallback
try {
const parsed = new URL(trimmed)
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
return fallback
}
return parsed.toString()
} catch {
return fallback
}
}
export function deriveBackendWsUrl(backendUrl: string): string {
const parsed = new URL(backendUrl)
const wsProtocol = parsed.protocol === 'https:' ? 'wss:' : 'ws:'
const basePath = parsed.pathname.replace(/\/+$/, '')
return `${wsProtocol}//${parsed.host}${basePath}/ws`
}
function readJsonFileSafe(filePath: string): PersistedUserConfig {
try {
if (!fs.existsSync(filePath)) return {}
const raw = fs.readFileSync(filePath, 'utf8')
const parsed = JSON.parse(raw)
if (!parsed || typeof parsed !== 'object') return {}
return parsed as PersistedUserConfig
} catch {
return {}
}
}
export function parseLaunchArgs(argv: string[]): {
endpoints: Partial<ServerEndpoints>
flags: DesktopLaunchFlags
} {
const endpoints: Partial<ServerEndpoints> = {}
const flags: DesktopLaunchFlags = {
fullscreen: false,
kiosk: false,
forceShowFps: false,
devtools: false,
headlessSmoke: false,
smokeOutputPath: null,
deepLinkUrl: null,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (!arg) continue
if (arg.startsWith('--backend-url=')) {
endpoints.backendUrl = arg.slice('--backend-url='.length)
} else if (arg === '--backend-url' && argv[i + 1]) {
endpoints.backendUrl = argv[++i]
} else if (arg.startsWith('--admin-url=')) {
endpoints.adminUrl = arg.slice('--admin-url='.length)
} else if (arg === '--admin-url' && argv[i + 1]) {
endpoints.adminUrl = argv[++i]
} else if (arg.startsWith('--motion-ws-url=')) {
endpoints.motionWsUrl = arg.slice('--motion-ws-url='.length)
} else if (arg === '--motion-ws-url' && argv[i + 1]) {
endpoints.motionWsUrl = argv[++i]
} else if (arg.startsWith('--splash-theme=')) {
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
} else if (arg === '--splash-theme' && argv[i + 1]) {
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
} else if (arg === '--fullscreen') {
flags.fullscreen = true
} else if (arg === '--kiosk') {
flags.kiosk = true
flags.fullscreen = true
} else if (arg === '--fps') {
flags.forceShowFps = true
} else if (arg === '--devtools') {
flags.devtools = true
} else if (arg === '--headless-smoke') {
flags.headlessSmoke = true
} else if (arg.startsWith('--smoke-output=')) {
flags.smokeOutputPath = arg.slice('--smoke-output='.length)
} else if (arg.startsWith('planet-earth://')) {
flags.deepLinkUrl = arg
}
}
return { endpoints, flags }
}
export class DesktopConfigStore {
private readonly userConfigPath: string
private readonly portableConfigPaths: string[]
private readonly cliEndpoints: Partial<ServerEndpoints>
private readonly launchFlags: DesktopLaunchFlags
private current: DesktopRuntimeConfig
constructor(options: {
userDataDir: string
exeDir: string
resourcesDir?: string
argv: string[]
env?: NodeJS.ProcessEnv
}) {
this.userConfigPath = path.join(options.userDataDir, 'config.json')
this.portableConfigPaths = [
path.join(options.exeDir, 'planet-earth.json'),
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
]
const parsed = parseLaunchArgs(options.argv)
this.cliEndpoints = parsed.endpoints
this.launchFlags = parsed.flags
this.current = this.resolve(options.env ?? process.env)
}
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
const userSaved = readJsonFileSafe(this.userConfigPath)
let portable: PersistedUserConfig = {}
for (const candidate of this.portableConfigPaths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
portable = data
break
}
}
const backendUrl = normalizeHttpUrl(
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
DEFAULT_ENDPOINTS.backendUrl,
)
const adminUrl = normalizeHttpUrl(
this.cliEndpoints.adminUrl ?? env.PLANET_ADMIN_URL ?? portable.adminUrl ?? userSaved.adminUrl,
DEFAULT_ENDPOINTS.adminUrl,
)
const motionWsUrl = normalizeWsUrl(
this.cliEndpoints.motionWsUrl ?? env.PLANET_MOTION_WS_URL ?? portable.motionWsUrl ?? userSaved.motionWsUrl,
DEFAULT_ENDPOINTS.motionWsUrl,
)
const splashTheme = normalizeSplashTheme(
this.launchFlags.splashThemeOverride ??
env.PLANET_SPLASH_THEME ??
portable.splashTheme ??
userSaved.splashTheme,
'singularity',
)
return {
backendUrl,
adminUrl,
motionWsUrl,
wsUrl: deriveBackendWsUrl(backendUrl),
splashTheme,
...this.launchFlags,
}
}
private writeUserConfig(patch: PersistedUserConfig): void {
const existing = readJsonFileSafe(this.userConfigPath)
const next: PersistedUserConfig = { ...existing, ...patch }
fs.mkdirSync(path.dirname(this.userConfigPath), { recursive: true })
fs.writeFileSync(this.userConfigPath, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
}
get(): DesktopRuntimeConfig {
return { ...this.current }
}
updateEndpoints(partial: Partial<ServerEndpoints>): DesktopRuntimeConfig {
const nextEndpoints: ServerEndpoints = {
backendUrl: normalizeHttpUrl(partial.backendUrl, this.current.backendUrl),
adminUrl: normalizeHttpUrl(partial.adminUrl, this.current.adminUrl),
motionWsUrl: normalizeWsUrl(partial.motionWsUrl, this.current.motionWsUrl),
}
this.writeUserConfig(nextEndpoints)
this.current = {
...this.current,
...nextEndpoints,
wsUrl: deriveBackendWsUrl(nextEndpoints.backendUrl),
}
return this.get()
}
updateSplashTheme(rawTheme: unknown): DesktopRuntimeConfig {
const nextTheme = normalizeSplashTheme(rawTheme, this.current.splashTheme)
this.writeUserConfig({ splashTheme: nextTheme })
this.current = {
...this.current,
splashTheme: nextTheme,
}
return this.get()
}
}