dev-mcps/dev-server-mcp/src/worker-client.js

27 lines
1.2 KiB
JavaScript

export class WorkerClient {
constructor({ baseUrl, token, timeoutMs = 610000 }) {
this.baseUrl = new URL(baseUrl);
if (!["http:", "https:"].includes(this.baseUrl.protocol) || this.baseUrl.username || this.baseUrl.password) throw new Error("Invalid development-server worker URL");
if (typeof token !== "string" || token.length < 32) throw new Error("DEV_SERVER_WORKER_TOKEN must contain at least 32 characters");
this.token = token;
this.timeoutMs = timeoutMs;
}
async call(action, input = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const response = await fetch(new URL(`/v1/${action}`, this.baseUrl), {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${this.token}` },
body: JSON.stringify(input),
redirect: "error",
signal: controller.signal
});
const body = await response.json().catch(() => ({ error: "Invalid worker response" }));
if (!response.ok) throw new Error(body.error || `Development-server worker returned HTTP ${response.status}`);
return body;
} finally { clearTimeout(timer); }
}
}