web/website/node/shop-sales.mjs
2026-11-27 23:43:05 +00:00

14 lines
2.5 KiB
JavaScript

const SHOP='https://shop.dunerealms.com';
const FEED=SHOP+'/catalog/dune-shop/sales-feed?currency=EUR';
const cleanText=(v,max)=>typeof v==='string'&&v.length>0&&v.length<=max&&!/[\x00-\x1f\x7f]/.test(v);
function shopURL(value,{product=false}={}){if(typeof value!=='string'||value.length>1800)return null;try{const url=new URL(value,SHOP+'/catalog/');if(url.hostname!=='shop.dunerealms.com'||!['https:','http:'].includes(url.protocol)||url.username||url.password||url.port||product&&!url.pathname.startsWith('/catalog/'))return null;url.protocol='https:';return url.href;}catch{return null;}}
export function projectShopSales(data){
if(data?.source!=='oscommerce'||data.currency!=='EUR'||!Array.isArray(data.items)||data.items.length>24)throw Error('Invalid osCommerce promotion feed');
const items=[];for(const row of data.items){const url=shopURL(row.url,{product:true}),image=shopURL(row.image);if(!Number.isSafeInteger(row.id)||row.id<1||!cleanText(row.name,240)||!cleanText(row.regularPrice,80)||!cleanText(row.salePrice,80)||!Number.isInteger(row.savingPercent)||row.savingPercent<1||row.savingPercent>100||!url)continue;items.push({id:row.id,name:row.name,url,image,regularPrice:row.regularPrice,salePrice:row.salePrice,savingPercent:row.savingPercent});if(items.length===3)break;}
return {source:'oscommerce',brand:'Imperial Heralds',currency:'EUR',items};
}
export function createShopSales({fetcher=fetch,clock=Date.now}={}){
let cached=null,expires=0,pending=null;
const read=()=>{if(cached&&clock()<expires)return Promise.resolve(cached);if(pending)return pending;pending=(async()=>{const response=await fetcher(FEED,{redirect:'error',signal:AbortSignal.timeout(8000),headers:{Accept:'application/json'}});if(!response.ok)throw Error('Shop offers unavailable');const text=await response.text();if(text.length>131072)throw Error('Shop offer response too large');const data=projectShopSales(JSON.parse(text));cached=data;expires=clock()+60000;return data;})().finally(()=>pending=null);return pending;};
return async request=>{if(request.method!=='GET')return Response.json({message:'Read-only shop offers.'},{status:405,headers:{Allow:'GET'}});if(new URL(request.url).search)return Response.json({message:'Unknown shop offer filter.'},{status:400});try{return Response.json(await read(),{headers:{'Cache-Control':'public, max-age=30','X-Content-Type-Options':'nosniff'}});}catch{return Response.json({source:'oscommerce',message:'Shop offers are temporarily unavailable.'},{status:503,headers:{'Cache-Control':'no-store'}});}};
}