domutils4.1.212.6 kB
import {
type AnyNode,
type Element,
hasChildren,
isTag,
isText,
} from "domhandler";
import { getElementsByTagName } from "./legacy.js";
import { textContent } from "./stringify.js";
/**
* The medium of a media item.
*
* @category Feeds
*/
export type FeedItemMediaMedium =
| "image"
| "audio"
| "video"
| "document"
| "executable";
/**
* The type of a media item.
*
* @category Feeds
*/
export type FeedItemMediaExpression = "sample" | "full" | "nonstop";
/**
* A media item of a feed entry.
*
* @category Feeds
*/
export interface FeedItemMedia {
medium: FeedItemMediaMedium | undefined;
isDefault: boolean;
url?: string;
fileSize?: number;
type?: string;
expression?: FeedItemMediaExpression;
bitrate?: number;
framerate?: number;
samplingrate?: number;
channels?: number;
duration?: number;
height?: number;
width?: number;
lang?: string;
}
/**
* An entry of a feed.
*
* @category Feeds
*/
export interface FeedItem {
id?: string;
title?: string;
link?: string;
description?: string;
pubDate?: Date;
media: FeedItemMedia[];
}
/**
* The root of a feed.
*
* @category Feeds
*/
export interface Feed {
type: string;
id?: string;
title?: string;
link?: string;
description?: string;
updated?: Date;
author?: string;
items: FeedItem[];
}
/**
* Get the feed object from the root of a DOM tree.
*
* @category Feeds
* @param document The DOM to extract the feed from.
* @returns The feed.
*/
export function getFeed(document: AnyNode[]): Feed | null {
const feedRoot = getOneElement(isValidFeed, document);
if (!feedRoot) return null;
const isAtom = feedRoot.name === "feed";
const itemName = isAtom ? "entry" : "item";
// Items are the outermost item elements below the root, in document order.
const items: Element[] = [];
// One child list and position per open level, searched depth-first.
const lists: AnyNode[][] = [feedRoot.children];
const indices = [0];
while (lists.length > 0) {
const top = lists.length - 1;
if (indices[top] >= lists[top].length) {
lists.pop();
indices.pop();
continue;
}
const node = lists[top][indices[top]++];
if (isTag(node) && node.name === itemName) {
items.push(node);
} else if (hasChildren(node)) {
lists.push(node.children);
indices.push(0);
}
}
if (isAtom) return getAtomFeed(feedRoot, items);
return getRssFeed(feedRoot, items);
}
/**
* Parse an Atom feed.
*
* @param feedRoot The root of the feed.
* @param items The entries of the feed.
* @returns The parsed feed.
*/
function getAtomFeed(feedRoot: Element, items: Element[]) {
const childs = feedRoot.children;
const feed: Feed = {
type: "atom",
items: items.map((item) => {
const { children } = item;
const entry: FeedItem = { media: getMediaElements(children) };
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
const href = getAtomLink(children);
if (href) {
entry.link = href;
}
const description =
fetch("summary", children) || fetch("content", children);
if (description) {
entry.description = description;
}
const pubDate =
fetch("published", children) || fetch("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
}),
};
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
const href = getAtomLink(childs);
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
const updated = fetch("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
const author = getAtomFeedAuthorEmail(childs);
if (author) {
feed.author = author;
}
return feed;
}
/**
* Get the email of the feed's author: the first direct feed author with an
* email, else the first author with one inside the feed's other elements.
*
* In HTML mode, an element written self-closing, such as
* `<category term="x"/>`, stays open around the elements after it, so the
* feed's author can end up inside it. Authors of entries and of embedded
* feeds, and authors inside authors, are never used.
*
* @param nodes Children of the feed.
* @returns The email, if any.
*/
function getAtomFeedAuthorEmail(nodes: AnyNode[]): string | undefined {
for (const node of nodes) {
if (!isTag(node) || node.name !== "author") continue;
const email = getAuthorEmail(node);
if (email) return email;
}
const stack: { children: AnyNode[]; index: number }[] = [];
let children = nodes;
let index = 0;
while (true) {
if (index === children.length) {
const frame = stack.pop();
if (!frame) return undefined;
({ children, index } = frame);
continue;
}
const node = children[index++];
if (isTag(node)) {
const { name } = node;
if (name === "entry" || name === "feed") continue;
if (name === "author") {
if (children !== nodes) {
const email = getAuthorEmail(node);
if (email) return email;
}
continue;
}
} else if (!hasChildren(node)) {
continue;
}
const descendants = node.children;
if (descendants.length === 0) continue;
// Save the scan only when there are siblings left to visit.
if (index < children.length) stack.push({ children, index });
children = descendants;
index = 0;
}
}
/**
* Get the email of an Atom author. In HTML mode, an element written
* self-closing before the email stays open, so the email can end up inside
* it; authors inside the author are skipped, also within the email's text.
*
* @param author The author element.
* @returns The email, or an empty string.
*/
function getAuthorEmail(author: Element): string {
const stack: AnyNode[] = [author];
let isInEmail = false;
let text = "";
for (let node = stack.pop(); node; node = stack.pop()) {
if (isInEmail) {
if (isText(node)) text += node.data;
} else if (isTag(node) && node.name === "email") {
// Only the email's own subtree is left to visit.
isInEmail = true;
stack.length = 0;
}
if (!hasChildren(node)) continue;
const { children } = node;
for (let index = children.length - 1; index >= 0; index--) {
const child = children[index];
if (!isTag(child) || child.name !== "author") stack.push(child);
}
}
return trimCopy(text);
}
/**
* Parse a RSS feed.
*
* @param feedRoot The root of the feed.
* @param items The items of the feed.
* @returns The parsed feed.
*/
function getRssFeed(feedRoot: Element, items: Element[]) {
const childs = getOneElement("channel", feedRoot.children)?.children ?? [];
const feed: Feed = {
type: feedRoot.name.substr(0, 3),
id: "",
items: items.map((item: Element) => {
const { children } = item;
const entry: FeedItem = { media: getMediaElements(children) };
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(entry, "description", "description", children);
const pubDate =
fetch("pubDate", children) || fetch("dc:date", children);
if (pubDate) entry.pubDate = new Date(pubDate);
return entry;
}),
};
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
const updated = fetch("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "managingEditor", childs, true);
return feed;
}
const MEDIA_KEYS_STRING = ["url", "type", "lang"] as const;
const MEDIA_NUMBERS = [
["fileSize", Number.parseInt],
["bitrate", Number.parseFloat],
["framerate", Number.parseFloat],
["samplingrate", Number.parseFloat],
["channels", Number.parseInt],
["duration", Number.parseFloat],
["height", Number.parseInt],
["width", Number.parseInt],
] as const;
/**
* Get all media elements of a feed item.
*
* @param where Nodes to search in.
* @returns Media elements.
*/
function getMediaElements(where: AnyNode[]): FeedItemMedia[] {
return getElementsByTagName("media:content", where).map((element) => {
const { attribs } = element;
const media: FeedItemMedia = {
medium: attribs["medium"] as unknown as
| FeedItemMediaMedium
| undefined,
isDefault: !!attribs["isDefault"],
};
for (const attrib of MEDIA_KEYS_STRING) {
const value = attribs[attrib];
if (value) media[attrib] = value;
}
for (const [attrib, parse] of MEDIA_NUMBERS) {
const value = attribs[attrib];
if (value) media[attrib] = parse(value, 10);
}
if (attribs["expression"]) {
media.expression = attribs[
"expression"
] as unknown as FeedItemMediaExpression;
}
return media;
});
}
/**
* Get one element by tag name.
*
* @param tagName Tag name to look for
* @param node Node to search in
* @returns The element or null
*/
function getOneElement(
tagName: string | ((name: string) => boolean),
node: AnyNode[],
): Element | null {
return getElementsByTagName(tagName, node, true, 1)[0];
}
// eslint-disable-next-line unicorn/prefer-https -- RFC 4287 spells this relation with HTTP.
const ATOM_ALTERNATE = "http://www.iana.org/assignments/relation/alternate";
/**
* Get the page an Atom feed or entry points to: the first `alternate` link
* (a link without `rel` is `alternate`, and RFC 4287 also writes it as an
* IANA URI), else the first link.
*
* @param nodes Children of the feed or entry.
* @returns The link's `href`, if any.
*/
function getAtomLink(nodes: AnyNode[]): string | undefined {
let first: Element | undefined;
for (const node of nodes) {
if (!isTag(node) || node.name !== "link") continue;
const { rel: relation } = node.attribs;
if (
!relation ||
relation === "alternate" ||
relation === ATOM_ALTERNATE
) {
return node.attribs["href"];
}
first ??= node;
}
return first?.attribs["href"];
}
/**
* Get the text content of an element with a certain tag name.
*
* @param tagName Tag name to look for.
* @param where Node to search in.
* @param shouldRecurse Whether to recurse into child nodes.
* @returns The text content of the element.
*/
function fetch(
tagName: string,
where: AnyNode | AnyNode[],
shouldRecurse = false,
): string {
return trimCopy(
textContent(getElementsByTagName(tagName, where, shouldRecurse, 1)),
);
}
/**
* Trim the text of a feed field.
*
* @param text The text to trim.
* @returns The trimmed text.
*/
function trimCopy(text: string): string {
const trimmed = text.trim();
// A trimmed string can share the memory of the whole text; copy it.
return trimmed.length === text.length ? trimmed : ` ${trimmed}`.slice(1);
}
/**
* Adds a property to an object if it has a value.
*
* @param object Object to be extended.
* @param property Property name.
* @param tagName Tag name that contains the conditionally added property.
* @param where Element to search for the property.
* @param shouldRecurse Whether to recurse into child nodes.
*/
function addConditionally<T>(
object: T,
property: keyof T,
tagName: string,
where: AnyNode[],
shouldRecurse = false,
) {
const value = fetch(tagName, where, shouldRecurse);
if (value) object[property] = value as unknown as T[keyof T];
}
/**
* Checks if an element is a feed root node.
*
* @param value The name of the element to check.
* @returns Whether an element is a feed root node.
*/
function isValidFeed(value: string) {
return ["rss", "feed", "rdf:RDF"].includes(value);
}
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.