fix: normalize trailing slashes for page backlinks (#42)

This commit is contained in:
Ben Senescu 2026-03-19 10:29:12 -04:00 committed by GitHub
parent e6d68493d7
commit 82c2f99ec1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 39 additions and 7 deletions

View File

@ -24,6 +24,24 @@ describe("normalizeBacklinksTarget", () => {
});
});
it("trims trailing slashes from non-root page URLs", () => {
expect(
normalizeBacklinksTarget("https://github.com/every-app/open-seo/"),
).toEqual({
apiTarget: "https://github.com/every-app/open-seo",
displayTarget: "https://github.com/every-app/open-seo",
scope: "page",
});
});
it("keeps trailing slashes for root page URLs", () => {
expect(normalizeBacklinksTarget("https://example.com/")).toEqual({
apiTarget: "https://example.com/",
displayTarget: "https://example.com/",
scope: "page",
});
});
it("treats bare hostnames as domain lookups", () => {
expect(normalizeBacklinksTarget("Example.com")).toEqual({
apiTarget: "example.com",

View File

@ -11,6 +11,17 @@ type NormalizeBacklinksTargetOptions = {
scope?: BacklinksLookupInput["scope"];
};
function normalizePageTargetUrl(url: URL, hostname: string): string {
const normalizedUrl = new URL(url.toString());
normalizedUrl.hostname = hostname;
if (normalizedUrl.pathname.length > 1) {
normalizedUrl.pathname = normalizedUrl.pathname.replace(/\/+$/, "");
}
return normalizedUrl.toString();
}
export function normalizeBacklinksTarget(
input: string,
options: NormalizeBacklinksTargetOptions = {},
@ -63,23 +74,26 @@ export function normalizeBacklinksTarget(
if (requestedScope === "page") {
const normalizedUrl = new URL(parsed.toString());
normalizedUrl.hostname = exactHostname;
if (!hasExplicitProtocol && !hasMeaningfulPath) {
normalizedUrl.pathname = "/";
}
const normalizedTarget = normalizePageTargetUrl(
normalizedUrl,
exactHostname,
);
return {
apiTarget: normalizedUrl.toString(),
displayTarget: normalizedUrl.toString(),
apiTarget: normalizedTarget,
displayTarget: normalizedTarget,
scope: "page",
};
}
if (hasExplicitProtocol || hasMeaningfulPath) {
const normalizedUrl = new URL(parsed.toString());
normalizedUrl.hostname = exactHostname;
const normalizedTarget = normalizePageTargetUrl(parsed, exactHostname);
return {
apiTarget: normalizedUrl.toString(),
displayTarget: normalizedUrl.toString(),
apiTarget: normalizedTarget,
displayTarget: normalizedTarget,
scope: "page",
};
}