import { CloudflareApiError } from "./api-error.js";
/**
 * Helper to extract and handle Cloudflare API errors
 *
 * @param response Fetch response object
 * @returns Formatted error message
 */
export async function extractCloudflareError(response) {
    try {
        const data = (await response.json());
        if (data.errors && data.errors.length > 0) {
            return data.errors.map((e) => `Error ${e.code}: ${e.message}`).join(", ");
        }
        return `HTTP ${response.status}: ${response.statusText}`;
    }
    catch {
        return `HTTP ${response.status}: ${response.statusText}`;
    }
}
export async function extractCloudflareResult(label, promise) {
    const response = await promise.catch((cause) => {
        throw new Error(`Failed to ${label}: Failed to fetch`, { cause });
    });
    const json = (await response.json().catch(() => {
        throw new Error(`Failed to ${label} (${response.status}): The API returned an invalid response`);
    }));
    if (json.success) {
        return json.result;
    }
    else {
        const error = new CloudflareApiError(`Failed to ${label} (${response.status} ${response.statusText}):\n${json.errors.map((e) => `- [${e.code}] ${e.message}${e.documentation_url ? ` (${e.documentation_url})` : ""}`).join("\n")}`, response, json.errors);
        Error.captureStackTrace(error, extractCloudflareResult);
        Object.assign(error, {
            status: response.status,
        });
        throw error;
    }
}
//# sourceMappingURL=api-response.js.map