Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(branding): declared brand marks as logo fallback (#4143)
Abimael Martell1d239bd4e892
diff --git a/apps/api/src/__tests__/lib/branding/declared-logo.test.ts b/apps/api/src/__tests__/lib/branding/declared-logo.test.tsnew file mode 100644index 000000000..40b4fe5d0--- /dev/null+++ b/apps/api/src/__tests__/lib/branding/declared-logo.test.ts@@ -0,0 +1,34 @@+import { describe, it, expect } from "vitest";+import { pickDeclaredLogo } from "../../../lib/branding/declared-logo";++describe("pickDeclaredLogo", () => {+ it("prefers JSON-LD declared logo over apple-touch icon", () => {+ expect(+ pickDeclaredLogo([+ { type: "favicon", src: "https://x.com/favicon.ico" },+ { type: "apple-touch-icon", src: "https://x.com/touch.png" },+ { type: "logo-jsonld", src: "https://x.com/logo.png" },+ ]),+ ).toEqual({ src: "https://x.com/logo.png", source: "logo-jsonld" });+ });++ it("falls back to apple-touch icon", () => {+ expect(+ pickDeclaredLogo([+ { type: "favicon", src: "https://x.com/favicon.ico" },+ { type: "apple-touch-icon", src: "https://x.com/touch.png" },+ ]),+ ).toEqual({ src: "https://x.com/touch.png", source: "apple-touch-icon" });+ });++ it("returns null when nothing is declared", () => {+ expect(+ pickDeclaredLogo([+ { type: "favicon", src: "https://x.com/favicon.ico" },+ { type: "og", src: "https://x.com/og.png" },+ ]),+ ).toBeNull();+ expect(pickDeclaredLogo(undefined)).toBeNull();+ expect(pickDeclaredLogo([])).toBeNull();+ });+});diff --git a/apps/api/src/__tests__/lib/branding/declared-marks.test.ts b/apps/api/src/__tests__/lib/branding/declared-marks.test.tsnew file mode 100644index 000000000..f693b5df1--- /dev/null+++ b/apps/api/src/__tests__/lib/branding/declared-marks.test.ts@@ -0,0 +1,389 @@+// @vitest-environment jsdom+import { describe, it, expect } from "vitest";+import {+ findDeclaredJsonLdLogo,+ findLargestAppleTouchIcon,+} from "../../../scraper/scrapeURL/engines/fire-engine/branding-script/declared-marks";++function docWith(...blocks: unknown[]): Document {+ document.head.innerHTML = blocks+ .map(+ b => `<script type="application/ld+json">${JSON.stringify(b)}</script>`,+ )+ .join("");+ return document;+}++describe("findDeclaredJsonLdLogo", () => {+ it("accepts an Organization logo", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({ "@type": "Organization", logo: "https://x.com/logo.png" }),+ ),+ ).toBe("https://x.com/logo.png");+ });++ it("resolves relative and protocol-relative URLs against the page", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({ "@type": "WebSite", logo: "/logo.svg" }),+ ),+ ).toMatch(/^https?:\/\/.+\/logo\.svg$/);+ });++ it("accepts ImageObject-shaped logos", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "LocalBusiness",+ logo: { "@type": "ImageObject", url: "https://x.com/lb.png" },+ }),+ ),+ ).toBe("https://x.com/lb.png");+ });++ it("skips product/brand logos (manufacturer, not the site)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Product",+ name: "Shoe",+ brand: { "@type": "Brand", logo: "https://nike.com/swoosh.png" },+ }),+ ),+ ).toBeNull();+ });++ it("skips Product-family subtypes (schema.org allows logo on Product)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "IndividualProduct",+ logo: "https://maker.com/product-logo.png",+ }),+ ),+ ).toBeNull();+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "ProductModel",+ logo: "https://maker.com/model-logo.png",+ }),+ ),+ ).toBeNull();+ });++ it("finds the site org even when a product block comes first", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith(+ {+ "@type": "Product",+ brand: { "@type": "Brand", logo: "https://nike.com/swoosh.png" },+ },+ { "@type": "Organization", logo: "https://shop.com/logo.png" },+ ),+ ),+ ).toBe("https://shop.com/logo.png");+ });++ it("handles @graph arrays and array @type", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@graph": [+ {+ "@type": ["Restaurant", "LocalBusiness"],+ logo: "https://r.com/l.png",+ },+ ],+ }),+ ),+ ).toBe("https://r.com/l.png");+ });++ it("prefers contentUrl over url when ImageObject declares both", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: {+ "@type": "ImageObject",+ url: "https://x.com/about-the-logo.html",+ contentUrl: "https://x.com/logo-file.png",+ },+ }),+ ),+ ).toBe("https://x.com/logo-file.png");+ });++ it("falls back to url when contentUrl is present but unusable", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: { contentUrl: "", url: "https://x.com/logo.png" },+ }),+ ),+ ).toBe("https://x.com/logo.png");+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: { contentUrl: "ipfs://Qm123", url: "https://x.com/logo.png" },+ }),+ ),+ ).toBe("https://x.com/logo.png");+ });++ it("accepts ImageObject contentUrl (canonical media URL property)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: { "@type": "ImageObject", contentUrl: "https://x.com/c.png" },+ }),+ ),+ ).toBe("https://x.com/c.png");+ });++ it("does not leak logos of untyped children under denied entities", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Product",+ brand: { name: "Nike", logo: "https://nike.com/swoosh.png" },+ }),+ ),+ ).toBeNull();+ });++ describe("findLargestAppleTouchIcon", () => {+ function docWithLinks(...links: string[]): Document {+ document.head.innerHTML = links.join("");+ return document;+ }++ it("uses the max dimension across multi-token sizes attributes", () => {+ expect(+ findLargestAppleTouchIcon(+ docWithLinks(+ '<link rel="apple-touch-icon" sizes="57x57 180x180" href="/multi.png">',+ '<link rel="apple-touch-icon" sizes="152x152" href="/single.png">',+ ),+ ),+ ).toMatch(/multi\.png$/);+ });++ it("rejects non-image schemes", () => {+ expect(+ findLargestAppleTouchIcon(+ docWithLinks(+ '<link rel="apple-touch-icon" href="javascript:alert(1)">',+ ),+ ),+ ).toBeNull();+ });+ });++ it("does not treat @context term definitions as logos", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith(+ {+ "@context": { logo: "https://schema.org/logo" },+ "@type": "Article",+ headline: "Post",+ },+ { "@type": "Organization", logo: "https://x.com/real-logo.png" },+ ),+ ),+ ).toBe("https://x.com/real-logo.png");+ });++ it("handles array-valued logos (first resolvable wins)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: ["", "https://x.com/a.png", "https://x.com/b.png"],+ }),+ ),+ ).toBe("https://x.com/a.png");+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: [{ "@type": "ImageObject", contentUrl: "https://x.com/c.png" }],+ }),+ ),+ ).toBe("https://x.com/c.png");+ });++ it("dereferences @id node references (Yoast @graph pattern)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "Organization",+ "@id": "https://site.com/#organization",+ logo: { "@id": "https://site.com/#/schema/logo/image/" },+ },+ {+ "@type": "ImageObject",+ "@id": "https://site.com/#/schema/logo/image/",+ url: "https://site.com/wp-content/logo.png",+ contentUrl: "https://site.com/wp-content/logo.png",+ },+ ],+ }),+ ),+ ).toBe("https://site.com/wp-content/logo.png");+ });++ it("dereferences @id across separate JSON-LD blocks", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith(+ {+ "@type": "Organization",+ logo: { "@id": "https://site.com/#logo-node" },+ },+ {+ "@type": "ImageObject",+ "@id": "https://site.com/#logo-node",+ contentUrl: "https://site.com/logo.svg",+ },+ ),+ ),+ ).toBe("https://site.com/logo.svg");+ });++ it("never uses a fragment @id as an image URL", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: { "@id": "https://site.com/#/schema/logo/image/" },+ }),+ ),+ ).toBeNull();+ });++ it("uses a fragment-free @id URL directly when unresolvable", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "Organization",+ logo: { "@id": "https://site.com/assets/logo.png" },+ }),+ ),+ ).toBe("https://site.com/assets/logo.png");+ });++ it("walks @included blocks", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@type": "WebPage",+ "@included": [+ { "@type": "Organization", logo: "https://x.com/inc-logo.png" },+ ],+ }),+ ),+ ).toBe("https://x.com/inc-logo.png");+ });++ it("does not dereference into denied entities", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@graph": [+ {+ "@type": "Organization",+ logo: { "@id": "https://site.com/#brandnode" },+ },+ {+ "@type": "Brand",+ "@id": "https://site.com/#brandnode",+ url: "https://nike.com/swoosh.png",+ },+ ],+ }),+ ),+ ).toBeNull();+ });++ it("prefers the @id definition carrying an image URL (split definitions)", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@graph": [+ {+ "@type": "Organization",+ logo: { "@id": "https://site.com/#logo" },+ },+ { "@id": "https://site.com/#logo", caption: "Logo" },+ {+ "@type": "ImageObject",+ "@id": "https://site.com/#logo",+ contentUrl: "https://site.com/full-logo.png",+ },+ ],+ }),+ ),+ ).toBe("https://site.com/full-logo.png");+ });++ it("split definition with unusable URLs does not shadow a usable one", () => {+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@graph": [+ {+ "@type": "Organization",+ logo: { "@id": "https://site.com/#logo" },+ },+ {+ "@type": "ImageObject",+ "@id": "https://site.com/#logo",+ contentUrl: "ipfs://Qm123",+ },+ {+ "@type": "ImageObject",+ "@id": "https://site.com/#logo",+ contentUrl: "https://site.com/usable-logo.png",+ },+ ],+ }),+ ),+ ).toBe("https://site.com/usable-logo.png");+ });++ it("matches relative and absolute @id spellings", () => {+ const abs = new URL("/#logo-rel", document.location.href).href;+ expect(+ findDeclaredJsonLdLogo(+ docWith({+ "@graph": [+ { "@type": "Organization", logo: { "@id": "/#logo-rel" } },+ {+ "@type": "ImageObject",+ "@id": abs,+ contentUrl: "https://site.com/rel-logo.png",+ },+ ],+ }),+ ),+ ).toBe("https://site.com/rel-logo.png");+ });++ it("ignores malformed JSON and non-http schemes", () => {+ document.head.innerHTML =+ '<script type="application/ld+json">{broken</script>' ++ `<script type="application/ld+json">${JSON.stringify({ "@type": "Organization", logo: "javascript:alert(1)" })}</script>`;+ expect(findDeclaredJsonLdLogo(document)).toBeNull();+ });+});diff --git a/apps/api/src/__tests__/snips/v2/scrape-branding.test.ts b/apps/api/src/__tests__/snips/v2/scrape-branding.test.tsindex a0d697219..d76e55479 100644--- a/apps/api/src/__tests__/snips/v2/scrape-branding.test.ts+++ b/apps/api/src/__tests__/snips/v2/scrape-branding.test.ts@@ -11,6 +11,30 @@ beforeAll(async () => {});}, 10000 + scrapeTimeout);+describe("Branding declared-logo fallback", () => {+ // The fixture page declares its logo via JSON-LD + apple-touch icon but+ // renders no logo image in the DOM, forcing the declared-mark fallback.+ concurrentIf(TEST_PRODUCTION)(+ "uses the JSON-LD declared logo when the DOM has none",+ async () => {+ const response = await scrape(+ {+ url: "https://firecrawl-test-site.vercel.app/branding-declared-only",+ formats: ["branding"],+ timeout: scrapeTimeout,+ },+ identity,+ );++ expect(response.branding).toBeDefined();+ expect(response.branding?.images?.logo).toBe(+ "https://firecrawl-test-site.vercel.app/declared-logo.png",+ );+ },+ scrapeTimeout,+ );+});+// TODO: fix this test// Need to run on fire-enginedescribe.skip("Branding extraction", () => {diff --git a/apps/api/src/lib/branding/declared-logo.ts b/apps/api/src/lib/branding/declared-logo.tsnew file mode 100644index 000000000..396ce7e19--- /dev/null+++ b/apps/api/src/lib/branding/declared-logo.ts@@ -0,0 +1,16 @@+/**+ * Fallback logo from site-declared brand marks, used only when the normal+ * candidate β heuristic β LLM pipeline produced no logo. JSON-LD `logo` is+ * the site explicitly naming its logo; the largest apple-touch icon is a+ * square brand mark by platform convention.+ */+export function pickDeclaredLogo(+ images: Array<{ type: string; src: string }> | undefined,+): { src: string; source: "logo-jsonld" | "apple-touch-icon" } | null {+ if (!images) return null;+ const jsonld = images.find(i => i.type === "logo-jsonld" && i.src);+ if (jsonld) return { src: jsonld.src, source: "logo-jsonld" };+ const touch = images.find(i => i.type === "apple-touch-icon" && i.src);+ if (touch) return { src: touch.src, source: "apple-touch-icon" };+ return null;+}diff --git a/apps/api/src/lib/branding/transformer.ts b/apps/api/src/lib/branding/transformer.tsindex b39eceff1..ba2d21c71 100644--- a/apps/api/src/lib/branding/transformer.ts+++ b/apps/api/src/lib/branding/transformer.ts@@ -11,6 +11,7 @@ import {getTopCandidatesForLLM,} from "./logo-selector";import { extractHeaderHtmlChunk } from "./extractHeaderHtmlChunk";+import { pickDeclaredLogo } from "./declared-logo";function isDebugBrandingEnabled(meta: Meta): boolean {return (@@ -422,6 +423,22 @@ export async function brandingTransformer(};}+ // Last-resort fallback: when the candidate β heuristic β LLM pipeline ended+ // with no logo (no candidates, LLM rejection, or LLM failure), use the+ // site-declared brand mark. Never overrides a selected logo.+ if (!brandingProfile.images?.logo) {+ const declared = pickDeclaredLogo(rawBranding.images);+ if (declared) {+ brandingProfile.images = {+ ...(brandingProfile.images ?? {}),+ logo: declared.src,+ };+ meta.logger.info("Using declared logo fallback", {+ source: declared.source,+ });+ }+ }+if (!isDebugBrandingEnabled(meta)) {delete (brandingProfile as any).__button_snapshots;delete (brandingProfile as any).__input_snapshots;diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/declared-marks.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/declared-marks.tsnew file mode 100644index 000000000..a42ab7e35--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/declared-marks.ts@@ -0,0 +1,242 @@+// Site-declared brand marks (JSON-LD logo, apple-touch icon), collected for+// the server-side declared-logo fallback.++// Entity types whose `logo` is NOT the site's own brand mark: product/brand+// nodes carry the manufacturer's logo on retailer pages, person nodes carry+// avatars, review/rating nodes carry third parties. A denylist (rather than+// an Organization/WebSite allowlist) keeps coverage of schema.org's hundreds+// of LocalBusiness subtypes (Restaurant, Dentist, ...), which small-business+// sites commonly use. Substring family match so schema.org subtypes are+// covered without enumerating the type tree: "product" catches Product,+// ProductModel, IndividualProduct, ProductGroup, SomeProducts; "offer"+// catches Offer, AggregateOffer; "review"/"rating" catch their+// Aggregate/User variants. No Organization/WebSite/LocalBusiness-family type+// name contains any of these words, so legitimate site entities are+// unaffected.+const WRONG_ENTITY_TYPE = /product|offer|brand|review|rating|person|comment/i;++function typeAllowsSiteLogo(t: unknown): boolean {+ const types = Array.isArray(t) ? t : t == null ? [] : [t];+ return !types.some(+ x => typeof x === "string" && WRONG_ENTITY_TYPE.test(x.trim()),+ );+}++function isAllowedImageUrl(href: string): boolean {+ return /^https?:\/\//i.test(href) || /^data:image\//i.test(href);+}++type IdMap = Map<string, Record<string, unknown>>;++function validateUrl(raw: unknown, baseUrl: string): string | null {+ if (typeof raw !== "string" || !raw.trim()) return null;+ try {+ const resolved = new URL(raw, baseUrl);+ if (resolved.protocol === "http:" || resolved.protocol === "https:") {+ return resolved.href;+ }+ } catch (_) {+ // Invalid URL β ignore+ }+ return null;+}++function resolveLogoUrl(+ logo: unknown,+ baseUrl: string,+ idMap: IdMap,+ depth = 0,+): string | null {+ if (depth > 3) return null;+ // Array-valued logo (legal JSON-LD): first item that resolves wins.+ if (Array.isArray(logo)) {+ for (const item of logo) {+ const r = resolveLogoUrl(item, baseUrl, idMap, depth + 1);+ if (r) return r;+ }+ return null;+ }+ if (typeof logo === "string") {+ return validateUrl(logo, baseUrl);+ }+ if (logo && typeof logo === "object") {+ const img = logo as Record<string, unknown>;+ // ImageObject: contentUrl is the actual media bytes; url is inherited+ // Thing.url and may point at a page *about* the image, so it's tried+ // second. A candidate that fails validation falls through to the next+ // rather than suppressing it.+ const direct =+ validateUrl(img.contentUrl, baseUrl) ?? validateUrl(img.url, baseUrl);+ if (direct) return direct;+ // Node reference ({"@id": ...}) β the Yoast/WordPress @graph pattern:+ // the Organization's logo points at a separate ImageObject node carrying+ // the actual URL. Dereference it. A fragment @id ("...#/schema/logo/...")+ // names a node, never an image, so it's only usable via dereference.+ const id = img["@id"];+ if (typeof id === "string" && id.trim()) {+ const referenced = idMap.get(normalizeId(id, baseUrl));+ // The referenced node must itself pass the wrong-entity filter β a+ // logo reference into e.g. a Brand node must not leak that entity's+ // URL past the type check.+ if (+ referenced &&+ referenced !== logo &&+ typeAllowsSiteLogo(referenced["@type"])+ ) {+ const deref =+ validateUrl(referenced.contentUrl, baseUrl) ??+ validateUrl(referenced.url, baseUrl);+ if (deref) return deref;+ }+ if (!id.includes("#")) {+ return validateUrl(id, baseUrl);+ }+ }+ }+ return null;+}++// JSON-LD keyword properties must not be walked for entity content:+// an inline @context can define a "logo" *term* (e.g. mapping to+// https://schema.org/logo) which is vocabulary, not data. @graph and+// @included are the keywords that legitimately contain node objects.+function isWalkableKey(key: string): boolean {+ return !key.startsWith("@") || key === "@graph" || key === "@included";+}++// Reference and definition may spell the same @id differently (relative+// "/#logo" vs absolute "https://site.com/#logo") β index and look up by the+// resolved form.+function normalizeId(id: string, baseUrl: string): string {+ try {+ return new URL(id, baseUrl).href;+ } catch (_) {+ return id;+ }+}++// Uses the same validation as dereferencing: a definition whose URLs are+// unusable (empty, ipfs://, malformed) must not win the index slot over a+// later definition that dereferencing could actually use.+function hasUsableImageUrl(+ obj: Record<string, unknown>,+ baseUrl: string,+): boolean {+ return (+ validateUrl(obj.contentUrl, baseUrl) !== null ||+ validateUrl(obj.url, baseUrl) !== null+ );+}++function collectIds(+ node: unknown,+ depth: number,+ idMap: IdMap,+ baseUrl: string,+): void {+ if (!node || typeof node !== "object" || depth > 6) return;+ if (Array.isArray(node)) {+ for (const item of node) collectIds(item, depth + 1, idMap, baseUrl);+ return;+ }+ const obj = node as Record<string, unknown>;+ const id = obj["@id"];+ // Register only node *definitions* β a bare {"@id": ...} is a reference+ // stub, and indexing it would shadow the real node it points to. When the+ // same @id is defined more than once (split definitions), prefer the one+ // that actually carries an image URL.+ if (typeof id === "string" && id.trim() && Object.keys(obj).length > 1) {+ const key = normalizeId(id, baseUrl);+ const existing = idMap.get(key);+ if (+ !existing ||+ (!hasUsableImageUrl(existing, baseUrl) && hasUsableImageUrl(obj, baseUrl))+ ) {+ idMap.set(key, obj);+ }+ }+ for (const [k, v] of Object.entries(obj)) {+ if (isWalkableKey(k)) collectIds(v, depth + 1, idMap, baseUrl);+ }+}++function findLogo(+ node: unknown,+ depth: number,+ baseUrl: string,+ idMap: IdMap,+): string | null {+ if (!node || typeof node !== "object" || depth > 6) return null;+ if (Array.isArray(node)) {+ for (const item of node) {+ const r = findLogo(item, depth + 1, baseUrl, idMap);+ if (r) return r;+ }+ return null;+ }+ const obj = node as Record<string, unknown>;+ // Skip the whole subtree of wrong-entity nodes: their children (brand+ // objects, offers, sellers) frequently omit @type, so walking into them+ // would leak a manufacturer/third-party logo via an untyped child.+ if (!typeAllowsSiteLogo(obj["@type"])) return null;+ const resolved = resolveLogoUrl(obj.logo, baseUrl, idMap);+ if (resolved) return resolved;+ for (const [k, v] of Object.entries(obj)) {+ if (!isWalkableKey(k)) continue;+ const r = findLogo(v, depth + 1, baseUrl, idMap);+ if (r) return r;+ }+ return null;+}++/**+ * Site-declared logo from JSON-LD structured data (Organization / WebSite /+ * LocalBusiness-family entities). Relative URLs are resolved against the+ * page URL; wrong-entity subtrees (products, third-party brands, people,+ * reviews) are skipped entirely; @id node references are dereferenced+ * across all JSON-LD blocks on the page (the Yoast @graph pattern).+ */+export function findDeclaredJsonLdLogo(doc: Document): string | null {+ const baseUrl = doc.location ? doc.location.href : "";+ const roots: unknown[] = [];+ doc.querySelectorAll('script[type="application/ld+json"]').forEach(el => {+ try {+ roots.push(JSON.parse(el.textContent || ""));+ } catch (_) {+ // Malformed JSON-LD β ignore+ }+ });+ // Pass 1: index @id β node across every block, so references resolve even+ // when the ImageObject lives in a different script tag than the Organization.+ const idMap: IdMap = new Map();+ for (const root of roots) collectIds(root, 0, idMap, baseUrl);+ // Pass 2: find the first usable declared logo.+ for (const root of roots) {+ const r = findLogo(root, 0, baseUrl, idMap);+ if (r) return r;+ }+ return null;+}++/**+ * Largest apple-touch icon (square brand mark by platform convention).+ * `sizes` may declare multiple tokens ("57x57 114x114") β the largest+ * dimension across all tokens wins. Only http(s)/data:image URLs qualify.+ */+export function findLargestAppleTouchIcon(doc: Document): string | null {+ let best: { href: string; size: number } | null = null;+ doc.querySelectorAll('link[rel*="apple-touch-icon" i]').forEach(el => {+ const link = el as HTMLLinkElement;+ if (!link.href || !isAllowedImageUrl(link.href)) return;+ const tokens = (link.getAttribute("sizes") || "").match(/\d+x\d+/gi) || [];+ let size = 1;+ for (const t of tokens) {+ const dim = Math.max(...t.toLowerCase().split("x").map(Number));+ if (dim > size) size = dim;+ }+ if (!best || size > best.size) {+ best = { href: link.href, size };+ }+ });+ return best ? (best as { href: string }).href : null;+}diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.tsindex bb3cbc227..32e52bdd1 100644--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts@@ -5,6 +5,10 @@ import {recordError,} from "./helpers";import { resolveSvgStyles } from "./svg-utils";+import {+ findDeclaredJsonLdLogo,+ findLargestAppleTouchIcon,+} from "./declared-marks";interface LogoCandidate {src: string;@@ -112,6 +116,24 @@ export const findImages = (): FindImagesResult => {"twitter",);+ // Declared brand marks β used server-side as a fallback when no logo is+ // selected from the DOM. Sites explicitly declare these, so they're the+ // most trustworthy signal available when heuristics/LLM come up empty.++ // Largest apple-touch icon (square brand mark by convention).+ try {+ push(findLargestAppleTouchIcon(document), "apple-touch-icon");+ } catch (_) {+ // Ignore errors+ }++ // JSON-LD "logo" (Organization/WebSite/LocalBusiness structured data).+ try {+ push(findDeclaredJsonLdLogo(document), "logo-jsonld");+ } catch (_) {+ // Ignore errors+ }+const ensureSvgEncoded = (url: string | null | undefined,): string | null | undefined => {