"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OriginalUrlExtractor = void 0;
const BadRequestHttpError_1 = require("../../../util/errors/BadRequestHttpError");
const HttpErrorUtil_1 = require("../../../util/errors/HttpErrorUtil");
const InternalServerError_1 = require("../../../util/errors/InternalServerError");
const HeaderUtil_1 = require("../../../util/HeaderUtil");
const PathUtil_1 = require("../../../util/PathUtil");
const TargetExtractor_1 = require("./TargetExtractor");
/**
 * Reconstructs the original URL of an incoming {@link HttpRequest}.
 */
class OriginalUrlExtractor extends TargetExtractor_1.TargetExtractor {
    identifierStrategy;
    includeQueryString;
    constructor(args) {
        super();
        this.identifierStrategy = args.identifierStrategy;
        this.includeQueryString = args.includeQueryString ?? true;
    }
    async handle({ request: { url, connection, headers } }) {
        if (!url) {
            throw new InternalServerError_1.InternalServerError('Missing URL');
        }
        // Extract host and protocol (possibly overridden by the Forwarded/X-Forwarded-* header)
        let { host } = headers;
        let protocol = connection?.encrypted ? 'https' : 'http';
        // Check Forwarded/X-Forwarded-* headers
        const forwarded = (0, HeaderUtil_1.parseForwarded)(headers);
        if (forwarded.host) {
            ({ host } = forwarded);
        }
        if (forwarded.proto) {
            ({ proto: protocol } = forwarded);
        }
        // Perform a sanity check on the host
        if (!host) {
            throw new BadRequestHttpError_1.BadRequestHttpError('Missing Host header');
        }
        if (/[/\\*]/u.test(host)) {
            throw new BadRequestHttpError_1.BadRequestHttpError(`The request has an invalid Host header: ${host}`);
        }
        // URL object applies punycode encoding to domain
        const originalUrl = new URL(`${protocol}://${host}`);
        const [, pathname, search] = /^([^?]*)(.*)/u.exec((0, PathUtil_1.toCanonicalUriPath)(url));
        originalUrl.pathname = pathname;
        if (this.includeQueryString && search) {
            originalUrl.search = search;
        }
        // Create ResourceIdentifier instance
        const identifier = { path: originalUrl.href };
        // Check if the configured IdentifierStrategy supports the identifier
        if (!this.identifierStrategy.supportsIdentifier(identifier)) {
            throw new InternalServerError_1.InternalServerError(`The identifier ${identifier.path} is outside the configured identifier space.`, { errorCode: 'E0001', metadata: (0, HttpErrorUtil_1.errorTermsToMetadata)({ path: identifier.path }) });
        }
        return identifier;
    }
}
exports.OriginalUrlExtractor = OriginalUrlExtractor;
//# sourceMappingURL=OriginalUrlExtractor.js.map