Resolve src refs for img and script

Handle absolute to relative resolution of the src attribute for img and
script elements.
This commit is contained in:
Hornwitser 2025-02-03 13:42:37 +01:00
parent 07a7386e1d
commit 9d27566b66
2 changed files with 22 additions and 7 deletions

View file

@ -25,6 +25,16 @@ suite("function resolveRefs", () => {
assert.equal((el as Element).attributes.get("href"), "../alt/page.html");
});
test("script src", () => {
const el = resolveRefs(<script src="/assets/script.js"></script>, "/subdir");
assert.equal((el as Element).attributes.get("src"), "../assets/script.js");
});
test("img src", () => {
const el = resolveRefs(<img src="/assets/image.png"></img>, "/subdir");
assert.equal((el as Element).attributes.get("src"), "../assets/image.png");
});
test("nested element", () => {
const el = resolveRefs(<div>Content with <a href="/page.html">Link</a></div>, "/");
assert.equal((el.childNodes[1] as Element).attributes.get("href"), "page.html");

View file

@ -8,6 +8,13 @@ function shallowCopyElement(element: Element) {
return copy;
}
const resolvedAttributes = new Map([
["a", "href"],
["img", "src"],
["link", "href"],
["script", "src"],
]);
/**
Resolves absolute href attributes in a and link elements the Node tree into relative references from the given directory.
@ -21,20 +28,18 @@ export function resolveRefs(node: Node, dir: string) {
}
let resolvedNode = node;
const name = node.name;
if (
(name === "link" || name === "a")
&& node.attributes.has("href")
) {
const original = node.attributes.get("href")!
let attribute = resolvedAttributes.get(name);
if (attribute && node.attributes.has(attribute)) {
const original = node.attributes.get(attribute)!
if (/^[a-z][a-z+.-]*:/i.test(original)) {
// Ignore refs that start with a URI scheme.
/* node:coverage ignore next 3 */
} else if (!original.startsWith("/")) {
console.log(`Warning: found relative href to ${original}`);
console.log(`Warning: found relative ${attribute} to ${original}`);
} else {
const ref = posix.relative(dir, original);
resolvedNode = shallowCopyElement(node);
resolvedNode.attributes.set("href", ref);
resolvedNode.attributes.set(attribute, ref);
}
}
const resolvedChildren: Node[] = [];