"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "DataLoaderModuleMiddleware", {
    enumerable: true,
    get: function() {
        return DataLoaderModuleMiddleware;
    }
});
function _config() {
    const data = require("@expo/config");
    _config = function() {
        return data;
    };
    return data;
}
const _ExpoMiddleware = require("./ExpoMiddleware");
const _fetchRouterManifest = require("../metro/fetchRouterManifest");
const LOADER_MODULE_ENDPOINT = '/_expo/loaders';
class DataLoaderModuleMiddleware extends _ExpoMiddleware.ExpoMiddleware {
    constructor(projectRoot, appDir, executeServerDataLoaderAsync, getDevServerUrl){
        super(projectRoot, [
            LOADER_MODULE_ENDPOINT
        ]), this.projectRoot = projectRoot, this.appDir = appDir, this.executeServerDataLoaderAsync = executeServerDataLoaderAsync, this.getDevServerUrl = getDevServerUrl;
    }
    /**
   * Only handles a request if `req.pathname` begins with `/_expo/loaders/` and if the request
   * headers include `Accept: application/json`.
   */ shouldHandleRequest(req) {
        var _exp_extra_router, _exp_extra;
        if (!req.url) return false;
        const { pathname } = new URL(req.url, 'http://localhost');
        if (!pathname.startsWith(`${LOADER_MODULE_ENDPOINT}/`)) {
            return false;
        }
        if (req.headers.accept !== 'application/json') {
            return false;
        }
        const { exp } = (0, _config().getConfig)(this.projectRoot);
        return !!((_exp_extra = exp.extra) == null ? void 0 : (_exp_extra_router = _exp_extra.router) == null ? void 0 : _exp_extra_router.unstable_useServerDataLoaders);
    }
    async handleRequestAsync(req, res, next) {
        if (![
            'GET',
            'HEAD'
        ].includes(req.method ?? '')) {
            return next();
        }
        const manifest = await (0, _fetchRouterManifest.fetchManifest)(this.projectRoot, {
            appDir: this.appDir
        });
        const { pathname } = new URL(req.url, 'http://localhost');
        try {
            const routePath = pathname.replace('/_expo/loaders', '').replace('/index', '/') || '/';
            const matchingRoute = manifest == null ? void 0 : manifest.htmlRoutes.find((route)=>{
                return route.namedRegex.test(routePath);
            });
            if (!matchingRoute) {
                throw new Error(`No matching route for ${routePath}`);
            }
            const loaderData = await this.executeServerDataLoaderAsync(new URL(routePath, this.getDevServerUrl()), matchingRoute);
            res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
            res.setHeader('Cache-Control', 'no-cache');
            res.statusCode = 200;
            res.end(JSON.stringify(loaderData ?? {}));
        } catch (error) {
            console.error(`Failed to generate loader module for ${pathname}:`, error);
            res.statusCode = 500;
            res.end(`{}`);
        }
    }
}

//# sourceMappingURL=DataLoaderModuleMiddleware.js.map