Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(shopping): classify merchant destinations and listing IDs (#1242)
Sanjeev Kumar3695cd0a4ad3
diff --git a/server/src/lib/merchant-detection.js b/server/src/lib/merchant-detection.jsnew file mode 100644index 000000000..82cc4f22f--- /dev/null+++ b/server/src/lib/merchant-detection.js@@ -0,0 +1,207 @@+import { createRequire } from 'node:module';+import { ownDomainMatcher } from './response-parser.js';++const require = createRequire(import.meta.url);+const MARKETPLACES = require('./merchant-marketplaces.json');+const MARKETPLACE_ENTRIES = Object.entries(MARKETPLACES);+const REDIRECTS = MARKETPLACE_ENTRIES.flatMap(([marketplace, config]) =>+ (config.redirects ?? []).map((redirect) => ({ marketplace, ...redirect })),+);++function normalizeHost(host) {+ return typeof host === 'string' ? host.trim().toLowerCase().replace(/\.$/, '') : '';+}++/** A host matches a registered domain only at a label boundary. */+function hostMatches(host, domain) {+ const candidate = normalizeHost(host);+ const registered = normalizeHost(domain);+ return Boolean(+ candidate && registered && (candidate === registered || candidate.endsWith(`.${registered}`)),+ );+}++/**+ * Parse only HTTP(S) destinations. Scheme-less merchant links are accepted,+ * but opaque schemes such as javascript: are not merchant URLs.+ */+function parseHttpUrl(value) {+ if (typeof value !== 'string' || !value.trim()) return null;+ const raw = value.trim();+ let parsed;++ try {+ parsed = new URL(raw);+ } catch {+ // Many merchant URLs omit the scheme. Do not prepend one to an explicitly+ // unsupported scheme, because that would turn malformed input into a host.+ if (/^[a-z][a-z\d+.-]*:/i.test(raw)) return null;+ try {+ parsed = new URL(`https://${raw}`);+ } catch {+ return null;+ }+ }++ if (!['http:', 'https:'].includes(parsed.protocol) || !parsed.hostname) return null;+ return parsed;+}++function redirectTarget(value, marketplace) {+ const candidates = [value];+ let decoded = value;+ // searchParams decodes one URL-encoding layer already. A few redirectors+ // encode the destination again, so allow two extra decode attempts.+ for (let i = 0; i < 2; i += 1) {+ try {+ const next = decodeURIComponent(decoded);+ if (next === decoded) break;+ decoded = next;+ candidates.push(decoded);+ } catch {+ break;+ }+ }++ const canonicalHost = MARKETPLACES[marketplace]?.hosts?.[0];+ for (const candidate of candidates) {+ if (typeof candidate !== 'string') continue;++ // Relative paths are common on affiliate links. Resolve them against the+ // marketplace's canonical host, never the affiliate redirect host.+ if (candidate.startsWith('/') && !candidate.startsWith('//') && canonicalHost) {+ try {+ return new URL(candidate, `https://${canonicalHost}/`);+ } catch {+ continue;+ }+ }++ // Only explicitly absolute HTTP(S) URLs are valid redirect destinations.+ // Do not reinterpret arbitrary strings such as "foo" as hosts.+ if (!/^https?:\/\//i.test(candidate)) continue;+ const absolute = parseHttpUrl(candidate);+ if (absolute) return absolute;+ }+ return null;+}++/** Resolve known affiliate links before checking marketplace or brand hosts. */+function resolveMerchantUrl(initialUrl) {+ let url = initialUrl;+ const visited = new Set([url.href]);++ // Do not follow untrusted general-purpose redirects. Only hosts and query+ // parameters listed in merchant-marketplaces.json are inspected.+ for (let depth = 0; depth < 3; depth += 1) {+ const host = normalizeHost(url.hostname);+ const redirect = REDIRECTS.find((entry) =>+ entry.hosts.some((registered) => hostMatches(host, registered)),+ );+ if (!redirect) break;++ let target = null;+ for (const parameter of redirect.parameters ?? []) {+ const candidate = url.searchParams.get(parameter);+ if (!candidate) continue;+ target = redirectTarget(candidate, redirect.marketplace);+ if (target) break;+ }+ if (!target || visited.has(target.href)) break;++ visited.add(target.href);+ url = target;+ }++ return url;+}++function detectMarketplace(host) {+ for (const [marketplace, config] of MARKETPLACE_ENTRIES) {+ if ((config.hosts ?? []).some((registered) => hostMatches(host, registered))) {+ return marketplace;+ }+ }++ // When a known affiliate URL has no usable destination parameter, classify+ // its redirect host itself instead of treating the merchant as a reseller.+ const redirect = REDIRECTS.find((entry) =>+ entry.hosts.some((registered) => hostMatches(host, registered)),+ );+ return redirect?.marketplace ?? null;+}++function isOwnDomain(url, brandDomains) {+ if (!Array.isArray(brandDomains)) return false;+ return ownDomainMatcher(brandDomains)(url.href);+}++function listingIdFor(marketplace, pathname) {+ const segments = pathname.split('/').filter(Boolean);+ const segmentIndex = (name) => segments.findIndex((segment) => segment.toLowerCase() === name);++ if (marketplace === 'amazon') {+ const match = pathname.match(/\/(?:dp|gp\/product)\/([a-z\d]{10})(?:\/|$)/i);+ return match ? match[1].toUpperCase() : null;+ }++ if (marketplace === 'ebay') {+ const index = segmentIndex('itm');+ if (index < 0) return null;+ const direct = segments[index + 1];+ if (/^\d+$/.test(direct ?? '')) return direct;+ const slugged = segments[index + 2];+ return /^\d+$/.test(slugged ?? '') ? slugged : null;+ }++ if (marketplace === 'walmart') {+ const index = segmentIndex('ip');+ if (index < 0) return null;+ const first = segments[index + 1];+ if (/^\d+$/.test(first ?? '')) return first;+ const withSlug = segments[index + 2];+ return /^\d+$/.test(withSlug ?? '') ? withSlug : null;+ }++ if (marketplace === 'etsy') {+ const index = segmentIndex('listing');+ const id = segments[index + 1];+ return index >= 0 && /^\d+$/.test(id ?? '') ? id : null;+ }++ return null;+}++/**+ * Classify the destination behind an AI shopping card's merchant URL.+ *+ * Marketplace host and redirect rules live in merchant-marketplaces.json, so+ * new country domains and redirectors can be added without changing logic.+ * Unknown and malformed URLs intentionally fall back to reseller.+ *+ * @param {string} merchantUrl+ * @param {{ brandDomains?: string[] }} [options]+ * @returns {{ kind: 'own'|'marketplace'|'reseller', marketplace: string|null, listingId: string|null }}+ */+export function classifyMerchant(merchantUrl, { brandDomains = [] } = {}) {+ const parsed = parseHttpUrl(merchantUrl);+ if (!parsed) return { kind: 'reseller', marketplace: null, listingId: null };++ const destination = resolveMerchantUrl(parsed);+ const host = normalizeHost(destination.hostname);+ const marketplace = detectMarketplace(host);++ if (marketplace) {+ return {+ kind: 'marketplace',+ marketplace,+ listingId: listingIdFor(marketplace, destination.pathname),+ };+ }++ if (isOwnDomain(destination, brandDomains)) {+ return { kind: 'own', marketplace: null, listingId: null };+ }++ return { kind: 'reseller', marketplace: null, listingId: null };+}diff --git a/server/src/lib/merchant-detection.test.js b/server/src/lib/merchant-detection.test.jsnew file mode 100644index 000000000..49a03db3f--- /dev/null+++ b/server/src/lib/merchant-detection.test.js@@ -0,0 +1,174 @@+import { describe, expect, it } from 'vitest';+import { classifyMerchant } from './merchant-detection.js';++describe('classifyMerchant', () => {+ it.each([+ ['exact brand domain', 'https://acme.example/products/coat?utm_source=ai', ['acme.example']],+ ['brand subdomain', 'https://shop.acme.example/products/coat', ['acme.example']],+ ['scheme-less brand domain', 'shop.acme.example/products/coat', ['acme.example']],+ ['www-prefixed brand domain', 'https://www.acme.example/products/coat', ['www.acme.example']],+ ])('classifies %s as own', (_label, url, brandDomains) => {+ expect(classifyMerchant(url, { brandDomains })).toEqual({+ kind: 'own',+ marketplace: null,+ listingId: null,+ });+ });++ it('does not treat a lookalike suffix as the brand domain', () => {+ expect(+ classifyMerchant('https://notacme.example/product', { brandDomains: ['acme.example'] }),+ ).toEqual({+ kind: 'reseller',+ marketplace: null,+ listingId: null,+ });+ });++ it.each([+ ['Amazon US', 'https://www.amazon.com/dp/B0C123ABCD?tag=tracked', 'amazon', 'B0C123ABCD'],+ [+ 'Amazon slugged detail path',+ 'https://www.amazon.com/a-product-slug/dp/B0C123ABCD/ref=detail?tag=tracked',+ 'amazon',+ 'B0C123ABCD',+ ],+ ['Amazon Belgium', 'https://www.amazon.com.be/dp/B0C123ABCD', 'amazon', 'B0C123ABCD'],+ ['Amazon South Africa', 'https://www.amazon.co.za/dp/B0C123ABCD', 'amazon', 'B0C123ABCD'],+ ['Amazon short link', 'https://amzn.to/3example', 'amazon', null],+ ['Amazon EU short link', 'https://amzn.eu/d/3example', 'amazon', null],+ ['Amazon generic short link', 'https://a.co/d/3example', 'amazon', null],+ [+ 'Amazon country domain',+ 'https://amazon.de/gp/product/1234567890/ref=detail?campaign=x',+ 'amazon',+ '1234567890',+ ],+ ['Amazon subdomain', 'https://affiliate.amazon.co.uk/dp/abc123def4', 'amazon', 'ABC123DEF4'],+ ['eBay Austria', 'https://www.ebay.at/itm/123456789012', 'ebay', '123456789012'],+ ['eBay Switzerland', 'https://www.ebay.ch/itm/123456789012', 'ebay', '123456789012'],+ ['eBay US short link', 'https://ebay.us/abc123', 'ebay', null],+ [+ 'eBay direct item path',+ 'https://www.ebay.com/itm/123456789012?campid=abc',+ 'ebay',+ '123456789012',+ ],+ [+ 'eBay slugged item path',+ 'https://www.ebay.co.uk/itm/vintage-lamp/123456789012?var=1',+ 'ebay',+ '123456789012',+ ],+ [+ 'Walmart item path',+ 'https://www.walmart.com/ip/Blue-Wool-Coat/123456789?athbdg=x',+ 'walmart',+ '123456789',+ ],+ ['Walmart item-only path', 'https://business.walmart.com/ip/987654321', 'walmart', '987654321'],+ [+ 'Etsy listing',+ 'https://www.etsy.com/listing/123456789/handmade-coat?ref=shop',+ 'etsy',+ '123456789',+ ],+ [+ 'AliExpress country host',+ 'https://www.aliexpress.us/item/1005001.html?spm=x',+ 'aliexpress',+ null,+ ],+ ['Temu', 'https://www.temu.com/product.html?goods_id=123', 'temu', null],+ ['Trendyol', 'https://www.trendyol.com/brand/p-123?boutiqueId=2', 'trendyol', null],+ ['Hepsiburada', 'https://www.hepsiburada.com/product-p-123', 'hepsiburada', null],+ ])('classifies %s', (_label, url, marketplace, listingId) => {+ expect(classifyMerchant(url)).toEqual({ kind: 'marketplace', marketplace, listingId });+ });++ it('follows the AliExpress dl_target_url affiliate redirect', () => {+ const url =+ 'https://s.click.aliexpress.com/deep_link.htm?dl_target_url=' ++ encodeURIComponent('https://www.aliexpress.com/item/1005001234567890.html?spm=track');++ expect(classifyMerchant(url)).toEqual({+ kind: 'marketplace',+ marketplace: 'aliexpress',+ listingId: null,+ });+ });++ it('resolves a relative Walmart redirect path against the marketplace host', () => {+ expect(classifyMerchant('https://goto.walmart.com/?u=%2Fip%2FBlue-Coat%2F123456789')).toEqual({+ kind: 'marketplace',+ marketplace: 'walmart',+ listingId: '123456789',+ });+ });++ it('does not interpret a non-URL redirect parameter as a destination host', () => {+ expect(classifyMerchant('https://goto.walmart.com/?u=foo')).toEqual({+ kind: 'marketplace',+ marketplace: 'walmart',+ listingId: null,+ });+ });++ it('follows the Walmart u affiliate redirect and extracts the listing id', () => {+ const destination = 'https://www.walmart.com/ip/Blue-Coat/987654321?tracking=1';+ const url = `https://goto.walmart.com/c/123?u=${encodeURIComponent(destination)}`;++ expect(classifyMerchant(url)).toEqual({+ kind: 'marketplace',+ marketplace: 'walmart',+ listingId: '987654321',+ });+ });++ it('classifies known redirect hosts without a valid destination as their marketplace', () => {+ expect(classifyMerchant('https://goto.walmart.com/c/123?other=x')).toEqual({+ kind: 'marketplace',+ marketplace: 'walmart',+ listingId: null,+ });+ });++ it('uses the final redirect destination to identify the brand store', () => {+ const destination = 'https://shop.acme.example/products/coat';+ const url = `https://goto.walmart.com/?u=${encodeURIComponent(destination)}`;++ expect(classifyMerchant(url, { brandDomains: ['acme.example'] })).toEqual({+ kind: 'own',+ marketplace: null,+ listingId: null,+ });+ });++ it.each([+ 'https://www.unknown-store.example/products/1?utm_campaign=tracked',+ 'https://redirector.example/?url=https%3A%2F%2Famazon.com%2Fdp%2FB0C123ABCD',+ ])('classifies unknown hosts as reseller: %s', (url) => {+ expect(classifyMerchant(url)).toEqual({+ kind: 'reseller',+ marketplace: null,+ listingId: null,+ });+ });++ it.each([+ null,+ undefined,+ '',+ '::::',+ 'not a url with spaces',+ 'javascript:alert(1)',+ 'https://',+ ])('returns a safe reseller fallback for malformed input: %s', (url) => {+ expect(() => classifyMerchant(url)).not.toThrow();+ expect(classifyMerchant(url)).toEqual({+ kind: 'reseller',+ marketplace: null,+ listingId: null,+ });+ });+});diff --git a/server/src/lib/merchant-marketplaces.json b/server/src/lib/merchant-marketplaces.jsonnew file mode 100644index 000000000..1627455e8--- /dev/null+++ b/server/src/lib/merchant-marketplaces.json@@ -0,0 +1,94 @@+{+ "amazon": {+ "hosts": [+ "a.co",+ "amazon.ae",+ "amazon.at",+ "amazon.be",+ "amazon.ca",+ "amazon.ch",+ "amazon.co.jp",+ "amazon.co.uk",+ "amazon.co.za",+ "amazon.com",+ "amazon.com.au",+ "amazon.com.be",+ "amazon.com.br",+ "amazon.com.mx",+ "amazon.com.tr",+ "amazon.de",+ "amazon.eg",+ "amazon.es",+ "amazon.fr",+ "amazon.ie",+ "amazon.in",+ "amazon.it",+ "amazon.nl",+ "amazon.pl",+ "amazon.sa",+ "amazon.se",+ "amazon.sg",+ "amzn.eu",+ "amzn.to"+ ],+ "redirects": []+ },+ "ebay": {+ "hosts": [+ "ebay.at",+ "ebay.be",+ "ebay.ca",+ "ebay.ch",+ "ebay.co.uk",+ "ebay.com",+ "ebay.com.au",+ "ebay.com.hk",+ "ebay.com.my",+ "ebay.com.sg",+ "ebay.de",+ "ebay.es",+ "ebay.fr",+ "ebay.ie",+ "ebay.it",+ "ebay.nl",+ "ebay.ph",+ "ebay.pl",+ "ebay.us"+ ],+ "redirects": []+ },+ "walmart": {+ "hosts": ["walmart.com", "walmart.ca", "walmart.com.mx"],+ "redirects": [+ {+ "hosts": ["goto.walmart.com"],+ "parameters": ["u"]+ }+ ]+ },+ "etsy": {+ "hosts": ["etsy.com", "etsy.co.uk", "etsy.de"],+ "redirects": []+ },+ "aliexpress": {+ "hosts": ["aliexpress.com", "aliexpress.us", "aliexpress.ru"],+ "redirects": [+ {+ "hosts": ["s.click.aliexpress.com"],+ "parameters": ["dl_target_url"]+ }+ ]+ },+ "temu": {+ "hosts": ["temu.com", "temu.co.uk", "temu.com.tr"],+ "redirects": []+ },+ "trendyol": {+ "hosts": ["trendyol.com"],+ "redirects": []+ },+ "hepsiburada": {+ "hosts": ["hepsiburada.com"],+ "redirects": []+ }+}