import "../../dialect-helpers-B9uSp2GJ.mjs";
import "../../base64-MBPo9ozB.mjs";
import "../../types-CMMN0pNg.mjs";
import { t as RedirectRepository } from "../../redirect-DIfIni3r.mjs";
import { defineMiddleware } from "astro:middleware";

//#region src/astro/middleware/redirect.ts
/**
* Redirect middleware
*
* Intercepts incoming requests and checks for matching redirect rules.
* Runs after runtime init (needs db) but before setup/auth (should handle
* ALL routes, including public ones, and should be fast).
*
* Skip paths:
* - /_emdash/* (admin UI, API routes, auth endpoints)
* - /_image (Astro image optimization)
* - Static assets (files with extensions)
*
* 404 logging happens post-response: if next() returns 404 and the path
* wasn't already matched by a redirect, log it.
*/
/** Paths that should never be intercepted by redirects */
const SKIP_PREFIXES = ["/_emdash", "/_image"];
/** Static asset extensions -- don't redirect file requests */
const ASSET_EXTENSION = /\.\w{1,10}$/;
function isRedirectCode(code) {
	return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
}
const onRequest = defineMiddleware(async (context, next) => {
	const { pathname } = context.url;
	if (SKIP_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return next();
	if (ASSET_EXTENSION.test(pathname)) return next();
	const { emdash } = context.locals;
	if (!emdash?.db) return next();
	try {
		const repo = new RedirectRepository(emdash.db);
		const match = await repo.matchPath(pathname);
		if (match) {
			if (match.resolvedDestination.startsWith("//") || match.resolvedDestination.startsWith("/\\")) return next();
			repo.recordHit(match.redirect.id).catch(() => {});
			const code = isRedirectCode(match.redirect.type) ? match.redirect.type : 301;
			return context.redirect(match.resolvedDestination, code);
		}
		const response = await next();
		if (response.status === 404) {
			const referrer = context.request.headers.get("referer") ?? null;
			const userAgent = context.request.headers.get("user-agent") ?? null;
			repo.log404({
				path: pathname,
				referrer,
				userAgent
			}).catch(() => {});
		}
		return response;
	} catch {
		return next();
	}
});

//#endregion
export { onRequest };
//# sourceMappingURL=redirect.mjs.map