import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import http from 'node:http' import {localApiPlugin} from '../server/local-api.mjs' test('API records captures once, commits decisions once, validates input and isolates origins',async()=>{ const root=fs.mkdtempSync(path.join(os.tmpdir(),'hp-api-'));let middleware localApiPlugin(root).configureServer({middlewares:{use:m=>middleware=m}}) const server=http.createServer((req,res)=>middleware(req,res,()=>{res.statusCode=404;res.end()})) await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)) const base='http://127.0.0.1:'+server.address().port,realFetch=globalThis.fetch globalThis.fetch=async(url,opts)=>String(url).startsWith('http://127.0.0.1:8765')?new Response(JSON.stringify({answers:{q1:{choice:'visible',abstained:false}},usage:{total_ms:12}}),{headers:{'Content-Type':'application/json'}}):realFetch(url,opts) const post=(route,body,headers={})=>fetch(base+route,{method:'POST',headers:{'Content-Type':'application/json',...headers},body:JSON.stringify(body)}) try{ const payload={instructions:'Is it visible?',criteria:{visible:'yes',absent:'no'},image:'data:image/jpeg;base64,eA==',meta:{captureId:'capture-1',itemName:'API test',kind:'grounding'}} const a=await post('/api/analyze',payload);assert.equal(a.status,200);const ar=await a.json() const b=await post('/api/analyze',{...payload,meta:{...payload.meta,kind:'observation'}});assert.equal(b.status,200);const br=await b.json() await post('/api/decision',{id:br.recordId,stateChanged:true,notified:true,verdict:'changed',engineMs:1}) await post('/api/decision',{id:br.recordId,stateChanged:false,notified:false,verdict:'duplicate'}) const m=await (await fetch(base+'/api/metrics')).json();assert.equal(m.captures,1);assert.equal(m.requests,2);assert.equal(m.notifications,1);assert.equal(m.stateChanges,1);assert.equal(m.records.find(r=>r.id===ar.recordId).inferenceMs,12) assert.equal((await post('/api/analyze',{})).status,422) assert.equal((await post('/api/analyze',payload,{Origin:'http://untrusted.test'})).status,403) assert.equal((await post('/api/decision',{id:'missing'})).status,404) assert.equal((await fetch(base+'/api/export')).status,200) }finally{globalThis.fetch=realFetch;await new Promise(resolve=>server.close(resolve));fs.rmSync(root,{recursive:true,force:true})} })