41 lines
1.7 KiB
JavaScript
41 lines
1.7 KiB
JavaScript
// Shared by quota.mjs and sync-models.mjs: locate the opencode config and the CommandCode
|
|
// API key the same way the provider does.
|
|
import { readFileSync } from "node:fs";
|
|
import { PROVIDER_ID } from "../dist/constants.js";
|
|
|
|
/** Parse an opencode.json; a missing file is `{ text: "", data: {}, exists: false }`. */
|
|
export function readConfig(path) {
|
|
try {
|
|
const text = readFileSync(path, "utf8");
|
|
return { text, data: JSON.parse(text), exists: true };
|
|
} catch (error) {
|
|
// A fresh install has no opencode.json yet; treat it as empty. Bad JSON or unreadable
|
|
// files still throw.
|
|
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** COMMANDCODE_API_KEY, then provider settings apiKey, then a configured Authorization header.
|
|
* Reads the opencode 2 shape (`providers.<id>.settings`) and the pre-2
|
|
* `provider.<id>.options` shape for older files. `{env:...}` templates resolve through the
|
|
* environment or count as absent. */
|
|
export function resolveKey(config, env) {
|
|
const fromEnv = env.COMMANDCODE_API_KEY;
|
|
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
|
|
const candidates = [
|
|
config?.providers?.[PROVIDER_ID]?.settings,
|
|
config?.provider?.[PROVIDER_ID]?.options,
|
|
];
|
|
for (const options of candidates) {
|
|
if (!options || typeof options !== "object") continue;
|
|
const apiKey = options.apiKey;
|
|
if (typeof apiKey === "string" && apiKey.trim() && !/^\{.*\}$/.test(apiKey.trim())) {
|
|
return apiKey.trim();
|
|
}
|
|
const auth = options.headers?.Authorization ?? options.headers?.authorization;
|
|
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
|
|
}
|
|
return undefined;
|
|
}
|