"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createExternalRewriteResponse = exports.isExternalRewrite = exports.getRewritePath = void 0;
const matcher_1 = require("./matcher");
const path_match_1 = require("next/dist/shared/lib/router/utils/path-match");
const prepare_destination_1 = require("next/dist/shared/lib/router/utils/prepare-destination");
const _ = __importStar(require("lodash"));
function getRewritePath({ path, queryParams, routesManifest, router, normalisedPath, cloudFrontHeaders }) {
    const headers = _.mapValues(cloudFrontHeaders, (listedHeaderValues) => _.map(listedHeaderValues, ({ value }) => value));
    const rewrites = routesManifest.rewrites;
    for (const rewrite of rewrites) {
        const matcher = path_match_1.getPathMatch(rewrite.source);
        let params = matcher(path);
        if (rewrite.has && params) {
            const hasParams = prepare_destination_1.matchHas({
                headers,
                cookies: {}
            }, rewrite.has, queryParams);
            if (hasParams) {
                params ? Object.assign(params, hasParams) : (params = hasParams);
            }
            else {
                params = false;
            }
        }
        if (params) {
            const destination = matcher_1.compileDestination(rewrite.destination, params);
            if (path === destination) {
                const url = router(normalisedPath);
                if (url === "pages/404.html" || url === "pages/_error.js") {
                    continue;
                }
            }
            return destination;
        }
    }
    return null;
}
exports.getRewritePath = getRewritePath;
function isExternalRewrite(customRewrite) {
    return (customRewrite.startsWith("http://") || customRewrite.startsWith("https://"));
}
exports.isExternalRewrite = isExternalRewrite;
const ignoredHeaders = [
    "connection",
    "expect",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "proxy-connection",
    "trailer",
    "upgrade",
    "x-accel-buffering",
    "x-accel-charset",
    "x-accel-limit-rate",
    "x-accel-redirect",
    "x-cache",
    "x-forwarded-proto",
    "x-real-ip",
    "content-length",
    "host",
    "transfer-encoding",
    "via",
    "content-encoding"
];
const ignoredHeaderPrefixes = ["x-amz-cf-", "x-amzn-", "x-edge-"];
function isIgnoredHeader(name) {
    const lowerCaseName = name.toLowerCase();
    for (const prefix of ignoredHeaderPrefixes) {
        if (lowerCaseName.startsWith(prefix)) {
            return true;
        }
    }
    return ignoredHeaders.includes(lowerCaseName);
}
function createExternalRewriteResponse(customRewrite, req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        const { default: fetch } = yield Promise.resolve().then(() => __importStar(require("node-fetch")));
        const fetchResponse = yield fetch(customRewrite);
        for (const [name, val] of fetchResponse.headers.entries()) {
            if (!isIgnoredHeader(name)) {
                res.setHeader(name, val);
            }
        }
        res.statusCode = fetchResponse.status;
        const text = yield fetchResponse.text();
        res.end(text);
    });
}
exports.createExternalRewriteResponse = createExternalRewriteResponse;
