/* Public station names only; never stores room aliases or login credentials. */ (function (root) { 'use strict'; const KEY = 'soop-auto-manager:original-names:v1'; const ID = /^[a-z0-9_]{2,32}$/; const TTL = 10 * 60 * 1000, RETRY = 60 * 1000, MAX_CACHE = 500; const validName = value => typeof value === 'string' && value.trim() && value.length <= 512 && !/[\u0000-\u001f\u007f]/.test(value); function createLookup(options = {}) { const now = options.now || Date.now; const fetchName = options.fetch; const setTimer = options.setTimeout || ((...args) => root.setTimeout(...args)); const clearTimer = options.clearTimeout || (id => root.clearTimeout(id)); const Controller = options.AbortController || root.AbortController; const cache = new Map(), jobs = new Map(), queue = [], failures = new Map(); let active = 0, closed = false, pumpTimer = null; try { const saved = JSON.parse(options.storage?.getItem(KEY) || 'null'); if (saved?.version === 1 && Array.isArray(saved.rows)) for (const row of saved.rows.slice(0,MAX_CACHE)) { if (ID.test(row?.id || '') && validName(row.nickname) && Number.isFinite(row.at) && row.at <= now() + 60000 && now() - row.at < TTL) cache.set(row.id,{nickname:row.nickname,at:row.at}); } } catch (_) { /* Blocked browser storage cannot prevent a public lookup. */ } function changed() { if (!closed) try { options.onChange?.(); } catch (_) {} } function persist() { const rows = [...cache].map(([id,row])=>({id,...row})).sort((a,b)=>b.at-a.at).slice(0,MAX_CACHE); cache.clear(); for (const row of rows) cache.set(row.id,{nickname:row.nickname,at:row.at}); try { options.storage?.setItem(KEY,JSON.stringify({version:1,rows})); } catch (_) {} } async function run(job) { let timer; try { const controller = job.controller = new Controller(); const timeout = new Promise((_,reject)=>{ timer=setTimer(()=>{controller.abort();reject(new Error('timeout'));},6000); }); const request = (async()=>{ const response = await fetchName(`https://chapi.sooplive.com/api/${job.id}/station`,{ method:'GET',credentials:'omit',mode:'cors',cache:'no-store',redirect:'error',signal:controller.signal, }); if (!response?.ok) throw new Error('station_unavailable'); const data = await response.json(), station = data?.station; if (station?.user_id !== job.id || !validName(station.user_nick)) throw new Error('invalid_station'); return station.user_nick; })(); const cancelled = new Promise((_,reject)=>{job.reject=reject;}); const nickname = await Promise.race([request,timeout,cancelled]); if (!closed) { cache.set(job.id,{nickname,at:now()});failures.delete(job.id);persist(); } } catch (_) { if (!closed) { failures.set(job.id,now()); if (failures.size>MAX_CACHE) failures.delete(failures.keys().next().value); } } finally { if (timer !== undefined) clearTimer(timer); jobs.delete(job.id);active--;pump();changed(); } } function pump() { while (!closed && active<3 && queue.length) { const job=queue.shift();active++;run(job); } } function ensure(ids) { if (closed || typeof fetchName!=='function' || typeof Controller!=='function' || !Array.isArray(ids) || ids.length>100) return; const wanted=new Set(ids.filter(id=>ID.test(id || ''))); // A row ID may still be changing while typed. Drop obsolete queued // spellings before the short registration debounce starts any requests. for (let i=queue.length-1;i>=0;i--) if (!wanted.has(queue[i].id)) { jobs.delete(queue[i].id);queue.splice(i,1); } for (const id of wanted) { if (!ID.test(id || '') || jobs.has(id) || (cache.has(id) && now()-cache.get(id).at=100) continue; const job={id};jobs.set(id,job);queue.push(job); } if (queue.length && pumpTimer===null) pumpTimer=setTimer(()=>{pumpTimer=null;pump();},250); } function get(id) { if (closed || !ID.test(id || '')) return null; const saved=cache.get(id); if (saved) return {nickname:saved.nickname,source:'station',present:false,state:jobs.has(id)?'refreshing':'ready'}; return jobs.has(id) ? {source:'station',state:'loading'} : failures.has(id) ? {source:'station',state:'error'} : null; } function close() { closed=true;queue.length=0; if (pumpTimer!==null) {clearTimer(pumpTimer);pumpTimer=null;} for (const job of jobs.values()) {job.controller?.abort();job.reject?.(new Error('closed'));} jobs.clear();cache.clear();failures.clear(); } return Object.freeze({ensure,get,close}); } root.SoopAutoManagerNicknames = Object.freeze({createLookup}); if (typeof module === 'object' && module.exports) module.exports = root.SoopAutoManagerNicknames; })(globalThis);