agentic-commerce-readiness 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/bin/agentic-commerce-readiness.js +100 -0
- package/package.json +56 -4
- package/src/feed/export.js +109 -0
- package/src/feed/parse.js +259 -0
- package/src/feed/validate.js +337 -0
- package/src/feed/values.js +182 -0
- package/src/index.js +123 -0
- package/src/live/catalog.js +131 -0
- package/src/live/consistency.js +135 -0
- package/src/live/discovery.js +149 -0
- package/src/live/http.js +28 -0
- package/src/report.js +128 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Value-level helpers shared by validation and export.
|
|
2
|
+
|
|
3
|
+
// ISO 4217 minor units that differ from 2. Source: ISO 4217 list (SIX).
|
|
4
|
+
const MINOR_UNITS = {
|
|
5
|
+
BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0, RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
|
|
6
|
+
BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
|
|
7
|
+
CLF: 4, UYW: 4,
|
|
8
|
+
};
|
|
9
|
+
export const minorUnits = (code) => (code in MINOR_UNITS ? MINOR_UNITS[code] : 2);
|
|
10
|
+
|
|
11
|
+
const SYMBOLS = { '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', 'Rs': 'PKR', 'Rs.': 'PKR', 'PKR': 'PKR', 'AED': 'AED', 'SAR': 'SAR' };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Parse a money string. Returns { ok, amount, currency, problems: [...], suggestion }.
|
|
15
|
+
* Strict format (OpenAI): "79.99 USD". Google also accepts this form.
|
|
16
|
+
*/
|
|
17
|
+
// ISO 4217 codes known to this Node.js runtime (Node 18+). Empty set means "cannot check".
|
|
18
|
+
const ISO_CURRENCIES = new Set(typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('currency') : []);
|
|
19
|
+
export const isKnownCurrency = (c) => !ISO_CURRENCIES.size || ISO_CURRENCIES.has(String(c).toUpperCase());
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Format an amount for a currency without changing its value.
|
|
23
|
+
* Returns undefined when that would need rounding: changing a price is never a "safe fix".
|
|
24
|
+
*/
|
|
25
|
+
function exactAmount(int, dec, currency) {
|
|
26
|
+
const units = minorUnits(currency);
|
|
27
|
+
const extra = dec.slice(units);
|
|
28
|
+
if (/[1-9]/.test(extra)) return undefined;
|
|
29
|
+
const kept = dec.slice(0, units).padEnd(units, '0');
|
|
30
|
+
const i = String(int).replace(/^0+(?=\d)/, '');
|
|
31
|
+
return units ? `${i}.${kept}` : i;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Parse an OpenAI-format money value ("79.99 USD").
|
|
36
|
+
* Returns { ok, amount, currency, problems, suggestion }. `suggestion` is only set when the fix is exact.
|
|
37
|
+
*/
|
|
38
|
+
export function parseMoney(raw) {
|
|
39
|
+
const problems = [];
|
|
40
|
+
if (raw === undefined || raw === null || String(raw).trim() === '') return { ok: false, problems: ['missing'] };
|
|
41
|
+
const s = String(raw).trim();
|
|
42
|
+
const strict = /^(\d+)(?:\.(\d+))? ([A-Z]{3})$/.exec(s);
|
|
43
|
+
if (strict) {
|
|
44
|
+
const [, int, dec = '', currency] = strict;
|
|
45
|
+
const amount = Number(`${int}.${dec || '0'}`);
|
|
46
|
+
let suggestion;
|
|
47
|
+
if (dec.length > minorUnits(currency)) {
|
|
48
|
+
suggestion = exactAmount(int, dec, currency);
|
|
49
|
+
problems.push(`has more decimal places than ${currency} allows (${minorUnits(currency)})${suggestion ? '' : '; check the real price, this tool will not round it'}`);
|
|
50
|
+
if (suggestion) suggestion = `${suggestion} ${currency}`;
|
|
51
|
+
}
|
|
52
|
+
if (amount <= 0) { problems.push('amount must be positive'); suggestion = undefined; }
|
|
53
|
+
if (!isKnownCurrency(currency)) { problems.push(`"${currency}" is not an ISO 4217 currency code`); suggestion = undefined; }
|
|
54
|
+
return { ok: problems.length === 0, amount, currency, problems, suggestion };
|
|
55
|
+
}
|
|
56
|
+
// Diagnose the common mistakes
|
|
57
|
+
let rest = s;
|
|
58
|
+
let currency = null;
|
|
59
|
+
// A 3-letter code next to digits or spaces ("19.99usd", "USD 19.99"), but not inside a longer word.
|
|
60
|
+
const codeMatch = /(?:^|[^A-Za-z])([A-Za-z]{3})(?![A-Za-z])/.exec(rest);
|
|
61
|
+
if (codeMatch && !isKnownCurrency(codeMatch[1])) return { ok: false, problems: [`"${codeMatch[1]}" is not an ISO 4217 currency code`] };
|
|
62
|
+
if (codeMatch) {
|
|
63
|
+
currency = codeMatch[1].toUpperCase();
|
|
64
|
+
if (codeMatch[1] !== currency) problems.push('currency code must be uppercase');
|
|
65
|
+
rest = rest.slice(0, codeMatch.index) + rest.slice(codeMatch.index).replace(codeMatch[1], ' ');
|
|
66
|
+
if (/^\s*[A-Za-z]{3}/.test(s)) problems.push('amount must come before the currency code');
|
|
67
|
+
}
|
|
68
|
+
for (const [sym, code] of Object.entries(SYMBOLS)) {
|
|
69
|
+
if (rest.includes(sym)) { problems.push(`uses a currency symbol "${sym}" instead of an ISO code`); currency ||= code; rest = rest.replace(sym, ''); break; }
|
|
70
|
+
}
|
|
71
|
+
if (!currency) problems.push('missing ISO 4217 currency code');
|
|
72
|
+
rest = rest.trim();
|
|
73
|
+
if (/e/i.test(rest)) return { ok: false, currency, problems: [...problems, 'uses exponent notation'] };
|
|
74
|
+
if (/^-\s*\d/.test(rest)) return { ok: false, currency, problems: [...problems, 'amount must be positive'] };
|
|
75
|
+
|
|
76
|
+
// Work out which character is the decimal mark, then keep the digits exactly.
|
|
77
|
+
let int, dec = '', ambiguous = false;
|
|
78
|
+
let m;
|
|
79
|
+
if ((m = /^(\d{1,3}(?:,\d{3})+)(?:\.(\d+))?$/.exec(rest))) { problems.push('uses thousands separators'); int = m[1].replace(/,/g, ''); dec = m[2] || ''; ambiguous = !m[2] && currency && minorUnits(currency) === 3 && /^\d{1,3},\d{3}$/.test(rest); }
|
|
80
|
+
else if ((m = /^(\d{1,3}(?:\.\d{3})+),(\d+)$/.exec(rest))) { problems.push('uses "." for thousands and "," as decimal point'); int = m[1].replace(/\./g, ''); dec = m[2]; }
|
|
81
|
+
else if ((m = /^(\d{1,3}(?:[ \u00a0\u202f]\d{3})+)(?:[.,](\d+))?$/.exec(rest))) { problems.push('uses spaces as thousands separators'); int = m[1].replace(/\D/g, ''); dec = m[2] || ''; }
|
|
82
|
+
else if ((m = /^(\d+),(\d{1,2})$/.exec(rest))) { problems.push('uses a comma as decimal point'); int = m[1]; dec = m[2]; }
|
|
83
|
+
else if ((m = /^(\d+)(?:\.(\d+))?$/.exec(rest))) { int = m[1]; dec = m[2] || ''; }
|
|
84
|
+
else return { ok: false, currency, problems: [...problems, 'amount is not a number'] };
|
|
85
|
+
|
|
86
|
+
const amount = Number(`${int}.${dec || '0'}`);
|
|
87
|
+
if (amount <= 0) problems.push('amount must be positive');
|
|
88
|
+
if (ambiguous) problems.push(`"${rest}" could mean thousands or decimals for ${currency}; write it as ${rest.replace(',', '')} or ${rest.replace(',', '.')}`);
|
|
89
|
+
if (currency && dec.length > minorUnits(currency)) problems.push(`has more decimal places than ${currency} allows (${minorUnits(currency)})`);
|
|
90
|
+
const exact = currency && amount > 0 && !ambiguous ? exactAmount(int, dec, currency) : undefined;
|
|
91
|
+
return { ok: false, amount, currency, problems: problems.length ? problems : ['not in "amount CURRENCY" format'], suggestion: exact ? `${exact} ${currency}` : undefined };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** GS1 check digit validation for GTIN-8/12/13/14. */
|
|
95
|
+
export function gtinCheckDigitOk(digits) {
|
|
96
|
+
const nums = digits.split('').map(Number);
|
|
97
|
+
const check = nums.pop();
|
|
98
|
+
let sum = 0;
|
|
99
|
+
for (let i = nums.length - 1, w = 3; i >= 0; i--, w = w === 3 ? 1 : 3) sum += nums[i] * w;
|
|
100
|
+
return (10 - (sum % 10)) % 10 === check;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Validate a GTIN. Returns { ok, problems, cleaned, googleProblems } */
|
|
104
|
+
export function checkGtin(raw) {
|
|
105
|
+
const s = String(raw).trim();
|
|
106
|
+
const problems = [];
|
|
107
|
+
const googleProblems = [];
|
|
108
|
+
const hasSeparators = /[\s-]/.test(s);
|
|
109
|
+
const cleaned = s.replace(/[\s-]/g, '');
|
|
110
|
+
if (hasSeparators) problems.push('contains spaces or dashes');
|
|
111
|
+
if (/^\d{9}[\dXx]$/.test(cleaned) || !/^\d+$/.test(cleaned)) {
|
|
112
|
+
if (/^\d{9}[\dXx]$/.test(cleaned)) return { ok: false, cleaned, problems: ['looks like an ISBN-10, which is not accepted; convert it to ISBN-13'], googleProblems: ['ISBN-10 is deprecated; use ISBN-13'] };
|
|
113
|
+
return { ok: false, cleaned, problems: ['must contain digits only'], googleProblems: ['must contain digits only'] };
|
|
114
|
+
}
|
|
115
|
+
if (![8, 12, 13, 14].includes(cleaned.length)) {
|
|
116
|
+
return { ok: false, cleaned, problems: [`has ${cleaned.length} digits; must be 8, 12, 13 or 14`], googleProblems: [`has ${cleaned.length} digits`] };
|
|
117
|
+
}
|
|
118
|
+
if (!gtinCheckDigitOk(cleaned)) {
|
|
119
|
+
problems.push('fails the GS1 check digit');
|
|
120
|
+
googleProblems.push('fails the GS1 check digit (Google disapproves incorrect GTINs)');
|
|
121
|
+
}
|
|
122
|
+
if (/^0+$/.test(cleaned)) { problems.push('is all zeros'); googleProblems.push('is all zeros'); }
|
|
123
|
+
// Google: restricted-circulation (02, 04, 2) and coupon (98-99) prefixes, judged on the GTIN-13 form.
|
|
124
|
+
const g13 = cleaned.length === 14 ? cleaned.slice(1) : cleaned.padStart(13, '0');
|
|
125
|
+
if (/^(02|04|2)/.test(g13)) googleProblems.push('uses a restricted-circulation prefix (store-internal codes), which Google rejects');
|
|
126
|
+
if (/^(98|99)/.test(g13)) googleProblems.push('uses a coupon prefix (98-99), which Google rejects');
|
|
127
|
+
return { ok: problems.length === 0, cleaned, problems, googleProblems };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const AVAIL_MAP = {
|
|
131
|
+
in_stock: 'in_stock', 'in stock': 'in_stock', instock: 'in_stock', 'https://schema.org/instock': 'in_stock', 'http://schema.org/instock': 'in_stock', available: 'in_stock',
|
|
132
|
+
out_of_stock: 'out_of_stock', 'out of stock': 'out_of_stock', outofstock: 'out_of_stock', 'https://schema.org/outofstock': 'out_of_stock', 'http://schema.org/outofstock': 'out_of_stock', soldout: 'out_of_stock', 'sold out': 'out_of_stock',
|
|
133
|
+
pre_order: 'pre_order', preorder: 'pre_order', 'pre-order': 'pre_order', 'https://schema.org/preorder': 'pre_order', 'http://schema.org/preorder': 'pre_order',
|
|
134
|
+
backorder: 'backorder', 'back order': 'backorder', 'https://schema.org/backorder': 'backorder', 'http://schema.org/backorder': 'backorder',
|
|
135
|
+
unknown: 'unknown',
|
|
136
|
+
};
|
|
137
|
+
/** Map any common spelling to a canonical availability (OpenAI spelling). */
|
|
138
|
+
export function canonicalAvailability(raw) {
|
|
139
|
+
if (raw === undefined || raw === null) return null;
|
|
140
|
+
return AVAIL_MAP[String(raw).trim().toLowerCase()] || null;
|
|
141
|
+
}
|
|
142
|
+
export const OPENAI_AVAILABILITY = ['in_stock', 'out_of_stock', 'pre_order', 'backorder', 'unknown'];
|
|
143
|
+
export const GOOGLE_AVAILABILITY = ['in_stock', 'out_of_stock', 'preorder', 'backorder'];
|
|
144
|
+
export const toGoogleAvailability = (canon) => (canon === 'pre_order' ? 'preorder' : canon === 'unknown' ? null : canon);
|
|
145
|
+
|
|
146
|
+
export function isAbsoluteHttpUrl(v) {
|
|
147
|
+
try {
|
|
148
|
+
const u = new URL(String(v).trim());
|
|
149
|
+
return u.protocol === 'http:' || u.protocol === 'https:';
|
|
150
|
+
} catch { return false; }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function parseBool(v) {
|
|
154
|
+
if (v === true || v === false) return v;
|
|
155
|
+
if (v === undefined || v === null || v === '') return undefined;
|
|
156
|
+
const s = String(v).trim().toLowerCase();
|
|
157
|
+
if (s === 'true') return true;
|
|
158
|
+
if (s === 'false') return false;
|
|
159
|
+
return 'invalid';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Parse a list field: JSON array, or comma-separated. */
|
|
163
|
+
export function parseList(v) {
|
|
164
|
+
if (v === undefined || v === null || v === '') return [];
|
|
165
|
+
if (Array.isArray(v)) return v.map(String);
|
|
166
|
+
const s = String(v).trim();
|
|
167
|
+
if (s.startsWith('[')) { try { return JSON.parse(s).map(String); } catch { return null; } }
|
|
168
|
+
return s.split(',').map((x) => x.trim()).filter(Boolean);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Parse an object field (variant_dict): object, or JSON text. */
|
|
172
|
+
export function parseObject(v) {
|
|
173
|
+
if (v === undefined || v === null || v === '') return undefined;
|
|
174
|
+
if (typeof v === 'object' && !Array.isArray(v)) return v;
|
|
175
|
+
try {
|
|
176
|
+
const o = JSON.parse(String(v));
|
|
177
|
+
return o && typeof o === 'object' && !Array.isArray(o) ? o : null;
|
|
178
|
+
} catch { return null; }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export const PLACEHOLDERS = new Set(['null', 'none', 'n/a', 'na', 'unknown', 'undefined', '-', '--', 'tbd', 'todo', '0']);
|
|
182
|
+
export const BRAND_PLACEHOLDERS = new Set(['n/a', 'na', 'generic', 'no brand', 'nobrand', 'unbranded', 'none', 'unknown', 'null', '-', 'brand', 'default', 'oem', 'other']);
|
package/src/index.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { loadFeed, parseFeedText } from './feed/parse.js';
|
|
2
|
+
import { validateFeed, groupIssues } from './feed/validate.js';
|
|
3
|
+
import { toOpenAIJsonl, toGoogleXml } from './feed/export.js';
|
|
4
|
+
import { detectPlatform, fetchShopify, fetchWoo, siteName } from './live/catalog.js';
|
|
5
|
+
import { checkDiscovery, validateUcpProfile, validateAcpDiscovery } from './live/discovery.js';
|
|
6
|
+
import { checkConsistency, compareRecordToPage, pageOffers } from './live/consistency.js';
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
loadFeed, parseFeedText, validateFeed, groupIssues, toOpenAIJsonl, toGoogleXml,
|
|
10
|
+
detectPlatform, fetchShopify, fetchWoo, checkDiscovery, validateUcpProfile, validateAcpDiscovery,
|
|
11
|
+
checkConsistency, compareRecordToPage, pageOffers,
|
|
12
|
+
};
|
|
13
|
+
export { parseMoney, checkGtin, gtinCheckDigitOk, canonicalAvailability } from './feed/values.js';
|
|
14
|
+
export { formatText, formatMarkdown } from './report.js';
|
|
15
|
+
|
|
16
|
+
/** Check a feed file. */
|
|
17
|
+
export async function checkFeed(path, opts = {}) {
|
|
18
|
+
const { format, records, errors = [] } = await loadFeed(path, opts);
|
|
19
|
+
const notes = [];
|
|
20
|
+
if (format === 'shopify-export') {
|
|
21
|
+
notes.push('Shopify product exports have no variant IDs, so variant URLs point to the product page. Exports from Shopify\'s Google & YouTube or ChatGPT channel apps include variant links.');
|
|
22
|
+
if (!opts.site) notes.push('Pass --site https://your-store.com so product URLs can be built from handles.');
|
|
23
|
+
if (!opts.currency) notes.push('Shopify exports have no currency. Pass --currency (for example --currency PKR).');
|
|
24
|
+
}
|
|
25
|
+
const result = validateFeed(records, opts);
|
|
26
|
+
return { mode: 'feed', target: path, format, records, parseErrors: errors, notes, defaults: opts.defaults || {}, ...result, readiness: readiness(result, null) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Check a live store: catalog (Shopify / WooCommerce), discovery files, crawler access, page consistency. */
|
|
30
|
+
export async function checkStore(inputUrl, opts = {}) {
|
|
31
|
+
const { maxProducts = 250, sample = 10, timeoutMs = 20000, log = () => {} } = opts;
|
|
32
|
+
const origin = new URL(/^https?:\/\//i.test(inputUrl) ? inputUrl : 'https://' + inputUrl).origin;
|
|
33
|
+
log(`Detecting platform at ${origin}`);
|
|
34
|
+
const platform = await detectPlatform(origin, { timeoutMs });
|
|
35
|
+
const notes = [];
|
|
36
|
+
let records = [];
|
|
37
|
+
let currency;
|
|
38
|
+
if (opts.feedPath) {
|
|
39
|
+
const loaded = await loadFeed(opts.feedPath, opts);
|
|
40
|
+
records = loaded.records;
|
|
41
|
+
notes.push(`Using your feed file (${loaded.format}, ${records.length} items) instead of the public catalog.`);
|
|
42
|
+
} else if (platform === 'shopify') {
|
|
43
|
+
log('Reading the public Shopify catalog');
|
|
44
|
+
({ records, currency } = await fetchShopify(origin, { maxProducts, timeoutMs }));
|
|
45
|
+
if (!currency) notes.push('Could not read the store currency from /cart.js, so prices lack a currency code. Pass --currency.');
|
|
46
|
+
notes.push('Shopify public catalog data does not include barcodes (GTIN) for most stores; check GTINs in your own export.');
|
|
47
|
+
notes.push('OpenAI says Shopify product data already reaches ChatGPT through Shopify Catalog, so a direct feed is optional. The feed checks still show what ChatGPT gets from your data: fix titles, descriptions and attributes in Shopify itself.');
|
|
48
|
+
} else if (platform === 'woocommerce') {
|
|
49
|
+
log('Reading the WooCommerce Store API');
|
|
50
|
+
({ records, currency } = await fetchWoo(origin, { maxProducts, timeoutMs }));
|
|
51
|
+
notes.push('Variable WooCommerce products are read at the parent level; check variants in your own feed.');
|
|
52
|
+
} else {
|
|
53
|
+
notes.push('Platform not detected (not Shopify or WooCommerce, or the public catalog is disabled). Pass your feed file with --feed to check products.');
|
|
54
|
+
}
|
|
55
|
+
if (opts.currency) records.forEach((r) => { if (r.price && !/[A-Z]{3}$/.test(r.price)) r.price = `${r.price} ${opts.currency}`; if (r.sale_price && !/[A-Z]{3}$/.test(r.sale_price)) r.sale_price = `${r.sale_price} ${opts.currency}`; });
|
|
56
|
+
const seller = opts.defaults?.seller_name || (records.length ? await siteName(origin, { timeoutMs }) : undefined);
|
|
57
|
+
const defaults = { seller_name: seller, ...opts.defaults };
|
|
58
|
+
const result = validateFeed(records, { ...opts, defaults });
|
|
59
|
+
|
|
60
|
+
log('Checking UCP / ACP discovery and robots.txt');
|
|
61
|
+
let productPath = '/';
|
|
62
|
+
try { if (records[0]?.url) productPath = new URL(records[0].url).pathname; } catch { /* ignore */ }
|
|
63
|
+
const discovery = await checkDiscovery(origin, { productPath, timeoutMs });
|
|
64
|
+
|
|
65
|
+
let consistency = [];
|
|
66
|
+
if (records.length && sample > 0) {
|
|
67
|
+
log(`Comparing ${Math.min(sample, records.length)} product pages with catalog data`);
|
|
68
|
+
consistency = await checkConsistency(records, { sample, timeoutMs, log });
|
|
69
|
+
}
|
|
70
|
+
if (platform === 'shopify' && discovery && !discovery.ucp?.present) notes.push('Shopify storefronts normally serve /.well-known/ucp automatically. It is missing here: check that the store is not password-protected and that no app, proxy or CDN rule blocks /.well-known/.');
|
|
71
|
+
return { mode: 'store', target: origin, platform, currency, defaults, records, notes, ...result, discovery, consistency, readiness: readiness(result, { discovery, consistency }) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Readiness per channel, 0-100, with the components shown so the score is explainable.
|
|
76
|
+
* Weights favour what actually blocks listing: eligible items first, then access and accuracy.
|
|
77
|
+
*/
|
|
78
|
+
export function readiness(result, live) {
|
|
79
|
+
const { perChannel, richness } = result.stats;
|
|
80
|
+
const botAllowed = (token) => {
|
|
81
|
+
const b = live?.discovery?.robots?.find((x) => x.token === token);
|
|
82
|
+
return b ? (b.allowed ? 100 : 0) : null;
|
|
83
|
+
};
|
|
84
|
+
const consistencyPct = live?.consistency?.length
|
|
85
|
+
? Math.round((live.consistency.filter((c) => !c.findings.some((f) => f.severity === 'error')).length / live.consistency.length) * 100)
|
|
86
|
+
: null;
|
|
87
|
+
const structuredPct = live?.consistency?.length
|
|
88
|
+
? Math.round((live.consistency.filter((c) => !c.findings.some((f) => f.code === 'page-no-product-schema')).length / live.consistency.length) * 100)
|
|
89
|
+
: null;
|
|
90
|
+
const ucpScore = live ? (live.discovery?.ucp?.valid ? 100 : live.discovery?.ucp?.present ? 40 : 0) : null;
|
|
91
|
+
const score = (parts) => {
|
|
92
|
+
const used = parts.filter((p) => p.value !== null && p.value !== undefined);
|
|
93
|
+
const w = used.reduce((s, p) => s + p.weight, 0);
|
|
94
|
+
return { score: w ? Math.round(used.reduce((s, p) => s + p.value * p.weight, 0) / w) : 0, parts: used };
|
|
95
|
+
};
|
|
96
|
+
const out = {};
|
|
97
|
+
if (perChannel.chatgpt) {
|
|
98
|
+
out.chatgpt = score([
|
|
99
|
+
{ name: 'Items eligible for the ChatGPT feed', weight: 55, value: perChannel.chatgpt.eligiblePct },
|
|
100
|
+
{ name: 'OAI-SearchBot can crawl product pages', weight: 15, value: botAllowed('OAI-SearchBot') },
|
|
101
|
+
{ name: 'Feed matches product pages', weight: 15, value: consistencyPct },
|
|
102
|
+
{ name: 'Attribute richness for AI matching', weight: 15, value: richness },
|
|
103
|
+
]);
|
|
104
|
+
}
|
|
105
|
+
if (perChannel.google) {
|
|
106
|
+
out.google = score([
|
|
107
|
+
{ name: 'Items eligible for Merchant Center', weight: 45, value: perChannel.google.eligiblePct },
|
|
108
|
+
{ name: 'Googlebot can crawl product pages', weight: 10, value: botAllowed('Googlebot') },
|
|
109
|
+
{ name: 'Feed matches product pages', weight: 20, value: consistencyPct },
|
|
110
|
+
{ name: 'Attribute richness for AI matching', weight: 15, value: richness },
|
|
111
|
+
{ name: 'UCP profile for agentic checkout', weight: 10, value: ucpScore },
|
|
112
|
+
]);
|
|
113
|
+
}
|
|
114
|
+
if (live) {
|
|
115
|
+
const allowedShare = live.discovery?.robots?.length ? Math.round((live.discovery.robots.filter((b) => b.allowed).length / live.discovery.robots.length) * 100) : null;
|
|
116
|
+
out.agents = score([
|
|
117
|
+
{ name: 'UCP discovery profile', weight: 40, value: ucpScore },
|
|
118
|
+
{ name: 'Shopping crawlers allowed in robots.txt', weight: 30, value: allowedShare },
|
|
119
|
+
{ name: 'Product structured data on pages', weight: 30, value: structuredPct },
|
|
120
|
+
]);
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Read a store's public catalog without credentials.
|
|
2
|
+
// Shopify: /products.json (public storefront JSON) + /cart.js for the currency
|
|
3
|
+
// WooCommerce: /wp-json/wc/store/v1/products (public Store API)
|
|
4
|
+
// Both are read-only, public endpoints that browsers and agents already use.
|
|
5
|
+
|
|
6
|
+
import { get, getJson } from './http.js';
|
|
7
|
+
import { normalizeRecord, stripHtml } from '../feed/parse.js';
|
|
8
|
+
|
|
9
|
+
export async function detectPlatform(origin, { timeoutMs } = {}) {
|
|
10
|
+
try {
|
|
11
|
+
const s = await getJson(`${origin}/products.json?limit=1`, { timeoutMs });
|
|
12
|
+
if (s.status === 200 && s.json && Array.isArray(s.json.products)) return 'shopify';
|
|
13
|
+
} catch { /* ignore */ }
|
|
14
|
+
try {
|
|
15
|
+
const w = await getJson(`${origin}/wp-json/wc/store/v1/products?per_page=1`, { timeoutMs });
|
|
16
|
+
if (w.status === 200 && Array.isArray(w.json)) return 'woocommerce';
|
|
17
|
+
} catch { /* ignore */ }
|
|
18
|
+
return 'unknown';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function siteName(origin, { timeoutMs } = {}) {
|
|
22
|
+
try {
|
|
23
|
+
const r = await get(origin + '/', { timeoutMs });
|
|
24
|
+
const og = /<meta[^>]+property=["']og:site_name["'][^>]+content=["']([^"']+)["']/i.exec(r.text) || /<meta[^>]+content=["']([^"']+)["'][^>]+property=["']og:site_name["']/i.exec(r.text);
|
|
25
|
+
if (og) return decode(og[1]).trim();
|
|
26
|
+
const t = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(r.text);
|
|
27
|
+
if (t) return decode(t[1]).split(/\s[|\-–—·]\s/).pop().trim();
|
|
28
|
+
} catch { /* ignore */ }
|
|
29
|
+
return new URL(origin).hostname.replace(/^www\./, '');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const decode = (s) => s.replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
33
|
+
|
|
34
|
+
export async function fetchShopify(origin, { maxProducts = 250, timeoutMs } = {}) {
|
|
35
|
+
let currency;
|
|
36
|
+
try {
|
|
37
|
+
const cart = await getJson(`${origin}/cart.js`, { timeoutMs });
|
|
38
|
+
currency = cart.json?.currency;
|
|
39
|
+
} catch { /* ignore */ }
|
|
40
|
+
const records = [];
|
|
41
|
+
let page = 1;
|
|
42
|
+
while (records.length < maxProducts && page <= 40) {
|
|
43
|
+
const r = await getJson(`${origin}/products.json?limit=250&page=${page}`, { timeoutMs });
|
|
44
|
+
const products = r.json?.products || [];
|
|
45
|
+
if (!products.length) break;
|
|
46
|
+
for (const p of products) {
|
|
47
|
+
const options = (p.options || []).map((o) => o.name);
|
|
48
|
+
const multi = (p.variants || []).length > 1 || !(options.length === 1 && options[0] === 'Title');
|
|
49
|
+
for (const v of p.variants || []) {
|
|
50
|
+
const opt = {};
|
|
51
|
+
['option1', 'option2', 'option3'].forEach((k, i) => {
|
|
52
|
+
if (v[k] && options[i] && !(options[i] === 'Title' && v[k] === 'Default Title')) opt[options[i]] = v[k];
|
|
53
|
+
});
|
|
54
|
+
const img = v.featured_image?.src || p.images?.[0]?.src;
|
|
55
|
+
const money = (n) => (n != null && n !== '' ? `${Number(n).toFixed(2)}${currency ? ' ' + currency : ''}` : undefined);
|
|
56
|
+
const compare = Number(v.compare_at_price);
|
|
57
|
+
const obj = {
|
|
58
|
+
item_id: v.sku || String(v.id),
|
|
59
|
+
group_id: multi ? String(p.id) : undefined,
|
|
60
|
+
title: [p.title, ...Object.values(opt)].join(' - '),
|
|
61
|
+
description: stripHtml(p.body_html || ''),
|
|
62
|
+
url: `${origin}/products/${p.handle}${multi ? `?variant=${v.id}` : ''}`,
|
|
63
|
+
image_url: img ? (img.startsWith('//') ? 'https:' + img : img) : undefined,
|
|
64
|
+
additional_image_urls: (p.images || []).slice(1, 11).map((i) => (i.src.startsWith('//') ? 'https:' + i.src : i.src)),
|
|
65
|
+
brand: p.vendor || undefined,
|
|
66
|
+
availability: v.available === true ? 'in_stock' : v.available === false ? 'out_of_stock' : undefined,
|
|
67
|
+
price: compare && compare > Number(v.price) ? money(compare) : money(v.price),
|
|
68
|
+
sale_price: compare && compare > Number(v.price) ? money(v.price) : undefined,
|
|
69
|
+
gtin: v.barcode || undefined,
|
|
70
|
+
product_type: p.product_type || undefined,
|
|
71
|
+
listing_has_variations: multi ? 'true' : undefined,
|
|
72
|
+
variant_dict: multi && Object.keys(opt).length ? opt : undefined,
|
|
73
|
+
};
|
|
74
|
+
if (Number(v.grams) > 0) { obj.weight = String(v.grams); obj.item_weight_unit = 'g'; }
|
|
75
|
+
const rec = normalizeRecord(obj, records.length + 1);
|
|
76
|
+
rec._source = 'shopify';
|
|
77
|
+
records.push(rec);
|
|
78
|
+
if (records.length >= maxProducts) break;
|
|
79
|
+
}
|
|
80
|
+
if (records.length >= maxProducts) break;
|
|
81
|
+
}
|
|
82
|
+
if (products.length < 250) break;
|
|
83
|
+
page++;
|
|
84
|
+
}
|
|
85
|
+
return { records, currency, currencyKnown: !!currency };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function fetchWoo(origin, { maxProducts = 250, timeoutMs } = {}) {
|
|
89
|
+
const records = [];
|
|
90
|
+
let page = 1;
|
|
91
|
+
let currency;
|
|
92
|
+
while (records.length < maxProducts && page <= 50) {
|
|
93
|
+
const r = await getJson(`${origin}/wp-json/wc/store/v1/products?per_page=100&page=${page}`, { timeoutMs });
|
|
94
|
+
const items = Array.isArray(r.json) ? r.json : [];
|
|
95
|
+
if (!items.length) break;
|
|
96
|
+
for (const p of items) {
|
|
97
|
+
const pr = p.prices || {};
|
|
98
|
+
const unit = Number(pr.currency_minor_unit ?? 2);
|
|
99
|
+
currency ||= pr.currency_code;
|
|
100
|
+
const money = (minor) => (minor != null && minor !== '' ? `${(Number(minor) / 10 ** unit).toFixed(unit)} ${pr.currency_code}` : undefined);
|
|
101
|
+
const onSale = pr.sale_price && pr.regular_price && Number(pr.sale_price) < Number(pr.regular_price);
|
|
102
|
+
const attrs = {};
|
|
103
|
+
for (const a of p.attributes || []) if (a.terms?.length === 1) attrs[a.name] = a.terms[0].name;
|
|
104
|
+
const obj = {
|
|
105
|
+
item_id: p.sku || String(p.id),
|
|
106
|
+
title: decode(p.name || ''),
|
|
107
|
+
description: stripHtml(p.description || p.short_description || ''),
|
|
108
|
+
url: p.permalink,
|
|
109
|
+
image_url: p.images?.[0]?.src,
|
|
110
|
+
additional_image_urls: (p.images || []).slice(1, 11).map((i) => i.src),
|
|
111
|
+
brand: p.brands?.[0]?.name || undefined,
|
|
112
|
+
availability: p.is_in_stock === true ? 'in_stock' : p.is_in_stock === false ? (p.stock_availability?.class === 'available-on-backorder' ? 'backorder' : 'out_of_stock') : undefined,
|
|
113
|
+
price: money(onSale ? pr.regular_price : pr.price),
|
|
114
|
+
sale_price: onSale ? money(pr.sale_price) : undefined,
|
|
115
|
+
product_type: (p.categories || []).map((c) => decode(c.name)).join(' > ') || undefined,
|
|
116
|
+
color: attrs.Color || attrs.Colour || attrs.color || undefined,
|
|
117
|
+
size: attrs.Size || attrs.size || undefined,
|
|
118
|
+
material: attrs.Material || attrs.material || undefined,
|
|
119
|
+
review_count: p.review_count != null ? String(p.review_count) : undefined,
|
|
120
|
+
star_rating: Number(p.review_count) > 0 && p.average_rating ? Number(p.average_rating).toFixed(2) : undefined,
|
|
121
|
+
};
|
|
122
|
+
const rec = normalizeRecord(obj, records.length + 1);
|
|
123
|
+
rec._source = 'woocommerce';
|
|
124
|
+
records.push(rec);
|
|
125
|
+
if (records.length >= maxProducts) break;
|
|
126
|
+
}
|
|
127
|
+
if (items.length < 100) break;
|
|
128
|
+
page++;
|
|
129
|
+
}
|
|
130
|
+
return { records, currency, currencyKnown: !!currency };
|
|
131
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Feed vs landing page consistency.
|
|
2
|
+
// Google disapproves items whose price or availability differ from the landing page and its
|
|
3
|
+
// structured data, and AI agents quote the feed to shoppers, so a mismatch means a shopper
|
|
4
|
+
// is told the wrong price. This samples product pages and compares.
|
|
5
|
+
|
|
6
|
+
import { get } from './http.js';
|
|
7
|
+
import { getJsonLd, typesOf } from 'ai-ready-audit';
|
|
8
|
+
import { parseMoney, canonicalAvailability, minorUnits } from '../feed/values.js';
|
|
9
|
+
|
|
10
|
+
const money = (amount, currency) => `${Number(amount).toFixed(currency ? minorUnits(currency) : 2)}${currency ? ' ' + currency : ''}`;
|
|
11
|
+
|
|
12
|
+
const gtinOf = (n) => n && (n.gtin13 || n.gtin || n.gtin12 || n.gtin14 || n.gtin8);
|
|
13
|
+
|
|
14
|
+
/** Pull Product offers from JSON-LD. gtin and sku may sit on the Offer or on the Product (both are valid schema.org). Returns [{sku, price, currency, availability, url}] */
|
|
15
|
+
export function pageOffers(html) {
|
|
16
|
+
const { items } = getJsonLd(html);
|
|
17
|
+
const out = [];
|
|
18
|
+
const products = items.filter((n) => typesOf(n).some((t) => t === 'Product' || t === 'ProductGroup'));
|
|
19
|
+
for (const p of products) {
|
|
20
|
+
const variants = Array.isArray(p.hasVariant) ? p.hasVariant : [];
|
|
21
|
+
for (const node of [p, ...variants]) {
|
|
22
|
+
const offers = Array.isArray(node.offers) ? node.offers : node.offers ? [node.offers] : [];
|
|
23
|
+
for (const o of offers) {
|
|
24
|
+
const inner = o['@type'] === 'AggregateOffer' ? { price: o.lowPrice ?? o.price, priceCurrency: o.priceCurrency, availability: o.availability } : o;
|
|
25
|
+
const spec = Array.isArray(inner.priceSpecification) ? inner.priceSpecification[0] : inner.priceSpecification;
|
|
26
|
+
const price = inner.price ?? spec?.price;
|
|
27
|
+
out.push({
|
|
28
|
+
sku: o.sku || node.sku || p.sku,
|
|
29
|
+
gtin: gtinOf(o) || gtinOf(node),
|
|
30
|
+
price: price != null && price !== '' ? Number(String(price).replace(/,/g, '')) : null,
|
|
31
|
+
currency: inner.priceCurrency || spec?.priceCurrency || null,
|
|
32
|
+
availability: inner.availability ? canonicalAvailability(String(inner.availability)) : null,
|
|
33
|
+
url: o.url || node.url,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { productFound: products.length > 0, offers: out };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Compare one feed record with the offers found on its page. Pure function. */
|
|
42
|
+
export function compareRecordToPage(record, page) {
|
|
43
|
+
const findings = [];
|
|
44
|
+
if (!page.productFound) {
|
|
45
|
+
findings.push({ severity: 'warning', code: 'page-no-product-schema', message: 'Product page has no Product structured data', fix: 'Add Product JSON-LD with offers (price, priceCurrency, availability). Google uses it to verify your feed and AI agents read it directly.' });
|
|
46
|
+
return findings;
|
|
47
|
+
}
|
|
48
|
+
if (!page.offers.length) {
|
|
49
|
+
findings.push({ severity: 'warning', code: 'page-no-offer', message: 'Product structured data has no offers', fix: 'Add offers with price, priceCurrency and availability.' });
|
|
50
|
+
return findings;
|
|
51
|
+
}
|
|
52
|
+
const feedPrice = parseMoney(record.sale_price || record.price);
|
|
53
|
+
const { offer, how } = matchOffer(record, page.offers, feedPrice);
|
|
54
|
+
if (!offer) {
|
|
55
|
+
const keys = page.offers.map((o) => o.sku || o.gtin).filter(Boolean);
|
|
56
|
+
findings.push({ severity: 'warning', code: 'variant-not-on-page', message: `No offer on the page matches this item${keys.length ? ` (page offers: ${keys.slice(0, 5).join(', ')}${keys.length > 5 ? ', ...' : ''})` : ''}`, fix: 'Give each variant its own offer in the Product JSON-LD with a sku (or gtin) equal to the feed id, so Google and agents can verify the right price and stock.' });
|
|
57
|
+
return findings;
|
|
58
|
+
}
|
|
59
|
+
if (how === 'first' && page.offers.length > 1) {
|
|
60
|
+
findings.push({ severity: 'warning', code: 'offers-unidentified', message: `Page has ${page.offers.length} offers without sku or gtin, so this item cannot be matched to one`, fix: 'Add sku (equal to the feed id) or gtin to each offer in the Product JSON-LD.' });
|
|
61
|
+
return findings;
|
|
62
|
+
}
|
|
63
|
+
if (feedPrice.ok && offer.price != null) {
|
|
64
|
+
const diff = Math.abs(offer.price - feedPrice.amount);
|
|
65
|
+
if (diff > 0.009 && diff / Math.max(offer.price, feedPrice.amount) > 0.005) {
|
|
66
|
+
findings.push({ severity: 'error', code: 'price-mismatch', message: `Feed price ${money(feedPrice.amount, feedPrice.currency)} but page says ${money(offer.price, offer.currency || feedPrice.currency)}`, fix: 'Make the feed and the page show the same current price. Google disapproves mismatches and agents would quote the wrong price.' });
|
|
67
|
+
}
|
|
68
|
+
if (offer.currency && feedPrice.currency && offer.currency.toUpperCase() !== feedPrice.currency) {
|
|
69
|
+
findings.push({ severity: 'error', code: 'currency-mismatch', message: `Feed currency ${feedPrice.currency} but page currency ${offer.currency}`, fix: 'Use the currency the page shows to shoppers in the target country.' });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const feedAvail = canonicalAvailability(record.availability);
|
|
73
|
+
if (feedAvail && offer.availability && feedAvail !== offer.availability) {
|
|
74
|
+
findings.push({ severity: 'error', code: 'availability-mismatch', message: `Feed says ${feedAvail} but page says ${offer.availability}`, fix: 'Update availability in the feed when stock changes, or fix the structured data.' });
|
|
75
|
+
}
|
|
76
|
+
if (!offer.availability) findings.push({ severity: 'tip', code: 'page-no-availability', message: 'Page offer has no availability', fix: 'Add offers.availability (for example https://schema.org/InStock).' });
|
|
77
|
+
return findings;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function variantParam(u) {
|
|
81
|
+
try { return new URL(u, 'http://x').searchParams.get('variant'); } catch { return null; }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Find the page offer that describes this feed item.
|
|
86
|
+
* Identifier matches win. If the page offers carry identifiers and none match, there is no match:
|
|
87
|
+
* comparing against another variant's offer would report false mismatches.
|
|
88
|
+
*/
|
|
89
|
+
export function matchOffer(record, offers, feedPrice = parseMoney(record.sale_price || record.price)) {
|
|
90
|
+
const ids = [record.item_id, record.sku, record.mpn].filter((x) => x != null && x !== '').map(String);
|
|
91
|
+
const byId = offers.find((o) => o.sku != null && ids.includes(String(o.sku)));
|
|
92
|
+
if (byId) return { offer: byId, how: 'sku' };
|
|
93
|
+
const gtin = record.gtin && String(record.gtin).replace(/\D/g, '');
|
|
94
|
+
const byGtin = gtin && offers.find((o) => o.gtin && String(o.gtin).replace(/\D/g, '').padStart(14, '0') === gtin.padStart(14, '0'));
|
|
95
|
+
if (byGtin) return { offer: byGtin, how: 'gtin' };
|
|
96
|
+
const v = record.url && variantParam(record.url);
|
|
97
|
+
const byUrl = v && offers.find((o) => o.url && variantParam(o.url) === v);
|
|
98
|
+
if (byUrl) return { offer: byUrl, how: 'url' };
|
|
99
|
+
if (offers.length === 1 && !(offers[0].sku || offers[0].gtin)) return { offer: offers[0], how: 'only' };
|
|
100
|
+
if (offers.some((o) => o.sku || o.gtin)) {
|
|
101
|
+
// Identified offers exist but none is this item. A single identified offer on a single-item listing still counts.
|
|
102
|
+
if (offers.length === 1 && !record.group_id) return { offer: offers[0], how: 'only' };
|
|
103
|
+
return { offer: null, how: 'none' };
|
|
104
|
+
}
|
|
105
|
+
const byPrice = feedPrice.ok && offers.find((o) => o.price != null && Math.abs(o.price - feedPrice.amount) < 0.005);
|
|
106
|
+
if (byPrice) return { offer: byPrice, how: 'price' };
|
|
107
|
+
return { offer: offers[0], how: 'first' };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Sample product pages and compare. */
|
|
111
|
+
export async function checkConsistency(records, { sample = 10, timeoutMs, log = () => {} } = {}) {
|
|
112
|
+
const withUrl = records.filter((r) => r.url);
|
|
113
|
+
const step = Math.max(1, Math.floor(withUrl.length / sample));
|
|
114
|
+
const picked = [];
|
|
115
|
+
for (let i = 0; i < withUrl.length && picked.length < sample; i += step) picked.push(withUrl[i]);
|
|
116
|
+
const results = [];
|
|
117
|
+
const seenPages = new Map();
|
|
118
|
+
for (const rec of picked) {
|
|
119
|
+
const pageUrl = rec.url;
|
|
120
|
+
try {
|
|
121
|
+
let page = seenPages.get(pageUrl);
|
|
122
|
+
if (!page) {
|
|
123
|
+
log(`Checking ${pageUrl}`);
|
|
124
|
+
const r = await get(pageUrl, { timeoutMs });
|
|
125
|
+
if (r.status >= 400) { results.push({ item_id: rec.item_id, url: pageUrl, findings: [{ severity: 'error', code: 'page-unreachable', message: `Product page returned HTTP ${r.status}`, fix: 'Feed URLs must open a live product page.' }] }); continue; }
|
|
126
|
+
page = pageOffers(r.text);
|
|
127
|
+
seenPages.set(pageUrl, page);
|
|
128
|
+
}
|
|
129
|
+
results.push({ item_id: rec.item_id, url: pageUrl, findings: compareRecordToPage(rec, page) });
|
|
130
|
+
} catch (e) {
|
|
131
|
+
results.push({ item_id: rec.item_id, url: pageUrl, findings: [{ severity: 'warning', code: 'page-fetch-failed', message: `Could not fetch page (${e.message})`, fix: 'Check the URL is public.' }] });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return results;
|
|
135
|
+
}
|