Files

174 lines
12 KiB
JavaScript

const cheerio = require('cheerio');
const { createHash } = require('node:crypto');
const { fail } = require('./workspace.cjs');
const { websiteUrl } = require('./public-fetch.cjs');
const { amount, displayPrice, product, publicLink, shopifyProducts, wooProducts, schemaProducts } = require('./products.cjs');
function loadHtml(buffer, contentType = '') {
const charset = /charset\s*=\s*["']?([^\s;"']+)/i.exec(contentType)?.[1];
return cheerio.loadBuffer(buffer, { encoding: { defaultEncoding: 'utf-8', ...(charset ? { transportLayerEncodingLabel: charset } : {}) } });
}
function htmlProducts(buffer, context, { maxProducts = 10000 } = {}) {
const $ = loadHtml(buffer, context.contentType);
const results = [], byIdentity = new Map();
function append(row) {
const key = row.title.trim().toLowerCase().replace(/\s+/g, ' ') + '\0' + row.link;
const candidates = byIdentity.get(key) || [];
const existing = candidates.find(old => !old.sku || !row.sku || old.sku === row.sku);
if (existing) {
if (existing.rawPrice === null && row.rawPrice !== null) {
existing.rawPrice = row.rawPrice; existing.currency ||= row.currency;
existing.price = displayPrice(existing.rawPrice, existing.currency);
}
if (!existing.image) existing.image = row.image;
if (!existing.sku) existing.sku = row.sku;
return;
}
if (results.length >= maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে।');
results.push(row); candidates.push(row); byIdentity.set(key, candidates);
}
$('script[type="application/ld+json"]').each((_i, element) => {
let data;
try { data = JSON.parse($(element).text()); } catch { return; }
for (const row of schemaProducts(data, context)) append(row);
});
$('[itemtype$="/Product"], li.product, .product-item, .product-card').each((_i, element) => {
const card = $(element);
const name = card.find('[itemprop="name"], .woocommerce-loop-product__title, .product-title, .product-card__title, .card__heading').first().text().trim();
if (!name) return;
let selling = card.find('[itemprop="price"]').first();
if (!selling.length) selling = card.find('.price ins .amount, .price ins').first();
if (!selling.length) selling = card.find('.price .amount').filter((_i, el) => !$(el).closest('del').length).first();
if (!selling.length) { selling = card.find('.price').first().clone(); selling.find('del').remove(); }
const explicit = selling.attr('content') || selling.text().trim();
const price = amount(explicit.replace(/\p{Sc}|\b(?:BDT|USD|EUR|GBP|CAD|AUD|SGD|INR)\b|\bTk\.?/giu, '').trim());
const currency = card.find('[itemprop="priceCurrency"]').first().attr('content') || (/৳|\b(?:BDT|Tk\.?)\b/i.test(explicit) ? 'BDT' : undefined);
const regularText = card.find('.price del .amount, .price del').first().text().trim();
const regular = amount(regularText.replace(/\p{Sc}|\b(?:BDT|USD|EUR|GBP|CAD|AUD|SGD|INR)\b|\bTk\.?/giu, '').trim());
const image = card.find('img').first();
const link = card.find('a[href]').first().attr('href');
append(product({
sourceId: card.attr('data-product-id') || publicLink(link, context.documentUrl || context.url) || name,
title: name, price, regular, currency, link,
image: image.attr('data-src') || image.attr('data-lazy-src') || image.attr('src')
}, context));
});
const next = $('a[rel="next"], link[rel="next"], .pagination a.next, .woocommerce-pagination a.next').first().attr('href');
return { products: results, next: publicLink(next, context.documentUrl || context.url), title: $('title').text().trim() };
}
function createScraper({ fetchPublic, maxRequests = 80, maxPages = 20, maxProducts = 10000, timeoutMs = 60000, pageDelayMs = 350 }) {
if (typeof fetchPublic !== 'function' || ![maxRequests, maxPages, maxProducts, timeoutMs].every(n => Number.isInteger(n) && n > 0) || !Number.isInteger(pageDelayMs) || pageDelayMs < 0) {
throw new Error('Invalid scraper limits');
}
return async function scrape(input, options = {}) {
const raw = typeof input.url === 'string' ? input.url.trim() : '';
if (!raw || raw.length > 2048) throw fail(400, 'INVALID_SOURCE_URL', 'সঠিক website URL দিন।');
const url = websiteUrl(/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : 'https://' + raw);
const name = typeof input.storeName === 'string' ? input.storeName.trim() : '';
const category = typeof input.category === 'string' ? input.category.trim() : 'general';
if (name.length > 160 || category.length > 80) throw fail(400, 'INVALID_STORE_DETAILS', 'Store-এর নাম বা category অতিরিক্ত বড়।');
const context = {
url: url.origin + '/', name: name || url.hostname,
id: 'store_' + createHash('sha256').update(url.origin).digest('hex'), category
};
const signal = options.signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), options.signal]) : AbortSignal.timeout(timeoutMs);
let requests = 0;
const evidence = [];
async function read(target) {
if (signal.aborted) throw fail(504, 'IMPORT_TIMEOUT', 'Product import-এর সময় শেষ হয়েছে।');
if (requests >= maxRequests) throw fail(422, 'IMPORT_LIMIT', 'এই store-এর জন্য import সীমা বাড়ানো প্রয়োজন; আগের data বদলায়নি।');
if (requests && pageDelayMs) await new Promise((resolve, reject) => {
const aborted = () => { clearTimeout(timer); signal.removeEventListener('abort', aborted); reject(fail(504, 'IMPORT_TIMEOUT', 'Product import বাতিল বা সময় শেষ হয়েছে।')); };
const timer = setTimeout(() => { signal.removeEventListener('abort', aborted); resolve(); }, pageDelayMs);
signal.addEventListener('abort', aborted, { once: true });
if (signal.aborted) aborted();
});
requests++;
const result = await fetchPublic(target, { signal });
evidence.push({ url: result.url || target, status: result.status, sha256: createHash('sha256').update(result.body).digest('hex') });
return result;
}
async function optional(target) {
try { return await read(target); }
catch (error) {
if (['NON_PUBLIC_SOURCE', 'INVALID_SOURCE_URL', 'IMPORT_LIMIT', 'SOURCE_TOO_LARGE'].includes(error.code) || signal.aborted) throw error;
return null;
}
}
function json(result) { try { return JSON.parse(result.body.toString('utf8')); } catch { return null; } }
function bounded(rows) {
if (rows.length > maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
return rows;
}
function finished(products, sourceType, extra = {}) {
const unique = [...new Map(bounded(products).map(item => [item.id, item])).values()];
if (!unique.length) throw fail(422, 'NO_PUBLIC_PRODUCTS', 'এই public source-এ product পাওয়া যায়নি; আগের data বদলায়নি।');
return { ...context, domain: new URL(context.url).hostname, syncedAt: new Date().toISOString(), count: unique.length, products: unique, sourceType, sources: evidence, ...extra };
}
async function pages(first, makeUrl, field, pageSize, map) {
const products = [], hashes = new Set();
let result = first;
for (let page = 1; page <= maxPages; page++) {
if (page > 1) result = await read(makeUrl(page));
if (result.status !== 200) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog-এর সব page পড়া যায়নি; আগের data বদলায়নি।');
const payload = json(result), rows = field ? payload?.[field] : payload;
if (!Array.isArray(rows)) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog response সঠিক নয়; আগের data বদলায়নি।');
const hash = createHash('sha256').update(result.body).digest('hex');
if (rows.length && hashes.has(hash)) throw fail(422, 'PAGINATION_UNSUPPORTED', 'Website একই catalog page বারবার দিচ্ছে; আগের data বদলায়নি।');
hashes.add(hash);
if (rows.length > maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে।');
for (const row of map(payload)) { products.push(row); bounded(products); }
const totalPages = Number(result.headers['x-wp-totalpages']);
const hasTotal = Number.isInteger(totalPages) && totalPages > 0;
if (hasTotal ? page >= totalPages : rows.length < pageSize) return products;
if (page === maxPages) throw fail(422, 'IMPORT_LIMIT', 'Catalog page সংখ্যা সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
}
return products;
}
const home = await optional(url.href);
const origin = websiteUrl(home?.url || url.href).origin;
context.url = origin + '/'; context.id = 'store_' + createHash('sha256').update(origin).digest('hex');
if (!name) context.name = new URL(origin).hostname;
let apiRoot = new URL('/wp-json/', origin);
if (home?.status === 200) {
const $ = loadHtml(home.body, home.headers['content-type']);
const discovered = publicLink($('link[rel="https://api.w.org/"]').first().attr('href'), home.url || url.href);
if (discovered && new URL(discovered).origin === origin) apiRoot = new URL(discovered);
}
const wooUrl = page => {
const target = apiRoot.searchParams.has('rest_route') ? new URL(apiRoot) : new URL('wc/store/v1/products', apiRoot.href.endsWith('/') ? apiRoot : apiRoot.href + '/');
if (target.searchParams.has('rest_route')) target.searchParams.set('rest_route', '/wc/store/v1/products');
target.searchParams.set('per_page', '100'); target.searchParams.set('page', String(page)); return target.href;
};
const woo = await optional(wooUrl(1));
if (woo?.status === 200 && Array.isArray(json(woo))) {
const rows = await pages(woo, wooUrl, null, 100, payload => wooProducts(payload, context));
return finished(rows, 'woo-store-api', { requiresVariantSelection: rows.some(row => row.requiresVariantSelection) });
}
const shopifyUrl = page => { const target = new URL('/products.json', origin); target.searchParams.set('limit', '250'); target.searchParams.set('page', String(page)); return target.href; };
const shopify = await optional(shopifyUrl(1));
if (shopify?.status === 200 && Array.isArray(json(shopify)?.products)) {
return finished(await pages(shopify, shopifyUrl, 'products', 250, payload => shopifyProducts(payload, context, payload.currency)), 'shopify-public-products');
}
if (!home || home.status !== 200) throw fail(422, 'NO_PUBLIC_PRODUCTS', 'Public product data পাওয়া যায়নি; অনুমোদিত store connection প্রয়োজন হতে পারে।');
let current = home, products = [], seen = new Set();
for (let page = 1; page <= maxPages; page++) {
const pageUrl = current.url || url.href;
if (seen.has(pageUrl)) throw fail(422, 'PAGINATION_UNSUPPORTED', 'Website-এর next page বারবার একই page-এ ফিরছে।');
seen.add(pageUrl);
const parsed = htmlProducts(current.body, { ...context, documentUrl: pageUrl, contentType: current.headers['content-type'] }, { maxProducts });
for (const row of parsed.products) { products.push(row); bounded(products); }
if (!parsed.next) return finished(products, 'public-html-pages', { coverage: 'Products found in public pages, not a guarantee of the entire site inventory' });
if (new URL(parsed.next).origin !== origin) throw fail(422, 'CROSS_ORIGIN_PAGINATION', 'Catalog-এর next page অন্য website-এ যাচ্ছে।');
if (page === maxPages) throw fail(422, 'IMPORT_LIMIT', 'Catalog page সংখ্যা সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
current = await read(parsed.next);
if (current.status !== 200) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog-এর পরের page পড়া যায়নি; আগের data বদলায়নি।');
}
};
}
module.exports = { createScraper, htmlProducts };