const { product, publicLink } = require('./products.cjs'); const { fail } = require('./workspace.cjs'); function createConnectedCatalog({ publicClientOrigin, ttlMs = 30000, maxCacheBytes = 64 * 1024 * 1024, maxEntries = 100, maxConcurrentReads = 2 } = {}) { const base = new URL(publicClientOrigin); if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.pathname !== '/' || base.search || base.hash) throw new Error('A public Client origin is required'); const cache = new Map(), inflight = new Map(); let cachedBytes = 0; return async function connected(workspace) { const key = workspace.namespace, now = Date.now(); for (const [id, item] of cache) if (item.expires <= now) { cache.delete(id); cachedBytes -= item.bytes; } if (cache.has(key)) return cache.get(key).store; if (inflight.has(key)) return inflight.get(key); if (inflight.size >= maxConcurrentReads) throw fail(503, 'CONNECTED_CATALOG_BUSY', 'Catalog পড়ার কাজ চলছে; অল্প পরে আবার চেষ্টা করুন।'); const task = (async () => { if (typeof workspace.readConnectedCatalog !== 'function') throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog service প্রস্তুত নয়।'); const source = await workspace.readConnectedCatalog(); if (!Array.isArray(source.products) || source.products.length > 20000 || !['supabase', 'database'].includes(source.source)) throw fail(502, 'INVALID_CONNECTED_CATALOG', 'Connected catalog সঠিক তালিকা দেয়নি।'); const id = 'connected:' + workspace.clientId; const context = { id, url: base.origin, documentUrl: base.origin, name: workspace.displayName || workspace.tenant, category: 'general' }; const products = source.products.map(row => ({ ...product({ sourceId: row.id, sku: row.sku, title: row.title, brand: row.brand, price: row.rawPrice, regular: row.rawRegularPrice, currency: row.currency, image: row.image, link: row.link, inStock: row.inStock }, context), link: publicLink(row.link, base.origin) })); const store = { id, name: context.name, url: '', domain: '', category: 'general', readOnly: true, sourceType: 'connected-' + source.source, fetchedAt: source.fetchedAt, count: products.length, products }; const bytes = Buffer.byteLength(JSON.stringify(store)); if (bytes <= maxCacheBytes && maxEntries > 0 && ttlMs > 0) { while (cache.size && (cache.size >= maxEntries || cachedBytes + bytes > maxCacheBytes)) { const oldest = cache.keys().next().value; cachedBytes -= cache.get(oldest).bytes; cache.delete(oldest); } cache.set(key, { store, bytes, expires: Date.now() + ttlMs }); cachedBytes += bytes; } return store; })(); inflight.set(key, task); try { return await task; } finally { if (inflight.get(key) === task) inflight.delete(key); } }; } module.exports = { createConnectedCatalog };