UNPKG

@mesh-tech/mesh-cli

Version:

CLI for Mesh platform development utilities

74 lines (73 loc) 2.73 kB
import { execFile } from "node:child_process"; import { promisify } from "node:util"; export const execFileAsync = promisify(execFile); export function redactToken(err, token) { const base = err instanceof Error ? err.message : String(err); const stderr = typeof err?.stderr === "string" ? err.stderr.trim() : ""; const combined = stderr && !base.includes(stderr) ? `${base}\n${stderr}` : base; const message = token ? combined.split(token).join("<redacted-token>") : combined; const out = new Error(message); const code = err?.code; if (code !== undefined) out.code = code; return out; } export async function gitWithAuth(args, token, cwd) { try { return await execFileAsync("git", args, cwd ? { cwd } : {}); } catch (err) { throw redactToken(err, token); } } export function parseRemote(remoteUrl) { const m = remoteUrl.trim().match(/^(https?:\/\/[^/]+)\/git\/([^/]+?)(?:\.git)?$/); return m ? { baseUrl: m[1], repo: m[2] } : null; } export async function resolveTarget(opts) { const explicitBase = opts.url ?? process.env.VCS_URL; let originTarget = null; try { const { stdout } = await execFileAsync("git", ["remote", "get-url", "origin"], { cwd: opts.cwd ?? process.cwd(), }); originTarget = parseRemote(stdout); } catch { } const baseUrl = (explicitBase ?? originTarget?.baseUrl)?.replace(/\/$/, ""); if (!baseUrl) { throw new Error("vcs service URL not found: pass --url, set VCS_URL, or run inside a vcs clone"); } return { baseUrl, repo: opts.repo ?? originTarget?.repo }; } export async function resolveToken(opts) { if (opts.token) return opts.token; if (process.env.VCS_TOKEN) return process.env.VCS_TOKEN; if (opts.context) { const { getValidToken } = await import("../login.js"); const token = await getValidToken(opts.context); if (token) return token; } throw new Error("no token: pass --token, set VCS_TOKEN, or pass --context <platform-context> (after mesh login)"); } export async function vcsApi(baseUrl, token, path, method = "GET", body) { const res = await fetch(`${baseUrl}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}), }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }); const data = (await res.json().catch(() => ({}))); if (!res.ok) { throw new Error(`${method} ${path} failed (${res.status}): ${String(data.error ?? "unknown error")}`); } return data; }