The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
feat(metatags): switch to `node-html-parser` for parsing html`
rwlc0fc4446e1e7b
diff --git a/package.json b/package.jsonindex 1274ad169b..9d20111414 100644--- a/package.json+++ b/package.json@@ -41,13 +41,13 @@"cobe": "^0.6.2","focus-trap-react": "^10.0.1","framer-motion": "^7.6.12",- "he": "^1.2.0","html-escaper": "^3.0.3","i": "^0.3.7","mailing-core": "^0.9.1","ms": "^2.1.3","next": "^13.0.5","next-auth": "^4.17.0",+ "node-html-parser": "^6.1.4","nodemailer": "^6.8.0","npm": "^9.1.2","prisma": "^4.6.1",@@ -63,7 +63,6 @@"swr": "^1.3.0","tailwind-scrollbar-hide": "^1.1.7","topojson-client": "^3.1.0",- "ultrahtml": "^1.0.1","use-debounce": "^8.0.4"},"devDependencies": {diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.tsindex 2836b08786..416d69ee84 100644--- a/pages/api/edge/metatags.ts+++ b/pages/api/edge/metatags.ts@@ -1,136 +1,129 @@import { NextFetchEvent, NextRequest } from "next/server";-import { parse, walk, ELEMENT_NODE, transform } from "ultrahtml";-import he from "he";-import { recordMetatags } from "@/lib/upstash";+import { parse } from "node-html-parser";import { getDomainWithoutWWW, isValidUrl } from "@/lib/utils";-import sanitize from "ultrahtml/transformers/sanitize";-import { ratelimit } from "@/lib/upstash";+import { ratelimit, recordMetatags } from "@/lib/upstash";import { getToken } from "next-auth/jwt";export const config = {- runtime: "experimental-edge",+ runtime: "experimental-edge",};export default async function handler(req: NextRequest, ev: NextFetchEvent) {- if (req.method === "GET") {- let url = req.nextUrl.searchParams.get("url");- if (!isValidUrl(url)) {- return new Response("Invalid URL", { status: 400 });- }-- // Rate limit if user is not logged in- const session = await getToken({- req,- secret: process.env.NEXTAUTH_SECRET,- });- if (!session?.email) {- const { success } = await ratelimit.limit("metatags");- if (!success) {- return new Response("Don't DDoS me pls 🥺", { status: 429 });- }- }-- const metatags = await getMetaTags(url, ev);- return new Response(JSON.stringify(metatags), {- status: 200,- headers: {- "Content-Type": "application/json",- },- });- } else {- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });- }+ if (req.method === "GET") {+ let url = req.nextUrl.searchParams.get("url");+ if (!isValidUrl(url)) {+ return new Response("Invalid URL", { status: 400 });+ }++ // Rate limit if user is not logged in+ const session = await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ });+ if (!session?.email) {+ const { success } = await ratelimit.limit("metatags");+ if (!success) {+ return new Response("Don't DDoS me pls 🥺", { status: 429 });+ }+ }++ const metatags = await getMetaTags(url, ev);+ return new Response(JSON.stringify(metatags), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ });+ } else {+ return new Response(`Method ${req.method} Not Allowed`, { status: 405 });+ }}const getHtml = async (url: string) => {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 seconds- return await fetch(url, {- signal: controller.signal,- headers: {- "User-Agent": "dub-bot/1.0",- },- }).then((res) => {- clearTimeout(timeoutId);- return res.text();- });+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 seconds+ return await fetch(url, {+ signal: controller.signal,+ headers: {+ "User-Agent": "dub-bot/1.0",+ },+ }).then((res) => {+ clearTimeout(timeoutId);+ return res.text();+ });};-const specialHostnames = new Set(["developer.mozilla.org"]);--const getAst = async (url: string) => {- const html = await getHtml(url);- const ast = parse(- specialHostnames.has(getDomainWithoutWWW(url))- ? await transform(html, [- sanitize({- blockElements: ["script"],- }),- ])- : html,- );- return ast;+const getAst = (html: string) => {+ const ast = parse(html);+ return ast;};-const escapeEntities = (string: string) => {- return he.decode(string);+const getHeadChildNodes = (ast: ReturnType<typeof getAst>) => {+ const metaTags = ast.querySelectorAll("meta").map(({ attributes }) => {+ const property = attributes.property || attributes.name || attributes.href;+ return {+ property,+ content: attributes.content,+ };+ });+ const title = ast.querySelector("title").innerText;+ const linkTags = ast.querySelectorAll("link").map((node) => node.attributes);++ return { metaTags, title, linkTags };};const getRelativeUrl = (url: string, imageUrl: string) => {- if (!imageUrl) return null;- if (isValidUrl(imageUrl)) {- return imageUrl;- }- const { protocol, host } = new URL(url);- const baseURL = `${protocol}//${host}`;- return new URL(imageUrl, baseURL).toString();+ if (!imageUrl) {+ return null;+ }+ if (isValidUrl(imageUrl)) {+ return imageUrl;+ }+ const { protocol, host } = new URL(url);+ const baseURL = `${protocol}//${host}`;+ return new URL(imageUrl, baseURL).toString();};export const getMetaTags = async (url: string, ev: NextFetchEvent) => {- const obj = {};- const ast = await getAst(url);-- await walk(ast, (node) => {- if (node.type === ELEMENT_NODE) {- const { name, attributes } = node;- const property =- attributes.name ||- attributes.property ||- attributes.itemprop ||- attributes.rel;-- const content = attributes.content || attributes.href;-- if (name === "title") {- obj["title"] = escapeEntities(node.children[0].value);- // if content is not string, skip- } else if (typeof content !== "string") {- return;- } else {- obj[property] = escapeEntities(content);- }- }- });-- const title = obj["og:title"] || obj["twitter:title"] || obj["title"];-- const description =- obj["description"] || obj["og:description"] || obj["twitter:description"];-- const image =- obj["og:image"] ||- obj["twitter:image"] ||- obj["image_src"] ||- obj["icon"] ||- obj["shortcut icon"];-- ev.waitUntil(- recordMetatags(url, title && description && image ? false : true),- );-- return {- title,- description,- image: getRelativeUrl(url, image),- };+ const html = await getHtml(url);+ const headAst = getAst(html);+ const { metaTags, title: pageTitle, linkTags } = getHeadChildNodes(headAst);++ let object = {};++ for (let k in metaTags) {+ let { property, content } = metaTags[k];++ property && (object[property] = content);+ }++ for (let m in linkTags) {+ let { rel, href } = linkTags[m];++ rel && (object[rel] = href);+ }++ const title = object["og:title"] || object["twitter:title"] || pageTitle;++ const description =+ object["description"] ||+ object["og:description"] ||+ object["twitter:description"];++ const image =+ object["og:image"] ||+ object["twitter:image"] ||+ object["image_src"] ||+ object["icon"] ||+ object["shortcut icon"];++ ev.waitUntil(+ recordMetatags(url, title && description && image ? false : true),+ );++ return {+ title,+ description,+ image: getRelativeUrl(url, image),+ };};diff --git a/yarn.lock b/yarn.lockindex f6805c1ba1..f4f9465550 100644--- a/yarn.lock+++ b/yarn.lock@@ -4715,7 +4715,7 @@ node-gyp@^9.0.0, node-gyp@^9.3.0:tar "^6.1.2"which "^2.0.2"-node-html-parser@^6.1.1:+node-html-parser@^6.1.1, node-html-parser@^6.1.4:version "6.1.4"resolved "https://registry.yarnpkg.com/node-html-parser/-/node-html-parser-6.1.4.tgz#763cd362497e427d51fc73dda3dcd8ac52ba85a3"integrity sha512-3muP9Uy/Pz7bQa9TNYVQzWJhNZMqyCx7xJle8kz2/y1UgzAUyXXShc1IcPaJy6u07CE3K5rQcRwlvHzmlySRjg==@@ -6189,11 +6189,6 @@ uglify-js@^3.15.4, uglify-js@^3.5.1:resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.17.4.tgz#61678cf5fa3f5b7eb789bb345df29afb8257c22c"integrity sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g==-ultrahtml@^1.0.1:- version "1.0.1"- resolved "https://registry.yarnpkg.com/ultrahtml/-/ultrahtml-1.0.1.tgz#ed7fd8c1046ae36d176e320772132dd48f73a864"- integrity sha512-VDt8gmBR5DPrsfdLS4GQqncojcsLTKMW6iHKVN9l6TohU5bdn/OPv8AmV/0/PBR7Z3qBmMpJHqxRdQFaFA8B9g==-unique-filename@^2.0.0:version "2.0.1"resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-2.0.1.tgz#e785f8675a9a7589e0ac77e0b5c34d2eaeac6da2"