Files
Tiber365/node_modules/astro/dist/vite-plugin-astro-server/trailing-slash.js
2025-07-24 18:46:24 +02:00

31 lines
1.2 KiB
JavaScript

import { collapseDuplicateTrailingSlashes, hasFileExtension } from "@astrojs/internal-helpers/path";
import { trailingSlashMismatchTemplate } from "../template/4xx.js";
import { writeHtmlResponse, writeRedirectResponse } from "./response.js";
function trailingSlashMiddleware(settings) {
const { trailingSlash } = settings.config;
return function devTrailingSlash(req, res, next) {
const url = new URL(`http://localhost${req.url}`);
let pathname;
try {
pathname = decodeURI(url.pathname);
} catch (e) {
return next(e);
}
if (pathname.startsWith("/_") || pathname.startsWith("/@")) {
return next();
}
const destination = collapseDuplicateTrailingSlashes(pathname, true);
if (pathname && destination !== pathname) {
return writeRedirectResponse(res, 301, `${destination}${url.search}`);
}
if (trailingSlash === "never" && pathname.endsWith("/") && pathname !== "/" || trailingSlash === "always" && !pathname.endsWith("/") && !hasFileExtension(pathname)) {
const html = trailingSlashMismatchTemplate(pathname, trailingSlash);
return writeHtmlResponse(res, 404, html);
}
return next();
};
}
export {
trailingSlashMiddleware
};