"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchDataset = fetchDataset;
exports.responseToDataset = responseToDataset;
const rdf_dereference_1 = require("rdf-dereference");
const global_logger_factory_1 = require("global-logger-factory");
const BasicRepresentation_1 = require("../http/representation/BasicRepresentation");
const ContentTypes_1 = require("./ContentTypes");
const BadRequestHttpError_1 = require("./errors/BadRequestHttpError");
const ErrorUtil_1 = require("./errors/ErrorUtil");
const StreamUtil_1 = require("./StreamUtil");
const logger = (0, global_logger_factory_1.getLoggerFor)('FetchUtil');
/**
 * Fetches an RDF dataset from the given URL.
 *
 * Response will be a Representation with content-type internal/quads.
 */
async function fetchDataset(url) {
    // Try content negotiation to parse quads from the URL
    return (async () => {
        try {
            const quadStream = (await rdf_dereference_1.rdfDereferencer.dereference(url)).data;
            const quadArray = await (0, StreamUtil_1.arrayifyStream)(quadStream);
            return new BasicRepresentation_1.BasicRepresentation(quadArray, { path: url }, ContentTypes_1.INTERNAL_QUADS, false);
        }
        catch (error) {
            throw new BadRequestHttpError_1.BadRequestHttpError(`Could not parse resource at URL (${url})! ${(0, ErrorUtil_1.createErrorMessage)(error)}`, { cause: error });
        }
    })();
}
/**
 * Converts a given Response (from a request that was already made) to  an RDF dataset.
 * In case the given Response object was already parsed its body can be passed along as a string.
 *
 * The converter will be used to convert the response body to RDF.
 *
 * Response will be a Representation with content-type internal/quads.
 */
async function responseToDataset(response, converter, body) {
    if (!body) {
        body = await response.text();
    }
    // Keeping the error message the same everywhere to prevent leaking possible information about intranet.
    const error = new BadRequestHttpError_1.BadRequestHttpError(`Unable to access data at ${response.url}`);
    if (response.status !== 200) {
        logger.warn(`Cannot fetch ${response.url}: ${body}`);
        throw error;
    }
    const contentType = response.headers.get('content-type');
    if (!contentType) {
        logger.warn(`Missing content-type header from ${response.url}`);
        throw error;
    }
    // Try to convert to quads
    const representation = new BasicRepresentation_1.BasicRepresentation(body, contentType);
    const preferences = { type: { [ContentTypes_1.INTERNAL_QUADS]: 1 } };
    return converter.handleSafe({ representation, identifier: { path: response.url }, preferences });
}
//# sourceMappingURL=FetchUtil.js.map