/** Create a public REST API router for Actuate CMS content. */
export function createApiRouter() {
    const routes = [];
    const globalMiddleware = [];
    function addRoute(method, path, handler) {
        routes.push({ method, path, handler });
    }
    return {
        routes,
        use(middleware) {
            globalMiddleware.push(middleware);
        },
        get(path, handler) {
            addRoute('GET', path, handler);
        },
        post(path, handler) {
            addRoute('POST', path, handler);
        },
        put(path, handler) {
            addRoute('PUT', path, handler);
        },
        patch(path, handler) {
            addRoute('PATCH', path, handler);
        },
        delete(path, handler) {
            addRoute('DELETE', path, handler);
        },
        options(path, handler) {
            addRoute('OPTIONS', path, handler);
        },
        async handle(request) {
            const url = new URL(request.url);
            const method = request.method.toUpperCase();
            const matched = routes.find((r) => r.method === method && matchPath(r.path, url.pathname));
            if (!matched) {
                return new Response(JSON.stringify({ error: 'Not Found' }), {
                    status: 404,
                    headers: { 'Content-Type': 'application/json' },
                });
            }
            const params = extractParams(matched.path, url.pathname);
            const allMiddleware = [...globalMiddleware, ...(matched.middleware ?? [])];
            let index = 0;
            const next = async () => {
                if (index < allMiddleware.length) {
                    return allMiddleware[index++](request, next);
                }
                return matched.handler(request, params);
            };
            return next();
        },
    };
}
function matchPath(pattern, pathname) {
    const regex = new RegExp('^' + pattern.replace(/:([^/]+)/g, '([^/]+)') + '$');
    return regex.test(pathname);
}
function extractParams(pattern, pathname) {
    const paramNames = [];
    const regex = new RegExp('^' +
        pattern.replace(/:([^/]+)/g, (_, name) => {
            paramNames.push(name);
            return '([^/]+)';
        }) +
        '$');
    const match = pathname.match(regex);
    if (!match)
        return {};
    const params = {};
    paramNames.forEach((name, i) => {
        params[name] = match[i + 1];
    });
    return params;
}
//# sourceMappingURL=router.js.map