Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
feat(links): offline link cards that read every link correctly
Deepender25bd1f73fd2d8d
diff --git a/electron/clipboard/formats.ts b/electron/clipboard/formats.tsindex 9571c7f..0474b74 100644--- a/electron/clipboard/formats.ts+++ b/electron/clipboard/formats.ts@@ -12,6 +12,7 @@ import { promisify } from 'node:util'import { existsSync } from 'node:fs'import koffi from 'koffi'import type { ClipboardImageSource, ItemData } from '../../shared/types'+import { isLinkText } from '../../shared/linkText'let getSeqNum: (() => number) | null = null@@ -641,7 +642,8 @@ export async function readClipboard(): Promise<ItemData | null> {const textToStore = normalizeClipboardText(rawText)- const isUrl = URL_RE.test(trimmedText)+ // A link card: scheme, www., mailto:/tel: or a bare domain (shared/linkText)+ const isUrl = isLinkText(trimmedText)const isColor = COLOR_HEX_RE.test(trimmedText)return { kind: 'text', text: textToStore, html, isUrl, isColor }@@ -745,7 +747,7 @@ export function clipboardSignature(): string {/** True if the text payload looks like a single URL. */export function isUrlText(s: string): boolean {- return URL_RE.test(s)+ return isLinkText(s)}/**diff --git a/electron/main/externalUrl.ts b/electron/main/externalUrl.tsindex 1ab1b0b..c8d5183 100644--- a/electron/main/externalUrl.ts+++ b/electron/main/externalUrl.ts@@ -2,11 +2,11 @@* Which URLs the renderer may hand to the OS (window.open -> shell.openExternal).** Links come from clipboard history, i.e. from anything the user ever copied,- * so only web links, mail links and the Microsoft Store review link the- * settings page uses are passed on. Everything else (file:, javascript:,+ * so only web links, mail and phone links and the Microsoft Store review link+ * the settings page uses are passed on. Everything else (file:, javascript:,* custom protocol handlers) is refused.*/-const ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'ms-windows-store:'])+const ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:', 'ms-windows-store:'])export function isSafeExternalUrl(raw: unknown): raw is string {if (typeof raw !== 'string' || raw.length === 0 || raw.length > 8192) return falsediff --git a/electron/preload/index.ts b/electron/preload/index.tsindex 7812c71..18aedcd 100644--- a/electron/preload/index.ts+++ b/electron/preload/index.ts@@ -55,6 +55,7 @@ function on<C extends EventChannel>(* to fail. Handling it here natively bypasses the bridge entirely.*/import { reduceGuard, isGuarded } from './internalDragGuard'+import { isLinkText } from '../../shared/linkText'let guard: import('./internalDragGuard').GuardState = { phase: 'idle', fireAt: null }let guardIdleTimer: ReturnType<typeof setTimeout> | null = null@@ -163,7 +164,7 @@ win.addEventListener('drop', (e: any) => {// 3. Plain Text / HTMLif (plainText) {e.preventDefault()- const isUrl = /^(https?:\/\/|www\.)[^\s]+$/i.test(plainText)+ const isUrl = isLinkText(plainText)const isColor = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(plainText)invoke('item:add-data', {kind: 'text',diff --git a/electron/store/ItemStore.ts b/electron/store/ItemStore.tsindex fc0b3a9..3e59e34 100644--- a/electron/store/ItemStore.ts+++ b/electron/store/ItemStore.ts@@ -28,6 +28,7 @@ import { createId } from './ids'import { contentSignature } from './signature'import { MAX_ITEM_HTML_CHARS } from '../clipboard/formats'import { isKept, joinNotes, normalizeNote, noteFromLegacy, type ItemMetaPatch } from '../../shared/itemMeta'+import { linkTitleFromHtml } from '../../shared/linkText'/** Write an already-normalized note, removing the field when empty. */function applyNote(it: ClipboardItem, note: string | undefined): void {@@ -125,6 +126,11 @@ export class ItemStore {applyNote(it, normalizeNote(it.note))}if (it.data.kind === 'text') {+ // links saved before page titles were kept: read it from the saved html once+ if (it.data.isUrl && it.data.html && !it.data.linkTitle) {+ const linkTitle = linkTitleFromHtml(it.data.html, it.data.text.trim())+ if (linkTitle) it.data.linkTitle = linkTitle+ }if (!it.data.hasFullPayload && it.data.text.length > 300) {this.writeTextPayload(it.id, it.data.text)it.data.hasFullPayload = true@@ -259,12 +265,22 @@ export class ItemStore {const existingId = this.sigToId.get(sig)const now = Date.now()+ // A link copied with its page title (browsers put `<a href>Title</a>` in+ // the html): keep the title for the card and search.+ if (data.kind === 'text' && data.isUrl && data.html && !data.linkTitle) {+ const linkTitle = linkTitleFromHtml(data.html, data.text.trim())+ if (linkTitle) data = { ...data, linkTitle }+ }+if (existingId) {const idx = this.items.findIndex((it) => it.id === existingId)if (idx >= 0) {const it = this.items[idx]- // Bump count and move to front.+ // Bump count and move to front (and learn the page title if this copy brought one).const updated: ClipboardItem = { ...it, hitCount: it.hitCount + 1, capturedAt: now }+ if (data.kind === 'text' && data.linkTitle && updated.data.kind === 'text' && !updated.data.linkTitle) {+ updated.data = { ...updated.data, linkTitle: data.linkTitle }+ }this.items.splice(idx, 1)this.items.unshift(updated)this.persist()@@ -850,6 +866,7 @@ export class ItemStore {isColor: d.isColor,hasFullPayload: d.hasFullPayload,previewText: d.previewText,+ linkTitle: d.linkTitle,// html itself stays in main (can be large); the renderer only// needs to know it exists to offer "Paste as plain text".hasHtml: !!d.htmldiff --git a/shared/linkText.ts b/shared/linkText.tsnew file mode 100644index 0000000..27a8d0a--- /dev/null+++ b/shared/linkText.ts@@ -0,0 +1,92 @@+/**+ * What counts as a copied link, and the page title a browser may copy with it.+ *+ * Shared by main (capture), the preload (drag-in) and the renderer, so a link+ * is recognized the same way wherever it comes from. Pure string work: no+ * network, no DOM.+ */++/** Links with a scheme or www.: anything without spaces. */+const SCHEME_LINK = /^(?:https?:\/\/|www\.)[^\s]+$/i+const MAILTO = /^mailto:[^\s@]+@[^\s@]+\.[^\s@]+$/i+const TEL = /^tel:\+?[\d\s().-]{5,}$/i++/**+ * Real top-level domains a bare "example.com/page" may end in. Kept to common+ * ones so ordinary text ("Node.js", "e.g.", "v1.2") never becomes a link.+ */+const TLDS = new Set([+ 'com', 'net', 'org', 'edu', 'gov', 'mil', 'int', 'info', 'biz', 'io', 'co', 'ai', 'app', 'dev', 'me', 'tv',+ 'in', 'uk', 'us', 'ca', 'au', 'de', 'fr', 'jp', 'cn', 'ru', 'br', 'it', 'es', 'nl', 'se', 'no', 'fi', 'dk', 'pl',+ 'ch', 'at', 'be', 'ie', 'nz', 'za', 'sg', 'hk', 'tw', 'kr', 'id', 'my', 'ph', 'vn', 'th', 'tr', 'ae', 'sa', 'il',+ 'eg', 'ng', 'ke', 'pk', 'bd', 'lk', 'np', 'mx', 'ar', 'cl', 'pe', 'eu', 'asia', 'xyz', 'online', 'site', 'tech',+ 'store', 'shop', 'blog', 'news', 'live', 'link', 'page', 'cloud', 'email', 'so', 'gg', 'ly', 'to', 'fm', 'sh',+ 'md', 'py', 'rs', 'cc', 'ws', 'one', 'zip', 'mov', 'design', 'studio', 'art', 'wiki', 'top', 'icu', 'pro', 'gl', 'gd', 'is'+])+/** TLDs that are also common file extensions ("notes.md", "logo.ai"): need a path to count. */+const NEEDS_PATH = new Set(['md', 'py', 'rs', 'sh', 'pl', 'cc', 'zip', 'mov', 'ai', 'so', 'app', 'is', 'to', 'gd'])+const BARE_LINK = /^((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+)([a-z]{2,24})(:\d{2,5})?([/?#][^\s]*)?$/i++/** True when the whole text is one link (scheme, www., mailto:, tel:, or a bare domain). */+export function isLinkText(text: string): boolean {+ const t = typeof text === 'string' ? text.trim() : ''+ if (!t || t.length > 8192) return false+ if (SCHEME_LINK.test(t) || MAILTO.test(t) || TEL.test(t)) return true+ const m = BARE_LINK.exec(t)+ if (!m) return false+ const tld = m[2].toLowerCase()+ if (!TLDS.has(tld)) return false+ if (NEEDS_PATH.has(tld) && !m[4]) return false+ return true+}++/* ------------------------------------------------------------------ */+/* Page title copied with the link */+/* ------------------------------------------------------------------ */++const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'" }++function decodeEntities(s: string): string {+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+|#39);/gi, (all, name: string) => {+ const n = name.toLowerCase()+ if (n.startsWith('#x')) {+ const code = parseInt(n.slice(2), 16)+ return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : all+ }+ if (n.startsWith('#')) {+ const code = parseInt(n.slice(1), 10)+ return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : all+ }+ return ENTITIES[n] ?? all+ })+}++/** Scheme, www., case of the host and a trailing slash don't make two links different. */+function sameLink(a: string, b: string): boolean {+ const norm = (s: string) => s.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').replace(/^www\./i, '').replace(/\/+(?=$|[?#])/, '').toLowerCase()+ return norm(a) === norm(b)+}++const TITLE_MAX = 200++/**+ * The page title a browser put on the clipboard next to the link (Edge+ * "friendly links" and other apps copy `<a href="link">Page title</a>`).+ * Only an anchor pointing at this same link counts, and only text that isn't+ * itself a link. Undefined when there is none.+ */+export function linkTitleFromHtml(html: string | undefined, link: string): string | undefined {+ if (!html || typeof html !== 'string' || html.length > 200000 || !link) return undefined+ const re = /<a\b[^>]*?\bhref\s*=\s*(["'])([\s\S]*?)\1[^>]*>([\s\S]*?)<\/a\s*>/gi+ let m: RegExpExecArray | null+ let guard = 0+ while ((m = re.exec(html)) && guard++ < 50) {+ const href = decodeEntities(m[2])+ if (!sameLink(href, link)) continue+ const text = decodeEntities(m[3].replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim()+ if (!text || sameLink(text, link) || isLinkText(text)) continue+ const chars = Array.from(text)+ return chars.length > TITLE_MAX ? chars.slice(0, TITLE_MAX - 1).join('').trimEnd() + '…' : text+ }+ return undefined+}diff --git a/shared/types.ts b/shared/types.tsindex 359a17a..30a1e41 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -63,7 +63,7 @@ export type ClipboardImageFields = {/** Discriminated union describing the payload of a clipboard item. */export type ItemData =- | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string }+ | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string; linkTitle?: string }| ({ kind: 'image' } & ClipboardImageFields)| { kind: 'image-collection'; images: ClipboardImageFields[] }| { kind: 'files'; paths: string[]; entries?: FileEntry[] }@@ -107,7 +107,7 @@ export interface FileEntry {/** Payload sent over IPC: same as ClipboardItem but with inline image previews. */export interface ClipboardItemDto extends Omit<ClipboardItem, 'data'> {data:- | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string; hasHtml?: boolean }+ | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string; hasHtml?: boolean; linkTitle?: string }| ({ kind: 'image'; preview: string } & ClipboardImageFields)| { kind: 'image-collection'; images: Array<ClipboardImageFields & { preview: string }> }| { kind: 'files'; paths: string[]; previews?: string[]; entries?: FileEntry[] }diff --git a/src/components/CardMenu.tsx b/src/components/CardMenu.tsxindex 1fe2363..975107f 100644--- a/src/components/CardMenu.tsx+++ b/src/components/CardMenu.tsx@@ -31,7 +31,7 @@ import { useTranslation } from '../i18n'import { edge } from '../lib/edge'import { tryPaste } from '../lib/tryPaste'import { colorFormats, type ColorFormat } from '../lib/colorUtils'-import { externalHref, stripTracking } from '../lib/urlPreview'+import { cleanLink, externalHref } from '../lib/urlPreview'import { acquireKeyboard, releaseKeyboard } from '../lib/keyboardFocus'import { playCardExpandSound, playDeleteSound, playToggleSound } from '../lib/soundEffects'import {@@ -365,7 +365,8 @@ function MenuList({ item }: { item: ClipboardItemDto }) {const isLink = isText && d.isUrlconst colors = isText && !d.isUrl ? colorFormats(text) : nullconst canPastePlain = isText && !colors && (!!d.hasHtml || text.includes('\t'))- const canCleanLink = isLink && (!!d.hasFullPayload || stripTracking(text) !== text.trim())+ // the real destination of a redirect link, tracking removed, stray punctuation dropped+ const canCleanLink = isLink && (!!d.hasFullPayload || cleanLink(text) !== text.trim())const isImage = d.kind === 'image' || d.kind === 'image-collection'const filePaths = d.kind === 'files' ? d.paths : []@@ -395,7 +396,7 @@ function MenuList({ item }: { item: ClipboardItemDto }) {label={t('menu.copyCleanLink')}onSelect={() => {close()- void fullTextOf(item).then((full) => store().copyText(stripTracking(full)))+ void fullTextOf(item).then((full) => store().copyText(cleanLink(full)))}}/>)diff --git a/src/components/ClipboardItem.tsx b/src/components/ClipboardItem.tsxindex b1ad7fa..e2a2a4e 100644--- a/src/components/ClipboardItem.tsx+++ b/src/components/ClipboardItem.tsx@@ -28,6 +28,7 @@ import { playButtonClickSound, playToggleSound, playDeleteSound, playCardExpandSimport { CopyIcon, FileKindIcon, FileStackPhoto, PinIcon, PinFillIcon, TrashIcon, MinusIcon, ChevronUpIcon, ChevronLeftIcon, ExpandIcon, ContractIcon, ExternalLinkIcon } from './icons'import { DashedOutline } from './DashedOutline'import { LinkPreviewCard } from './LinkPreviewCard'+import { parseUrlPreview } from '../lib/urlPreview'import { CodeBlock } from './CodeBlock'import { StackHeader, StackItems, fileStackEntries, imageCollectionEntries, stackOpenWidth } from './StackItems'import { detectCode } from '../lib/codeDetect'@@ -1601,7 +1602,7 @@ function Preview({ item }: { item: ClipboardItemDto }) {switch (item.data.kind) {case 'text': {if (item.data.isUrl) {- return <LinkPreviewCard url={item.data.text} />+ return <LinkPreviewCard url={item.data.text} pageTitle={item.data.linkTitle} />}const colorInfo = parseColor(item.data.text)if (colorInfo) {@@ -1755,13 +1756,8 @@ function ItemDetails({ item }: { item: ClipboardItemDto }) {switch (item.data.kind) {case 'text': {if (item.data.isUrl) {- let domain = ''- try {- const urlStr = item.data.text.startsWith('http://') || item.data.text.startsWith('https://')- ? item.data.text- : `https://${item.data.text}`- domain = new URL(urlStr).hostname.replace(/^www\./, '')- } catch {}+ // same readable host as the card (cached parse, international names decoded)+ const domain = parseUrlPreview(item.data.text).domainif (domain) {return <span className="meta-detail">· {domain}</span>}diff --git a/src/components/LinkPreviewCard.tsx b/src/components/LinkPreviewCard.tsxindex 4b26400..eb190c2 100644--- a/src/components/LinkPreviewCard.tsx+++ b/src/components/LinkPreviewCard.tsx@@ -4,32 +4,39 @@ import { LinkIcon } from './icons'interface LinkPreviewCardProps {url: string+ /** The page title copied with the link, when the browser provided one. */+ pageTitle?: stringcompact?: booleanonClick?: (e: React.MouseEvent) => void}+/**+ * A link card, worked out offline (lib/urlPreview.ts):+ * top — the site's name and what kind of page it is ("GitHub · Issue")+ * body — the page title copied with the link, else what the link itself+ * tells (repo, article, search, place), else the link+ * bottom — the link, readable, when the body shows a title+ */export const LinkPreviewCard: React.FC<LinkPreviewCardProps> = ({url,+ pageTitle,compact = false,onClick}) => {const info: UrlPreviewInfo = useMemo(() => parseUrlPreview(url), [url])- // Clean, professional display:- // Top: Link SVG + Domain (e.g. 🔗 github.com)- const domain = info.domain || 'link'+ const top = info.subtitle ? `${info.serviceName} · ${info.subtitle}` : info.serviceName+ const link = info.displayUrl || info.url- // Clean URL without protocol (e.g. linkedin.com/in/gaurav-jha-hr)- const displayUrl = info.cleanUrl.replace(/^https?:\/\//, '')-- // Main: Clean, human-readable title if distinct from domain and URL- const rawTitle = info.title?.trim()- const hasDistinctTitle = Boolean(- rawTitle &&- rawTitle.toLowerCase() !== displayUrl.toLowerCase() &&- rawTitle.toLowerCase() !== domain.toLowerCase()+ // The body says something the other two lines don't+ const candidate = (pageTitle || info.title || '').trim()+ const lower = candidate.toLowerCase()+ const hasTitle = Boolean(+ candidate &&+ lower !== link.toLowerCase() &&+ lower !== info.domain.toLowerCase() &&+ lower !== info.serviceName.toLowerCase())- const displayTitle = hasDistinctTitle ? rawTitle : displayUrlreturn (<div@@ -38,16 +45,16 @@ export const LinkPreviewCard: React.FC<LinkPreviewCardProps> = ({><div className="link-card-top"><LinkIcon width={12} height={12} className="link-card-icon" />- <span className="link-card-domain">{domain}</span>+ <span className="link-card-domain" title={top}>{top}</span></div>- <div className="link-card-body" title={info.cleanUrl}>- {displayTitle}+ <div className="link-card-body" title={hasTitle ? candidate : link}>+ {hasTitle ? candidate : link}</div>- {hasDistinctTitle && (- <div className="link-card-url" title={info.cleanUrl}>- {displayUrl}+ {hasTitle && (+ <div className="link-card-url" title={link}>+ {link}</div>)}</div>diff --git a/src/components/PreviewFlyout.tsx b/src/components/PreviewFlyout.tsxindex e278629..108fc40 100644--- a/src/components/PreviewFlyout.tsx+++ b/src/components/PreviewFlyout.tsx@@ -3,7 +3,7 @@ import { useStore } from '../store/appStore'import { formatBytes, formatImageDisplayName, relativeTime } from '../lib/format'import { getFileKind } from '../lib/fileType'import { FileKindIcon, FolderOpenIcon, CopyIcon, CheckIcon, ExternalLinkIcon, CloseIcon, GlobeIcon, TypeIcon, ImageIcon, PaletteIcon, FilesIcon } from './icons'-import { externalHref, parseUrlPreview, stripTracking } from '../lib/urlPreview'+import { cleanLink, externalHref, parseUrlPreview } from '../lib/urlPreview'import { colorFormats, parseColor } from '../lib/colorUtils'import { fitPreviewImage, type PreviewImageFit } from '../lib/previewImageFit'import { detectCode } from '../lib/codeDetect'@@ -688,6 +688,8 @@ function PreviewContent({if (isUrl) {const info = parseUrlPreview(activeText)+ // the page title copied with the link, else what the link itself tells+ const linkTitle = (item.data.linkTitle || info.title || '').trim()return frame(<FlyoutHead icon={<GlobeIcon />} title={info.serviceName} detail={info.domain} time={time}><QuickActionButton@@ -699,7 +701,7 @@ function PreviewContent({title={t('flyout.copyText')}icon={CopyIcon}// Through main (watcher paused): the copy is not captured as a new card.- onClick={() => void useStore.getState().copyText(stripTracking(activeText), { quiet: true })}+ onClick={() => void useStore.getState().copyText(cleanLink(activeText), { quiet: true })}/></FlyoutHead>,<div@@ -707,8 +709,8 @@ function PreviewContent({title={t('flyout.clickToPaste')}style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 12, cursor: 'pointer' }}>- {info.title && <div className="pf-link-title">{info.title}</div>}- {info.title && info.subtitle && <span className="pf-link-sub">{info.subtitle}</span>}+ {linkTitle && <div className="pf-link-title">{linkTitle}</div>}+ {info.subtitle && <span className="pf-link-sub">{info.subtitle}</span>}<divonClick={(e) => {e.stopPropagation()@@ -716,7 +718,7 @@ function PreviewContent({}}className="flyout-url">- {info.cleanUrl || activeText}+ {info.displayUrl || activeText}</div></div>)diff --git a/src/hooks/useFilteredItems.ts b/src/hooks/useFilteredItems.tsindex 8d58cf2..86e0a2f 100644--- a/src/hooks/useFilteredItems.ts+++ b/src/hooks/useFilteredItems.ts@@ -21,7 +21,8 @@ function itemText(it: ClipboardItemDto): SearchText {const d = it.data// Images have no text of their own: they are found through their note.const content = d.kind === 'text' ? d.text : d.kind === 'files' ? d.paths.map((p) => basename(p)).join('\n') : ''- text = searchText([content, it.note])+ // a link is also found by the page title copied with it+ text = searchText([content, d.kind === 'text' ? d.linkTitle : undefined, it.note])textCache.set(it, text)}return textdiff --git a/src/lib/itemSignature.ts b/src/lib/itemSignature.tsindex 29d7dd1..6b967e8 100644--- a/src/lib/itemSignature.ts+++ b/src/lib/itemSignature.ts@@ -26,7 +26,7 @@ export function itemRenderKey(item: ClipboardItemDto): string {// text feeds both the plain preview and the offline link-preview card;// isUrl switches the whole body layout. Do not include html: Excel// CF_HTML can be megabytes and cards never render it.- key = `t|${d.isUrl ? 1 : 0}|${d.isColor ? 1 : 0}|${d.text}`+ key = `t|${d.isUrl ? 1 : 0}|${d.isColor ? 1 : 0}|${d.linkTitle ?? ''}|${d.text}`breakcase 'image':key = `i|${d.imageId}|${d.width}x${d.height}|${d.bytes}|${d.ext ?? ''}|${d.source ?? ''}|${d.fileName ?? ''}|${d.preview}`diff --git a/src/lib/urlPreview.ts b/src/lib/urlPreview.tsindex e134d62..c291f7b 100644--- a/src/lib/urlPreview.ts+++ b/src/lib/urlPreview.ts@@ -1,30 +1,38 @@/**- * Enterprise-Grade, 100% Offline URL Intelligence & Semantic Extraction Engine.+ * Link cards, worked out offline from the link text alone (no network).*- * Capabilities:- * 1. Global Public Suffix (ccTLD/eTLD+1) Trie resolution (handling .co.uk, .com.au, .gov.in, etc.).- * 2. 200+ Curated Top-Tier Tech, Cloud, AI, Media, and Knowledge Platform Presets.- * 3. Intelligent Subdomain & Microservice Specialization (e.g., docs.github.com, music.apple.com).- * 4. Deep Semantic Path Interpreters for 18+ platform families (GitHub, GitLab, YouTube, Reddit,- * Spotify, Wikipedia, Figma, Notion, Linear, Google Workspace, ArXiv, Steam, NPM, etc.).- * 5. Natural Domain Name Humanizer for any unknown URL with acronym & camelCase awareness.- * 6. Aggressive Tracking & UTM Parameter Stripper for pristine canonical breadcrumbs.- * 7. Zero Network I/O, < 0.05ms Execution Budget, Guaranteed Exception-Free.+ * What a card shows: the site's name and what kind of page it is ("GitHub ·+ * Issue"), a title when the link tells one (a repo, an article slug, a search,+ * a place), and the link itself, readable (decoded, international domains in+ * their own script). Everything is string work: exact host matching against a+ * directory of known sites, page-type rules for common platforms, and for any+ * other site a scored pick of the path part that reads like a title (IDs,+ * hashes and filler words are skipped). Redirect wrappers are unwrapped to the+ * real destination; short links say so. Results are cached per link.*/export interface UrlPreviewInfo {+ /** The link as given (trimmed). */url: string+ /** The destination with tracking parameters removed (redirect wrappers unwrapped). */cleanUrl: string+ /** The link to show: readable, without scheme or credentials. */+ displayUrl: string+ /** Host to show (international domains decoded, no www.). */domain: stringrootDomain: string+ /** The site's name ("GitHub", "Times of India", "This computer"). */serviceName: string+ /** A title the link itself tells, when it says more than the site name. */title?: string+ /** What kind of page it is ("Issue", "Video", "Search", "Short link"). */subtitle?: string+ /** Path, query and hash of the destination, decoded. */displayPath: string}/* ------------------------------------------------------------------ */-/* 1. Comprehensive Global Multi-Part eTLD Suffix Registry */+/* Domains *//* ------------------------------------------------------------------ */const MULTI_PART_TLDS = new Set([@@ -35,7 +43,7 @@ const MULTI_PART_TLDS = new Set(['co.za', 'org.za', 'web.za', 'gov.za', 'ac.za', 'net.za',// Asia & Oceania'co.jp', 'ne.jp', 'or.jp', 'go.jp', 'ac.jp', 'ed.jp', 'lg.jp', 'ad.jp', 'gr.jp',- 'co.in', 'net.in', 'org.in', 'gen.in', 'firm.in', 'ind.in', 'gov.in', 'res.in', 'ac.in', 'edu.in', 'mil.in',+ 'co.in', 'net.in', 'org.in', 'gen.in', 'firm.in', 'ind.in', 'gov.in', 'res.in', 'ac.in', 'edu.in', 'mil.in', 'nic.in','co.kr', 'ne.kr', 'or.kr', 're.kr', 'pe.kr', 'go.kr', 'ac.kr', 'hs.kr', 'ms.kr', 'es.kr','com.sg', 'net.sg', 'org.sg', 'gov.sg', 'edu.sg', 'per.sg','com.tw', 'org.tw', 'net.tw', 'gov.tw', 'edu.tw', 'idv.tw', 'club.tw',@@ -50,11 +58,13 @@ const MULTI_PART_TLDS = new Set(['co.ae', 'net.ae', 'org.ae', 'gov.ae', 'ac.ae', 'sch.ae','com.sa', 'net.sa', 'org.sa', 'gov.sa', 'edu.sa', 'med.sa','com.pk', 'org.pk', 'gov.pk', 'edu.pk', 'net.pk',+ 'com.bd', 'org.bd', 'gov.bd', 'edu.bd', 'com.np', 'org.np', 'gov.np', 'com.lk', 'org.lk', 'gov.lk',// Europe'com.tr', 'org.tr', 'gov.tr', 'edu.tr', 'net.tr', 'k12.tr', 'av.tr', 'bel.tr','co.at', 'or.at', 'gv.at', 'ac.at','co.hu', 'org.hu', 'gov.hu', 'edu.hu','co.ee', 'org.ee', 'fie.ee', 'med.ee',+ 'com.pl', 'org.pl', 'net.pl', 'gov.pl', 'com.ua', 'org.ua', 'gov.ua', 'com.ru', 'org.ru', 'com.gr', 'gov.gr', 'com.es', 'gob.es', 'co.it',// Americas'com.br', 'net.br', 'org.br', 'gov.br', 'edu.br', 'art.br', 'app.br', 'dev.br', 'srv.br','com.mx', 'org.mx', 'gob.mx', 'edu.mx', 'net.mx',@@ -70,290 +80,237 @@ const MULTI_PART_TLDS = new Set([])/* ------------------------------------------------------------------ */-/* 2. 200+ Curated Top-Tier Platform & Company Directory */+/* Known sites (exact host, or any subdomain of it) *//* ------------------------------------------------------------------ */const BRAND_DIRECTORY: Record<string, string> = {// Developer & Infrastructure- 'github.com': 'GitHub',- 'gist.github.com': 'GitHub Gist',- 'docs.github.com': 'GitHub Docs',- 'gitlab.com': 'GitLab',- 'bitbucket.org': 'Bitbucket',- 'codeberg.org': 'Codeberg',- 'stackoverflow.com': 'Stack Overflow',- 'stackexchange.com': 'Stack Exchange',- 'superuser.com': 'Super User',- 'serverfault.com': 'Server Fault',- 'askubuntu.com': 'Ask Ubuntu',- 'npmjs.com': 'npm',- 'pypi.org': 'PyPI',- 'crates.io': 'crates.io',- 'packagist.org': 'Packagist',- 'rubygems.org': 'RubyGems',- 'pkg.go.dev': 'Go Packages',- 'hub.docker.com': 'Docker Hub',- 'codepen.io': 'CodePen',- 'jsfiddle.net': 'JSFiddle',- 'replit.com': 'Replit',- 'codesandbox.io': 'CodeSandbox',- 'stackblitz.com': 'StackBlitz',- 'jsdelivr.com': 'jsDelivr',- 'cdnjs.com': 'cdnjs',- 'vercel.com': 'Vercel',- 'vercel.app': 'Vercel App',- 'netlify.com': 'Netlify',- 'netlify.app': 'Netlify App',- 'render.com': 'Render',- 'railway.app': 'Railway',- 'fly.io': 'Fly.io',- 'supabase.com': 'Supabase',- 'firebase.google.com': 'Firebase',- 'cloudflare.com': 'Cloudflare',- 'aws.amazon.com': 'AWS',- 'digitalocean.com': 'DigitalOcean',- 'heroku.com': 'Heroku',- 'neon.tech': 'Neon Database',- 'planetscale.com': 'PlanetScale',- 'upstash.com': 'Upstash',- 'sentry.io': 'Sentry',- 'datadoghq.com': 'Datadog',- 'postman.com': 'Postman',- 'swagger.io': 'Swagger',+ 'github.com': 'GitHub', 'gist.github.com': 'GitHub Gist', 'docs.github.com': 'GitHub Docs',+ 'githubusercontent.com': 'GitHub', 'github.io': 'GitHub Pages', 'github.dev': 'GitHub',+ 'gitlab.com': 'GitLab', 'bitbucket.org': 'Bitbucket', 'codeberg.org': 'Codeberg',+ 'stackoverflow.com': 'Stack Overflow', 'stackexchange.com': 'Stack Exchange', 'superuser.com': 'Super User',+ 'serverfault.com': 'Server Fault', 'askubuntu.com': 'Ask Ubuntu', 'mathoverflow.net': 'MathOverflow',+ 'npmjs.com': 'npm', 'pypi.org': 'PyPI', 'crates.io': 'crates.io', 'packagist.org': 'Packagist', 'rubygems.org': 'RubyGems',+ 'pkg.go.dev': 'Go Packages', 'hub.docker.com': 'Docker Hub', 'docker.com': 'Docker', 'nuget.org': 'NuGet',+ 'codepen.io': 'CodePen', 'jsfiddle.net': 'JSFiddle', 'replit.com': 'Replit', 'codesandbox.io': 'CodeSandbox', 'stackblitz.com': 'StackBlitz',+ 'jsdelivr.com': 'jsDelivr', 'cdnjs.com': 'cdnjs', 'unpkg.com': 'unpkg',+ 'vercel.com': 'Vercel', 'vercel.app': 'Vercel', 'netlify.com': 'Netlify', 'netlify.app': 'Netlify', 'render.com': 'Render',+ 'railway.app': 'Railway', 'fly.io': 'Fly.io', 'supabase.com': 'Supabase', 'firebase.google.com': 'Firebase',+ 'cloudflare.com': 'Cloudflare', 'pages.dev': 'Cloudflare Pages', 'workers.dev': 'Cloudflare Workers',+ 'aws.amazon.com': 'AWS', 'console.aws.amazon.com': 'AWS Console', 'digitalocean.com': 'DigitalOcean', 'heroku.com': 'Heroku', 'herokuapp.com': 'Heroku',+ 'neon.tech': 'Neon', 'planetscale.com': 'PlanetScale', 'upstash.com': 'Upstash', 'sentry.io': 'Sentry', 'datadoghq.com': 'Datadog',+ 'postman.com': 'Postman', 'swagger.io': 'Swagger', 'readthedocs.io': 'Read the Docs', 'gitbook.io': 'GitBook',+ 'developer.mozilla.org': 'MDN Web Docs', 'w3schools.com': 'W3Schools', 'freecodecamp.org': 'freeCodeCamp',+ 'geeksforgeeks.org': 'GeeksforGeeks', 'leetcode.com': 'LeetCode', 'hackerrank.com': 'HackerRank', 'codeforces.com': 'Codeforces', 'codechef.com': 'CodeChef',+ 'tailwindcss.com': 'Tailwind CSS', 'react.dev': 'React', 'reactjs.org': 'React', 'vuejs.org': 'Vue.js', 'svelte.dev': 'Svelte', 'angular.dev': 'Angular', 'angular.io': 'Angular',+ 'nextjs.org': 'Next.js', 'nodejs.org': 'Node.js', 'deno.com': 'Deno', 'bun.sh': 'Bun', 'typescriptlang.org': 'TypeScript',+ 'python.org': 'Python', 'docs.python.org': 'Python Docs', 'rust-lang.org': 'Rust', 'go.dev': 'Go', 'kotlinlang.org': 'Kotlin',+ 'learn.microsoft.com': 'Microsoft Learn', 'electronjs.org': 'Electron', 'vitejs.dev': 'Vite', 'vite.dev': 'Vite',// AI & Machine Learning- 'openai.com': 'OpenAI',- 'chatgpt.com': 'ChatGPT',- 'chat.openai.com': 'ChatGPT',- 'anthropic.com': 'Anthropic',- 'claude.ai': 'Claude',- 'perplexity.ai': 'Perplexity',- 'gemini.google.com': 'Google Gemini',- 'huggingface.co': 'Hugging Face',- 'kaggle.com': 'Kaggle',- 'midjourney.com': 'Midjourney',- 'stability.ai': 'Stability AI',- 'replicate.com': 'Replicate',- 'mistral.ai': 'Mistral AI',- 'cohere.com': 'Cohere',- 'elevenlabs.io': 'ElevenLabs',- 'runwayml.com': 'Runway',- 'suno.com': 'Suno AI',- 'civitai.com': 'Civitai',- 'cursor.com': 'Cursor',- 'cursor.sh': 'Cursor',- 'phind.com': 'Phind',- 'deepseek.com': 'DeepSeek',- 'x.ai': 'Grok / xAI',- 'grok.com': 'Grok',-- // Design, Prototyping & Creative- 'figma.com': 'Figma',- 'dribbble.com': 'Dribbble',- 'behance.net': 'Behance',- 'canva.com': 'Canva',- 'adobe.com': 'Adobe',- 'artstation.com': 'ArtStation',- 'unsplash.com': 'Unsplash',- 'pexels.com': 'Pexels',- 'freepik.com': 'Freepik',- 'spline.design': 'Spline 3D',- 'webflow.com': 'Webflow',- 'framer.com': 'Framer',- 'fontawesome.com': 'Font Awesome',- 'iconify.design': 'Iconify',- 'lucide.dev': 'Lucide Icons',-- // Productivity, Workspace & Collaboration- 'notion.so': 'Notion',- 'notion.site': 'Notion',- 'obsidian.md': 'Obsidian',- 'linear.app': 'Linear',- 'jira.atlassian.com': 'Jira',- 'atlassian.net': 'Atlassian',- 'confluence.atlassian.com': 'Confluence',- 'trello.com': 'Trello',- 'asana.com': 'Asana',- 'monday.com': 'Monday.com',- 'clickup.com': 'ClickUp',- 'basecamp.com': 'Basecamp',- 'airtable.com': 'Airtable',- 'coda.io': 'Coda',- 'miro.com': 'Miro',- 'lucidchart.com': 'Lucidchart',- 'dropbox.com': 'Dropbox',- 'box.com': 'Box',- 'evernote.com': 'Evernote',- 'raycast.com': 'Raycast',- 'loom.com': 'Loom',- 'calendly.com': 'Calendly',-- // Google Workspace Ecosystem- 'google.com': 'Google',- 'docs.google.com': 'Google Docs',- 'drive.google.com': 'Google Drive',- 'maps.google.com': 'Google Maps',- 'meet.google.com': 'Google Meet',- 'calendar.google.com': 'Google Calendar',- 'mail.google.com': 'Gmail',- 'photos.google.com': 'Google Photos',- 'keep.google.com': 'Google Keep',- 'cloud.google.com': 'Google Cloud',-- // Microsoft Ecosystem- 'microsoft.com': 'Microsoft',- 'office.com': 'Microsoft 365',- 'live.com': 'Microsoft Live',- 'outlook.com': 'Outlook',- 'teams.microsoft.com': 'Microsoft Teams',- 'onedrive.live.com': 'OneDrive',- 'azure.microsoft.com': 'Azure',-- // Apple Ecosystem- 'apple.com': 'Apple',- 'icloud.com': 'iCloud',- 'developer.apple.com': 'Apple Developer',- 'music.apple.com': 'Apple Music',- 'podcasts.apple.com': 'Apple Podcasts',- 'tv.apple.com': 'Apple TV+',-- // Social, Communities & Messaging- 'twitter.com': 'X / Twitter',- 'x.com': 'X',- 'reddit.com': 'Reddit',- 'discord.com': 'Discord',- 'discord.gg': 'Discord',- 'slack.com': 'Slack',- 'telegram.org': 'Telegram',- 't.me': 'Telegram',- 'whatsapp.com': 'WhatsApp',- 'wa.me': 'WhatsApp',- 'signal.org': 'Signal',- 'threads.net': 'Threads',- 'bsky.app': 'Bluesky',- 'instagram.com': 'Instagram',- 'facebook.com': 'Facebook',- 'fb.com': 'Facebook',- 'linkedin.com': 'LinkedIn',- 'pinterest.com': 'Pinterest',- 'tiktok.com': 'TikTok',- 'snapchat.com': 'Snapchat',- 'tumblr.com': 'Tumblr',- 'quora.com': 'Quora',- 'medium.com': 'Medium',- 'substack.com': 'Substack',- 'dev.to': 'DEV Community',- 'hashnode.com': 'Hashnode',- 'producthunt.com': 'Product Hunt',- 'news.ycombinator.com': 'Hacker News',-- // Video, Streaming & Entertainment- 'youtube.com': 'YouTube',- 'youtu.be': 'YouTube',- 'music.youtube.com': 'YouTube Music',- 'vimeo.com': 'Vimeo',- 'twitch.tv': 'Twitch',- 'netflix.com': 'Netflix',- 'primevideo.com': 'Prime Video',- 'disneyplus.com': 'Disney+',- 'hulu.com': 'Hulu',- 'max.com': 'Max',- 'spotify.com': 'Spotify',- 'soundcloud.com': 'SoundCloud',- 'tidal.com': 'Tidal',- 'bandcamp.com': 'Bandcamp',- 'deezer.com': 'Deezer',- 'imdb.com': 'IMDb',- 'rottentomatoes.com': 'Rotten Tomatoes',- 'letterboxd.com': 'Letterboxd',- 'goodreads.com': 'Goodreads',- 'audible.com': 'Audible',+ 'openai.com': 'OpenAI', 'platform.openai.com': 'OpenAI Platform', 'chatgpt.com': 'ChatGPT', 'chat.openai.com': 'ChatGPT',+ 'anthropic.com': 'Anthropic', 'claude.ai': 'Claude', 'console.anthropic.com': 'Anthropic Console',+ 'perplexity.ai': 'Perplexity', 'gemini.google.com': 'Google Gemini', 'aistudio.google.com': 'Google AI Studio', 'notebooklm.google.com': 'NotebookLM',+ 'huggingface.co': 'Hugging Face', 'kaggle.com': 'Kaggle', 'midjourney.com': 'Midjourney', 'stability.ai': 'Stability AI',+ 'replicate.com': 'Replicate', 'mistral.ai': 'Mistral AI', 'chat.mistral.ai': 'Le Chat', 'cohere.com': 'Cohere', 'elevenlabs.io': 'ElevenLabs',+ 'runwayml.com': 'Runway', 'suno.com': 'Suno', 'civitai.com': 'Civitai', 'cursor.com': 'Cursor', 'cursor.sh': 'Cursor',+ 'phind.com': 'Phind', 'deepseek.com': 'DeepSeek', 'chat.deepseek.com': 'DeepSeek', 'x.ai': 'xAI', 'grok.com': 'Grok', 'copilot.microsoft.com': 'Microsoft Copilot',+ 'poe.com': 'Poe', 'character.ai': 'Character.AI',++ // Design & Creative+ 'figma.com': 'Figma', 'dribbble.com': 'Dribbble', 'behance.net': 'Behance', 'canva.com': 'Canva', 'adobe.com': 'Adobe',+ 'artstation.com': 'ArtStation', 'unsplash.com': 'Unsplash', 'pexels.com': 'Pexels', 'freepik.com': 'Freepik', 'pixabay.com': 'Pixabay',+ 'spline.design': 'Spline', 'webflow.com': 'Webflow', 'webflow.io': 'Webflow', 'framer.com': 'Framer', 'framer.website': 'Framer', 'framer.app': 'Framer',+ 'fontawesome.com': 'Font Awesome', 'fonts.google.com': 'Google Fonts', 'iconify.design': 'Iconify', 'lucide.dev': 'Lucide', 'coolors.co': 'Coolors',++ // Productivity & Collaboration+ 'notion.so': 'Notion', 'notion.site': 'Notion', 'obsidian.md': 'Obsidian', 'linear.app': 'Linear',+ 'atlassian.net': 'Atlassian', 'atlassian.com': 'Atlassian', 'jira.atlassian.com': 'Jira', 'confluence.atlassian.com': 'Confluence', 'trello.com': 'Trello',+ 'asana.com': 'Asana', 'monday.com': 'monday.com', 'clickup.com': 'ClickUp', 'basecamp.com': 'Basecamp', 'airtable.com': 'Airtable',+ 'coda.io': 'Coda', 'miro.com': 'Miro', 'lucidchart.com': 'Lucidchart', 'excalidraw.com': 'Excalidraw',+ 'dropbox.com': 'Dropbox', 'box.com': 'Box', 'evernote.com': 'Evernote', 'raycast.com': 'Raycast', 'loom.com': 'Loom', 'calendly.com': 'Calendly',+ 'zoom.us': 'Zoom', 'zoom.com': 'Zoom', 'webex.com': 'Webex', 'whereby.com': 'Whereby', 'typeform.com': 'Typeform', 'tally.so': 'Tally',++ 'google.com': 'Google', 'docs.google.com': 'Google Docs', 'drive.google.com': 'Google Drive', 'maps.google.com': 'Google Maps',+ 'meet.google.com': 'Google Meet', 'calendar.google.com': 'Google Calendar', 'mail.google.com': 'Gmail', 'photos.google.com': 'Google Photos',+ 'keep.google.com': 'Google Keep', 'cloud.google.com': 'Google Cloud', 'console.cloud.google.com': 'Google Cloud Console',+ 'play.google.com': 'Google Play', 'news.google.com': 'Google News', 'translate.google.com': 'Google Translate',+ 'sites.google.com': 'Google Sites', 'chat.google.com': 'Google Chat', 'scholar.google.com': 'Google Scholar', 'books.google.com': 'Google Books',+ 'forms.gle': 'Google Forms', 'g.co': 'Google', 'goo.gl': 'Google', 'maps.app.goo.gl': 'Google Maps', 'blogspot.com': 'Blogger', 'blogger.com': 'Blogger',+ 'web.app': 'Firebase', 'firebaseapp.com': 'Firebase',++ // Microsoft+ 'microsoft.com': 'Microsoft', 'office.com': 'Microsoft 365', 'microsoft365.com': 'Microsoft 365', 'live.com': 'Microsoft', 'outlook.com': 'Outlook',+ 'outlook.live.com': 'Outlook', 'outlook.office.com': 'Outlook', 'teams.microsoft.com': 'Microsoft Teams', 'teams.live.com': 'Microsoft Teams',+ 'onedrive.live.com': 'OneDrive', '1drv.ms': 'OneDrive', 'sharepoint.com': 'SharePoint', 'azure.microsoft.com': 'Azure', 'portal.azure.com': 'Azure Portal',+ 'bing.com': 'Bing', 'msn.com': 'MSN', 'aka.ms': 'Microsoft', 'apps.microsoft.com': 'Microsoft Store', 'xbox.com': 'Xbox', 'linkedin.com': 'LinkedIn', 'lnkd.in': 'LinkedIn',++ // Apple+ 'apple.com': 'Apple', 'icloud.com': 'iCloud', 'developer.apple.com': 'Apple Developer', 'music.apple.com': 'Apple Music',+ 'podcasts.apple.com': 'Apple Podcasts', 'tv.apple.com': 'Apple TV', 'apps.apple.com': 'App Store', 'support.apple.com': 'Apple Support', 'apple.co': 'Apple',++ // Social & Messaging+ 'twitter.com': 'X', 'x.com': 'X', 't.co': 'X', 'reddit.com': 'Reddit', 'redd.it': 'Reddit', 'discord.com': 'Discord', 'discord.gg': 'Discord',+ 'slack.com': 'Slack', 'telegram.org': 'Telegram', 't.me': 'Telegram', 'telegram.me': 'Telegram', 'web.telegram.org': 'Telegram Web',+ 'whatsapp.com': 'WhatsApp', 'web.whatsapp.com': 'WhatsApp Web', 'chat.whatsapp.com': 'WhatsApp', 'wa.me': 'WhatsApp',+ 'signal.org': 'Signal', 'signal.me': 'Signal', 'threads.net': 'Threads', 'threads.com': 'Threads', 'bsky.app': 'Bluesky', 'mastodon.social': 'Mastodon',+ 'instagram.com': 'Instagram', 'instagr.am': 'Instagram', 'facebook.com': 'Facebook', 'fb.com': 'Facebook', 'fb.me': 'Facebook', 'fb.watch': 'Facebook',+ 'messenger.com': 'Messenger', 'pinterest.com': 'Pinterest', 'pin.it': 'Pinterest', 'tiktok.com': 'TikTok', 'snapchat.com': 'Snapchat', 'tumblr.com': 'Tumblr',+ 'quora.com': 'Quora', 'medium.com': 'Medium', 'substack.com': 'Substack', 'dev.to': 'DEV Community', 'hashnode.com': 'Hashnode', 'hashnode.dev': 'Hashnode',+ 'producthunt.com': 'Product Hunt', 'news.ycombinator.com': 'Hacker News', 'linktr.ee': 'Linktree', 'wordpress.com': 'WordPress', 'ghost.io': 'Ghost',++ // Video, Music & Entertainment+ 'youtube.com': 'YouTube', 'youtu.be': 'YouTube', 'music.youtube.com': 'YouTube Music', 'studio.youtube.com': 'YouTube Studio',+ 'vimeo.com': 'Vimeo', 'twitch.tv': 'Twitch', 'netflix.com': 'Netflix', 'primevideo.com': 'Prime Video', 'disneyplus.com': 'Disney+',+ 'hotstar.com': 'JioHotstar', 'jiohotstar.com': 'JioHotstar', 'jiocinema.com': 'JioCinema', 'sonyliv.com': 'SonyLIV', 'zee5.com': 'ZEE5',+ 'hulu.com': 'Hulu', 'max.com': 'Max', 'spotify.com': 'Spotify', 'spotify.link': 'Spotify', 'spoti.fi': 'Spotify',+ 'soundcloud.com': 'SoundCloud', 'tidal.com': 'Tidal', 'bandcamp.com': 'Bandcamp', 'deezer.com': 'Deezer', 'gaana.com': 'Gaana', 'jiosaavn.com': 'JioSaavn',+ 'wynk.in': 'Wynk Music', 'imdb.com': 'IMDb', 'rottentomatoes.com': 'Rotten Tomatoes', 'letterboxd.com': 'Letterboxd',+ 'goodreads.com': 'Goodreads', 'audible.com': 'Audible', 'audible.in': 'Audible',// Gaming- 'steampowered.com': 'Steam',- 'steamcommunity.com': 'Steam',- 'epicgames.com': 'Epic Games',- 'playstation.com': 'PlayStation',- 'xbox.com': 'Xbox',- 'nintendo.com': 'Nintendo',- 'roblox.com': 'Roblox',- 'gog.com': 'GOG.com',- 'itch.io': 'itch.io',-- // E-Commerce & Finance- 'amazon.com': 'Amazon',- 'ebay.com': 'eBay',- 'aliexpress.com': 'AliExpress',- 'shopify.com': 'Shopify',- 'etsy.com': 'Etsy',- 'walmart.com': 'Walmart',- 'target.com': 'Target',- 'bestbuy.com': 'Best Buy',- 'stripe.com': 'Stripe',- 'paypal.com': 'PayPal',- 'wise.com': 'Wise',- 'coinbase.com': 'Coinbase',- 'binance.com': 'Binance',- 'robinhood.com': 'Robinhood',-- // News, Knowledge & Publications- 'wikipedia.org': 'Wikipedia',- 'wikimedia.org': 'Wikimedia',- 'wiktionary.org': 'Wiktionary',- 'theverge.com': 'The Verge',- 'techcrunch.com': 'TechCrunch',- 'wired.com': 'WIRED',- 'arstechnica.com': 'Ars Technica',- 'engadget.com': 'Engadget',- '9to5mac.com': '9to5Mac',- 'macrumors.com': 'MacRumors',- 'androidauthority.com': 'Android Authority',- 'nytimes.com': 'The New York Times',- 'wsj.com': 'The Wall Street Journal',- 'washingtonpost.com': 'The Washington Post',- 'bloomberg.com': 'Bloomberg',- 'reuters.com': 'Reuters',- 'ft.com': 'Financial Times',- 'forbes.com': 'Forbes',- 'bbc.com': 'BBC',- 'cnn.com': 'CNN',- 'theguardian.com': 'The Guardian',- 'ign.com': 'IGN',- 'polygon.com': 'Polygon',- 'arxiv.org': 'arXiv',- 'nature.com': 'Nature',- 'sciencedirect.com': 'ScienceDirect',- 'pubmed.ncbi.nlm.nih.gov': 'PubMed'+ 'steampowered.com': 'Steam', 'steamcommunity.com': 'Steam', 'epicgames.com': 'Epic Games', 'playstation.com': 'PlayStation',+ 'nintendo.com': 'Nintendo', 'roblox.com': 'Roblox', 'gog.com': 'GOG', 'itch.io': 'itch.io', 'chess.com': 'Chess.com', 'lichess.org': 'Lichess',++ // Shopping, Food, Travel & Finance+ 'amazon.com': 'Amazon', 'amzn.to': 'Amazon', 'amzn.in': 'Amazon', 'amzn.eu': 'Amazon', 'a.co': 'Amazon',+ 'ebay.com': 'eBay', 'aliexpress.com': 'AliExpress', 'shopify.com': 'Shopify', 'myshopify.com': 'Shopify', 'etsy.com': 'Etsy',+ 'walmart.com': 'Walmart', 'target.com': 'Target', 'bestbuy.com': 'Best Buy', 'ikea.com': 'IKEA',+ 'flipkart.com': 'Flipkart', 'dl.flipkart.com': 'Flipkart', 'myntra.com': 'Myntra', 'meesho.com': 'Meesho', 'nykaa.com': 'Nykaa',+ 'ajio.com': 'AJIO', 'snapdeal.com': 'Snapdeal', 'bigbasket.com': 'BigBasket', 'blinkit.com': 'Blinkit', 'zeptonow.com': 'Zepto',+ 'swiggy.com': 'Swiggy', 'zomato.com': 'Zomato', 'uber.com': 'Uber', 'olacabs.com': 'Ola', 'rapido.bike': 'Rapido',+ 'makemytrip.com': 'MakeMyTrip', 'goibibo.com': 'Goibibo', 'cleartrip.com': 'Cleartrip', 'bookmyshow.com': 'BookMyShow',+ 'irctc.co.in': 'IRCTC', 'booking.com': 'Booking.com', 'airbnb.com': 'Airbnb', 'tripadvisor.com': 'Tripadvisor', 'expedia.com': 'Expedia', 'skyscanner.net': 'Skyscanner',+ 'stripe.com': 'Stripe', 'paypal.com': 'PayPal', 'paypal.me': 'PayPal', 'wise.com': 'Wise', 'coinbase.com': 'Coinbase', 'binance.com': 'Binance', 'robinhood.com': 'Robinhood',+ 'paytm.com': 'Paytm', 'phonepe.com': 'PhonePe', 'razorpay.com': 'Razorpay', 'groww.in': 'Groww', 'zerodha.com': 'Zerodha', 'kite.zerodha.com': 'Kite',+ 'moneycontrol.com': 'Moneycontrol', 'onlinesbi.sbi': 'SBI', 'sbi.co.in': 'SBI', 'hdfcbank.com': 'HDFC Bank', 'icicibank.com': 'ICICI Bank', 'axisbank.com': 'Axis Bank',+ 'uidai.gov.in': 'UIDAI', 'incometax.gov.in': 'Income Tax India', 'digilocker.gov.in': 'DigiLocker', 'naukri.com': 'Naukri',+ 'indeed.com': 'Indeed', 'glassdoor.com': 'Glassdoor', 'internshala.com': 'Internshala',++ // Learning+ 'coursera.org': 'Coursera', 'udemy.com': 'Udemy', 'edx.org': 'edX', 'khanacademy.org': 'Khan Academy', 'unacademy.com': 'Unacademy',+ 'byjus.com': "BYJU'S", 'duolingo.com': 'Duolingo', 'brilliant.org': 'Brilliant', 'nptel.ac.in': 'NPTEL', 'swayam.gov.in': 'SWAYAM',++ // News & Knowledge+ 'wikipedia.org': 'Wikipedia', 'wikimedia.org': 'Wikimedia', 'wiktionary.org': 'Wiktionary', 'wikihow.com': 'wikiHow', 'britannica.com': 'Britannica',+ 'theverge.com': 'The Verge', 'techcrunch.com': 'TechCrunch', 'wired.com': 'WIRED', 'arstechnica.com': 'Ars Technica', 'engadget.com': 'Engadget',+ '9to5mac.com': '9to5Mac', '9to5google.com': '9to5Google', 'macrumors.com': 'MacRumors', 'androidauthority.com': 'Android Authority', 'gsmarena.com': 'GSMArena',+ 'nytimes.com': 'The New York Times', 'wsj.com': 'The Wall Street Journal', 'washingtonpost.com': 'The Washington Post', 'bloomberg.com': 'Bloomberg',+ 'reuters.com': 'Reuters', 'apnews.com': 'AP News', 'ft.com': 'Financial Times', 'economist.com': 'The Economist', 'forbes.com': 'Forbes',+ 'bbc.com': 'BBC', 'bbc.co.uk': 'BBC', 'cnn.com': 'CNN', 'theguardian.com': 'The Guardian', 'aljazeera.com': 'Al Jazeera', 'ign.com': 'IGN', 'polygon.com': 'Polygon',+ 'timesofindia.indiatimes.com': 'Times of India', 'economictimes.indiatimes.com': 'The Economic Times', 'indiatimes.com': 'Indiatimes',+ 'ndtv.com': 'NDTV', 'thehindu.com': 'The Hindu', 'hindustantimes.com': 'Hindustan Times', 'indianexpress.com': 'The Indian Express',+ 'livemint.com': 'Mint', 'news18.com': 'News18', 'indiatoday.in': 'India Today', 'aajtak.in': 'Aaj Tak', 'thewire.in': 'The Wire', 'scroll.in': 'Scroll',+ 'arxiv.org': 'arXiv', 'nature.com': 'Nature', 'sciencedirect.com': 'ScienceDirect', 'pubmed.ncbi.nlm.nih.gov': 'PubMed', 'researchgate.net': 'ResearchGate',+ 'doi.org': 'DOI', 'archive.org': 'Internet Archive', 'web.archive.org': 'Wayback Machine',++ // Short-link services+ 'bit.ly': 'Bitly', 'bitly.com': 'Bitly', 'tinyurl.com': 'TinyURL', 'ow.ly': 'Hootsuite', 'buff.ly': 'Buffer', 'rebrand.ly': 'Rebrandly',+ 'is.gd': 'is.gd', 'v.gd': 'v.gd', 'cutt.ly': 'Cuttly', 'rb.gy': 'rb.gy', 'shorturl.at': 'ShortURL', 's.id': 's.id', 't.ly': 'T.LY',+ 'bl.ink': 'BL.INK', 'dub.sh': 'Dub', 'tiny.cc': 'tiny.cc', 'ift.tt': 'IFTTT', 'lnk.to': 'Linkfire', 'trib.al': 'Trib.al', 'surl.li': 'surl.li',+ 'msft.it': 'Microsoft', 'shorte.st': 'Shorte.st',++ // Search engines+ 'duckduckgo.com': 'DuckDuckGo', 'search.yahoo.com': 'Yahoo Search', 'yahoo.com': 'Yahoo', 'baidu.com': 'Baidu', 'yandex.com': 'Yandex',+ 'yandex.ru': 'Yandex', 'ecosia.org': 'Ecosia', 'search.brave.com': 'Brave Search', 'brave.com': 'Brave', 'startpage.com': 'Startpage', 'mozilla.org': 'Mozilla'}+/**+ * Sites people build on as subdomains (you.github.io, app.vercel.app): the+ * subdomain is the site, the platform says where it is hosted.+ */+const HOSTED_PLATFORMS = new Set([+ 'github.io', 'vercel.app', 'netlify.app', 'pages.dev', 'workers.dev', 'web.app', 'firebaseapp.com', 'herokuapp.com',+ 'blogspot.com', 'wordpress.com', 'substack.com', 'medium.com', 'notion.site', 'webflow.io', 'framer.website', 'framer.app',+ 'gitbook.io', 'readthedocs.io', 'tumblr.com', 'myshopify.com', 'hashnode.dev', 'ghost.io', 'wixsite.com', 'carrd.co',+ 'neocities.org', 'glitch.me', 'surge.sh', 'onrender.com', 'fly.dev', 'replit.app', 'streamlit.app', 'bearblog.dev'+])++/** Short-link services: the destination can't be known offline. */+const SHORTENERS = new Set([+ 'bit.ly', 'bitly.com', 't.co', 'tinyurl.com', 'ow.ly', 'buff.ly', 'rebrand.ly', 'is.gd', 'v.gd', 'cutt.ly', 'rb.gy', 'shorturl.at',+ 's.id', 't.ly', 'bl.ink', 'dub.sh', 'tiny.cc', 'shorte.st', 'lnkd.in', 'amzn.to', 'amzn.in', 'amzn.eu', 'a.co', 'goo.gl', 'maps.app.goo.gl',+ 'forms.gle', 'g.co', 'fb.me', 'pin.it', 'spoti.fi', 'spotify.link', 'apple.co', 'aka.ms', '1drv.ms', 'redd.it',+ 'dl.flipkart.com', 'vm.tiktok.com', 'vt.tiktok.com', 'instagr.am', 'trib.al', 'ift.tt', 'lnk.to', 'msft.it', 'surl.li'+])+/* ------------------------------------------------------------------ */-/* 3. Tracking Query Parameters to Strip */+/* Tracking parameters *//* ------------------------------------------------------------------ */-const TRACKING_PARAM_PREFIXES = ['utm_', 'ga_', 'mc_', 'hs_']+const TRACKING_PARAM_PREFIXES = ['utm_', 'ga_', 'mc_', 'hs_', 'pk_', 'mtm_']const TRACKING_PARAMS = new Set(['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_id',- 'fbclid', 'gclid', 'dclid', 'msclkid', 'twclid', 'gbraid', 'wbraid',- 'ref', 'ref_src', 'ref_url', 'source', 'si', 'igshid', 'feature', 'trk',- '_hsenc', '_hsmi', 'mc_cid', 'mc_eid', 'yclid', 'zanpid', 'sc_cid',- 'mkt_tok', 'spReportId', '__twitter_impression', 'vero_id', 'vero_conv'+ 'fbclid', 'gclid', 'dclid', 'msclkid', 'twclid', 'gbraid', 'wbraid', 'ttclid', 'li_fat_id', 'epik', 'srsltid',+ 'ref', 'ref_src', 'ref_url', 'source', 'si', 'igshid', 'igsh', 'feature', 'trk', 'trkid', 'pp',+ '_hsenc', '_hsmi', 'mc_cid', 'mc_eid', 'yclid', 'zanpid', 'sc_cid', 'cmpid', 'icid', 'ncid',+ 'mkt_tok', 'spreportid', '__twitter_impression', 'vero_id', 'vero_conv', 'oly_anon_id', 'oly_enc_id', 'rb_clickid', 's_cid', 'share_id'])+function isTrackingParam(key: string): boolean {+ const k = key.toLowerCase()+ return TRACKING_PARAMS.has(k) || TRACKING_PARAM_PREFIXES.some((p) => k.startsWith(p))+}++/* ------------------------------------------------------------------ */+/* Text helpers */+/* ------------------------------------------------------------------ */++/** Safe decodeURIComponent that never throws URIError on truncated sequences */+export function safeDecodeURIComponent(value: string): string {+ try {+ return decodeURIComponent(value)+ } catch {+ return value+ }+}++/** Decodes each %XX run it can, leaving broken ones as written. */+function decodeLoose(value: string): string {+ if (!value.includes('%')) return value+ const whole = safeDecodeURIComponent(value)+ if (whole !== value) return whole+ return value.replace(/(%[0-9a-f]{2})+/gi, (run) => safeDecodeURIComponent(run))+}++/**+ * Punctuation that was copied around a link, not part of it: a closing+ * bracket without its opening one, a sentence's full stop, quotes.+ */+export function trimLinkText(raw: string): string {+ let t = typeof raw === 'string' ? raw.trim() : ''+ t = t.replace(/^[<"'(\[]+(?=[a-z])/i, (m) => (m.includes('(') || m.includes('[') ? m.replace(/[(\[]/g, '') : '').replace(/[<"']/g, ''))+ for (let i = 0; i < 8; i++) {+ const last = t.slice(-1)+ if ('.,;:!?\'">'.includes(last) && t.length > 1) {+ t = t.slice(0, -1)+ continue+ }+ const pairs: Record<string, string> = { ')': '(', ']': '[', '}': '{' }+ if (pairs[last]) {+ const open = t.split(pairs[last]).length - 1+ const close = t.split(last).length - 1+ if (close > open) {+ t = t.slice(0, -1)+ continue+ }+ }+ break+ }+ return t+}+/*** A copied link as something the browser can open: "www.example.com" (no- * scheme) becomes "https://www.example.com". Without this, window.open- * resolves it relative to the app page and nothing useful opens.+ * scheme) becomes "https://www.example.com", and stray punctuation copied+ * around it is dropped.*/export function externalHref(text: string): string {- const t = typeof text === 'string' ? text.trim() : ''+ const t = trimLinkText(typeof text === 'string' ? text : '')return /^[a-z][a-z0-9+.-]*:/i.test(t) ? t : `https://${t}`}-function isTrackingParam(key: string): boolean {- const k = key.toLowerCase()- return TRACKING_PARAMS.has(k) || TRACKING_PARAM_PREFIXES.some((p) => k.startsWith(p))-}-/*** The link with only its tracking parameters removed (utm_*, fbclid, gclid,* ...). Everything else is kept exactly as written: host, www., path,@@ -382,86 +339,100 @@ export function stripTracking(rawUrl: string): string {return `${head}${kept.length ? `?${kept.join('&')}` : ''}${hash}`}+/**+ * The real link inside a redirect wrapper (google.com/url?q=..., Facebook's+ * l.php?u=..., Outlook safe links, ...), or null when it is not one.+ */+export function unwrapRedirect(rawUrl: string): string | null {+ let u: URL+ try {+ u = new URL(rawUrl)+ } catch {+ return null+ }+ const host = u.hostname.toLowerCase().replace(/^www\./, '')+ const path = u.pathname+ const p = (k: string) => u.searchParams.get(k)+ let target: string | null = null+ if ((host === 'google.com' || /^google\.[a-z.]+$/.test(host)) && path === '/url') target = p('q') || p('url')+ else if ((host === 'l.facebook.com' || host === 'lm.facebook.com' || host === 'l.messenger.com') && path.startsWith('/l.php')) target = p('u')+ else if (host === 'l.instagram.com') target = p('u')+ else if (host === 'youtube.com' && path === '/redirect') target = p('q')+ else if (host.endsWith('safelinks.protection.outlook.com')) target = p('url')+ else if (host === 'linkedin.com' && path.startsWith('/redir/redirect')) target = p('url')+ else if (host === 'out.reddit.com') target = p('url')+ else if (host === 't.umblr.com' && path.startsWith('/redirect')) target = p('z')+ else if (host === 'steamcommunity.com' && path.startsWith('/linkfilter')) target = p('url') || p('u')+ else if (host === 'duckduckgo.com' && path.startsWith('/l/')) target = p('uddg')+ else if (host === 'href.li') target = u.search.slice(1) || null+ else if (host === 'slack-redir.net' && path.startsWith('/link')) target = p('url')+ if (!target || !/^https?:\/\//i.test(target)) return null+ return target+}++/** The link to copy as "clean": the real destination, tracking removed, stray punctuation dropped. */+export function cleanLink(rawUrl: string): string {+ let t = trimLinkText(rawUrl)+ for (let i = 0; i < 3; i++) {+ const inner = unwrapRedirect(/^[a-z][a-z0-9+.-]*:/i.test(t) ? t : `https://${t}`)+ if (!inner) break+ t = inner+ }+ return stripTracking(t)+}+/* ------------------------------------------------------------------ */-/* 4. Common Acronyms & Short Words to Keep Upper-Cased */+/* Names and titles *//* ------------------------------------------------------------------ */const ACRONYMS = new Set(['AI', 'API', 'UI', 'UX', 'SDK', 'CLI', 'URL', 'URI', 'CSS', 'HTML', 'JS', 'TS','SQL', 'DB', 'AWS', 'GCP', 'OS', 'ID', 'IP', 'VR', 'AR', 'MR', 'ML', 'LLM','PR', 'FAQ', 'PDF', 'CSV', 'JSON', 'YAML', 'XML', 'SVG', 'PNG', 'JPG', 'GIF',- 'BBC', 'CNN', 'WSJ', 'IMDB', 'NPM', 'PYPI', 'DEV', 'APP', 'LAB', 'LABS',- 'USA', 'UK', 'EU', 'NZ', 'AU', 'CA', 'IN', 'JP', 'KR', 'BR', 'DE', 'FR'+ 'BBC', 'CNN', 'WSJ', 'IMDB', 'NPM', 'PYPI', 'USA', 'UK', 'EU',+ 'GB', 'TB', 'MB', 'KB', 'HD', 'UHD', 'TV', 'PC', 'USB', 'SSD', 'GPU', 'CPU', 'RAM', 'IOS', 'NFT', 'CEO', 'GPT'])--/* ------------------------------------------------------------------ */-/* 5. Pure Helpers */-/* ------------------------------------------------------------------ */--/** Safe decodeURIComponent that never throws URIError on truncated sequences */-export function safeDecodeURIComponent(value: string): string {- try {- return decodeURIComponent(value)- } catch {- return value- }+/** Words with a fixed spelling ("iphone" in a slug means iPhone). */+const CASED_WORDS: Record<string, string> = {+ iphone: 'iPhone', ipad: 'iPad', ipod: 'iPod', imac: 'iMac', macbook: 'MacBook', airpods: 'AirPods', ios: 'iOS', macos: 'macOS',+ ipados: 'iPadOS', watchos: 'watchOS', icloud: 'iCloud', itunes: 'iTunes', youtube: 'YouTube', github: 'GitHub', gitlab: 'GitLab',+ javascript: 'JavaScript', typescript: 'TypeScript', nodejs: 'Node.js', linkedin: 'LinkedIn', paypal: 'PayPal', whatsapp: 'WhatsApp',+ tiktok: 'TikTok', chatgpt: 'ChatGPT', openai: 'OpenAI', wifi: 'Wi-Fi', ebay: 'eBay', playstation: 'PlayStation', xbox: 'Xbox',+ oneplus: 'OnePlus', powerpoint: 'PowerPoint', onedrive: 'OneDrive', sharepoint: 'SharePoint', wordpress: 'WordPress', mongodb: 'MongoDB',+ postgresql: 'PostgreSQL', mysql: 'MySQL', graphql: 'GraphQL', webassembly: 'WebAssembly', devops: 'DevOps', faq: 'FAQ', faqs: 'FAQs'}+const SMALL_WORDS = new Set(['a', 'an', 'the', 'and', 'or', 'but', 'of', 'in', 'on', 'at', 'to', 'for', 'by', 'with', 'vs', 'via', 'as', 'from', 'into'])-/** Resolves eTLD+1 root domain taking multi-part TLDs into account */-export function extractRootDomain(hostname: string): { rootDomain: string; mainName: string } {- const parts = hostname.toLowerCase().split('.').filter(Boolean)- if (parts.length <= 1) {- return { rootDomain: hostname, mainName: hostname }- }-- // Check 2-part and 3-part suffix matches (e.g. amazon.co.uk or gov.bc.ca)- if (parts.length >= 3) {- const lastTwo = `${parts[parts.length - 2]}.${parts[parts.length - 1]}`- if (MULTI_PART_TLDS.has(lastTwo)) {- const main = parts[parts.length - 3]- return {- rootDomain: `${main}.${lastTwo}`,- mainName: main- }- }- }-- if (parts.length >= 4) {- const lastThree = `${parts[parts.length - 3]}.${parts[parts.length - 2]}.${parts[parts.length - 1]}`- if (MULTI_PART_TLDS.has(lastThree)) {- const main = parts[parts.length - 4]- return {- rootDomain: `${main}.${lastThree}`,- mainName: main- }- }- }-- const main = parts[parts.length - 2]- const tld = parts[parts.length - 1]- return {- rootDomain: `${main}.${tld}`,- mainName: main- }+/** Title-cases one word, keeping deliberate casing ("iPhone", "GB") and known acronyms. */+function titleWord(word: string, first: boolean): string {+ const upper = word.toUpperCase()+ if (ACRONYMS.has(upper)) return upper+ const lower = word.toLowerCase()+ if (CASED_WORDS[lower]) return CASED_WORDS[lower]+ if (lower === 'i') return 'I'+ if (!first && SMALL_WORDS.has(lower)) return lower+ // already mixed case (iPhone, GitHub) or a short all-caps code: as written+ if (word !== lower && word !== upper) return word+ if (word === upper && /[A-Z]/.test(word) && word.length <= 4) return word+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()}/** Humanizes raw domain slugs into properly formatted company / site names */export function humanizeDomainName(rawName: string): string {if (!rawName) return 'Web Link'- // Split on hyphens, underscores, and camelCase boundariesconst words = rawName.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[-_.]+/g, ' ').trim().split(/\s+/).filter(Boolean)-if (words.length === 0) return rawName-return words.map((word) => {const upper = word.toUpperCase()if (ACRONYMS.has(upper)) return upper+ // no vowels at all ("ndtv", "xkcd"): an acronym+ if (/^[a-z]{2,6}$/i.test(word) && !/[aeiouy]/i.test(word)) return upperreturn word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()}).join(' ')@@ -469,272 +440,780 @@ export function humanizeDomainName(rawName: string): string {/** Humanizes URL path slugs into clean readable article / document titles */export function humanizeSlug(slug: string): string {- const decoded = safeDecodeURIComponent(slug)+ const decoded = decodeLoose(slug).replace(/[-_+]+/g, ' ')- .replace(/\.(html?|php|aspx?|jsp|json|md|txt)$/i, '')+ .replace(/\.(html?|php|aspx?|jsp|json|md|txt|cms|shtml|cfm)$/i, '').trim()-if (!decoded || decoded.length < 2) return ''// Skip pure hex hashes or raw numbersif (/^[0-9a-f]{8,}$/i.test(decoded) || /^\d+$/.test(decoded)) return ''-return decoded.split(/\s+/).filter(Boolean)- .map((word) => {- const upper = word.toUpperCase()- if (ACRONYMS.has(upper)) return upper- if (word.length <= 2) return word.toLowerCase()- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()- })+ .map((word, i) => titleWord(word, i === 0)).join(' ')}+/** Path parts that never name a page by themselves. */+const FILLER_SEGMENTS = new Set([+ 'view', 'edit', 'index', 'default', 'home', 'main', 'p', 'dp', 'gp', 'd', 's', 'w', 'r', 'u', 'c', 'g', 'e', 't', 'a', 'b', 'l', 'x',+ 'product', 'products', 'item', 'items', 'itm', 'article', 'articles', 'post', 'posts', 'page', 'pages', 'search', 'amp', 'm',+ 'share', 'shared', 'embed', 'watch', 'file', 'files', 'folder', 'folders', 'open', 'details', 'detail', 'show', 'read',+ 'story', 'stories', 'content', 'contents', 'entry', 'category', 'categories', 'tag', 'tags', 'id', 'preview', 'download',+ 'status', 'comments', 'thread', 'topic', 'articleshow', 'photostory', 'videoshow', 'liveblog', 'web', 'www', 'public',+ 'static', 'assets', 'en', 'us', 'html', 'php', 'aspx', 'redirect', 'link', 'out', 'go', 'click'+])++/** True for an ID, hash, version, locale or parameter blob rather than words. */+function isIdLike(seg: string): boolean {+ if (!seg) return true+ if (/[=;&]/.test(seg)) return true+ if (/^\d+$/.test(seg)) return true+ if (/^[0-9a-f]{8,}$/i.test(seg)) return true+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(seg)) return true+ if (/^v?\d+(\.\d+)+$/i.test(seg) || /^v\d+$/i.test(seg)) return true+ if (/^[a-z]{2}([-_][a-z]{2,4})?$/i.test(seg) && seg.length <= 5 && /[-_]/.test(seg)) return true // en-us, intl-de+ if (/^intl-[a-z]{2}$/i.test(seg)) return true+ // letters and digits run together with no separators: B09G9FPHY6, itm6ac64…, C1a2b3c4d5e+ if (seg.length >= 6 && /\d/.test(seg) && /[a-z]/i.test(seg) && !/[-_.~+ ]/.test(seg)) return true+ return false+}++/** Removes an ID glued to the end (or start) of a word slug: "how-to-x-3f2a9b1c4d5e", "world-news-12345678". */+function stripSlugId(seg: string): string {+ let s = seg+ s = s.replace(/[-_](?:[0-9a-f]{8,}|\d{5,}|[0-9a-z]*\d[0-9a-z]*\d[0-9a-z]{6,})$/i, '')+ s = s.replace(/^\d{4,}[-_](?=[a-z])/i, '')+ return s+}++/** The path part that reads most like a title, from the end; '' when none does. */+function titleFromSegments(segments: string[]): string {+ for (let i = segments.length - 1; i >= 0; i--) {+ let seg = decodeLoose(segments[i]).replace(/\.(html?|php|aspx?|jsp|cms|shtml|cfm|asp)$/i, '')+ if (isIdLike(seg)) continue+ seg = stripSlugId(seg)+ if (isIdLike(seg) || FILLER_SEGMENTS.has(seg.toLowerCase())) continue+ if (!/\p{L}/u.test(seg)) continue+ const title = humanizeSlug(seg)+ if (title && title.length >= 2) return title+ }+ return ''+}++const SEARCH_PARAMS = ['q', 'query', 'search_query', 'search', 'k', 'keywords', 'keyword', 'term', 'text', 'p', 'wd', 'searchTerm', 'st']++/** A search query in the link, as typed ('' when none). */+function searchQuery(u: URL, keys = SEARCH_PARAMS): string {+ for (const key of keys) {+ const v = u.searchParams.get(key)+ if (v && v.trim() && !/^https?:\/\//i.test(v)) return v.replace(/\s+/g, ' ').trim()+ }+ return ''+}++/** "dQw4w9WgXcQ&t=1m30s" → "1:30" (YouTube-style start times). */+function formatStart(t: string | null): string {+ if (!t) return ''+ let secs = 0+ const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/.exec(t.trim())+ if (!m || (!m[1] && !m[2] && !m[3])) return ''+ secs = (Number(m[1] || 0) * 3600) + (Number(m[2] || 0) * 60) + Number(m[3] || 0)+ if (!secs) return ''+ const h = Math.floor(secs / 3600), mm = Math.floor((secs % 3600) / 60), ss = secs % 60+ return h ? `${h}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}` : `${mm}:${String(ss).padStart(2, '0')}`+}++/** "1234567890" → "123 456 7890" (meeting IDs as people read them). */+function groupDigits(id: string): string {+ const d = id.replace(/\D/g, '')+ if (d.length === 10) return `${d.slice(0, 3)} ${d.slice(3, 6)} ${d.slice(6)}`+ if (d.length === 11) return `${d.slice(0, 3)} ${d.slice(3, 7)} ${d.slice(7)}`+ if (d.length === 9) return `${d.slice(0, 3)} ${d.slice(3, 6)} ${d.slice(6)}`+ return d+}+/* ------------------------------------------------------------------ */-/* 6. Main Parse Engine */+/* International domain names (punycode, RFC 3492 decode) *//* ------------------------------------------------------------------ */-export function parseUrlPreview(rawUrl: string): UrlPreviewInfo {- let urlObj: URL | null = null- try {- urlObj = new URL(rawUrl.startsWith('http://') || rawUrl.startsWith('https://') ? rawUrl : `https://${rawUrl}`)- } catch {- const fallbackHost = rawUrl.replace(/^https?:\/\//, '').split('/')[0] || rawUrl- const fallbackClean = humanizeDomainName(fallbackHost.split('.')[0] || fallbackHost)- return {- url: rawUrl,- cleanUrl: rawUrl,- domain: fallbackHost,- rootDomain: fallbackHost,- serviceName: fallbackClean,- title: rawUrl,- displayPath: ''+function punycodeDecode(input: string): string {+ const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700+ const out: number[] = []+ let basic = input.lastIndexOf('-')+ if (basic < 0) basic = 0+ for (let j = 0; j < basic; j++) out.push(input.charCodeAt(j))+ let n = 128, i = 0, bias = 72+ const adapt = (delta: number, numPoints: number, first: boolean) => {+ delta = first ? Math.floor(delta / damp) : delta >> 1+ delta += Math.floor(delta / numPoints)+ let k = 0+ while (delta > ((base - tMin) * tMax) >> 1) {+ delta = Math.floor(delta / (base - tMin))+ k += base}+ return k + Math.floor(((base - tMin + 1) * delta) / (delta + skew))}-- const fullHost = urlObj.hostname.toLowerCase()- const displayHost = fullHost.replace(/^www\./, '')- const { rootDomain, mainName } = extractRootDomain(displayHost)- const path = urlObj.pathname- const pathSegments = path.split('/').filter(Boolean)-- let serviceName = ''- let title: string | undefined = undefined- let subtitle: string | undefined = undefined-- // 1. Direct Subdomain Match -> Root Domain Match -> Brand Directory- if (BRAND_DIRECTORY[displayHost]) {- serviceName = BRAND_DIRECTORY[displayHost]- } else if (BRAND_DIRECTORY[rootDomain]) {- serviceName = BRAND_DIRECTORY[rootDomain]- } else {- // Check partial endswith match for subdomains- for (const [key, name] of Object.entries(BRAND_DIRECTORY)) {- if (displayHost === key || displayHost.endsWith(`.${key}`)) {- serviceName = name- break- }+ for (let idx = basic > 0 ? basic + 1 : 0; idx < input.length;) {+ const oldi = i+ let w = 1+ for (let k = base; ; k += base) {+ if (idx >= input.length) throw new Error('bad punycode')+ const c = input.charCodeAt(idx++)+ const digit = c - 48 < 10 ? c - 22 : c - 65 < 26 ? c - 65 : c - 97 < 26 ? c - 97 : base+ if (digit >= base) throw new Error('bad punycode')+ i += digit * w+ const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias+ if (digit < t) break+ w *= base - t}+ bias = adapt(i - oldi, out.length + 1, oldi === 0)+ n += Math.floor(i / (out.length + 1))+ i %= out.length + 1+ out.splice(i++, 0, n)}+ return String.fromCodePoint(...out)+}- // Fallback Service Name from Main Name- if (!serviceName) {- serviceName = humanizeDomainName(mainName)- }-- // 2. Deep Semantic Path Interpreters- if (displayHost.includes('github.com')) {- if (pathSegments.length >= 2) {- const cleanRepo = pathSegments[1].replace(/\.git$/i, '')- const repo = `${pathSegments[0]}/${cleanRepo}`- if (pathSegments.length >= 4 && pathSegments[2] === 'pull') {- title = `${repo} · Pull Request #${pathSegments[3]}`- subtitle = 'Pull Request'- } else if (pathSegments.length >= 4 && pathSegments[2] === 'issues') {- title = `${repo} · Issue #${pathSegments[3]}`- subtitle = 'Issue'- } else if (pathSegments.length >= 4 && (pathSegments[2] === 'commit' || pathSegments[2] === 'commits')) {- title = `${repo} · Commit ${pathSegments[3].slice(0, 7)}`- subtitle = 'Commit'- } else if (pathSegments.length >= 4 && (pathSegments[2] === 'tree' || pathSegments[2] === 'blob')) {- title = `${repo} · ${pathSegments.slice(4).join('/') || pathSegments[3]}`- subtitle = 'Repository Tree'- } else if (pathSegments.length >= 3 && pathSegments[2] === 'releases') {- title = `${repo} · Releases`- subtitle = 'Releases'- } else {- title = repo- subtitle = 'GitHub Repository'+/**+ * Letters from other scripts that look like Latin ones. A domain written only+ * in these ("аррӏе.com" in Cyrillic) is shown encoded, as browsers do, so it+ * can never pass for a Latin name ("apple.com").+ */+const LATIN_LOOKALIKES = new Set(Array.from(+ 'аеорсухіјӏԁѕԛԝһкмпвтгьзΑΒΕΖΗΙΚΜΝΟΡΤΥΧαβεικνορτυχοаАВЕКМНОРСТХѵѡԑɡ'+))++/** A decoded label is safe to show when it doesn't mix Latin with another script and isn't all look-alikes. */+function safeToShow(label: string): boolean {+ const letters = Array.from(label).filter((c) => /\p{L}/u.test(c))+ if (letters.length === 0) return true+ const latin = letters.filter((c) => /\p{Script=Latin}/u.test(c)).length+ if (latin > 0 && latin < letters.length) return false+ if (latin === 0 && letters.every((c) => LATIN_LOOKALIKES.has(c))) return false+ return true+}++/** "xn--fsqu00a.xn--0zwm56d" → "例子.测试" for display; look-alike or undecodable labels stay encoded. */+export function hostToUnicode(host: string): string {+ if (!host.includes('xn--')) return host+ return host+ .split('.')+ .map((label) => {+ if (!label.startsWith('xn--')) return label+ try {+ const decoded = punycodeDecode(label.slice(4))+ return safeToShow(decoded) ? decoded : label+ } catch {+ return label}- } else if (pathSegments.length === 1) {- title = `@${pathSegments[0]}`- subtitle = 'GitHub Profile'+ })+ .join('.')+}++/** Resolves eTLD+1 root domain taking multi-part TLDs into account */+export function extractRootDomain(hostname: string): { rootDomain: string; mainName: string } {+ const parts = hostname.toLowerCase().split('.').filter(Boolean)+ if (parts.length <= 1) return { rootDomain: hostname, mainName: hostname }+ if (parts.length >= 3) {+ const lastTwo = `${parts[parts.length - 2]}.${parts[parts.length - 1]}`+ if (MULTI_PART_TLDS.has(lastTwo)) {+ const main = parts[parts.length - 3]+ return { rootDomain: `${main}.${lastTwo}`, mainName: main }}- } else if (displayHost.includes('gitlab.com') || displayHost.includes('bitbucket.org') || displayHost.includes('codeberg.org')) {- if (pathSegments.length >= 2) {- const repo = `${pathSegments[0]}/${pathSegments[1].replace(/\.git$/i, '')}`- if (pathSegments.includes('merge_requests') || pathSegments.includes('pull-requests')) {- title = `${repo} · Merge Request`- } else if (pathSegments.includes('issues')) {- title = `${repo} · Issue`- } else {- title = repo- }+ }+ if (parts.length >= 4) {+ const lastThree = `${parts[parts.length - 3]}.${parts[parts.length - 2]}.${parts[parts.length - 1]}`+ if (MULTI_PART_TLDS.has(lastThree)) {+ const main = parts[parts.length - 4]+ return { rootDomain: `${main}.${lastThree}`, mainName: main }}- } else if (displayHost.includes('youtube.com') || displayHost.includes('youtu.be')) {- const v = urlObj.searchParams.get('v')- const list = urlObj.searchParams.get('list')- if (v) {- title = `YouTube Video (${v})`- subtitle = list ? 'Playlist Video' : 'Video'- } else if (displayHost.includes('youtu.be') && pathSegments.length > 0) {- title = `YouTube Video (${pathSegments[0]})`- subtitle = 'Video'- } else if (pathSegments.length >= 2 && pathSegments[0] === 'shorts') {- title = `YouTube Shorts · ${pathSegments[1]}`- subtitle = 'Shorts'- } else if (pathSegments.length >= 1 && pathSegments[0].startsWith('@')) {- title = `YouTube · ${pathSegments[0]}`- subtitle = 'Channel'- } else if (list) {- title = `YouTube Playlist (${list})`- subtitle = 'Playlist'+ }+ const main = parts[parts.length - 2]+ const tld = parts[parts.length - 1]+ return { rootDomain: `${main}.${tld}`, mainName: main }+}++/** The host is this domain or a subdomain of it. */+function onHost(host: string, domain: string): boolean {+ return host === domain || host.endsWith(`.${domain}`)+}++/** The known name for a host: exact host first, then the nearest parent domain. */+function brandFor(host: string): string {+ let h = host+ while (h.includes('.')) {+ const name = BRAND_DIRECTORY[h]+ if (name) return name+ h = h.slice(h.indexOf('.') + 1)+ }+ return ''+}++const PRIVATE_IPV4 = /^(10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+)$/++/* ------------------------------------------------------------------ */+/* Parse */+/* ------------------------------------------------------------------ */++type Page = { title?: string; subtitle?: string; serviceName?: string }++/** Page-type rules for common platforms. `segs` are the raw path parts. */+function platformPage(host: string, rootMain: string, u: URL, segs: string[]): Page | null {+ const seg = (i: number) => (segs[i] !== undefined ? decodeLoose(segs[i]) : '')+ const first = seg(0).toLowerCase()+ const q = (k: string) => u.searchParams.get(k)++ // GitHub+ if (host === 'github.com') {+ const RESERVED = new Set(['settings', 'features', 'marketplace', 'orgs', 'topics', 'explore', 'notifications', 'pulls', 'issues', 'sponsors',+ 'about', 'pricing', 'login', 'join', 'new', 'codespaces', 'enterprise', 'collections', 'trending', 'events', 'search', 'apps', 'security',+ 'customer-stories', 'readme', 'site', 'team', 'solutions', 'resources', 'contact', 'organizations', 'dashboard', 'copilot', 'premium-support'])+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ if (RESERVED.has(first)) return { title: humanizeSlug(seg(segs.length - 1)) || humanizeSlug(first) }+ if (segs.length >= 2) {+ const repo = `${seg(0)}/${seg(1).replace(/\.git$/i, '')}`+ const kind = seg(2)+ if (kind === 'pull' && segs[3]) return { title: `${repo} #${seg(3)}`, subtitle: 'Pull request' }+ if (kind === 'issues' && segs[3]) return { title: `${repo} #${seg(3)}`, subtitle: 'Issue' }+ if (kind === 'issues') return { title: repo, subtitle: 'Issues' }+ if (kind === 'pulls') return { title: repo, subtitle: 'Pull requests' }+ if (kind === 'discussions') return { title: segs[3] ? `${repo} #${seg(3)}` : repo, subtitle: 'Discussion' }+ if ((kind === 'commit' || kind === 'commits') && segs[3]) return { title: `${repo} @ ${seg(3).slice(0, 7)}`, subtitle: 'Commit' }+ if ((kind === 'blob' || kind === 'tree') && segs.length >= 4) return { title: `${repo} · ${segs.slice(4).map(decodeLoose).join('/') || seg(3)}`, subtitle: kind === 'blob' ? 'File' : 'Folder' }+ if (kind === 'releases') return { title: repo, subtitle: segs[4] ? `Release ${seg(4)}` : 'Releases' }+ if (kind === 'actions') return { title: repo, subtitle: 'Actions' }+ if (kind === 'wiki') return { title: segs[3] ? humanizeSlug(seg(3)) : repo, subtitle: 'Wiki' }+ return { title: repo, subtitle: 'Repository' }}- } else if (displayHost.includes('reddit.com')) {- if (pathSegments.length >= 4 && pathSegments[0] === 'r' && pathSegments[2] === 'comments') {- const sub = pathSegments[1]- const rawSlug = pathSegments.length >= 5 ? pathSegments[4] : pathSegments[3]- const postTitle = humanizeSlug(rawSlug)- title = postTitle ? `r/${sub} · ${postTitle}` : `r/${sub} · Post`- subtitle = 'Reddit Post'- } else if (pathSegments.length >= 2 && pathSegments[0] === 'r') {- title = `r/${pathSegments[1]}`- subtitle = 'Subreddit'- } else if (pathSegments.length >= 2 && (pathSegments[0] === 'u' || pathSegments[0] === 'user')) {- title = `u/${pathSegments[1]}`- subtitle = 'Reddit User'+ if (segs.length === 1) return { title: `@${seg(0)}`, subtitle: 'Profile' }+ return null+ }+ if (host === 'gist.github.com' && segs.length >= 1) return { title: `@${seg(0)}`, subtitle: 'Gist' }+ if (host === 'raw.githubusercontent.com' && segs.length >= 2) {+ return { title: `${seg(0)}/${seg(1)} · ${segs.slice(3).map(decodeLoose).join('/') || ''}`.replace(/ · $/, ''), subtitle: 'Raw file' }+ }+ if (host === 'gitlab.com' || host === 'bitbucket.org' || host === 'codeberg.org') {+ if (segs.length >= 2) {+ const repo = `${seg(0)}/${seg(1).replace(/\.git$/i, '')}`+ const mr = segs.indexOf('merge_requests') >= 0 ? segs.indexOf('merge_requests') : segs.indexOf('pull-requests') >= 0 ? segs.indexOf('pull-requests') : segs.indexOf('pulls')+ if (mr >= 0) return { title: segs[mr + 1] ? `${repo} !${seg(mr + 1)}` : repo, subtitle: host === 'gitlab.com' ? 'Merge request' : 'Pull request' }+ const is = segs.indexOf('issues')+ if (is >= 0) return { title: segs[is + 1] ? `${repo} #${seg(is + 1)}` : repo, subtitle: 'Issue' }+ return { title: repo, subtitle: 'Repository' }}- } else if (displayHost.includes('wikipedia.org') || displayHost.includes('wiktionary.org')) {- if (pathSegments.length >= 2 && pathSegments[0] === 'wiki') {- title = safeDecodeURIComponent(pathSegments[1]).replace(/_/g, ' ')- subtitle = 'Wikipedia Article'+ if (segs.length === 1) return { title: `@${seg(0)}`, subtitle: 'Profile' }+ return null+ }++ // YouTube+ if (onHost(host, 'youtube.com') || host === 'youtu.be') {+ const start = formatStart(q('t') || q('start'))+ const startTitle = start ? `Starts at ${start}` : undefined+ if (host === 'youtu.be' && segs[0]) return { title: startTitle, subtitle: 'Video' }+ if (first === 'watch' && q('v')) return { title: startTitle, subtitle: q('list') ? 'Playlist video' : 'Video' }+ if (first === 'shorts') return { subtitle: 'Short' }+ if (first === 'live') return { title: startTitle, subtitle: 'Live' }+ if (first === 'playlist') return { subtitle: 'Playlist' }+ if (first === 'results') return { title: searchQuery(u, ['search_query', 'q']) || undefined, subtitle: 'Search' }+ if (first.startsWith('@')) return { title: seg(0), subtitle: 'Channel' }+ if (first === 'channel' || first === 'c' || first === 'user') return { title: first === 'channel' ? undefined : seg(1), subtitle: 'Channel' }+ if (first === 'embed' || first === 'v') return { subtitle: 'Video' }+ return null+ }++ if (onHost(host, 'reddit.com')) {+ if (first === 'r' && segs[2] === 'comments') {+ const post = humanizeSlug(seg(4)) || undefined+ return { title: post, subtitle: `r/${seg(1)}` }}- } else if (displayHost.includes('spotify.com')) {- if (pathSegments.length >= 2) {- const type = pathSegments[0]- const typeName = type.charAt(0).toUpperCase() + type.slice(1)- title = `Spotify ${typeName}`- subtitle = 'Spotify Music'+ if (first === 'r' && segs[1]) return { title: `r/${seg(1)}`, subtitle: segs[2] === 'wiki' ? 'Wiki' : 'Community' }+ if ((first === 'u' || first === 'user') && segs[1]) return { title: `u/${seg(1)}`, subtitle: 'Profile' }+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ return null+ }++ // Wikipedia and friends+ if (onHost(host, 'wikipedia.org') || onHost(host, 'wiktionary.org') || onHost(host, 'wikimedia.org')) {+ if (first === 'wiki' && segs[1]) {+ const name = decodeLoose(segs.slice(1).join('/')).replace(/_/g, ' ')+ if (/^Special:Search/i.test(name)) return { title: searchQuery(u, ['search', 'q']) || undefined, subtitle: 'Search' }+ const section = u.hash ? decodeLoose(u.hash.slice(1)).replace(/_/g, ' ') : ''+ return { title: section ? `${name} § ${section}` : name, subtitle: 'Article' }}- } else if (displayHost.includes('music.apple.com') || displayHost.includes('podcasts.apple.com')) {- if (pathSegments.length >= 2) {- const last = pathSegments[pathSegments.length - 1]- const name = humanizeSlug(last)- title = name || (displayHost.includes('podcasts') ? 'Apple Podcast' : 'Apple Music')+ if (first === 'w' && q('search')) return { title: q('search') || undefined, subtitle: 'Search' }+ return null+ }++ // Spotify / Apple Music / SoundCloud+ if (onHost(host, 'spotify.com')) {+ const parts = first.startsWith('intl-') ? segs.slice(1) : segs+ const kind = (parts[0] || '').toLowerCase()+ const names: Record<string, string> = { track: 'Track', album: 'Album', playlist: 'Playlist', artist: 'Artist', episode: 'Episode', show: 'Podcast', user: 'Profile', search: 'Search' }+ if (names[kind]) return { title: kind === 'search' && parts[1] ? decodeLoose(parts[1]) : undefined, subtitle: names[kind] }+ return null+ }+ if (host === 'music.apple.com' || host === 'podcasts.apple.com' || host === 'apps.apple.com') {+ const kinds: Record<string, string> = { album: 'Album', playlist: 'Playlist', song: 'Song', artist: 'Artist', podcast: 'Podcast', app: 'App' }+ const idx = segs.findIndex((s) => kinds[s.toLowerCase()])+ if (idx >= 0) {+ const name = humanizeSlug(seg(idx + 1))+ return { title: name || undefined, subtitle: kinds[segs[idx].toLowerCase()] }}- } else if (displayHost.includes('twitter.com') || displayHost.includes('x.com')) {- if (pathSegments.length >= 3 && pathSegments[1] === 'status') {- title = `Post by @${pathSegments[0]}`- subtitle = 'X Post'- } else if (pathSegments.length >= 1) {- title = `@${pathSegments[0]}`- subtitle = 'X Profile'+ return null+ }+ if (host === 'soundcloud.com' && segs.length >= 1) {+ if (segs.length >= 2 && segs[1] !== 'sets') return { title: humanizeSlug(seg(1)) || undefined, subtitle: 'Track' }+ if (segs[1] === 'sets') return { title: humanizeSlug(seg(2)) || undefined, subtitle: 'Playlist' }+ return { title: seg(0), subtitle: 'Profile' }+ }++ // X / Twitter+ if (host === 'x.com' || onHost(host, 'twitter.com')) {+ const RESERVED = new Set(['home', 'explore', 'notifications', 'messages', 'settings', 'i', 'search', 'compose', 'login', 'signup', 'tos', 'privacy'])+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ if (segs[1] === 'status' && segs[2]) return { title: `@${seg(0)}`, subtitle: 'Post' }+ if (segs[0] && !RESERVED.has(first)) return { title: `@${seg(0)}`, subtitle: 'Profile' }+ return null+ }++ if (host === 'docs.google.com') {+ if (segs.includes('document')) return { serviceName: 'Google Docs', subtitle: 'Document' }+ if (segs.includes('spreadsheets')) return { serviceName: 'Google Sheets', subtitle: 'Spreadsheet' }+ if (segs.includes('presentation')) return { serviceName: 'Google Slides', subtitle: 'Presentation' }+ if (segs.includes('forms')) return { serviceName: 'Google Forms', subtitle: 'Form' }+ if (segs.includes('drawings')) return { serviceName: 'Google Drawings', subtitle: 'Drawing' }+ return null+ }+ if (host === 'drive.google.com') {+ if (first === 'file') return { subtitle: 'File' }+ if (segs.includes('folders')) return { subtitle: 'Folder' }+ if (first === 'open' || first === 'uc') return { subtitle: 'File' }+ return null+ }+ if (host === 'meet.google.com' && segs[0] && /^[a-z]{3,4}-[a-z]{4}-[a-z]{3,4}$/i.test(seg(0))) return { title: seg(0).toLowerCase(), subtitle: 'Meeting' }+ if (host === 'maps.google.com' || ((host === 'google.com' || /^google\.[a-z.]+$/.test(host)) && first === 'maps')) {+ const parts = first === 'maps' ? segs.slice(1) : segs+ const k = (parts[0] || '').toLowerCase()+ const words = (s: string) => decodeLoose(s.replace(/\+/g, ' ')).trim()+ if (k === 'place' && parts[1]) return { serviceName: 'Google Maps', title: words(parts[1]), subtitle: 'Place' }+ if (k === 'search' && parts[1]) return { serviceName: 'Google Maps', title: words(parts[1]), subtitle: 'Search' }+ if (k === 'dir') {+ const stops = parts.slice(1).filter((p) => p && !p.startsWith('@') && !p.startsWith('data=')).map(words).filter(Boolean)+ return { serviceName: 'Google Maps', title: stops.length ? stops.join(' → ') : undefined, subtitle: 'Directions' }}- } else if (displayHost.includes('docs.google.com')) {- if (pathSegments.includes('document')) {- title = 'Google Doc'- subtitle = 'Document'- } else if (pathSegments.includes('spreadsheets')) {- title = 'Google Sheet'- subtitle = 'Spreadsheet'- } else if (pathSegments.includes('presentation')) {- title = 'Google Slides'- subtitle = 'Presentation'- } else if (pathSegments.includes('forms')) {- title = 'Google Form'- subtitle = 'Form'+ const qq = q('q') || q('query')+ return { serviceName: 'Google Maps', title: qq ? qq.trim() : undefined, subtitle: qq ? 'Search' : 'Map' }+ }+ if ((host === 'google.com' || /^google\.[a-z.]+$/.test(host)) && (first === 'search' || first === 'webhp' || (!first && q('q')))) {+ return { title: searchQuery(u) || undefined, subtitle: q('tbm') === 'isch' || q('udm') === '2' ? 'Image search' : 'Search' }+ }+ if (host === 'play.google.com' && q('id')) {+ const pkg = q('id') || ''+ return { title: humanizeDomainName(pkg.split('.').pop() || pkg), subtitle: 'App' }+ }++ // Other search engines+ if ((onHost(host, 'bing.com') && first === 'search') || (host === 'duckduckgo.com' && q('q')) || (host === 'search.yahoo.com') ||+ (onHost(host, 'baidu.com') && first === 's') || (rootMain === 'yandex' && first === 'search') || (host === 'ecosia.org' && first === 'search') ||+ (host === 'search.brave.com' && first === 'search') || host === 'startpage.com') {+ return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ }+ if (host === 'perplexity.ai' && first === 'search') {+ const fromPath = segs[1] ? humanizeSlug(stripSlugId(seg(1))) : ''+ return { title: searchQuery(u) || fromPath || undefined, subtitle: 'Search' }+ }++ // Meetings+ if (onHost(host, 'zoom.us') || onHost(host, 'zoom.com')) {+ if ((first === 'j' || first === 'w' || first === 's') && segs[1]) return { title: groupDigits(seg(1)), subtitle: first === 'w' ? 'Webinar' : 'Meeting' }+ if (first === 'my' && segs[1]) return { title: seg(1), subtitle: 'Personal room' }+ if (first === 'rec') return { subtitle: 'Recording' }+ return null+ }+ if (host === 'teams.microsoft.com' || host === 'teams.live.com') {+ const path = segs.map((s) => s.toLowerCase()).join('/')+ if (path.includes('meetup-join') || first === 'meet') return { subtitle: 'Meeting' }+ if (path.includes('channel')) return { subtitle: 'Channel' }+ if (path.includes('chat')) return { subtitle: 'Chat' }+ return null+ }+ if (onHost(host, 'webex.com')) {+ if (first === 'meet' && segs[1]) return { title: seg(1), subtitle: 'Meeting' }+ if (segs.some((s) => /^j\.php$|^join$/i.test(s))) return { subtitle: 'Meeting' }+ return null+ }++ if (host === 'linkedin.com' || onHost(host, 'linkedin.com')) {+ if (first === 'in' && segs[1]) return { title: seg(1), subtitle: 'Profile' }+ if (first === 'company' && segs[1]) return { title: humanizeSlug(seg(1)) || seg(1), subtitle: 'Company' }+ if (first === 'school' && segs[1]) return { title: humanizeSlug(seg(1)) || seg(1), subtitle: 'School' }+ if (first === 'jobs') return { title: segs[2] ? humanizeSlug(stripSlugId(seg(2))) || undefined : undefined, subtitle: segs[1] === 'view' ? 'Job' : 'Jobs' }+ if (first === 'posts' && segs[1]) {+ const m = /^([^_]+)_(.*?)-(?:activity|ugcpost|share)-\d+/i.exec(seg(1))+ const words = m ? humanizeSlug(m[2]) : ''+ return { title: m ? (words && words.split(' ').length >= 2 ? words : m[1]) : undefined, subtitle: 'Post' }}- } else if (displayHost.includes('figma.com')) {- if (pathSegments.length >= 3 && (pathSegments[0] === 'file' || pathSegments[0] === 'design')) {- const docName = humanizeSlug(pathSegments[2])- title = docName ? `Figma · ${docName}` : 'Figma Design File'- subtitle = 'Design File'+ if (first === 'feed' && segs[1] === 'update') return { subtitle: 'Post' }+ if (first === 'pulse' && segs[1]) return { title: humanizeSlug(stripSlugId(seg(1))) || undefined, subtitle: 'Article' }+ if (first === 'groups') return { subtitle: 'Group' }+ if (first === 'events') return { subtitle: 'Event' }+ return null+ }++ // Instagram / Facebook / TikTok / Threads / Pinterest+ if (host === 'instagram.com' || onHost(host, 'instagram.com')) {+ if (first === 'p' && segs[1]) return { subtitle: 'Post' }+ if ((first === 'reel' || first === 'reels') && segs[1]) return { subtitle: 'Reel' }+ if (first === 'stories' && segs[1]) return { title: `@${seg(1)}`, subtitle: 'Story' }+ if (first === 'explore' && segs[1] === 'tags' && segs[2]) return { title: `#${seg(2)}`, subtitle: 'Tag' }+ if (segs[0] && !['explore', 'accounts', 'direct', 'tv', 'about', 'developer', 'legal'].includes(first)) {+ if (segs[1] === 'p' || segs[1] === 'reel') return { title: `@${seg(0)}`, subtitle: segs[1] === 'p' ? 'Post' : 'Reel' }+ return { title: `@${seg(0)}`, subtitle: 'Profile' }}- } else if (displayHost.includes('notion.so') || displayHost.includes('notion.site')) {- if (pathSegments.length >= 1) {- const last = pathSegments[pathSegments.length - 1]- const cleanNotion = last.replace(/-[a-f0-9]{32}$/i, '')- const notionTitle = humanizeSlug(cleanNotion)- if (notionTitle) {- title = notionTitle- subtitle = 'Notion Page'- }+ return null+ }+ if (onHost(host, 'facebook.com') || host === 'fb.com' || host === 'fb.watch') {+ if (host === 'fb.watch') return { subtitle: 'Video' }+ if (first === 'groups' && segs[1]) {+ const name = /^\d+$/.test(seg(1)) ? undefined : humanizeSlug(seg(1)) || undefined+ return { title: name, subtitle: segs[2] === 'posts' || segs[2] === 'permalink' ? 'Group post' : 'Group' }}- } else if (displayHost.includes('linear.app')) {- if (pathSegments.length >= 2 && pathSegments[1] === 'issue') {- title = `Linear Issue · ${pathSegments[2] || ''}`- subtitle = 'Linear Issue'+ if (first === 'watch' || segs[1] === 'videos' || first === 'reel') return { subtitle: first === 'reel' ? 'Reel' : 'Video' }+ if (first === 'events') return { subtitle: 'Event' }+ if (first === 'marketplace') return { subtitle: segs[1] === 'item' ? 'Marketplace item' : 'Marketplace' }+ if (first === 'photo' || first === 'photo.php' || segs[1] === 'photos') return { subtitle: 'Photo' }+ if (first === 'story.php' || first === 'permalink.php' || segs[1] === 'posts') return { subtitle: 'Post' }+ if (first === 'share') return { subtitle: 'Shared link' }+ if (first === 'profile.php') return { subtitle: 'Profile' }+ if (segs[0] && !['login', 'help', 'settings', 'pages', 'gaming', 'business', 'privacy', 'policies'].includes(first)) {+ return { title: seg(0), subtitle: 'Page' }}- } else if (displayHost.includes('arxiv.org')) {- if (pathSegments.length >= 2 && (pathSegments[0] === 'abs' || pathSegments[0] === 'pdf')) {- title = `arXiv Paper · ${pathSegments[1].replace(/\.pdf$/i, '')}`- subtitle = 'Research Paper'+ return null+ }+ if (onHost(host, 'tiktok.com')) {+ if (first.startsWith('@') && segs[1] === 'video') return { title: seg(0), subtitle: 'Video' }+ if (first.startsWith('@')) return { title: seg(0), subtitle: 'Profile' }+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ return null+ }+ if (host === 'threads.net' || host === 'threads.com') {+ if (first.startsWith('@') && segs[1] === 'post') return { title: seg(0), subtitle: 'Post' }+ if (first.startsWith('@')) return { title: seg(0), subtitle: 'Profile' }+ return null+ }+ if (host === 'bsky.app' && first === 'profile' && segs[1]) return { title: `@${seg(1)}`, subtitle: segs[2] === 'post' ? 'Post' : 'Profile' }+ if (onHost(host, 'pinterest.com')) {+ if (first === 'pin') return { subtitle: 'Pin' }+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ if (segs[0] && segs[1]) return { title: humanizeSlug(seg(1)) || undefined, subtitle: 'Board' }+ return null+ }++ // Messaging and invites+ if (host === 'discord.gg' || (host === 'discord.com' && first === 'invite')) return { subtitle: 'Invite' }+ if (host === 'discord.com' && first === 'channels') return { subtitle: 'Channel' }+ if (host === 't.me' || host === 'telegram.me') {+ if (first.startsWith('+') || first === 'joinchat') return { subtitle: 'Invite' }+ if (segs[0]) return { title: `@${seg(0)}`, subtitle: segs[1] && /^\d+$/.test(seg(1)) ? 'Message' : 'Chat' }+ return null+ }+ if (host === 'wa.me' && segs[0]) return { title: `+${seg(0).replace(/^\+/, '')}`, subtitle: 'Chat' }+ if (host === 'chat.whatsapp.com') return { subtitle: 'Group invite' }+ if (host === 'linktr.ee' && segs[0]) return { title: `@${seg(0)}`, subtitle: 'Profile' }++ // Video and streaming+ if (host === 'twitch.tv' || onHost(host, 'twitch.tv')) {+ if (first === 'videos') return { subtitle: 'Video' }+ if (segs[1] === 'clip' || host === 'clips.twitch.tv') return { subtitle: 'Clip' }+ if (segs[0] && !['directory', 'settings', 'search', 'downloads', 'jobs', 'p'].includes(first)) return { title: seg(0), subtitle: 'Channel' }+ return null+ }+ if (onHost(host, 'netflix.com')) {+ const parts = /^[a-z]{2}(-[a-z]{2})?$/i.test(first) ? segs.slice(1) : segs+ const k = (parts[0] || '').toLowerCase()+ if (k === 'title') return { subtitle: 'Title' }+ if (k === 'watch') return { subtitle: 'Watch' }+ if (k === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ return null+ }+ if (host === 'vimeo.com' && segs[0] && /^\d+$/.test(seg(0))) return { subtitle: 'Video' }+ if (onHost(host, 'imdb.com')) {+ if (first === 'title') return { subtitle: 'Title' }+ if (first === 'name') return { subtitle: 'Person' }+ if (first === 'find') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ return null+ }++ // Shopping+ if (rootMain === 'amazon' || host.startsWith('amazon.')) {+ if (first === 's' && (q('k') || q('field-keywords'))) return { title: (q('k') || q('field-keywords') || '').trim(), subtitle: 'Search' }+ const dp = segs.findIndex((s) => s === 'dp' || s === 'product' || s === 'd')+ if (dp >= 0 || first === 'gp') {+ const slug = dp > 0 ? seg(dp - 1) : ''+ return { title: slug && !isIdLike(slug) ? humanizeSlug(slug) || undefined : undefined, subtitle: 'Product' }}- } else if (displayHost.includes('npmjs.com')) {- if (pathSegments.length >= 2 && pathSegments[0] === 'package') {- title = `npm · ${pathSegments.slice(1).join('/')}`- subtitle = 'Package'+ return null+ }+ if (host === 'flipkart.com') {+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ const p = segs.indexOf('p')+ if (p > 0) return { title: humanizeSlug(seg(p - 1)) || undefined, subtitle: 'Product' }+ return null+ }++ // AI chats+ if (host === 'chatgpt.com' || host === 'chat.openai.com') {+ if (first === 'c' || (first === 'g' && segs[2] === 'c')) return { subtitle: 'Conversation' }+ if (first === 'share') return { subtitle: 'Shared conversation' }+ if (first === 'g' && segs[1]) {+ const name = seg(1).replace(/^g-[a-z0-9]+-?/i, '')+ return { title: name ? humanizeSlug(name) || undefined : undefined, subtitle: 'GPT' }}- } else if (displayHost.includes('pypi.org')) {- if (pathSegments.length >= 2 && pathSegments[0] === 'project') {- title = `PyPI · ${pathSegments[1]}`- subtitle = 'Python Package'+ return null+ }+ if (host === 'claude.ai') {+ if (first === 'chat') return { subtitle: 'Chat' }+ if (first === 'share') return { subtitle: 'Shared chat' }+ if (first === 'project') return { subtitle: 'Project' }+ return null+ }+ if (host === 'gemini.google.com') {+ if (first === 'app') return { subtitle: 'Chat' }+ if (first === 'share') return { subtitle: 'Shared chat' }+ if (first === 'gem') return { subtitle: 'Gem' }+ return null+ }++ // Writing platforms+ if (host === 'medium.com' || onHost(host, 'medium.com')) {+ const last = segs.length ? seg(segs.length - 1) : ''+ if (segs.length >= 1 && !last.startsWith('@')) return { title: humanizeSlug(stripSlugId(last)) || undefined, subtitle: 'Article' }+ if (last.startsWith('@')) return { title: last, subtitle: 'Profile' }+ return null+ }+ if (onHost(host, 'substack.com') && first === 'p' && segs[1]) return { title: humanizeSlug(seg(1)) || undefined, subtitle: 'Post' }+ if (host === 'dev.to' && segs.length >= 2) return { title: humanizeSlug(stripSlugId(seg(1))) || undefined, subtitle: 'Article' }++ // Q&A+ if (['stackoverflow.com', 'superuser.com', 'serverfault.com', 'askubuntu.com', 'mathoverflow.net'].includes(host) || onHost(host, 'stackexchange.com')) {+ if ((first === 'questions' || first === 'q') && segs[1]) return { title: segs[2] ? humanizeSlug(seg(2)) || undefined : undefined, subtitle: 'Question' }+ if (first === 'a') return { subtitle: 'Answer' }+ if (first === 'users' && segs[2]) return { title: humanizeSlug(seg(2)) || undefined, subtitle: 'Profile' }+ if (first === 'search') return { title: searchQuery(u) || undefined, subtitle: 'Search' }+ return null+ }+ if (host === 'quora.com' && segs[0]) return { title: humanizeSlug(seg(0)) || undefined, subtitle: 'Question' }+ if (host === 'news.ycombinator.com' && first === 'item') return { subtitle: 'Discussion' }++ // Design and workspace+ if (onHost(host, 'figma.com')) {+ const kinds: Record<string, string> = { file: 'Design', design: 'Design', proto: 'Prototype', board: 'FigJam board', slides: 'Slides', community: 'Community file' }+ if (kinds[first] && segs[2]) return { title: humanizeSlug(seg(2)) || undefined, subtitle: kinds[first] }+ if (kinds[first]) return { subtitle: kinds[first] }+ return null+ }+ if (onHost(host, 'notion.so') || onHost(host, 'notion.site')) {+ if (segs.length >= 1) {+ const name = humanizeSlug(seg(segs.length - 1).replace(/-?[a-f0-9]{32}$/i, ''))+ return { title: name || undefined, subtitle: 'Page' }}- } else if (displayHost.includes('crates.io')) {- if (pathSegments.length >= 2 && pathSegments[0] === 'crates') {- title = `crates.io · ${pathSegments[1]}`- subtitle = 'Rust Crate'+ return null+ }+ if (host === 'linear.app' && segs[1] === 'issue' && segs[2]) {+ const name = segs[3] ? humanizeSlug(seg(3)) : ''+ return { title: name ? `${seg(2)} · ${name}` : seg(2), subtitle: 'Issue' }+ }+ if (onHost(host, 'atlassian.net')) {+ if (first === 'browse' && segs[1]) return { serviceName: 'Jira', title: seg(1), subtitle: 'Issue' }+ if (first === 'wiki') {+ const pi = segs.indexOf('pages')+ return { serviceName: 'Confluence', title: pi >= 0 && segs[pi + 2] ? humanizeSlug(seg(pi + 2)) || undefined : undefined, subtitle: 'Page' }}- } else if (displayHost.includes('steampowered.com') || displayHost.includes('steamcommunity.com')) {- if (pathSegments.length >= 3 && pathSegments[0] === 'app') {- const game = humanizeSlug(pathSegments[2])- title = game ? `Steam · ${game}` : 'Steam Game'- subtitle = 'Game'+ return null+ }+ if (host === 'trello.com' && (first === 'b' || first === 'c') && segs[1]) {+ return { title: segs[2] ? humanizeSlug(seg(2).replace(/^\d+-/, '')) || undefined : undefined, subtitle: first === 'b' ? 'Board' : 'Card' }+ }+ if (host === 'miro.com' && first === 'app') return { subtitle: 'Board' }+ if (host === 'canva.com' && first === 'design') return { subtitle: 'Design' }+ if (onHost(host, 'dropbox.com') && (first === 's' || first === 'scl')) return { title: humanizeSlug(seg(segs.length - 1)) || undefined, subtitle: 'Shared file' }++ // Packages, papers, models+ if (host === 'npmjs.com' && first === 'package' && segs[1]) return { title: segs.slice(1).map(decodeLoose).join('/'), subtitle: 'Package' }+ if (host === 'pypi.org' && first === 'project' && segs[1]) return { title: seg(1), subtitle: 'Python package' }+ if (host === 'crates.io' && first === 'crates' && segs[1]) return { title: seg(1), subtitle: 'Rust crate' }+ if (host === 'pkg.go.dev' && segs[0]) return { title: segs.map(decodeLoose).join('/'), subtitle: 'Go package' }+ if (host === 'hub.docker.com' && (first === 'r' || first === '_') && segs[1]) return { title: first === '_' ? seg(1) : segs.slice(1, 3).map(decodeLoose).join('/'), subtitle: 'Image' }+ if (host === 'arxiv.org' && (first === 'abs' || first === 'pdf') && segs[1]) return { title: seg(1).replace(/\.pdf$/i, ''), subtitle: 'Paper' }+ if (host === 'doi.org' && segs[0]) return { title: segs.map(decodeLoose).join('/'), subtitle: 'Paper' }+ if (host === 'huggingface.co') {+ if ((first === 'datasets' || first === 'spaces') && segs[2]) return { title: `${seg(1)}/${seg(2)}`, subtitle: first === 'datasets' ? 'Dataset' : 'Space' }+ if (segs.length >= 2 && !['docs', 'blog', 'papers', 'learn', 'tasks', 'models'].includes(first)) return { title: `${seg(0)}/${seg(1)}`, subtitle: 'Model' }+ return null+ }+ if (host === 'leetcode.com' && first === 'problems' && segs[1]) return { title: humanizeSlug(seg(1)) || undefined, subtitle: 'Problem' }+ if ((host === 'store.steampowered.com' || host === 'steamcommunity.com') && first === 'app' && segs[1]) {+ return { title: segs[2] ? humanizeSlug(seg(2)) || undefined : undefined, subtitle: 'Game' }+ }++ return null+}++const cache = new Map<string, UrlPreviewInfo>()+const CACHE_MAX = 400++export function parseUrlPreview(rawUrl: string): UrlPreviewInfo {+ const key = typeof rawUrl === 'string' ? rawUrl : String(rawUrl ?? '')+ const hit = cache.get(key)+ if (hit) return hit+ const info = parse(key, 0)+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value as string)+ cache.set(key, info)+ return info+}++function parse(raw: string, depth: number): UrlPreviewInfo {+ const url = raw.trim()+ const link = trimLinkText(url)++ // Email and phone links+ const mail = /^mailto:([^?]+)(\?.*)?$/i.exec(link)+ if (mail) {+ const address = decodeLoose(mail[1])+ let subject = ''+ try {+ subject = new URLSearchParams(mail[2] || '').get('subject') || ''+ } catch { /* ignore */ }+ const domain = address.split('@')[1] || ''+ return { url, cleanUrl: link, displayUrl: address, domain, rootDomain: domain, serviceName: 'Email', title: subject || undefined, displayPath: '' }+ }+ const tel = /^tel:(.+)$/i.exec(link)+ if (tel) {+ const number = decodeLoose(tel[1]).trim()+ return { url, cleanUrl: link, displayUrl: number, domain: '', rootDomain: '', serviceName: 'Phone', subtitle: 'Call', displayPath: '' }+ }++ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(link)+ let u: URL | null = null+ try {+ u = new URL(hasScheme ? link : `https://${link}`)+ } catch {+ u = null+ }+ if (u && u.protocol === 'file:') {+ const segsF = u.pathname.split('/').filter(Boolean)+ const name = decodeLoose(segsF[segsF.length - 1] || '')+ const path = decodeLoose(u.pathname.replace(/^\/(?=[a-z]:)/i, ''))+ return { url, cleanUrl: link, displayUrl: path, domain: 'This computer', rootDomain: '', serviceName: 'File', title: name || undefined, subtitle: 'Local file', displayPath: path }+ }+ if (!u || !u.hostname) {+ const host = link.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split(/[/?#]/)[0] || link+ return { url, cleanUrl: link, displayUrl: link, domain: host, rootDomain: host, serviceName: humanizeDomainName(host.split('.')[0] || host), displayPath: '' }+ }++ // Redirect wrappers: show (and clean to) the real destination+ if (depth < 2 && /^https?:$/.test(u.protocol)) {+ const inner = unwrapRedirect(u.href)+ if (inner) {+ const dest = parse(inner, depth + 1)+ return { ...dest, url }}- } else if (pathSegments.length > 0) {- // Generic intelligent slug humanization- const lastSeg = pathSegments[pathSegments.length - 1]- const humanized = humanizeSlug(lastSeg)- if (humanized) {- title = humanized+ }++ const asciiHost = u.hostname.toLowerCase().replace(/^\[|\]$/g, '')+ const host = asciiHost.replace(/^www\d?\./, '').replace(/^m\.(?=[^.]+\.[^.]+)/, '')+ const unicodeHost = hostToUnicode(asciiHost.replace(/^www\d?\./, ''))+ const port = u.port ? `:${u.port}` : ''+ const segs = u.pathname.split('/').filter(Boolean)+ const isWeb = /^https?:$/.test(u.protocol)++ // Clean, readable link+ const cleanParams: string[] = []+ u.searchParams.forEach((val, k) => {+ if (!isTrackingParam(k)) cleanParams.push(`${k}${val || u!.search.includes(`${k}=`) ? `=${val}` : ''}`)+ })+ const pathPart = u.pathname === '/' ? '' : u.pathname+ const queryPart = cleanParams.length ? `?${cleanParams.join('&')}` : ''+ const displayPath = `${decodeLoose(pathPart)}${queryPart}${decodeLoose(u.hash)}`+ const displayUrl = `${isWeb ? '' : `${u.protocol}//`}${unicodeHost}${port}${displayPath}`+ const cleanUrl = isWeb ? stripTracking(hasScheme ? link : `https://${link}`) : link++ const base = { url, cleanUrl, displayUrl, domain: `${unicodeHost}${port}`, displayPath }++ // Other schemes+ if (!isWeb && u.protocol !== 'ftp:' && u.protocol !== 'ftps:') {+ return { ...base, rootDomain: host, serviceName: humanizeDomainName(u.protocol.replace(':', '')), title: titleFromSegments(segs) || undefined }+ }++ // This computer / local network / plain IP addresses+ const isIp = /^\d+\.\d+\.\d+\.\d+$/.test(host) || host.includes(':')+ if (host === 'localhost' || host.endsWith('.localhost') || /^127\./.test(host) || host === '::1' || host === '0.0.0.0') {+ return { ...base, rootDomain: host, serviceName: 'This computer', title: titleFromSegments(segs) || undefined, subtitle: port ? `Port ${u.port}` : undefined }+ }+ if (PRIVATE_IPV4.test(host) || host.endsWith('.local') || host.endsWith('.lan') || host.endsWith('.internal') || host.endsWith('.home.arpa')) {+ return { ...base, rootDomain: host, serviceName: 'Local network', title: titleFromSegments(segs) || undefined }+ }+ if (isIp) {+ return { ...base, rootDomain: host, serviceName: host, title: titleFromSegments(segs) || undefined }+ }++ const { rootDomain, mainName } = extractRootDomain(host)+ let serviceName = brandFor(host)++ // you.github.io, app.vercel.app, someone.substack.com: the subdomain is the site+ let hostedOn = ''+ const platform = [...HOSTED_PLATFORMS].find((p) => host.endsWith(`.${p}`))+ if (platform) {+ const sub = host.slice(0, -(platform.length + 1)).split('.').pop() || ''+ if (sub && sub !== 'www') {+ hostedOn = BRAND_DIRECTORY[platform] || humanizeDomainName(platform.split('.')[0])+ serviceName = humanizeDomainName(hostToUnicode(sub))}}+ if (!serviceName) {+ // a domain that stays encoded (look-alike letters) is named by itself, never "humanized"+ const main = hostToUnicode(mainName)+ serviceName = main.startsWith('xn--') ? hostToUnicode(rootDomain) : humanizeDomainName(main)+ }++ // Short links: nothing more can be known without opening them+ const shortKey = SHORTENERS.has(host) ? host : ''+ if (shortKey) {+ return { ...base, rootDomain, serviceName, subtitle: 'Short link' }+ }- // 3. Clean Display Path (strip tracking query parameters)- const cleanParams = new URLSearchParams()- urlObj.searchParams.forEach((val, key) => {- const k = key.toLowerCase()- const isTracking = TRACKING_PARAMS.has(k) || TRACKING_PARAM_PREFIXES.some((p) => k.startsWith(p))- if (!isTracking) {- cleanParams.append(key, val)+ const page = platformPage(host, mainName, u, segs)+ if (page) {+ return {+ ...base,+ rootDomain,+ serviceName: page.serviceName || serviceName,+ title: page.title || undefined,+ subtitle: page.subtitle || (hostedOn || undefined)}- })+ }- const searchStr = cleanParams.toString()- const cleanSearch = searchStr ? `?${searchStr}` : ''- const cleanHash = urlObj.hash ? urlObj.hash : ''- const cleanPathAndQuery = `${path === '/' ? '' : path}${cleanSearch}${cleanHash}`- const cleanUrl = `${urlObj.protocol}//${displayHost}${cleanPathAndQuery}`- const displayPath = cleanPathAndQuery.length > 1 ? safeDecodeURIComponent(cleanPathAndQuery) : ''-- return {- url: rawUrl,- cleanUrl,- domain: displayHost,- rootDomain,- serviceName,- title,- subtitle,- displayPath+ // Any other site: the most title-like path part, else a search query, else a named parameter+ let title = titleFromSegments(segs)+ let subtitle = hostedOn || undefined+ if (!title) {+ const query = searchQuery(u, ['q', 'query', 'search', 'search_query', 'keywords', 'keyword', 'k', 'term'])+ if (query) {+ title = query+ subtitle = 'Search'+ } else {+ for (const k of ['title', 'name', 'page', 'topic']) {+ const v = u.searchParams.get(k)+ if (v && /\p{L}/u.test(v) && !isIdLike(v)) {+ title = humanizeSlug(v)+ break+ }+ }+ }}+ return { ...base, rootDomain, serviceName, title: title || undefined, subtitle }}diff --git a/tests/itemMeta.test.ts b/tests/itemMeta.test.tsindex cd7b52e..1cedd36 100644--- a/tests/itemMeta.test.ts+++ b/tests/itemMeta.test.ts@@ -171,6 +171,27 @@ describe('ItemStore notes', () => {expect(Array.from(store.get('x3')!.note!)).toHaveLength(NOTE_MAX)})+ it('a link copied with its page title keeps it; a repeat copy can bring it; old saved links learn it on load', () => {+ const store = new ItemStore()+ const link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'+ const html = `<html><body><!--StartFragment--><a href="${link}">Never Gonna Give You Up</a><!--EndFragment--></body></html>`+ store.add({ kind: 'text', text: link, html, isUrl: true }, 50)+ expect(store.toDto()[0].data).toMatchObject({ kind: 'text', linkTitle: 'Never Gonna Give You Up', hasHtml: true })+ // plain copy first, then the same link with its title: the card learns the title+ store.add({ kind: 'text', text: 'https://example.com/a', isUrl: true }, 50)+ expect(store.toDto()[0].data).not.toHaveProperty('linkTitle', expect.anything())+ store.add({ kind: 'text', text: 'https://example.com/a', html: '<a href="https://example.com/a">Example A</a>', isUrl: true }, 50)+ expect(store.toDto()[0]).toMatchObject({ hitCount: 2, data: { linkTitle: 'Example A' } })+ // not a link: no title is read+ store.add({ kind: 'text', text: 'hello', html: '<a href="hello">Hi</a>', isUrl: false }, 50)+ expect(store.toDto()[0].data).not.toHaveProperty('linkTitle', expect.anything())+ // saved before titles were kept+ writeFileSync(PATHS.indexFile(), JSON.stringify({ items: [{ id: 'old', data: { kind: 'text', text: 'https://e.com/x', html: '<a href="https://e.com/x">Old Page</a>', isUrl: true }, capturedAt: 1, hitCount: 1, pinned: true }] }))+ const reopened = new ItemStore()+ reopened.load()+ expect(reopened.toDto()[0].data).toMatchObject({ linkTitle: 'Old Page' })+ })+it('the DTO tells the renderer when a text item has html, without sending the html', () => {const store = new ItemStore()store.add({ kind: 'text', text: 'rich', html: '<b>rich</b>', isUrl: false }, 50)diff --git a/tests/urlPreview.test.ts b/tests/urlPreview.test.tsindex b8498ea..8b656b2 100644--- a/tests/urlPreview.test.ts+++ b/tests/urlPreview.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'-import { parseUrlPreview, safeDecodeURIComponent, extractRootDomain, humanizeDomainName, humanizeSlug } from '../src/lib/urlPreview'+import { parseUrlPreview, safeDecodeURIComponent, extractRootDomain, humanizeDomainName, humanizeSlug, cleanLink, unwrapRedirect, hostToUnicode, externalHref } from '../src/lib/urlPreview'+import { isLinkText, linkTitleFromHtml } from '../shared/linkText'describe('safeDecodeURIComponent', () => {it('decodes a complete sequence', () => {@@ -35,7 +36,8 @@ describe('extractRootDomain with Global eTLD Registry', () => {describe('humanizeDomainName with Acronym & CamelCase Intelligence', () => {it('humanizes unknown domains cleanly with proper casing and acronyms', () => {expect(humanizeDomainName('super-ai-tools')).toBe('Super AI Tools')- expect(humanizeDomainName('myCoolApiDev')).toBe('My Cool API DEV')+ expect(humanizeDomainName('myCoolApiDev')).toBe('My Cool API Dev')+ expect(humanizeSlug('made-in-india')).toBe('Made in India')expect(humanizeDomainName('fast-ui-sdk')).toBe('Fast UI SDK')expect(humanizeDomainName('hacker-news-feed')).toBe('Hacker News Feed')})@@ -81,61 +83,217 @@ describe('parseUrlPreview tracking parameter stripper', () => {})})-describe('parseUrlPreview deep semantic path extractors', () => {- it('extracts GitHub PRs, Issues, and Repos', () => {- const pr = parseUrlPreview('https://github.com/facebook/react/pull/28000')- expect(pr.title).toBe('facebook/react · Pull Request #28000')- expect(pr.subtitle).toBe('Pull Request')- expect(pr.serviceName).toBe('GitHub')+/** What the card shows: top line, body, and the link line under a title. */+function card(url: string, pageTitle?: string) {+ const i = parseUrlPreview(url)+ const top = i.subtitle ? `${i.serviceName} · ${i.subtitle}` : i.serviceName+ const t = (pageTitle || i.title || '').trim()+ const has = !!t && t.toLowerCase() !== i.displayUrl.toLowerCase() && t.toLowerCase() !== i.domain.toLowerCase() && t.toLowerCase() !== i.serviceName.toLowerCase()+ return { top, body: has ? t : i.displayUrl, link: has ? i.displayUrl : undefined }+}- const issue = parseUrlPreview('https://github.com/microsoft/vscode/issues/199000')- expect(issue.title).toBe('microsoft/vscode · Issue #199000')- expect(issue.subtitle).toBe('Issue')+describe('titles: the path part that reads like a title, never an ID', () => {+ it('product pages show the product, not codes or tracking', () => {+ expect(card('https://www.amazon.in/Apple-iPhone-15-128-GB/dp/B0CHX1W1XY/ref=sr_1_3?crid=2X&keywords=iphone')).toMatchObject({ top: 'Amazon · Product', body: 'Apple iPhone 15 128 GB' })+ expect(card('https://www.flipkart.com/apple-iphone-15-black-128-gb/p/itm6ac6485515ae4')).toMatchObject({ top: 'Flipkart · Product', body: 'Apple iPhone 15 Black 128 GB' })+ // an Amazon link with only the product code: no made-up title+ expect(card('https://www.amazon.co.uk/dp/B09G9FPHY6')).toEqual({ top: 'Amazon · Product', body: 'amazon.co.uk/dp/B09G9FPHY6', link: undefined })+ })++ it('articles: IDs glued to slugs and file endings are dropped', () => {+ expect(card('https://timesofindia.indiatimes.com/india/some-news-headline/articleshow/104123456.cms')).toMatchObject({ top: 'Times of India', body: 'Some News Headline' })+ expect(card('https://medium.com/@someone/how-i-built-a-thing-3f2a9b1c4d5e')).toMatchObject({ top: 'Medium · Article', body: 'How I Built a Thing' })+ expect(card('https://www.bbc.co.uk/news/world-asia-india-12345678')).toMatchObject({ top: 'BBC', body: 'World Asia India' })+ expect(card('https://www.example.com/blog/2026/10/how-to-make-great-coffee-at-home').body).toBe('How to Make Great Coffee at Home')+ })++ it('pages with nothing to tell show the link instead of junk', () => {+ expect(card('https://chatgpt.com/c/671234ab-1234-5678-9abc-def012345678')).toMatchObject({ top: 'ChatGPT · Conversation', body: 'chatgpt.com/c/671234ab-1234-5678-9abc-def012345678' })+ expect(card('https://claude.ai/chat/0b1c2d3e-4f5a-6b7c-8d9e-0f1a2b3c4d5e').top).toBe('Claude · Chat')+ expect(card('https://drive.google.com/file/d/1AbCdEf/view?usp=sharing')).toMatchObject({ top: 'Google Drive · File', body: 'drive.google.com/file/d/1AbCdEf/view?usp=sharing' })+ expect(card('https://shop.example.com/products/12345?variant=67890').body).toBe('shop.example.com/products/12345?variant=67890')+ })++ it('searches show what was searched', () => {+ expect(card('https://www.google.com/search?q=best+mechanical+keyboard+2026')).toMatchObject({ top: 'Google · Search', body: 'best mechanical keyboard 2026' })+ expect(card('https://www.youtube.com/results?search_query=lofi+beats')).toMatchObject({ top: 'YouTube · Search', body: 'lofi beats' })+ expect(card('https://www.amazon.in/s?k=usb+c+hub')).toMatchObject({ top: 'Amazon · Search', body: 'usb c hub' })+ expect(card('https://duckduckgo.com/?q=electron+tray')).toMatchObject({ top: 'DuckDuckGo · Search', body: 'electron tray' })+ })+})++describe('site rules match the exact site', () => {+ it('a site whose name contains another never borrows its rules (netflix.com ⊃ "x.com")', () => {+ const n = card('https://www.netflix.com/title/80057281')+ expect(n.top).toBe('Netflix · Title')+ expect(n.body).toBe('netflix.com/title/80057281')+ expect(card('https://www.max.com/movies/dune').top).not.toContain('X')+ })++ it('GitHub: repos, issues, PRs, files; site pages are not repos', () => {+ expect(card('https://github.com/facebook/react/pull/28000')).toMatchObject({ top: 'GitHub · Pull request', body: 'facebook/react #28000' })+ expect(card('https://github.com/microsoft/vscode/issues/199000')).toMatchObject({ top: 'GitHub · Issue', body: 'microsoft/vscode #199000' })+ expect(card('https://github.com/kushagrasinghx/BitChord.git')).toMatchObject({ top: 'GitHub · Repository', body: 'kushagrasinghx/BitChord' })+ expect(card('https://github.com/vercel/next.js/blob/canary/packages/next/src/server/next.ts')).toMatchObject({ top: 'GitHub · File', body: 'vercel/next.js · packages/next/src/server/next.ts' })+ expect(card('https://github.com/features/copilot')).toMatchObject({ top: 'GitHub', body: 'Copilot' })+ expect(card('https://github.com/settings/profile').top).toBe('GitHub')+ expect(card('https://github.com/torvalds')).toMatchObject({ top: 'GitHub · Profile', body: '@torvalds' })+ })++ it('YouTube: kind of page, start time when there is one, never the raw video ID as a title', () => {+ expect(card('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s')).toMatchObject({ top: 'YouTube · Video', body: 'Starts at 0:42' })+ expect(card('https://youtu.be/dQw4w9WgXcQ?t=1h2m3s').body).toBe('Starts at 1:02:03')+ expect(card('https://youtu.be/dQw4w9WgXcQ?si=abc')).toMatchObject({ top: 'YouTube · Video', body: 'youtu.be/dQw4w9WgXcQ' })+ expect(card('https://m.youtube.com/watch?v=dQw4w9WgXcQ').top).toBe('YouTube · Video')+ expect(card('https://youtube.com/shorts/abc123xyz').top).toBe('YouTube · Short')+ expect(card('https://www.youtube.com/@mkbhd/videos')).toMatchObject({ top: 'YouTube · Channel', body: '@mkbhd' })+ })++ it('Reddit, Wikipedia, X, LinkedIn, Instagram, Facebook', () => {+ expect(card('https://www.reddit.com/r/reactjs/comments/12345/awesome_new_state_manager/')).toMatchObject({ top: 'Reddit · r/reactjs', body: 'Awesome New State Manager' })+ expect(card('https://reddit.com/r/webdev')).toMatchObject({ top: 'Reddit · Community', body: 'r/webdev' })+ expect(card('https://en.wikipedia.org/wiki/Artificial_intelligence')).toMatchObject({ top: 'Wikipedia · Article', body: 'Artificial intelligence' })+ expect(card('https://en.m.wikipedia.org/wiki/Mount_Everest#History').body).toBe('Mount Everest § History')+ expect(card('https://x.com/elonmusk/status/1712345678901234567')).toMatchObject({ top: 'X · Post', body: '@elonmusk' })+ expect(card('https://www.linkedin.com/in/satyanadella/')).toMatchObject({ top: 'LinkedIn · Profile', body: 'satyanadella' })+ expect(card('https://www.linkedin.com/jobs/view/3912345678/').top).toBe('LinkedIn · Job')+ expect(card('https://www.instagram.com/p/C1a2b3c4d5e/').top).toBe('Instagram · Post')+ expect(card('https://www.instagram.com/natgeo/')).toMatchObject({ top: 'Instagram · Profile', body: '@natgeo' })+ expect(card('https://www.facebook.com/groups/123456789/posts/987654321/').top).toBe('Facebook · Group post')+ })++ it('maps, meetings and documents', () => {+ expect(card('https://www.google.com/maps/place/Eiffel+Tower/@48.85,2.29,17z')).toMatchObject({ top: 'Google Maps · Place', body: 'Eiffel Tower' })+ expect(card('https://www.google.com/maps/dir/Home/Office/@12.9,77.6,13z')).toMatchObject({ top: 'Google Maps · Directions', body: 'Home → Office' })+ expect(card('https://meet.google.com/abc-defg-hij')).toMatchObject({ top: 'Google Meet · Meeting', body: 'abc-defg-hij' })+ expect(card('https://us02web.zoom.us/j/1234567890?pwd=abc')).toMatchObject({ top: 'Zoom · Meeting', body: '123 456 7890' })+ expect(card('https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc').top).toBe('Microsoft Teams · Meeting')+ expect(card('https://docs.google.com/spreadsheets/d/1AbCdEfGh/edit#gid=0').top).toBe('Google Sheets · Spreadsheet')+ expect(card('https://www.figma.com/design/AbC123/Edge-Drop-UI?node-id=1-2')).toMatchObject({ top: 'Figma · Design', body: 'Edge Drop UI' })+ expect(card('https://www.notion.so/myteam/Project-Roadmap-0123456789abcdef0123456789abcdef')).toMatchObject({ top: 'Notion · Page', body: 'Project Roadmap' })+ })++ it('packages and papers', () => {+ expect(card('https://www.npmjs.com/package/@types/react')).toMatchObject({ top: 'npm · Package', body: '@types/react' })+ expect(card('https://arxiv.org/abs/2401.12345')).toMatchObject({ top: 'arXiv · Paper', body: '2401.12345' })+ expect(card('https://chatgpt.com/g/g-1234').top).toBe('ChatGPT · GPT')+ })+})- const repo = parseUrlPreview('https://github.com/kushagrasinghx/BitChord.git')- expect(repo.title).toBe('kushagrasinghx/BitChord')- expect(repo.subtitle).toBe('GitHub Repository')+describe('site names', () => {+ it('known sites by name, hosted sites by their own name, unknown ones humanized', () => {+ expect(parseUrlPreview('https://raw.githubusercontent.com/user/repo/main/README.md').serviceName).toBe('GitHub')+ expect(parseUrlPreview('https://someone.substack.com/p/the-future-of-work').serviceName).toBe('Someone')+ expect(card('https://my-app.vercel.app/')).toMatchObject({ top: 'My App · Vercel' })+ expect(parseUrlPreview('https://www.irctc.co.in/nget/train-search').serviceName).toBe('IRCTC')+ expect(parseUrlPreview('https://subdomain.my-cool-startup.io/').serviceName).toBe('My Cool Startup')+ expect(parseUrlPreview('https://xkcd.com/927/').serviceName).toBe('XKCD')})- it('extracts YouTube videos, shorts, and channels', () => {- const vid = parseUrlPreview('https://www.youtube.com/watch?v=dQw4w9WgXcQ')- expect(vid.title).toBe('YouTube Video (dQw4w9WgXcQ)')- expect(vid.serviceName).toBe('YouTube')+ it('this computer, the local network and plain IP addresses', () => {+ expect(card('http://localhost:3000/dashboard')).toEqual({ top: 'This computer · Port 3000', body: 'Dashboard', link: 'localhost:3000/dashboard' })+ expect(card('http://127.0.0.1:8080/').top).toBe('This computer · Port 8080')+ expect(card('http://192.168.1.1/admin')).toMatchObject({ top: 'Local network', body: 'Admin' })+ expect(card('http://printer.local/').top).toBe('Local network')+ expect(parseUrlPreview('http://8.8.8.8/').serviceName).toBe('8.8.8.8')+ })++ it('short links say so, under their service', () => {+ expect(card('https://bit.ly/3xYzAbC')).toEqual({ top: 'Bitly · Short link', body: 'bit.ly/3xYzAbC', link: undefined })+ expect(card('https://t.co/AbCdEf123').top).toBe('X · Short link')+ expect(card('https://maps.app.goo.gl/AbCdEf123').top).toBe('Google Maps · Short link')+ expect(card('https://amzn.to/3AbCdEf').top).toBe('Amazon · Short link')+ })+})- const shorts = parseUrlPreview('https://youtube.com/shorts/abc123xyz')- expect(shorts.title).toBe('YouTube Shorts · abc123xyz')- expect(shorts.subtitle).toBe('Shorts')+describe('redirect wrappers show and clean to the real destination', () => {+ it('Google, Facebook, Outlook safe links, YouTube redirects', () => {+ expect(card('https://www.google.com/url?q=https://example.com/page&sa=D').body).toBe('example.com/page')+ expect(cleanLink('https://www.google.com/url?q=https://example.com/page&sa=D')).toBe('https://example.com/page')+ expect(cleanLink('https://l.facebook.com/l.php?u=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26utm_source%3Dfb&h=AT0')).toBe('https://example.com/a?x=1')+ expect(cleanLink('https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fexample.org%2Fdoc&data=05')).toBe('https://example.org/doc')+ expect(cleanLink('https://www.youtube.com/redirect?event=video_description&q=https%3A%2F%2Fexample.com%2F')).toBe('https://example.com/')+ expect(unwrapRedirect('https://example.com/url?q=https://evil.test')).toBeNull()})- it('extracts Reddit subreddits and posts', () => {- const post = parseUrlPreview('https://www.reddit.com/r/reactjs/comments/12345/awesome_new_state_manager/')- expect(post.title).toBe('r/reactjs · Awesome New State Manager')- expect(post.subtitle).toBe('Reddit Post')+ it('clean link removes tracking and stray punctuation only', () => {+ expect(cleanLink('https://example.com/page?utm_source=x&id=5)')).toBe('https://example.com/page?id=5')+ expect(cleanLink('(https://example.com/a_(b))')).toBe('https://example.com/a_(b)')+ expect(cleanLink('https://example.com/end.')).toBe('https://example.com/end')+ })+})- const sub = parseUrlPreview('https://reddit.com/r/webdev')- expect(sub.title).toBe('r/webdev')- expect(sub.subtitle).toBe('Subreddit')+describe('readable links', () => {+ it('decodes percent-encoding and international domains for display only', () => {+ const hi = parseUrlPreview('https://hi.wikipedia.org/wiki/%E0%A4%AD%E0%A4%BE%E0%A4%B0%E0%A4%A4')+ expect(hi.title).toBe('भारत')+ expect(hi.displayUrl).toBe('hi.wikipedia.org/wiki/भारत')+ const idn = parseUrlPreview('https://例子.测试/路径')+ expect(idn.domain).toBe('例子.测试')+ expect(idn.displayUrl).toBe('例子.测试/路径')+ expect(hostToUnicode('xn--fsqu00a.xn--0zwm56d')).toBe('例子.测试')})- it('extracts Wikipedia articles with proper decoding', () => {- const wiki = parseUrlPreview('https://en.wikipedia.org/wiki/Artificial_intelligence')- expect(wiki.title).toBe('Artificial intelligence')- expect(wiki.subtitle).toBe('Wikipedia Article')+ it('a look-alike domain (Cyrillic "аррӏе") stays encoded so it can never pass for apple.com', () => {+ const fake = parseUrlPreview('https://xn--80ak6aa92e.com/')+ expect(fake.domain).toBe('xn--80ak6aa92e.com')+ expect(fake.serviceName).toBe('xn--80ak6aa92e.com')+ expect(hostToUnicode('xn--80ak6aa92e.com')).toBe('xn--80ak6aa92e.com')})- it('extracts AI, Dev & Knowledge platform metadata', () => {- const claude = parseUrlPreview('https://claude.ai/chat/abc-123')- expect(claude.serviceName).toBe('Claude')+ it('credentials never show; spaces and brackets copied around a link are ignored', () => {+ expect(parseUrlPreview('https://user:[email protected]/secret').displayUrl).toBe('example.com/secret')+ expect(card(' https://example.com/trailing-space ').top).toBe('Example')+ expect(parseUrlPreview('https://example.com/page)').displayUrl).toBe('example.com/page')+ expect(externalHref('(www.example.com/page).')).toBe('https://www.example.com/page')+ })- const chatgpt = parseUrlPreview('https://chatgpt.com/g/g-1234')- expect(chatgpt.serviceName).toBe('ChatGPT')+ it('email and phone links', () => {+ expect(card('mailto:[email protected]')).toEqual({ top: 'Email', body: '[email protected]', link: undefined })+ expect(card('mailto:[email protected]?subject=Invoice%20March')).toEqual({ top: 'Email', body: 'Invoice March', link: '[email protected]' })+ expect(card('tel:+919876543210')).toEqual({ top: 'Phone · Call', body: '+919876543210', link: undefined })+ })- const arxiv = parseUrlPreview('https://arxiv.org/abs/2401.12345')- expect(arxiv.title).toBe('arXiv Paper · 2401.12345')- expect(arxiv.serviceName).toBe('arXiv')+ it('every link parses fast and never throws, and results are cached', () => {+ const weird = ['', ' ', 'https://', 'http://[::1]:3000/x', 'https://a..b/', 'https://example.com/%', 'ftp://files.example.com/a.zip', 'file:///C:/x/y.pdf', 'javascript:alert(1)', 'https://' + 'a'.repeat(5000) + '.com']+ for (const w of weird) expect(() => parseUrlPreview(w)).not.toThrow()+ const t0 = performance.now()+ for (let i = 0; i < 2000; i++) parseUrlPreview(`https://example.com/post-${i}/how-to-do-thing-${i}?utm_source=x`)+ expect(performance.now() - t0).toBeLessThan(1500)+ expect(parseUrlPreview('https://github.com/a/b')).toBe(parseUrlPreview('https://github.com/a/b'))+ })+})++describe('what counts as a link (capture, drag-in)', () => {+ it('scheme, www., bare domains with real endings, mailto and tel', () => {+ for (const yes of ['https://example.com', 'http://localhost:3000', 'www.example.com', 'example.com', 'example.com/page', 'docs.example.dev/v2',+ 'sub.domain.co.in/path?x=1', 'mailto:[email protected]', 'tel:+91 98765 43210', 'notion.so/page', 'claude.ai/chat', 'github.io/x']) {+ expect(isLinkText(yes), yes).toBe(true)+ }+ })++ it('ordinary text, file names and versions are not links', () => {+ for (const no of ['hello world', 'Node.js', 'e.g.', 'v1.2.3', '3.14', 'readme.md', 'notes.md', 'logo.ai', 'script.sh', 'archive.zip', 'app.py',+ 'Safari.app', 'report.pdf', '[email protected]', 'example.com is great', 'https://a.com https://b.com', 'example.c', 'my.file.txt']) {+ expect(isLinkText(no), no).toBe(false)+ }+ })+})++describe('page title copied with the link', () => {+ it('reads the title from an anchor pointing at this same link', () => {+ const link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'+ expect(linkTitleFromHtml(`<html><body><!--StartFragment--><a href="${link}">Rick Astley - Never Gonna Give You Up (Official Video)</a><!--EndFragment--></body></html>`, link))+ .toBe('Rick Astley - Never Gonna Give You Up (Official Video)')+ // scheme, www., trailing slash and entity encoding don't matter+ expect(linkTitleFromHtml('<a href="https://example.com/a?x=1&y=2">Tom & Jerry – <b>Episode</b> 1</a>', 'example.com/a?x=1&y=2/')).toBe('Tom & Jerry – Episode 1')+ })- const npm = parseUrlPreview('https://www.npmjs.com/package/@types/react')- expect(npm.title).toBe('npm · @types/react')- expect(npm.serviceName).toBe('npm')+ it('ignores anchors to other links, link-looking text and empty text; caps the length', () => {+ expect(linkTitleFromHtml('<a href="https://other.com">Other</a>', 'https://example.com')).toBeUndefined()+ expect(linkTitleFromHtml('<a href="https://example.com">https://example.com</a>', 'https://example.com')).toBeUndefined()+ expect(linkTitleFromHtml('<a href="https://example.com"> </a>', 'https://example.com')).toBeUndefined()+ expect(linkTitleFromHtml(undefined, 'https://example.com')).toBeUndefined()+ expect(Array.from(linkTitleFromHtml(`<a href="https://example.com">${'x '.repeat(400)}</a>`, 'https://example.com')!).length).toBeLessThanOrEqual(200)})})