@tangle-network/agent-app 0.60.37 → 0.60.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -218,7 +218,29 @@ var GENERIC_FAMILIES = /* @__PURE__ */ new Set([
|
|
|
218
218
|
"initial",
|
|
219
219
|
"unset"
|
|
220
220
|
]);
|
|
221
|
-
var
|
|
221
|
+
var BLOCK_FONT_DECL_RE = /^[^{}]*font-family\s*:\s*([^;}{]+)[;}]/i;
|
|
222
|
+
function fontDeclarations(html) {
|
|
223
|
+
const declarations = [];
|
|
224
|
+
const braces = /[{}]/g;
|
|
225
|
+
const nextBrace = /[{}]/g;
|
|
226
|
+
let previousBrace = -1;
|
|
227
|
+
let resumeAt = 0;
|
|
228
|
+
for (let brace = braces.exec(html); brace; brace = braces.exec(html)) {
|
|
229
|
+
const at = brace.index;
|
|
230
|
+
if (html[at] === "{") {
|
|
231
|
+
nextBrace.lastIndex = at + 1;
|
|
232
|
+
const next = nextBrace.exec(html);
|
|
233
|
+
const end = next ? next.index + 1 : html.length;
|
|
234
|
+
const match = BLOCK_FONT_DECL_RE.exec(html.slice(at + 1, end));
|
|
235
|
+
if (match) {
|
|
236
|
+
declarations.push({ selector: html.slice(Math.max(previousBrace + 1, resumeAt), at), stack: match[1] });
|
|
237
|
+
resumeAt = at + 1 + match[0].length;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
previousBrace = at;
|
|
241
|
+
}
|
|
242
|
+
return declarations;
|
|
243
|
+
}
|
|
222
244
|
function parseFontStack(raw) {
|
|
223
245
|
if (!raw) return [];
|
|
224
246
|
return raw.split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
|
|
@@ -242,12 +264,11 @@ function extractFonts(html) {
|
|
|
242
264
|
byFamily.set(key, { family, stack, role, occurrences: 1 });
|
|
243
265
|
}
|
|
244
266
|
};
|
|
245
|
-
for (const
|
|
246
|
-
const
|
|
247
|
-
const stack = parseFontStack(m[2]);
|
|
267
|
+
for (const declaration of fontDeclarations(html)) {
|
|
268
|
+
const stack = parseFontStack(declaration.stack);
|
|
248
269
|
const primary = stack[0];
|
|
249
270
|
if (!primary) continue;
|
|
250
|
-
consider(primary, stack, roleFromSelector(selector));
|
|
271
|
+
consider(primary, stack, roleFromSelector(declaration.selector));
|
|
251
272
|
}
|
|
252
273
|
const BARE_RE = /font-family\s*:\s*([^;"'}{]+)/gi;
|
|
253
274
|
for (const m of html.matchAll(BARE_RE)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/brand-extraction/extract.ts","../../src/brand-extraction/map.ts"],"sourcesContent":["/**\n * Brand-kit extraction engine.\n *\n * Given a website URL (or raw HTML), parse the page and pull a typed BrandKit:\n * logo candidates, color palette, fonts, and prominent images. Parsing is\n * regex-based on purpose — this runs on Cloudflare Workers and other edge\n * runtimes where DOM libraries (jsdom/cheerio) are unavailable, and the page\n * structures we read (link tags, meta tags, CSS custom properties, font-family\n * declarations) are flat enough that a DOM buys nothing.\n *\n * Degrades gracefully: a missing favicon, no CSS tokens, or an image-only page\n * each narrow the kit rather than failing it. The ONLY hard failures are a bad\n * input (no html and no fetch) and a fetch error — both returned as a typed\n * `{ succeeded: false }` outcome so callers never mistake an empty kit for a\n * real one.\n */\n\nimport type {\n BrandColor,\n BrandExtractionResult,\n BrandFont,\n BrandImage,\n BrandKit,\n BrandLogoCandidate,\n ExtractBrandKitOptions,\n FetchLike,\n} from './types'\n\nconst DEFAULT_TIMEOUT_MS = 15000\nconst DEFAULT_MAX_PER_LIST = 12\n\n// ── URL helpers ──────────────────────────────────────────────────────────────\n\n/** Normalize a user-supplied site URL: add https:// when scheme-less, validate. */\nexport function normalizeSiteUrl(raw: string): string | null {\n const trimmed = raw.trim()\n if (!trimmed) return null\n // A non-http(s) scheme is an explicit reject — don't paper over it by\n // prepending https:// (that would turn \"ftp://x\" into host \"ftp\").\n if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^https?:\\/\\//i.test(trimmed)) return null\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n const u = new URL(withScheme)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** Resolve a possibly-relative href against the page URL. Returns null for\n * data: URIs and unresolvable values — we want servable http(s) URLs only. */\nfunction absolutize(href: string, base: string): string | null {\n const v = href.trim()\n if (!v || v.startsWith('data:') || v.startsWith('javascript:')) return null\n try {\n const u = new URL(v, base)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n// ── Attribute parsing ────────────────────────────────────────────────────────\n\n/** Pull all `<tag ...>` open-tags from html (case-insensitive). */\nfunction matchTags(html: string, tag: string): string[] {\n const re = new RegExp(`<${tag}\\\\b[^>]*>`, 'gi')\n return html.match(re) ?? []\n}\n\n/** Read an attribute value from a single tag string. Handles quoted and\n * unquoted values. Returns undefined when absent. */\nfunction attr(tag: string, name: string): string | undefined {\n const quoted = new RegExp(`\\\\b${name}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`, 'i').exec(tag)\n if (quoted) return decodeEntities(quoted[1] ?? '')\n const bare = new RegExp(`\\\\b${name}\\\\s*=\\\\s*([^\\\\s\"'>]+)`, 'i').exec(tag)\n return bare ? decodeEntities(bare[1] ?? '') : undefined\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(///gi, '/')\n}\n\n// ── Name / description ───────────────────────────────────────────────────────\n\nfunction extractName(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:site_name') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n const title = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html)?.[1]\n if (title) {\n // \"Acme — the best widget\" → \"Acme\". Split on common separators, take head.\n const head = (decodeEntities(title).split(/\\s+[|–—\\-:·]\\s+/)[0] ?? '').trim()\n if (head) return head\n }\n return undefined\n}\n\nfunction extractDescription(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'description' || prop === 'og:description') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n return undefined\n}\n\n// ── Logos ────────────────────────────────────────────────────────────────────\n\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n}\n\nfunction mimeFromUrl(url: string): string | undefined {\n const ext = new URL(url).pathname.split('.').pop()?.toLowerCase()\n return ext ? MIME_BY_EXT[ext] : undefined\n}\n\nfunction parseSizes(sizes: string | undefined): { width?: number; height?: number } {\n if (!sizes) return {}\n const m = /(\\d+)\\s*[x×]\\s*(\\d+)/i.exec(sizes)\n if (!m) return {}\n return { width: Number(m[1]), height: Number(m[2]) }\n}\n\nfunction extractLogos(html: string, base: string): BrandLogoCandidate[] {\n const out: BrandLogoCandidate[] = []\n const seen = new Set<string>()\n const push = (c: BrandLogoCandidate) => {\n if (seen.has(c.url)) return\n seen.add(c.url)\n out.push(c)\n }\n\n // link rel icons / apple-touch-icon\n for (const tag of matchTags(html, 'link')) {\n const rel = attr(tag, 'rel')?.toLowerCase() ?? ''\n const href = attr(tag, 'href')\n if (!href) continue\n const url = absolutize(href, base)\n if (!url) continue\n const { width, height } = parseSizes(attr(tag, 'sizes'))\n if (rel.includes('apple-touch-icon')) {\n push({ url, source: 'apple-touch-icon', confidence: 0.7, width, height, mimeType: mimeFromUrl(url) })\n } else if (rel.split(/\\s+/).includes('icon') || rel.includes('shortcut icon')) {\n push({ url, source: 'favicon', confidence: 0.5, width, height, mimeType: mimeFromUrl(url) })\n }\n }\n\n // og:image (often shows the logo in context — moderate confidence)\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:image' || prop === 'og:image:url') {\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (url) push({ url, source: 'og:image', confidence: 0.55, mimeType: mimeFromUrl(url) })\n }\n }\n\n // <img> whose src/class/alt/id mentions \"logo\" — the strongest in-page signal\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const alt = attr(tag, 'alt')\n const cls = attr(tag, 'class') ?? ''\n const id = attr(tag, 'id') ?? ''\n const looksLikeLogo = /logo|brand|wordmark/i.test(`${src} ${alt ?? ''} ${cls} ${id}`)\n if (!looksLikeLogo) continue\n const url = absolutize(src, base)\n if (!url) continue\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: 'img-logo',\n confidence: 0.85,\n alt,\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n mimeType: mimeFromUrl(url),\n })\n }\n\n // No favicon link tag at all? Fall back to the conventional /favicon.ico —\n // it almost always exists. Lowest confidence.\n if (!out.some((l) => l.source === 'favicon' || l.source === 'apple-touch-icon')) {\n const fav = absolutize('/favicon.ico', base)\n if (fav) push({ url: fav, source: 'favicon', confidence: 0.3, mimeType: 'image/x-icon' })\n }\n\n return out.sort((a, b) => b.confidence - a.confidence)\n}\n\n// ── Colors ───────────────────────────────────────────────────────────────────\n\n/** Normalize any CSS color literal to #rrggbb / #rrggbbaa hex, or null. */\nexport function normalizeColor(raw: string): string | null {\n const v = raw.trim().toLowerCase()\n // #rgb / #rgba / #rrggbb / #rrggbbaa\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(v)\n if (hex) {\n const h = hex[1] ?? ''\n // Expand 3/4-digit shorthand by doubling each nibble.\n if (h.length === 3 || h.length === 4) {\n return `#${h.split('').map((c) => c + c).join('')}`\n }\n return `#${h}`\n }\n // rgb()/rgba()\n const rgb = /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)(?:[\\s,/]+([\\d.%]+))?\\s*\\)$/.exec(v)\n if (rgb) {\n const to255 = (n: string | undefined) => Math.max(0, Math.min(255, Math.round(Number(n))))\n const r = to255(rgb[1]).toString(16).padStart(2, '0')\n const g = to255(rgb[2]).toString(16).padStart(2, '0')\n const b = to255(rgb[3]).toString(16).padStart(2, '0')\n let a = ''\n if (rgb[4] !== undefined) {\n const av = rgb[4].endsWith('%') ? Number(rgb[4].slice(0, -1)) / 100 : Number(rgb[4])\n const ai = Math.max(0, Math.min(255, Math.round(av * 255)))\n if (ai < 255) a = ai.toString(16).padStart(2, '0')\n }\n return `#${r}${g}${b}${a}`\n }\n return null\n}\n\nconst COLOR_LITERAL_RE = /#[0-9a-fA-F]{3,8}\\b|rgba?\\([^)]*\\)/g\nconst ROOT_VAR_RE = /(--[a-z0-9-]*(?:color|colour|bg|background|accent|brand|primary|secondary|surface|text|fg|ink)[a-z0-9-]*)\\s*:\\s*([^;}{]+)/gi\n\nfunction extractPalette(html: string): BrandColor[] {\n const byHex = new Map<string, BrandColor>()\n const bump = (hex: string, fromToken: boolean, tokenName?: string) => {\n const existing = byHex.get(hex)\n if (existing) {\n existing.occurrences += 1\n if (fromToken && !existing.fromToken) {\n existing.fromToken = true\n existing.tokenName = tokenName\n }\n } else {\n byHex.set(hex, { hex, occurrences: 1, fromToken, ...(tokenName ? { tokenName } : {}) })\n }\n }\n\n // CSS custom properties — highest-fidelity design tokens.\n for (const m of html.matchAll(ROOT_VAR_RE)) {\n const tokenName = m[1]\n const value = m[2]\n if (!value) continue\n const lit = value.match(COLOR_LITERAL_RE)?.[0]\n if (!lit) continue\n const hex = normalizeColor(lit)\n if (hex) bump(hex, true, tokenName)\n }\n\n // All other color literals across the document (inline styles, <style>).\n for (const m of html.matchAll(COLOR_LITERAL_RE)) {\n const hex = normalizeColor(m[0])\n if (hex) bump(hex, false)\n }\n\n // Rank: token-sourced first, then by popularity. Drop pure white/black noise\n // to the back so a real brand color leads.\n const isNeutral = (h: string) => /^#(0{6}|f{6})(ff)?$/i.test(h)\n return [...byHex.values()].sort((a, b) => {\n if (a.fromToken !== b.fromToken) return a.fromToken ? -1 : 1\n const an = isNeutral(a.hex) ? 1 : 0\n const bn = isNeutral(b.hex) ? 1 : 0\n if (an !== bn) return an - bn\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Fonts ────────────────────────────────────────────────────────────────────\n\nconst GENERIC_FAMILIES = new Set([\n 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui',\n 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', 'inherit', 'initial', 'unset',\n])\n\n/** font-family declarations, with the selector chunk preceding them for role\n * inference. Captures the selector text in group 1, the stack in group 2. */\nconst FONT_DECL_RE = /([^{}]*)\\{[^{}]*font-family\\s*:\\s*([^;}{]+)[;}]/gi\n\nfunction parseFontStack(raw: string | undefined): string[] {\n if (!raw) return []\n return raw\n .split(',')\n .map((s) => s.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter(Boolean)\n}\n\nfunction roleFromSelector(selector: string): 'display' | 'body' | 'unknown' {\n const s = selector.toLowerCase()\n if (/\\b(h[1-3]|\\.h[1-3]|heading|title|display|hero)\\b/.test(s)) return 'display'\n if (/\\b(body|p|html|\\.text|\\.content|root|:root|\\*)\\b/.test(s)) return 'body'\n return 'unknown'\n}\n\nfunction extractFonts(html: string): BrandFont[] {\n // Restrict to <style> blocks + the whole doc; inline style=\"\" attributes are\n // included because the regex matches any `{...font-family...}` chunk, but we\n // also scan style attributes explicitly below.\n const byFamily = new Map<string, BrandFont>()\n const consider = (family: string, stack: string[], role: BrandFont['role']) => {\n const key = family.toLowerCase()\n if (!family || GENERIC_FAMILIES.has(key)) return\n const existing = byFamily.get(key)\n if (existing) {\n existing.occurrences += 1\n if (existing.role === 'unknown' && role !== 'unknown') existing.role = role\n } else {\n byFamily.set(key, { family, stack, role, occurrences: 1 })\n }\n }\n\n for (const m of html.matchAll(FONT_DECL_RE)) {\n const selector = m[1] ?? ''\n const stack = parseFontStack(m[2])\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, roleFromSelector(selector))\n }\n\n // Bare `font-family:` declarations inside inline style attributes and tokens.\n const BARE_RE = /font-family\\s*:\\s*([^;\"'}{]+)/gi\n for (const m of html.matchAll(BARE_RE)) {\n const stack = parseFontStack(m[1])\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, 'unknown')\n }\n\n // Google Fonts <link href=\"...family=Inter:wght@400...\"> — strong signal.\n for (const tag of matchTags(html, 'link')) {\n const href = attr(tag, 'href') ?? ''\n if (!/fonts\\.googleapis\\.com/i.test(href)) continue\n for (const fam of href.matchAll(/family=([^:&]+)/gi)) {\n const captured = fam[1]\n if (!captured) continue\n const family = decodeURIComponent(captured.replace(/\\+/g, ' ')).trim()\n consider(family, [family], 'display')\n }\n }\n\n return [...byFamily.values()].sort((a, b) => {\n const rank = (r: BrandFont['role']) => (r === 'display' ? 0 : r === 'body' ? 1 : 2)\n const rr = rank(a.role) - rank(b.role)\n if (rr !== 0) return rr\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Images ───────────────────────────────────────────────────────────────────\n\nfunction extractImages(html: string, base: string): BrandImage[] {\n const out: BrandImage[] = []\n const seen = new Set<string>()\n const push = (img: BrandImage) => {\n if (seen.has(img.url)) return\n seen.add(img.url)\n out.push(img)\n }\n\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (!url) continue\n if (prop === 'og:image' || prop === 'og:image:url') push({ url, source: 'og:image' })\n else if (prop === 'twitter:image' || prop === 'twitter:image:src') push({ url, source: 'twitter:image' })\n }\n\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const url = absolutize(src, base)\n if (!url) continue\n const cls = `${attr(tag, 'class') ?? ''} ${attr(tag, 'id') ?? ''}`\n // Skip obvious logos/icons — those go in the logos list, not images.\n if (/logo|icon|favicon|wordmark/i.test(`${url} ${cls}`)) continue\n const isHero = /hero|banner|cover|feature|splash/i.test(cls)\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: isHero ? 'img-hero' : 'img-content',\n alt: attr(tag, 'alt'),\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n })\n }\n\n const rank = (s: BrandImage['source']) =>\n s === 'og:image' ? 0 : s === 'twitter:image' ? 1 : s === 'img-hero' ? 2 : 3\n return out.sort((a, b) => rank(a.source) - rank(b.source))\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/** Parse already-fetched HTML into a BrandKit. Pure — no network. Exposed so\n * callers that hold the HTML (or want to combine multiple pages) can reuse the\n * parsing without re-fetching. */\nexport function parseBrandKit(html: string, sourceUrl: string, maxPerList = DEFAULT_MAX_PER_LIST): BrandKit {\n const logos = extractLogos(html, sourceUrl).slice(0, maxPerList)\n const palette = extractPalette(html).slice(0, maxPerList)\n const fonts = extractFonts(html).slice(0, maxPerList)\n const images = extractImages(html, sourceUrl).slice(0, maxPerList)\n const name = extractName(html)\n const description = extractDescription(html)\n\n return {\n sourceUrl,\n ...(name ? { name } : {}),\n ...(description ? { description } : {}),\n logos,\n palette,\n fonts,\n images,\n extractedFrom: [sourceUrl],\n }\n}\n\n/**\n * Fetch a website (or use supplied HTML) and extract its BrandKit.\n *\n * Returns a typed outcome — callers MUST check `succeeded`. A fetch failure or\n * empty input is a real, surfaced error, never an empty kit masquerading as a\n * result. Parsing itself never throws: a malformed page yields a sparse kit\n * with warnings, which is information, not failure.\n */\nexport async function extractBrandKit(\n url: string,\n options: ExtractBrandKitOptions = {},\n): Promise<BrandExtractionResult> {\n const { html: providedHtml, fetchImpl, timeoutMs = DEFAULT_TIMEOUT_MS, maxPerList = DEFAULT_MAX_PER_LIST } = options\n const warnings: string[] = []\n\n const sourceUrl = normalizeSiteUrl(url)\n if (!sourceUrl) {\n return { succeeded: false, error: `Not a valid http(s) URL: ${JSON.stringify(url)}`, stage: 'input' }\n }\n\n let html = providedHtml\n if (html === undefined) {\n const doFetch: FetchLike | undefined =\n fetchImpl ?? (typeof globalThis.fetch === 'function'\n ? (u, init) => globalThis.fetch(u, init as RequestInit)\n : undefined)\n if (!doFetch) {\n return { succeeded: false, error: 'No html provided and no fetch implementation available', stage: 'input' }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await doFetch(sourceUrl, {\n signal: controller.signal,\n headers: { 'user-agent': 'TangleBrandExtractor/1.0 (+https://tangle.tools)' },\n })\n if (!res.ok) {\n return { succeeded: false, error: `Fetch failed: HTTP ${res.status} for ${sourceUrl}`, stage: 'fetch' }\n }\n html = await res.text()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n return { succeeded: false, error: `Fetch error for ${sourceUrl}: ${reason}`, stage: 'fetch' }\n } finally {\n clearTimeout(timer)\n }\n }\n\n if (!html.trim()) {\n return { succeeded: false, error: `Empty document for ${sourceUrl}`, stage: 'parse' }\n }\n\n const kit = parseBrandKit(html, sourceUrl, maxPerList)\n\n if (kit.logos.length === 0) warnings.push('No logo candidates found.')\n if (kit.palette.length === 0) warnings.push('No colors extracted — page has no inline CSS or design tokens.')\n if (kit.fonts.length === 0) warnings.push('No custom fonts found — site likely uses system defaults.')\n if (kit.images.length === 0) warnings.push('No prominent images found.')\n\n return { succeeded: true, kit, warnings }\n}\n","/**\n * Pure mapping helpers from an extracted BrandKit onto consumable shapes.\n *\n * Extraction yields ranked candidate lists; products need decided roles\n * (background vs accent, display vs body). These helpers make the obvious,\n * defensible default choice and expose the reasoning so a confirmation UI can\n * show \"we picked X — change it?\". They NEVER invent a value: when a role can't\n * be filled from the kit, it is omitted, and the caller decides the fallback.\n */\n\nimport type { BrandColor, BrandFont, BrandKit } from './types'\n\n/** Relative luminance (0..1) of an #rrggbb(aa) hex — for light/dark sorting. */\nexport function luminance(hex: string): number {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const lin = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)\n return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)\n}\n\nfunction isGreyish(hex: string): boolean {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16)\n const g = parseInt(h.slice(2, 4), 16)\n const b = parseInt(h.slice(4, 6), 16)\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n return max - min < 18\n}\n\n/** Define a color palette with background, surface, text, and accent colors for UI elements */\nexport interface DecidedPalette {\n /** Lightest neutral — page background. */\n background?: string\n /** A raised neutral one step from background. */\n surface?: string\n /** Darkest readable color — primary text. */\n textPrimary?: string\n /** Mid-tone neutral — secondary text. */\n textSecondary?: string\n /** Most saturated / popular brand color — accent. */\n accent?: string\n /** Readable text color to sit on the accent (black or white by contrast). */\n accentText?: string\n}\n\n/**\n * Assign palette roles from the ranked colors. Heuristic, not authoritative —\n * a confirmation step should let the user correct it. Roles only appear when\n * the kit actually contained a color that fits.\n */\nexport function decidePalette(palette: BrandColor[]): DecidedPalette {\n if (palette.length === 0) return {}\n const hexes = palette.map((c) => c.hex)\n const greys = hexes.filter(isGreyish).sort((a, b) => luminance(b) - luminance(a))\n const colored = hexes.filter((h) => !isGreyish(h))\n\n // Accent: the top-ranked non-grey (token-first, popularity-first) color.\n const accent = colored[0]\n // Background: lightest grey (or lightest overall when no greys).\n const sortedLight = [...hexes].sort((a, b) => luminance(b) - luminance(a))\n const background = greys[0] ?? sortedLight[0]\n // Surface: next grey under background, else second-lightest.\n const surface = greys[1] ?? sortedLight.find((h) => h !== background)\n // Text primary: darkest color overall.\n const textPrimary = [...hexes].sort((a, b) => luminance(a) - luminance(b))[0]\n // Text secondary: a mid-luminance grey distinct from primary/background.\n const textSecondary = greys.find((h) => h !== background && h !== surface && h !== textPrimary)\n\n const result: DecidedPalette = {}\n if (background) result.background = background\n if (surface) result.surface = surface\n if (textPrimary) result.textPrimary = textPrimary\n if (textSecondary) result.textSecondary = textSecondary\n if (accent) {\n result.accent = accent\n result.accentText = luminance(accent) > 0.45 ? '#000000' : '#ffffff'\n }\n return result\n}\n\n/** Define font selections for display and body text with optional BrandFont properties */\nexport interface DecidedFonts {\n display?: BrandFont\n body?: BrandFont\n}\n\n/** Pick a display and body font from the ranked list. When only one usable\n * font exists it fills both roles — a single-typeface brand is valid. */\nexport function decideFonts(fonts: BrandFont[]): DecidedFonts {\n if (fonts.length === 0) return {}\n const display = fonts.find((f) => f.role === 'display') ?? fonts[0]\n const body = fonts.find((f) => f.role === 'body') ?? fonts.find((f) => f !== display) ?? display\n return { display, body }\n}\n\n/** Everything a confirmation step needs from a kit, with roles decided. */\nexport interface DecidedBrandKit {\n name?: string\n description?: string\n sourceUrl: string\n palette: DecidedPalette\n fonts: DecidedFonts\n /** Best logo URL, when any candidate was found. */\n primaryLogoUrl?: string\n /** All logo URLs, ranked. */\n logoUrls: string[]\n /** Prominent image URLs, ranked. */\n imageUrls: string[]\n extractedFrom: string[]\n}\n\n/** Collapse a raw BrandKit into decided roles — the shape a product persists. */\nexport function decideBrandKit(kit: BrandKit): DecidedBrandKit {\n const palette = decidePalette(kit.palette)\n const fonts = decideFonts(kit.fonts)\n const logoUrls = kit.logos.map((l) => l.url)\n const result: DecidedBrandKit = {\n sourceUrl: kit.sourceUrl,\n palette,\n fonts,\n logoUrls,\n imageUrls: kit.images.map((i) => i.url),\n extractedFrom: kit.extractedFrom,\n }\n if (kit.name) result.name = kit.name\n if (kit.description) result.description = kit.description\n if (logoUrls[0]) result.primaryLogoUrl = logoUrls[0]\n return result\n}\n"],"mappings":";AA4BA,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAKtB,SAAS,iBAAiB,KAA4B;AAC3D,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AAGrB,MAAI,uBAAuB,KAAK,OAAO,KAAK,CAAC,gBAAgB,KAAK,OAAO,EAAG,QAAO;AACnF,QAAM,aAAa,gBAAgB,KAAK,OAAO,IAAI,UAAU,WAAW,OAAO;AAC/E,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,UAAU;AAC5B,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,SAAS,WAAW,MAAc,MAA6B;AAC7D,QAAM,IAAI,KAAK,KAAK;AACpB,MAAI,CAAC,KAAK,EAAE,WAAW,OAAO,KAAK,EAAE,WAAW,aAAa,EAAG,QAAO;AACvE,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG,IAAI;AACzB,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAKA,SAAS,UAAU,MAAc,KAAuB;AACtD,QAAM,KAAK,IAAI,OAAO,IAAI,GAAG,aAAa,IAAI;AAC9C,SAAO,KAAK,MAAM,EAAE,KAAK,CAAC;AAC5B;AAIA,SAAS,KAAK,KAAa,MAAkC;AAC3D,QAAM,SAAS,IAAI,OAAO,MAAM,IAAI,6BAA6B,GAAG,EAAE,KAAK,GAAG;AAC9E,MAAI,OAAQ,QAAO,eAAe,OAAO,CAAC,KAAK,EAAE;AACjD,QAAM,OAAO,IAAI,OAAO,MAAM,IAAI,yBAAyB,GAAG,E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9F,QAAM,SAAyB,CAAC;AAChC,MAAI,WAAY,QAAO,aAAa;AACpC,MAAI,QAAS,QAAO,UAAU;AAC9B,MAAI,YAAa,QAAO,cAAc;AACtC,MAAI,cAAe,QAAO,gBAAgB;AAC1C,MAAI,QAAQ;AACV,WAAO,SAAS;AAChB,WAAO,aAAa,UAAU,MAAM,IAAI,OAAO,YAAY;AAAA,EAC7D;AACA,SAAO;AACT;AAUO,SAAS,YAAY,OAAkC;AAC5D,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAChC,QAAM,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS,KAAK,MAAM,CAAC;AAClE,QAAM,OAAO,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,KAAK,MAAM,KAAK,CAAC,MAAM,MAAM,OAAO,KAAK;AACzF,SAAO,EAAE,SAAS,KAAK;AACzB;AAmBO,SAAS,eAAe,KAAgC;AAC7D,QAAM,UAAU,cAAc,IAAI,OAAO;AACzC,QAAM,QAAQ,YAAY,IAAI,KAAK;AACnC,QAAM,WAAW,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG;AAC3C,QAAM,SAA0B;AAAA,IAC9B,WAAW,IAAI;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG;AAAA,IACtC,eAAe,IAAI;AAAA,EACrB;AACA,MAAI,IAAI,KAAM,QAAO,OAAO,IAAI;AAChC,MAAI,IAAI,YAAa,QAAO,cAAc,IAAI;AAC9C,MAAI,SAAS,CAAC,EAAG,QAAO,iBAAiB,SAAS,CAAC;AACnD,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/brand-extraction/extract.ts","../../src/brand-extraction/map.ts"],"sourcesContent":["/**\n * Brand-kit extraction engine.\n *\n * Given a website URL (or raw HTML), parse the page and pull a typed BrandKit:\n * logo candidates, color palette, fonts, and prominent images. Parsing is\n * regex-based on purpose — this runs on Cloudflare Workers and other edge\n * runtimes where DOM libraries (jsdom/cheerio) are unavailable, and the page\n * structures we read (link tags, meta tags, CSS custom properties, font-family\n * declarations) are flat enough that a DOM buys nothing.\n *\n * Degrades gracefully: a missing favicon, no CSS tokens, or an image-only page\n * each narrow the kit rather than failing it. The ONLY hard failures are a bad\n * input (no html and no fetch) and a fetch error — both returned as a typed\n * `{ succeeded: false }` outcome so callers never mistake an empty kit for a\n * real one.\n */\n\nimport type {\n BrandColor,\n BrandExtractionResult,\n BrandFont,\n BrandImage,\n BrandKit,\n BrandLogoCandidate,\n ExtractBrandKitOptions,\n FetchLike,\n} from './types'\n\nconst DEFAULT_TIMEOUT_MS = 15000\nconst DEFAULT_MAX_PER_LIST = 12\n\n// ── URL helpers ──────────────────────────────────────────────────────────────\n\n/** Normalize a user-supplied site URL: add https:// when scheme-less, validate. */\nexport function normalizeSiteUrl(raw: string): string | null {\n const trimmed = raw.trim()\n if (!trimmed) return null\n // A non-http(s) scheme is an explicit reject — don't paper over it by\n // prepending https:// (that would turn \"ftp://x\" into host \"ftp\").\n if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^https?:\\/\\//i.test(trimmed)) return null\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n const u = new URL(withScheme)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** Resolve a possibly-relative href against the page URL. Returns null for\n * data: URIs and unresolvable values — we want servable http(s) URLs only. */\nfunction absolutize(href: string, base: string): string | null {\n const v = href.trim()\n if (!v || v.startsWith('data:') || v.startsWith('javascript:')) return null\n try {\n const u = new URL(v, base)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n// ── Attribute parsing ────────────────────────────────────────────────────────\n\n/** Pull all `<tag ...>` open-tags from html (case-insensitive). */\nfunction matchTags(html: string, tag: string): string[] {\n const re = new RegExp(`<${tag}\\\\b[^>]*>`, 'gi')\n return html.match(re) ?? []\n}\n\n/** Read an attribute value from a single tag string. Handles quoted and\n * unquoted values. Returns undefined when absent. */\nfunction attr(tag: string, name: string): string | undefined {\n const quoted = new RegExp(`\\\\b${name}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`, 'i').exec(tag)\n if (quoted) return decodeEntities(quoted[1] ?? '')\n const bare = new RegExp(`\\\\b${name}\\\\s*=\\\\s*([^\\\\s\"'>]+)`, 'i').exec(tag)\n return bare ? decodeEntities(bare[1] ?? '') : undefined\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(///gi, '/')\n}\n\n// ── Name / description ───────────────────────────────────────────────────────\n\nfunction extractName(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:site_name') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n const title = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html)?.[1]\n if (title) {\n // \"Acme — the best widget\" → \"Acme\". Split on common separators, take head.\n const head = (decodeEntities(title).split(/\\s+[|–—\\-:·]\\s+/)[0] ?? '').trim()\n if (head) return head\n }\n return undefined\n}\n\nfunction extractDescription(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'description' || prop === 'og:description') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n return undefined\n}\n\n// ── Logos ────────────────────────────────────────────────────────────────────\n\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n}\n\nfunction mimeFromUrl(url: string): string | undefined {\n const ext = new URL(url).pathname.split('.').pop()?.toLowerCase()\n return ext ? MIME_BY_EXT[ext] : undefined\n}\n\nfunction parseSizes(sizes: string | undefined): { width?: number; height?: number } {\n if (!sizes) return {}\n const m = /(\\d+)\\s*[x×]\\s*(\\d+)/i.exec(sizes)\n if (!m) return {}\n return { width: Number(m[1]), height: Number(m[2]) }\n}\n\nfunction extractLogos(html: string, base: string): BrandLogoCandidate[] {\n const out: BrandLogoCandidate[] = []\n const seen = new Set<string>()\n const push = (c: BrandLogoCandidate) => {\n if (seen.has(c.url)) return\n seen.add(c.url)\n out.push(c)\n }\n\n // link rel icons / apple-touch-icon\n for (const tag of matchTags(html, 'link')) {\n const rel = attr(tag, 'rel')?.toLowerCase() ?? ''\n const href = attr(tag, 'href')\n if (!href) continue\n const url = absolutize(href, base)\n if (!url) continue\n const { width, height } = parseSizes(attr(tag, 'sizes'))\n if (rel.includes('apple-touch-icon')) {\n push({ url, source: 'apple-touch-icon', confidence: 0.7, width, height, mimeType: mimeFromUrl(url) })\n } else if (rel.split(/\\s+/).includes('icon') || rel.includes('shortcut icon')) {\n push({ url, source: 'favicon', confidence: 0.5, width, height, mimeType: mimeFromUrl(url) })\n }\n }\n\n // og:image (often shows the logo in context — moderate confidence)\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:image' || prop === 'og:image:url') {\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (url) push({ url, source: 'og:image', confidence: 0.55, mimeType: mimeFromUrl(url) })\n }\n }\n\n // <img> whose src/class/alt/id mentions \"logo\" — the strongest in-page signal\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const alt = attr(tag, 'alt')\n const cls = attr(tag, 'class') ?? ''\n const id = attr(tag, 'id') ?? ''\n const looksLikeLogo = /logo|brand|wordmark/i.test(`${src} ${alt ?? ''} ${cls} ${id}`)\n if (!looksLikeLogo) continue\n const url = absolutize(src, base)\n if (!url) continue\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: 'img-logo',\n confidence: 0.85,\n alt,\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n mimeType: mimeFromUrl(url),\n })\n }\n\n // No favicon link tag at all? Fall back to the conventional /favicon.ico —\n // it almost always exists. Lowest confidence.\n if (!out.some((l) => l.source === 'favicon' || l.source === 'apple-touch-icon')) {\n const fav = absolutize('/favicon.ico', base)\n if (fav) push({ url: fav, source: 'favicon', confidence: 0.3, mimeType: 'image/x-icon' })\n }\n\n return out.sort((a, b) => b.confidence - a.confidence)\n}\n\n// ── Colors ───────────────────────────────────────────────────────────────────\n\n/** Normalize any CSS color literal to #rrggbb / #rrggbbaa hex, or null. */\nexport function normalizeColor(raw: string): string | null {\n const v = raw.trim().toLowerCase()\n // #rgb / #rgba / #rrggbb / #rrggbbaa\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(v)\n if (hex) {\n const h = hex[1] ?? ''\n // Expand 3/4-digit shorthand by doubling each nibble.\n if (h.length === 3 || h.length === 4) {\n return `#${h.split('').map((c) => c + c).join('')}`\n }\n return `#${h}`\n }\n // rgb()/rgba()\n const rgb = /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)(?:[\\s,/]+([\\d.%]+))?\\s*\\)$/.exec(v)\n if (rgb) {\n const to255 = (n: string | undefined) => Math.max(0, Math.min(255, Math.round(Number(n))))\n const r = to255(rgb[1]).toString(16).padStart(2, '0')\n const g = to255(rgb[2]).toString(16).padStart(2, '0')\n const b = to255(rgb[3]).toString(16).padStart(2, '0')\n let a = ''\n if (rgb[4] !== undefined) {\n const av = rgb[4].endsWith('%') ? Number(rgb[4].slice(0, -1)) / 100 : Number(rgb[4])\n const ai = Math.max(0, Math.min(255, Math.round(av * 255)))\n if (ai < 255) a = ai.toString(16).padStart(2, '0')\n }\n return `#${r}${g}${b}${a}`\n }\n return null\n}\n\nconst COLOR_LITERAL_RE = /#[0-9a-fA-F]{3,8}\\b|rgba?\\([^)]*\\)/g\nconst ROOT_VAR_RE = /(--[a-z0-9-]*(?:color|colour|bg|background|accent|brand|primary|secondary|surface|text|fg|ink)[a-z0-9-]*)\\s*:\\s*([^;}{]+)/gi\n\nfunction extractPalette(html: string): BrandColor[] {\n const byHex = new Map<string, BrandColor>()\n const bump = (hex: string, fromToken: boolean, tokenName?: string) => {\n const existing = byHex.get(hex)\n if (existing) {\n existing.occurrences += 1\n if (fromToken && !existing.fromToken) {\n existing.fromToken = true\n existing.tokenName = tokenName\n }\n } else {\n byHex.set(hex, { hex, occurrences: 1, fromToken, ...(tokenName ? { tokenName } : {}) })\n }\n }\n\n // CSS custom properties — highest-fidelity design tokens.\n for (const m of html.matchAll(ROOT_VAR_RE)) {\n const tokenName = m[1]\n const value = m[2]\n if (!value) continue\n const lit = value.match(COLOR_LITERAL_RE)?.[0]\n if (!lit) continue\n const hex = normalizeColor(lit)\n if (hex) bump(hex, true, tokenName)\n }\n\n // All other color literals across the document (inline styles, <style>).\n for (const m of html.matchAll(COLOR_LITERAL_RE)) {\n const hex = normalizeColor(m[0])\n if (hex) bump(hex, false)\n }\n\n // Rank: token-sourced first, then by popularity. Drop pure white/black noise\n // to the back so a real brand color leads.\n const isNeutral = (h: string) => /^#(0{6}|f{6})(ff)?$/i.test(h)\n return [...byHex.values()].sort((a, b) => {\n if (a.fromToken !== b.fromToken) return a.fromToken ? -1 : 1\n const an = isNeutral(a.hex) ? 1 : 0\n const bn = isNeutral(b.hex) ? 1 : 0\n if (an !== bn) return an - bn\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Fonts ────────────────────────────────────────────────────────────────────\n\nconst GENERIC_FAMILIES = new Set([\n 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui',\n 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', 'inherit', 'initial', 'unset',\n])\n\n/** The last terminated font-family declaration in one rule body. Applied to a\n * body that holds no brace except an optional closing one, so its\n * backtracking stays inside that body. */\nconst BLOCK_FONT_DECL_RE = /^[^{}]*font-family\\s*:\\s*([^;}{]+)[;}]/i\n\n/**\n * Each rule body's font-family stack, with the selector text before the body\n * for role inference.\n *\n * One pass over the braces. A single unanchored `([^{}]*)\\{[^{}]*font-family`\n * pattern restarted its selector scan at every character of a brace-free run,\n * so a long run of page markup before a rule without a font-family made it\n * quadratic: a 366 KB page took 74 s and the brand intake request exceeded its\n * CPU limit. This walk gives the same selectors and stacks: the selector is\n * the text since the previous brace or the end of the previous declaration it\n * found, whichever is later.\n */\nfunction fontDeclarations(html: string): Array<{ selector: string; stack: string }> {\n const declarations: Array<{ selector: string; stack: string }> = []\n const braces = /[{}]/g\n const nextBrace = /[{}]/g\n let previousBrace = -1\n let resumeAt = 0\n for (let brace = braces.exec(html); brace; brace = braces.exec(html)) {\n const at = brace.index\n if (html[at] === '{') {\n nextBrace.lastIndex = at + 1\n const next = nextBrace.exec(html)\n // The body runs to the next brace and keeps a closing one, which can end the declaration.\n const end = next ? next.index + 1 : html.length\n const match = BLOCK_FONT_DECL_RE.exec(html.slice(at + 1, end))\n if (match) {\n declarations.push({ selector: html.slice(Math.max(previousBrace + 1, resumeAt), at), stack: match[1]! })\n resumeAt = at + 1 + match[0].length\n }\n }\n previousBrace = at\n }\n return declarations\n}\n\nfunction parseFontStack(raw: string | undefined): string[] {\n if (!raw) return []\n return raw\n .split(',')\n .map((s) => s.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter(Boolean)\n}\n\nfunction roleFromSelector(selector: string): 'display' | 'body' | 'unknown' {\n const s = selector.toLowerCase()\n if (/\\b(h[1-3]|\\.h[1-3]|heading|title|display|hero)\\b/.test(s)) return 'display'\n if (/\\b(body|p|html|\\.text|\\.content|root|:root|\\*)\\b/.test(s)) return 'body'\n return 'unknown'\n}\n\nfunction extractFonts(html: string): BrandFont[] {\n // Restrict to <style> blocks + the whole doc; inline style=\"\" attributes are\n // included because the regex matches any `{...font-family...}` chunk, but we\n // also scan style attributes explicitly below.\n const byFamily = new Map<string, BrandFont>()\n const consider = (family: string, stack: string[], role: BrandFont['role']) => {\n const key = family.toLowerCase()\n if (!family || GENERIC_FAMILIES.has(key)) return\n const existing = byFamily.get(key)\n if (existing) {\n existing.occurrences += 1\n if (existing.role === 'unknown' && role !== 'unknown') existing.role = role\n } else {\n byFamily.set(key, { family, stack, role, occurrences: 1 })\n }\n }\n\n for (const declaration of fontDeclarations(html)) {\n const stack = parseFontStack(declaration.stack)\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, roleFromSelector(declaration.selector))\n }\n\n // Bare `font-family:` declarations inside inline style attributes and tokens.\n const BARE_RE = /font-family\\s*:\\s*([^;\"'}{]+)/gi\n for (const m of html.matchAll(BARE_RE)) {\n const stack = parseFontStack(m[1])\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, 'unknown')\n }\n\n // Google Fonts <link href=\"...family=Inter:wght@400...\"> — strong signal.\n for (const tag of matchTags(html, 'link')) {\n const href = attr(tag, 'href') ?? ''\n if (!/fonts\\.googleapis\\.com/i.test(href)) continue\n for (const fam of href.matchAll(/family=([^:&]+)/gi)) {\n const captured = fam[1]\n if (!captured) continue\n const family = decodeURIComponent(captured.replace(/\\+/g, ' ')).trim()\n consider(family, [family], 'display')\n }\n }\n\n return [...byFamily.values()].sort((a, b) => {\n const rank = (r: BrandFont['role']) => (r === 'display' ? 0 : r === 'body' ? 1 : 2)\n const rr = rank(a.role) - rank(b.role)\n if (rr !== 0) return rr\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Images ───────────────────────────────────────────────────────────────────\n\nfunction extractImages(html: string, base: string): BrandImage[] {\n const out: BrandImage[] = []\n const seen = new Set<string>()\n const push = (img: BrandImage) => {\n if (seen.has(img.url)) return\n seen.add(img.url)\n out.push(img)\n }\n\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (!url) continue\n if (prop === 'og:image' || prop === 'og:image:url') push({ url, source: 'og:image' })\n else if (prop === 'twitter:image' || prop === 'twitter:image:src') push({ url, source: 'twitter:image' })\n }\n\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const url = absolutize(src, base)\n if (!url) continue\n const cls = `${attr(tag, 'class') ?? ''} ${attr(tag, 'id') ?? ''}`\n // Skip obvious logos/icons — those go in the logos list, not images.\n if (/logo|icon|favicon|wordmark/i.test(`${url} ${cls}`)) continue\n const isHero = /hero|banner|cover|feature|splash/i.test(cls)\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: isHero ? 'img-hero' : 'img-content',\n alt: attr(tag, 'alt'),\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n })\n }\n\n const rank = (s: BrandImage['source']) =>\n s === 'og:image' ? 0 : s === 'twitter:image' ? 1 : s === 'img-hero' ? 2 : 3\n return out.sort((a, b) => rank(a.source) - rank(b.source))\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/** Parse already-fetched HTML into a BrandKit. Pure — no network. Exposed so\n * callers that hold the HTML (or want to combine multiple pages) can reuse the\n * parsing without re-fetching. */\nexport function parseBrandKit(html: string, sourceUrl: string, maxPerList = DEFAULT_MAX_PER_LIST): BrandKit {\n const logos = extractLogos(html, sourceUrl).slice(0, maxPerList)\n const palette = extractPalette(html).slice(0, maxPerList)\n const fonts = extractFonts(html).slice(0, maxPerList)\n const images = extractImages(html, sourceUrl).slice(0, maxPerList)\n const name = extractName(html)\n const description = extractDescription(html)\n\n return {\n sourceUrl,\n ...(name ? { name } : {}),\n ...(description ? { description } : {}),\n logos,\n palette,\n fonts,\n images,\n extractedFrom: [sourceUrl],\n }\n}\n\n/**\n * Fetch a website (or use supplied HTML) and extract its BrandKit.\n *\n * Returns a typed outcome — callers MUST check `succeeded`. A fetch failure or\n * empty input is a real, surfaced error, never an empty kit masquerading as a\n * result. Parsing itself never throws: a malformed page yields a sparse kit\n * with warnings, which is information, not failure.\n */\nexport async function extractBrandKit(\n url: string,\n options: ExtractBrandKitOptions = {},\n): Promise<BrandExtractionResult> {\n const { html: providedHtml, fetchImpl, timeoutMs = DEFAULT_TIMEOUT_MS, maxPerList = DEFAULT_MAX_PER_LIST } = options\n const warnings: string[] = []\n\n const sourceUrl = normalizeSiteUrl(url)\n if (!sourceUrl) {\n return { succeeded: false, error: `Not a valid http(s) URL: ${JSON.stringify(url)}`, stage: 'input' }\n }\n\n let html = providedHtml\n if (html === undefined) {\n const doFetch: FetchLike | undefined =\n fetchImpl ?? (typeof globalThis.fetch === 'function'\n ? (u, init) => globalThis.fetch(u, init as RequestInit)\n : undefined)\n if (!doFetch) {\n return { succeeded: false, error: 'No html provided and no fetch implementation available', stage: 'input' }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await doFetch(sourceUrl, {\n signal: controller.signal,\n headers: { 'user-agent': 'TangleBrandExtractor/1.0 (+https://tangle.tools)' },\n })\n if (!res.ok) {\n return { succeeded: false, error: `Fetch failed: HTTP ${res.status} for ${sourceUrl}`, stage: 'fetch' }\n }\n html = await res.text()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n return { succeeded: false, error: `Fetch error for ${sourceUrl}: ${reason}`, stage: 'fetch' }\n } finally {\n clearTimeout(timer)\n }\n }\n\n if (!html.trim()) {\n return { succeeded: false, error: `Empty document for ${sourceUrl}`, stage: 'parse' }\n }\n\n const kit = parseBrandKit(html, sourceUrl, maxPerList)\n\n if (kit.logos.length === 0) warnings.push('No logo candidates found.')\n if (kit.palette.length === 0) warnings.push('No colors extracted — page has no inline CSS or design tokens.')\n if (kit.fonts.length === 0) warnings.push('No custom fonts found — site likely uses system defaults.')\n if (kit.images.length === 0) warnings.push('No prominent images found.')\n\n return { succeeded: true, kit, warnings }\n}\n","/**\n * Pure mapping helpers from an extracted BrandKit onto consumable shapes.\n *\n * Extraction yields ranked candidate lists; products need decided roles\n * (background vs accent, display vs body). These helpers make the obvious,\n * defensible default choice and expose the reasoning so a confirmation UI can\n * show \"we picked X — change it?\". They NEVER invent a value: when a role can't\n * be filled from the kit, it is omitted, and the caller decides the fallback.\n */\n\nimport type { BrandColor, BrandFont, BrandKit } from './types'\n\n/** Relative luminance (0..1) of an #rrggbb(aa) hex — for light/dark sorting. */\nexport function luminance(hex: string): number {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const lin = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)\n return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)\n}\n\nfunction isGreyish(hex: string): boolean {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16)\n const g = parseInt(h.slice(2, 4), 16)\n const b = parseInt(h.slice(4, 6), 16)\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n return max - min < 18\n}\n\n/** Define a color palette with background, surface, text, and accent colors for UI elements */\nexport interface DecidedPalette {\n /** Lightest neutral — page background. */\n background?: string\n /** A raised neutral one step from background. */\n surface?: string\n /** Darkest readable color — primary text. */\n textPrimary?: string\n /** Mid-tone neutral — secondary text. */\n textSecondary?: string\n /** Most saturated / popular brand color — accent. */\n accent?: string\n /** Readable text color to sit on the accent (black or white by contrast). */\n accentText?: string\n}\n\n/**\n * Assign palette roles from the ranked colors. Heuristic, not authoritative —\n * a confirmation step should let the user correct it. Roles only appear when\n * the kit actually contained a color that fits.\n */\nexport function decidePalette(palette: BrandColor[]): DecidedPalette {\n if (palette.length === 0) return {}\n const hexes = palette.map((c) => c.hex)\n const greys = hexes.filter(isGreyish).sort((a, b) => luminance(b) - luminance(a))\n const colored = hexes.filter((h) => !isGreyish(h))\n\n // Accent: the top-ranked non-grey (token-first, popularity-first) color.\n const accent = colored[0]\n // Background: lightest grey (or lightest overall when no greys).\n const sortedLight = [...hexes].sort((a, b) => luminance(b) - luminance(a))\n const background = greys[0] ?? sortedLight[0]\n // Surface: next grey under background, else second-lightest.\n const surface = greys[1] ?? sortedLight.find((h) => h !== background)\n // Text primary: darkest color overall.\n const textPrimary = [...hexes].sort((a, b) => luminance(a) - luminance(b))[0]\n // Text secondary: a mid-luminance grey distinct from primary/background.\n const textSecondary = greys.find((h) => h !== background && h !== surface && h !== textPrimary)\n\n const result: DecidedPalette = {}\n if (background) result.background = background\n if (surface) result.surface = surface\n if (textPrimary) result.textPrimary = textPrimary\n if (textSecondary) result.textSecondary = textSecondary\n if (accent) {\n result.accent = accent\n result.accentText = luminance(accent) > 0.45 ? '#000000' : '#ffffff'\n }\n return result\n}\n\n/** Define font selections for display and body text with optional BrandFont properties */\nexport interface DecidedFonts {\n display?: BrandFont\n body?: BrandFont\n}\n\n/** Pick a display and body font from the ranked list. When only one usable\n * font exists it fills both roles — a single-typeface brand is valid. */\nexport function decideFonts(fonts: BrandFont[]): DecidedFonts {\n if (fonts.length === 0) return {}\n const display = fonts.find((f) => f.role === 'display') ?? fonts[0]\n const body = fonts.find((f) => f.role === 'body') ?? fonts.find((f) => f !== display) ?? display\n return { display, body }\n}\n\n/** Everything a confirmation step needs from a kit, with roles decided. */\nexport interface DecidedBrandKit {\n name?: string\n description?: string\n sourceUrl: string\n palette: DecidedPalette\n fonts: DecidedFonts\n /** Best logo URL, when any candidate was found. */\n primaryLogoUrl?: string\n /** All logo URLs, ranked. */\n logoUrls: string[]\n /** Prominent image URLs, ranked. */\n imageUrls: string[]\n extractedFrom: string[]\n}\n\n/** Collapse a raw BrandKit into decided roles — the shape a product persists. */\nexport function decideBrandKit(kit: BrandKit): DecidedBrandKit {\n const palette = decidePalette(kit.palette)\n const fonts = decideFonts(kit.fonts)\n const logoUrls = kit.logos.map((l) => l.url)\n const result: DecidedBrandKit = {\n sourceUrl: kit.sourceUrl,\n palette,\n fonts,\n logoUrls,\n imageUrls: kit.images.map((i) => i.url),\n extractedFrom: kit.extractedFrom,\n }\n if (kit.name) result.name = kit.name\n if (kit.description) result.description = kit.description\n if (logoUrls[0]) result.primaryLogoUrl = logoUrls[0]\n return result\n}\n"],"mappings":";AA4BA,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAKtB,SAAS,iBAAiB,KAA4B;AAC3D,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AAGrB,MAAI,uBAAuB,KAAK,OAAO,KAAK,CAAC,gBAAgB,KAAK,OAAO,EAAG,QAAO;AACnF,QAAM,aAAa,gBAAgB,KAAK,OAAO,IAAI,UAAU,WAAW,OAAO;AAC/E,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,UAAU;AAC5B,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,SAAS,WAAW,MAAc,MAA6B;AAC7D,QAAM,IAAI,KAAK,KAAK;AACpB,MAAI,CAAC,KAAK,EAAE,WAAW,OAAO,KAAK,EAAE,WAAW,aAAa,EAAG,QAAO;AACvE,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG,IAAI;AACzB,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAKA,SAAS,UAAU,MAAc,KAAuB;AACtD,QAAM,KAAK,IAAI,OAAO,IAAI,GAAG,aAAa,IAAI;AAC9C,SAAO,KAAK,MAAM,EAAE,KAAK,CAAC;AAC5B;AAIA,SAAS,KAAK,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