import { userInfo } from "node:os"; import { parse, parseBinary } from "plist"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { isEnoentError } from "./ClientConfigPath.js"; import { err, ok, type Result } from "../domain/result.js"; import { readRegularFile } from "../process/RegularFileRead.js"; import { parseClientConfiguration, type ClientConfigurationDocument, } from "./ClientConfigurationDocument.js"; import { openCodeManagedPreferencePaths } from "./SupportedClientLocations.js"; import type { ClientPathContext, ClientPathFailure, } from "./SupportedClients.js"; export const currentUser = (): string | undefined => { try { return userInfo().username; } catch { // An account without a password entry has no per-user profile to name. return undefined; } }; /** A preference domain holds OpenCode's configuration keys as property values. */ const decode = (bytes: Buffer): string => JSON.stringify( bytes.subarray(0, 6).toString("latin1") === "bplist" ? parseBinary(bytes) : parse(bytes.toString("utf8")), ); /** The managed preference file OpenCode applies, as a configuration document. */ export const readOpenCodeManagedPreferences = async ( context: ClientPathContext, ): Promise< Result< { path: string; document: ClientConfigurationDocument } | undefined, ClientPathFailure > > => { for (const path of openCodeManagedPreferencePaths(context, currentUser())) { let text: string; try { const { resources } = context; text = decode( await readRegularFile( path, resources === undefined ? {} : { resources }, ), ); } catch (cause: unknown) { if (isEnoentError(cause)) continue; // Without a scope to retain it, the failure must carry its owner out. if ( cause instanceof RegularFileCleanupFailure && context.resources === undefined ) throw cause; return err({ path, message: `Managed preferences ${path} could not be read: ${errorMessage(cause)}`, }); } const parsed = parseClientConfiguration(text, "opencode"); return parsed.ok ? ok({ path, document: parsed.value }) : err({ path, message: `Managed preferences ${path} are malformed: ${parsed.error.detail}`, }); } return ok(undefined); };