/* The Raisina Post ยท contextual reader pathways. No tracking, no AI calls. */ const ORIGIN='https://theraisinapost.com'; const SECTIONS=new Set(['business','governance','in-depth','opinion']); const STOP=new Set(('a an the and or but for from with into onto through who whom whose what where why how when of to in on at by is are was were be been being as this that these those it its their they them has have had will can may not than about after before more new latest today yesterday 2024 2025 2026 2027 india indian world reports report says said amid over under big biggest year years news post raisina crore lakh million billion trillion thousand percent percentage rupees amount amounts data major large public').split(' ')); const CONCEPTS=[ ['equity',/^(owner|ownership|owns?|sharehold|shares?|stake|equity|stockholder)/], ['investment',/^(invest|fund|venture|capital)/], ['ipo',/^(ipo|ipos|listing|listed|float)/], ['banking',/^(fintech|financ|bank|credit)/], ['valuation',/^(valuat)/], ['startup',/^(startup|startups|founder|unicorn)/], ['election',/^(elect|vot|poll|ballot|parliament|assembly)/], ['policy',/^(regulat|legislat|legisl|policy|policies|minister|bill|laws?|act)$/], ['economy',/^(economic|economy|gdp|inflation|interest|rbi|budget|macroeconom)/], ['rail',/^(railway|railroads?|freight|logistics|rail)/], ['trade',/^(export|import|tariff|trade|customs)/] ]; export function normalizeArticlePath(value) { if(typeof value!=='string'||!value.trim())return null; try{ const u=new URL(value,ORIGIN); if(u.origin!==ORIGIN||u.search||u.hash)return null; const path=u.pathname.replace(/\/index\.html$/,'/').replace(/\/?$/,'/'); if(!/^(?:\/(?:business|governance|in-depth|opinion)\/[a-z0-9]+(?:-[a-z0-9]+)*\/|\/24-hours\/(?:india-news|world-news)\/\d{4}-\d{2}-\d{2}\/)$/.test(path))return null; return path; }catch{return null;} } function normalTerm(word){ if(STOP.has(word)||word.length<3||/^\d/.test(word))return ''; const concept=CONCEPTS.find(([,rx])=>rx.test(word)); if(concept)return concept[0]; return word.endsWith('s')&&word.length>5?word.slice(0,-1):word; } function terms(text) { const parts=String(text||'').toLowerCase().normalize('NFKD').replace(/\p{M}/gu,'').match(/[\p{L}\p{N}]+/gu)||[]; return [...new Set(parts.map(normalTerm).filter(Boolean))]; } function dateValue(row){ const raw=row.date_iso||row.date||''; const parsed=Date.parse(raw); return Number.isFinite(parsed)?parsed:0; } function candidate(row){ if(!row||typeof row!=='object'||typeof row.title!=='string'||!row.title.trim())return null; const path=normalizeArticlePath(row.url||row.path); if(!path)return null; return {path,title:row.title.trim().slice(0,180), summary:String(row.summary||row.description||'').trim().slice(0,230), section:path.startsWith('/24-hours/')?path.split('/').slice(1,3).join('/'):path.split('/')[1],date:dateValue(row)}; } export function pickRelated(context,rows,now=new Date()){ if(!Array.isArray(rows))return []; const current=normalizeArticlePath(context?.path||context?.url||''); const weights=new Map(); const headlineTerms=new Set(terms(context?.title)); for(const [source,weight] of [[context?.title,3],[context?.deck||context?.summary,1],[context?.keywords,1]]){ for(const t of terms(source))weights.set(t,Math.max(weight,weights.get(t)||0)); } const seen=new Set(); const nowMs=now instanceof Date?now.getTime():new Date(now).getTime(); const possibilities=[]; for(const raw of rows){ const item=candidate(raw); if(!item||item.path===current||seen.has(item.path))continue; seen.add(item.path); const titleTerms=new Set(terms(item.title)); const summaryTerms=new Set(terms(item.summary)); let score=0,matches=0,headlineMatches=0; for(const [t,w] of weights){ if(titleTerms.has(t)){score+=w*2;matches++;if(headlineTerms.has(t))headlineMatches++;} else if(summaryTerms.has(t)){score+=w;matches++;if(headlineTerms.has(t))headlineMatches++;} } const ageDays=Number.isFinite(nowMs)&&item.date?(nowMs-item.date)/86400000:Infinity; if(ageDays>=0&&ageDays<=14)score+=0.75; if(ageDays>=0&&ageDays<=3)score+=0.35; if(item.section===context?.section)score+=0.5; // Old breaking news should not eclipse more useful, still-current analysis. if(ageDays>60&&['business','governance'].includes(item.section))score-=2; possibilities.push({...item,score,matches,headlineMatches}); } const relevant=possibilities.filter(x=>x.matches>=2&&x.headlineMatches>=1&&x.score>=4).sort((a,b)=>b.score-a.score||b.date-a.date); if(relevant.length)return relevant.slice(0,3).map(x=>({...x,reason:'Related reporting'})); return possibilities.filter(x=>x.section===context?.section) .sort((a,b)=>b.date-a.date||b.score-a.score).slice(0,2) .map(x=>({...x,reason:'Latest from this desk'})); } export function pickTools(context){ const title=String(context?.title||''); const deck=String(context?.deck||context?.summary||''); const subject=(title+' '+deck).toLowerCase(); const tools={ atlas:{href:'/ownership-atlas/',title:'Ownership Atlas',description:'Trace who holds and controls major companies.'}, terminal:{href:'/terminal/',title:'Raisina Terminal',description:'Explore company and policy research.'}, parliament:{href:'/parliament-file/',title:'Parliament File',description:'Find parliamentary reports and institutional documents.'}, markets:{href:'/markets/',title:'Market desk',description:'Put financial and economic developments in context.'}, brief:{href:'/power-brief/',title:'The Power Brief',description:'Start the next day with a concise editorial briefing.'} }; if(/\b(railway|railways|freight|rail transport|train network|passenger subsidy)\b/i.test(subject)) return [tools.parliament,tools.markets]; if(/\b(air quality|pollution|emissions|construction ban|environmental clearance)\b/i.test(subject)) return [tools.parliament,tools.brief]; if(/\b(ownership|owns?|sharehold|shareholder|stake|ipo|investor|startup|unicorn|acquisition|merger|company|corporate|listing|listed|valuation)\b/i.test(subject)) return [tools.atlas,tools.terminal]; if(/\b(parliament|bill|regulation|regulatory|legislation|court|minister|cabinet|government|governance|policy|laws?|constitution|election|poll|rights)\b/i.test(subject)) return [tools.parliament,tools.brief]; if(/\b(market|inflation|stock|gdp|rbi|economy|economic|trade|budget|export|interest rate|currency|oil price)\b/i.test(subject)) return [tools.markets,tools.terminal]; return [tools.brief,context?.section==='business'?tools.terminal:tools.parliament]; } function element(tag,className,text){ const node=document.createElement(tag); if(className)node.className=className; if(text!==undefined)node.textContent=text; return node; } function makeLink(href,title,description,eyebrow){ const a=element('a','rp-context-item'); a.href=href; if(eyebrow)a.append(element('span','rp-context-meta',eyebrow)); a.append(element('span','rp-context-item-title',title)); if(description)a.append(element('span','rp-context-desc',description)); return a; } async function boot(){ const root=document.querySelector('main.ra-article'); const grid=root?.querySelector('.ra-story-grid'); const story=grid?.querySelector('article.ra-story-main'); if(!root||!grid||!story||root.classList.contains('rp-context-article'))return; const title=story.querySelector('.ra-mast h1')?.textContent?.trim()||document.title; const deck=story.querySelector('.ra-deck')?.textContent?.trim()||''; const canonical=document.querySelector('link[rel="canonical"]')?.href||location.href; const path=normalizeArticlePath(canonical); if(!path)return; const context={title,deck,path,section:path.split('/')[1], keywords:document.querySelector('meta[name="keywords"]')?.content||''}; const left=element('aside','rp-context-left'); left.setAttribute('aria-label','Explore Raisina research'); const leftBody=element('div','rp-context-sticky'); leftBody.append(element('h2','rp-context-heading','Go deeper')); for(const tool of pickTools(context))leftBody.append(makeLink(tool.href,tool.title)); left.append(leftBody); const right=element('aside','rp-context-right'); right.setAttribute('aria-label','Related reporting'); const rightBody=element('div','rp-context-sticky'); right.append(rightBody); const style=element('link'); style.rel='stylesheet'; style.href='/context-rails.css?v=20261119-1'; document.head.append(style); grid.append(left,right); root.classList.add('rp-context-article'); try { const response=await fetch('/data/search-index.json',{cache:'no-cache',credentials:'same-origin'}); if(!response.ok)throw new Error('index unavailable'); const data=await response.json(); const picks=pickRelated(context,Array.isArray(data)?data:data.items||[],new Date()); if(picks.length){ rightBody.append(element('h2','rp-context-heading',picks[0].reason==='Related reporting'?'Continue reading':'From this desk')); for(const item of picks)rightBody.append(makeLink(item.path,item.title,'',item.section.replace(/-/g,' '))); }else { right.remove(); } }catch { // Missing index must never interfere with the article, navigation or reader controls. right.remove(); } } if(typeof document!=='undefined'){ const start=()=>{if(typeof requestIdleCallback==='function')requestIdleCallback(boot,{timeout:1000});else setTimeout(boot,150);}; if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true}); else start(); }