export type Config = { host: string; port: number; debug: boolean; timeoutMs?: number; tags: string[];};export type ConfigErrorKind = "missing" | "wrong_type" | "out_of_range";export class ConfigError extends Error { constructor( public readonly kind: ConfigErrorKind, public readonly field: string, ) { super(`${kind}: ${field}`); }}const present = (v: unknown): boolean => v !== null && v !== undefined;/** Throws ConfigError on invalid input. */export function parseConfig(raw: Record<string, unknown>): Config { const host = raw.host; if (!present(host)) throw new ConfigError("missing", "host"); if (typeof host !== "string") throw new ConfigError("wrong_type", "host"); if (host.trim() === "") throw new ConfigError("out_of_range", "host"); let port = 8080; if (present(raw.port)) { if (typeof raw.port !== "number") throw new ConfigError("wrong_type", "port"); if (!Number.isInteger(raw.port) || raw.port < 1 || raw.port > 65535) { throw new ConfigError("out_of_range", "port"); } port = raw.port; } let debug = false; if (present(raw.debug)) { if (typeof raw.debug !== "boolean") throw new ConfigError("wrong_type", "debug"); debug = raw.debug; } let timeoutMs: number | undefined; if (present(raw.timeoutMs)) { if (typeof raw.timeoutMs !== "number") throw new ConfigError("wrong_type", "timeoutMs"); if (!Number.isInteger(raw.timeoutMs) || raw.timeoutMs <= 0) { throw new ConfigError("out_of_range", "timeoutMs"); } timeoutMs = raw.timeoutMs; } let tags: string[] = []; if (present(raw.tags)) { if (!Array.isArray(raw.tags) || !raw.tags.every((t) => typeof t === "string")) { throw new ConfigError("wrong_type", "tags"); } tags = [...raw.tags]; } const config: Config = { host: host.trim(), port, debug, tags }; if (timeoutMs !== undefined) config.timeoutMs = timeoutMs; return config;}