import { HTTPError } from './common.js';
/**
 * Transform a response from the API
 * @param resp - The response to transform
 * @throws HTTPError if the response is an error
 * @returns The transformed response
 */
export function transformResponse(resp) {
    // Handle errors
    if (resp.error || resp.response.status >= 400) {
        throw HTTPError.fromResponse(resp);
    }
    // Decode dates
    resp.data = decodeDates(resp.data);
    return resp.data;
}
const ISODateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?(?:[-+]\d{2}:?\d{2}|Z)?$/;
export function isIsoDateString(value) {
    return typeof value === 'string' && ISODateFormat.test(value);
}
export function decodeDates(data) {
    // if it's a date string, return a date
    if (isIsoDateString(data)) {
        return new Date(data);
    }
    // if it's not an object or array, return it
    if (data === null || data === undefined || typeof data !== 'object') {
        return data;
    }
    // if it's an array, decode each element
    if (Array.isArray(data)) {
        return data.map((val) => decodeDates(val));
    }
    // if it's an object, decode each key
    for (const [key, val] of Object.entries(data)) {
        // @ts-expect-error we know this will give back the same type
        data[key] = decodeDates(val);
    }
    return data;
}
export function encodeDates(data) {
    // if it's a date, return a date string
    if (data instanceof Date) {
        return data.toISOString();
    }
    // if it's not an object or array, return it
    if (data === null || data === undefined || typeof data !== 'object') {
        return data;
    }
    // if it's an array, encode each element
    if (Array.isArray(data)) {
        return data.map((val) => encodeDates(val));
    }
    // if it's an object, encode each key
    for (const [key, val] of Object.entries(data)) {
        // @ts-expect-error we know this will give back the same type
        data[key] = encodeDates(val);
    }
    return data;
}
//# sourceMappingURL=utils.js.map