import { hubFetchHeaders } from './hub-url';
function normalizeErrorMessage(payload, fallback) {
    if (payload &&
        typeof payload === 'object' &&
        typeof payload.error === 'string') {
        return payload.error;
    }
    return fallback;
}
export async function probeHubInitAccess(hubHttpUrl, fetchImpl = fetch) {
    try {
        const response = await fetchImpl(`${hubHttpUrl}/api/hub/init`, {
            headers: hubFetchHeaders({ accept: 'application/json' }),
            signal: AbortSignal.timeout(5_000),
        });
        let payload;
        try {
            payload = await response.json();
        }
        catch {
            payload = undefined;
        }
        if (response.status === 401 || response.status === 403) {
            return {
                ok: false,
                code: 'unauthorized',
                message: normalizeErrorMessage(payload, `${response.status} ${response.statusText}`),
            };
        }
        if (!response.ok) {
            return {
                ok: false,
                code: 'http_error',
                message: normalizeErrorMessage(payload, `${response.status} ${response.statusText}`),
            };
        }
        if (!payload ||
            typeof payload !== 'object' ||
            payload.type !== 'init') {
            return {
                ok: false,
                code: 'invalid_response',
                message: 'Hub init endpoint did not return an init payload',
            };
        }
        return { ok: true };
    }
    catch (error) {
        return {
            ok: false,
            code: 'network_error',
            message: error instanceof Error ? error.message : String(error),
        };
    }
}
//# sourceMappingURL=tui-init.js.map