


import { pathToFileURL } from "node:url";
export const ENDPOINT = "https://www.chngmkr.com/api/chngmkr-mcp";
export async function forward(message, { key, fetcher = fetch, protocolVersion } = {}) {
  const id = message?.id ?? null;
  if (
    !message ||
    Array.isArray(message) ||
    message.jsonrpc !== "2.0" ||
    typeof message.method !== "string"
  )
    return { jsonrpc: "2.0", id, error: { code: -32600, message: "Invalid Request" } };
  try {
    const r = await fetcher(ENDPOINT, {
      method: "POST",
      redirect: "error",
      headers: {
        Authorization: "Bearer " + key,
        "Content-Type": "application/json",
        Accept: "application/json, text/event-stream",
        ...(protocolVersion ? { "MCP-Protocol-Version": protocolVersion } : {}),
      },
      body: JSON.stringify(message),
      signal: AbortSignal.timeout(20000),
    });
    if (r.status === 202 || r.status === 204) return null;
    const body = await r.json();
    if (message.id === undefined) return null;
    if (body?.jsonrpc === "2.0" && body.id === id) return body;
    return {
      jsonrpc: "2.0",
      id,
      error: {
        code: -32001,
        message:
          r.status === 401
            ? "Clé absente, expirée ou révoquée."
            : r.status === 403
              ? "Abonnement actif requis."
              : r.status === 429
                ? "Quota atteint."
                : "CHNGMKR indisponible.",
      },
    };
  } catch {
    return message.id === undefined
      ? null
      : { jsonrpc: "2.0", id, error: { code: -32001, message: "Connexion CHNGMKR indisponible." } };
  }
}
export function start({
  input = process.stdin,
  output = process.stdout,
  key = process.env.CHNGMKR_MCP_KEY,
  fetcher = fetch,
} = {}) {
  if (!/^chngmkr_mcp_[a-f0-9]{64}$/.test(key || ""))
    throw Error("Configurez CHNGMKR_MCP_KEY avec votre clé personnelle.");
  let buffer = "",
    pending = 0,
    chain = Promise.resolve(),
    protocolVersion;
  input.setEncoding("utf8");
  const send = (message) => {
    if (message) output.write(JSON.stringify(message) + "\n");
  };
  input.on("data", (chunk) => {
    buffer += chunk;
    if (buffer.length > 65536) {
      input.destroy();
      send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Message too large" } });
      return;
    }
    let split;
    while ((split = buffer.indexOf("\n")) >= 0) {
      const line = buffer.slice(0, split);
      buffer = buffer.slice(split + 1);
      if (!line.trim()) continue;
      if (++pending > 32) {
        input.destroy();
        return;
      }
      chain = chain.then(async () => {
        try {
          let message;
          try {
            message = JSON.parse(line);
          } catch {
            send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
            return;
          }
          const result = await forward(message, { key, fetcher, protocolVersion });
          if (message.method === "initialize" && result?.result?.protocolVersion)
            protocolVersion = result.result.protocolVersion;
          send(result);
        } finally {
          pending--;
        }
      });
    }
  });
  return () => chain;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  try {
    start();
  } catch {
    process.stderr.write(
      "CHNGMKR : définissez CHNGMKR_MCP_KEY avec votre clé personnelle (Node.js 22+).\n",
    );
    process.exitCode = 1;
  }
}
