import test from 'node:test' import assert from 'node:assert/strict' import {createDisplayConnection,DISPLAY_STORAGE_KEY} from './frontend/src/tv/connection.mjs' const a='a'.repeat(43),b='b'.repeat(43) const flush=async()=>{for(let n=0;n<8;n++)await Promise.resolve()} function fixture(saved=a){ const stored=new Map(saved?[[DISPLAY_STORAGE_KEY,saved]]:[]),requests=[],timers=new Map(),states=[] let id=0;const url={hash:'',pathname:'/tv',search:'?client=android'} const connection=createDisplayConnection({url,historyApi:{replaceState(_s,_t,path){url.hash=path.includes('#')?'#'+path.split('#')[1]:''}}, storage:{getItem:k=>stored.get(k),setItem:(k,v)=>stored.set(k,v),removeItem:k=>stored.delete(k)}, fetcher:(_path,options)=>new Promise((resolve,reject)=>requests.push({options,resolve:(status,body)=>resolve({status,ok:status===200,json:async()=>body}),reject})), later:(fn,delay)=>{timers.set(++id,{fn,delay});return id},cancel:i=>timers.delete(i),now:()=>1000,onChange:s=>states.push(s)}) return {connection,url,stored,requests,timers,states,get state(){return states.at(-1)}} } test('new pairing fragment replaces cached authorization and clears private display data',async()=>{ const f=fixture();f.connection.start();f.requests[0].resolve(200,{home:{name:'Old'}});await flush() f.url.hash='#display='+b;f.connection.hashChanged();assert.equal(f.state.data,null) assert.equal(f.requests[1].options.headers.Authorization,'Bearer '+b);assert.equal(f.url.hash,'') f.requests[1].resolve(200,{home:{name:'New'}});await flush();assert.equal(f.state.data.home.name,'New');assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),b) }) test('late unauthorized response cannot clear the newly paired token',async()=>{ const f=fixture();f.connection.start();f.url.hash='#display='+b;f.connection.hashChanged() assert.ok(f.requests[0].options.signal.aborted);f.requests[0].resolve(401,{error:'Old revoked'});await flush() assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),b);assert.equal(f.state.authRequired,false) f.requests[1].resolve(200,{home:{name:'New'}});await flush();assert.equal(f.state.data.home.name,'New') }) test('real expiry hides household data and stops polling',async()=>{ const f=fixture();f.connection.start();f.requests[0].resolve(200,{locations:[{name:'Fixture'}]});await flush() f.connection.retry();f.requests[1].resolve(401,{error:'Expired'});await flush() assert.equal(f.state.data,null);assert.equal(f.state.authRequired,true);assert.equal(f.timers.size,0);assert.equal(f.stored.size,0) }) test('network failure retains authorization and schedules bounded retry',async()=>{ const f=fixture();f.connection.start();f.requests[0].reject(Error('Offline'));await flush() assert.equal(f.state.authRequired,false);assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),a) assert.deepEqual([...f.timers.values()].map(v=>v.delay),[30000]) }) test('fresh link works even if local storage is blocked',async()=>{ const requests=[];let state;const connection=createDisplayConnection({url:{hash:'#display='+a,pathname:'/tv',search:''},historyApi:{replaceState(){}}, storage:{getItem(){throw Error()},setItem(){throw Error()},removeItem(){throw Error()}},onChange:s=>state=s, fetcher:async(_u,o)=>{requests.push(o);return {ok:true,status:200,json:async()=>({home:{name:'Home'}})}}}) connection.start();await flush();assert.equal(state.data.home.name,'Home');assert.equal(requests.length,1);connection.stop() }) test('other-tab re-pair wins over stale 401, stop cancels all future work',async()=>{ const f=fixture();f.connection.start();f.stored.set(DISPLAY_STORAGE_KEY,b);f.requests[0].resolve(401,{});await flush() assert.equal(f.requests.length,2);f.connection.stop();f.requests[1].resolve(200,{home:{name:'Ignore'}});await flush() assert.equal(f.state.data,null);assert.equal(f.timers.size,0) }) test('unpaired and invalid explicit links never reuse a previous household',()=>{ const f=fixture();f.url.hash='#display=bad';f.connection.start();assert.equal(f.requests.length,0);assert.equal(f.state.authRequired,true);assert.equal(f.stored.size,0) })