@withstudiocms/effect
Version:
Effect-TS Utilities for Astro
49 lines (48 loc) • 1.77 kB
JavaScript
import { sequence } from "astro/middleware";
import micromatch from "micromatch";
import { defineMiddleware } from "../middleware.js";
const matchFilterCheck = (paths, pathname, defaultValue) => {
if (paths === null || Array.isArray(paths) && paths.length === 0 || typeof paths === "string" && paths.trim() === "") {
return defaultValue;
}
let cleanedPaths;
if (typeof paths === "string") {
if (paths.trim() === "") {
return defaultValue;
}
cleanedPaths = [paths.trim()];
} else if (Array.isArray(paths)) {
if (paths.length === 0 || paths.every((p) => p.trim() === "")) {
return defaultValue;
}
cleanedPaths = paths.map((p) => p.trim()).filter((p) => p !== "");
} else {
return defaultValue;
}
return micromatch.isMatch(pathname, cleanedPaths, {
nocase: true
// Case-insensitive matching
});
};
function handlerFilter(includePaths, excludePaths, pathname) {
const include = matchFilterCheck(includePaths, pathname, true);
const exclude = matchFilterCheck(excludePaths, pathname, false);
return include && !exclude;
}
const sortByPriority = (a, b) => {
const priorityA = a ?? Number.MAX_SAFE_INTEGER;
const priorityB = b ?? Number.MAX_SAFE_INTEGER;
return priorityA - priorityB;
};
function buildMiddlewareSequence(context, next, router) {
const pathname = context.url.pathname;
const handlers = router.filter(({ includePaths, excludePaths }) => handlerFilter(includePaths, excludePaths, pathname)).sort((a, b) => sortByPriority(a.priority, b.priority)).map(({ handler }) => defineMiddleware(handler));
if (handlers.length === 0) return next();
return sequence(...handlers)(context, next);
}
export {
buildMiddlewareSequence,
handlerFilter,
matchFilterCheck,
sortByPriority
};