- Restructured as bun monorepo with packages/cfg and packages/worker - CLI rewritten in TypeScript with modular architecture - Published as @shazhou/cfg@1.0.0 (replaces @shazhou/config) - Deprecated @shazhou/config on npm - Removed legacy Python scripts and old cli-npm package
71 lines
1.8 KiB
TypeScript
71 lines
1.8 KiB
TypeScript
import { getToken, getEndpoint, loadCache, saveCache } from "./config.js";
|
|
|
|
export async function api(
|
|
method: string,
|
|
path: string,
|
|
body?: unknown
|
|
): Promise<{ data: any; status: number }> {
|
|
const url = `${getEndpoint()}${path}`;
|
|
const headers: Record<string, string> = {
|
|
Authorization: `Bearer ${getToken()}`,
|
|
"Content-Type": "application/json",
|
|
};
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(url, {
|
|
method,
|
|
headers,
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
} catch (err: any) {
|
|
console.error(
|
|
`Error: ${err?.cause?.message || err?.message || "network error"}`
|
|
);
|
|
process.exit(1);
|
|
}
|
|
if (res.status === 204) return { data: null, status: 204 };
|
|
const text = await res.text();
|
|
let data: any;
|
|
try {
|
|
data = JSON.parse(text);
|
|
} catch {
|
|
data = text;
|
|
}
|
|
if (!res.ok) {
|
|
const msg = data?.error || text;
|
|
console.error(`Error: ${msg}`);
|
|
process.exit(1);
|
|
}
|
|
return { data, status: res.status };
|
|
}
|
|
|
|
export async function trySyncRemote(): Promise<boolean> {
|
|
const url = `${getEndpoint()}/config`;
|
|
const headers: Record<string, string> = {
|
|
Authorization: `Bearer ${getToken()}`,
|
|
"Content-Type": "application/json",
|
|
};
|
|
try {
|
|
const res = await fetch(url, { method: "GET", headers });
|
|
if (!res.ok) return false;
|
|
const data = await res.json() as any;
|
|
if (!data?.secrets) return false;
|
|
const now = new Date().toISOString();
|
|
const cache = {
|
|
agent_id: data.agent_id,
|
|
secrets: data.secrets,
|
|
synced_at: now,
|
|
attempted_at: now,
|
|
};
|
|
saveCache(cache);
|
|
return true;
|
|
} catch {
|
|
const cache = loadCache();
|
|
if (cache) {
|
|
cache.attempted_at = new Date().toISOString();
|
|
saveCache(cache);
|
|
}
|
|
return false;
|
|
}
|
|
}
|