import test from 'node:test'; import assert from 'node:assert/strict'; import {build} from 'esbuild'; const result=await build({entryPoints:[new URL('../src/core/fleet/useVehicleObservation.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){ b.onResolve({filter:/^(react|\.\/useFleet)$/},a=>({path:a.path,namespace:'fixture'})); b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'? 'export const useState=v=>globalThis.observationUI.state(v),useRef=v=>globalThis.observationUI.ref(v),useEffect=(f,d)=>globalThis.observationUI.effect(f,d);': 'export const fleetRequest=(...args)=>globalThis.observationUI.request(...args);'})); }}]}); const {useVehicleObservation}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); const receipt=(document=null,writable=false,revision=1)=>({document,writable,revision,source:writable?'onboard':'mirror',available:true}); async function fixture(run){ const keys=['observationUI','localStorage','setTimeout','clearTimeout'],old=new Map(keys.map(k=>[k,globalThis[k]])); const values=[],effects=[],queue=[],timers=new Map(),storage=new Map();let cursor=0,dirty=true,closed=false,time=0,serial=0; const h={next:receipt(),calls:[],view:null,readGate:null, state(v){const i=cursor++;if(!(i in values))values[i]=typeof v==='function'?v():v;return[values[i],next=>{values[i]=typeof next==='function'?next(values[i]):next;dirty=true;}];}, ref(v){const i=cursor++;return values[i]??=( {current:v} );}, effect(f,d){const i=cursor++,prior=effects[i];if(!prior||d.some((v,j)=>v!==prior.d[j])){prior?.cleanup?.();effects[i]={d};queue.push(()=>{effects[i].cleanup=f();});}}, async request(path,method='GET',body){h.calls.push({path,method,body});if(method==='GET'){if(h.readGate)await h.readGate;if(h.next instanceof Error)throw h.next;return structuredClone(h.next);}if(!h.next.writable)throw Error('offline write');h.next=receipt(body.document,true,body.expected_revision+1);if(h.loseAck){h.next.writable=false;throw Error('lost acknowledgement');}return h.next;}, async settle(){for(let n=0;n<50;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useVehicleObservation('recovery-fixture');for(const f of queue.splice(0))f();}}}, async tick(ms){time+=ms;for(const [id,v]of [...timers])if(v.at<=time){timers.delete(id);v.f();}await h.settle();}, close(){closed=true;for(const e of effects)e?.cleanup?.();}, }; globalThis.observationUI=h;globalThis.localStorage={getItem:k=>storage.get(k)??null,setItem:(k,v)=>storage.set(k,v),removeItem:k=>storage.delete(k)}; globalThis.setTimeout=(f,delay)=>{timers.set(++serial,{f,at:time+delay});return serial;};globalThis.clearTimeout=id=>timers.delete(id); try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}} } test('mirror warning clears after fresh board receipt without edits, reopen or PUT',()=>fixture(async h=>{ await h.settle();assert.equal(h.view.ready,true);assert.match(h.view.error,/хранилищем/); h.next=receipt(null,true);await h.tick(5000);assert.equal(h.view.error,null);assert.equal(h.calls.filter(x=>x.method==='PUT').length,0); })); test('failed initial read retries and becomes ready without reopening',()=>fixture(async h=>{ h.next=Error('temporary outage');await h.settle();assert.equal(h.view.ready,false); h.next=receipt(null,true);await h.tick(5000);assert.equal(h.view.ready,true);assert.equal(h.view.error,null); })); test('recovery preserves local draft, merges remote edits and saves once availability returns',()=>fixture(async h=>{ await h.settle();h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350); assert.equal(h.view.pending,true); const draft=h.calls.find(x=>x.method==='PUT').body.document; h.next=receipt({...draft,cameras:{other:{yaw:45}}},true,2); await h.tick(5000); assert.deepEqual(h.view.cameras,{camera:{yaw:90},other:{yaw:45}}); assert.equal(h.view.pending,false);assert.equal(h.view.error,null); assert.equal(h.next.document.cameras.camera.yaw,90);assert.equal(h.next.document.cameras.other.yaw,45); })); test('conflicting remote edits never overwrite a local draft or trigger blind retry',()=>fixture(async h=>{ await h.settle();h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350); const prior=h.calls.filter(x=>x.method==='PUT').length,draft=h.calls.find(x=>x.method==='PUT').body.document; h.next=receipt({...draft,cameras:{camera:{yaw:180}}},true,2);await h.tick(5000); assert.equal(h.view.cameras.camera.yaw,90);assert.equal(h.view.pending,true); assert.equal(h.calls.filter(x=>x.method==='PUT').length,prior); })); test('fresh read-back of a committed save clears its lost acknowledgement error without rewriting',()=>fixture(async h=>{ h.next=receipt(null,true);await h.settle();h.loseAck=true; h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350); assert.equal(h.view.pending,true);assert.match(h.view.error,/acknowledgement/); h.next.writable=true;h.next.source='onboard';await h.tick(5000); assert.equal(h.view.pending,false);assert.equal(h.view.error,null); assert.deepEqual(h.view.cameras,{camera:{yaw:90}}); assert.equal(h.calls.filter(x=>x.method==='PUT').length,1); })); test('late initial response after unmount cannot schedule another read or mutate mounted view',()=>fixture(async h=>{ let release;h.readGate=new Promise(r=>{release=r;});await h.settle();h.close();release();await h.settle();await h.tick(30000); assert.equal(h.calls.length,1);assert.equal(h.view.ready,false); }));