All files / apps/huella-legal/layers/articles/server/mappers articleBody.ts

100% Statements 69/69
85.18% Branches 46/54
100% Functions 20/20
100% Lines 60/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145                7x                 7x   7x 7x 133x     742x         7x                             7x   7x 54x 148x   148x 9x     54x     7x 94x       7x 54x   54x   10x 13x 11x 9x   2x 4x       10x   10x     7x 54x 111x   10x 10x                 69x   7x 54x 54x   54x 15x   15x 10x   5x     54x 111x   10x   10x 10x 4x 5x         7x 56x   54x     7x 54x   54x 54x 54x   54x 54x   54x   54x    
import type { Root, RootContent } from "hast";
import rehypeSanitize, { defaultSchema, type Options as Schema } from "rehype-sanitize";
import { unified } from "unified";
import type { ArticleBody } from "../../shared/types/ArticleBody";
import { eachElement, parseFragment, slugify, stringifyNodes, textContent } from "../utils/hast";
import { extractNotes } from "./note";
import { annotateHeadings } from "./tocItem";
 
const CLASS_MAP: Record<string, string> = {
    contenedor: "hl-note",
    "cita-larga": "hl-quote",
    "cita-corta": "hl-quote-short",
    "texto-importante": "hl-callout",
    "texto-destacado": "hl-highlight",
    "wp-block-table": "wp-block-table",
};
 
const BIBLIOGRAPHY_HEADING = /^(?:bibliografia|fuentes|referencias)(?:-bibliograficas)?$/;
 
const withoutClassLists = (attributes: NonNullable<Schema["attributes"]>): Schema["attributes"] =>
    Object.fromEntries(
        Object.entries(attributes).map(([tagName, definitions]) => [
            tagName,
            definitions.filter(
                (definition) => !(Array.isArray(definition) && definition[0] === "className"),
            ),
        ]),
    );
 
const SCHEMA: Schema = {
    ...defaultSchema,
    clobber: [],
    strip: ["script", "style"],
    tagNames: [...(defaultSchema.tagNames ?? []), "cite", "figcaption", "figure"],
    attributes: {
        ...withoutClassLists(defaultSchema.attributes ?? {}),
        img: [...(defaultSchema.attributes?.img ?? []), "sizes", "srcSet"],
        "*": [
            ...(defaultSchema.attributes?.["*"] ?? []),
            ["className", ...Object.values(CLASS_MAP)],
        ],
    },
};
 
const sanitizer = unified().use(rehypeSanitize, SCHEMA);
 
const sanitize = (tree: Root): Root => {
    eachElement(tree, (element) => {
        const { className } = element.properties;
 
        if (Array.isArray(className))
            element.properties.className = className.map((name) => CLASS_MAP[String(name)] ?? "");
    });
 
    return sanitizer.runSync(tree);
};
 
const isBibliographyHeading = (node: RootContent): boolean =>
    node.type === "element" &&
    /^h[1-6]$/.test(node.tagName) &&
    BIBLIOGRAPHY_HEADING.test(slugify(textContent(node)));
 
const splitBibliography = (tree: Root): string[] => {
    const start = tree.children.findLastIndex(isBibliographyHeading);
 
    if (start === -1) return [];
 
    const references = tree.children.slice(start + 1).flatMap((node) => {
        if (node.type !== "element" || !textContent(node)) return [];
        if (node.tagName !== "ul" && node.tagName !== "ol")
            return [stringifyNodes(node.tagName === "p" ? node.children : [node])];
 
        return node.children.flatMap((item) =>
            item.type === "element" && textContent(item) ? [stringifyNodes(item.children)] : [],
        );
    });
 
    if (references.length) tree.children = tree.children.slice(0, start);
 
    return references;
};
 
const lazyLoadImages = (tree: Root): void => {
    eachElement(tree, (element) => {
        if (element.tagName !== "img") return;
 
        element.properties.loading = "lazy";
        element.properties.decoding = "async";
    });
};
 
export interface Origins {
    siteUrl: string;
    wordpressUrl: string;
}
 
const bareHost = (url: URL): string => url.hostname.replace(/^www\./, "");
 
const rehostImages = (tree: Root, { siteUrl, wordpressUrl }: Origins): void => {
    const site = bareHost(new URL(siteUrl));
    const wordpress = wordpressUrl.endsWith("/") ? wordpressUrl : `${wordpressUrl}/`;
 
    const rehost = (value: string): string => {
        const url = URL.parse(value, siteUrl);
 
        if (!url || bareHost(url) !== site || !url.pathname.startsWith("/wp-content/"))
            return value;
 
        return new URL(`${url.pathname.slice(1)}${url.search}`, wordpress).href;
    };
 
    eachElement(tree, (element) => {
        if (element.tagName !== "img") return;
 
        const { src, srcSet } = element.properties;
 
        Eif (typeof src === "string") element.properties.src = rehost(src);
        if (srcSet)
            element.properties.srcSet = (Array.isArray(srcSet) ? srcSet : String(srcSet).split(","))
                .map((candidate) => String(candidate).trim().replace(/^\S+/, rehost))
                .join(", ");
    });
};
 
const splitLead = (nodes: RootContent[]): [RootContent[], RootContent[]] => {
    const end = nodes.findIndex((node) => node.type === "element" && node.tagName === "p") + 1;
 
    return [nodes.slice(0, end), nodes.slice(end)];
};
 
export const toArticleBody = (html: string, origins: Origins): ArticleBody => {
    const tree = sanitize(parseFragment(html));
    // Notes close the post, after the bibliography, so they must leave before it is split off
    const notes = extractNotes(tree);
    const bibliography = splitBibliography(tree);
    const toc = annotateHeadings(tree);
 
    lazyLoadImages(tree);
    rehostImages(tree, origins);
 
    const [lead, rest] = splitLead(tree.children);
 
    return { lead: stringifyNodes(lead), html: stringifyNodes(rest), toc, notes, bibliography };
};