import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createApp } from './server.mjs'; test('shared concurrent writes, validation and persistence after restart', async () => { const dataDir=mkdtempSync(join(tmpdir(),'amesa-test-'));let server; async function start(){server=createApp({dataDir});await new Promise(r=>server.listen(0,'127.0.0.1',r));return `http://127.0.0.1:${server.address().port}`;} async function stop(){await new Promise(r=>server.close(r));} try{ let url=await start(); const call=async(path,method='GET',body)=>{const r=await fetch(url+'/api/'+path,{method,headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});return {status:r.status,data:await r.json()};}; const image='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII='; const a={id:'device-a',name:'Sopa da Ana',image,ingredients:'Cenoura\nÁgua',preparation:'Cozer e triturar.'},b={...a,id:'device-b',name:'Sopa do João'}; assert.deepEqual((await Promise.all([call('recipes','POST',a),call('recipes','POST',b)])).map(r=>r.status),[201,201]); let shared=(await call('state')).data; assert.ok(shared.recipes.some(r=>r.id===a.id));assert.ok(shared.recipes.some(r=>r.id===b.id)); assert.equal(shared.recipes.find(r=>r.id===a.id).image,image); assert.equal((await call('recipes','POST',a)).status,200); assert.equal((await call('recipes','POST',{...a,name:'Overwrite'})).status,409); const slot='2026-9-7:1'; await Promise.all([call('entries','POST',{id:'entry-a',slot,recipeId:a.id}),call('entries','POST',{id:'entry-b',slot,recipeId:b.id})]); assert.equal((await call('state')).data.entries.length,2); await call('entries','POST',{id:'entry-a',slot,recipeId:a.id});assert.equal((await call('state')).data.entries.length,2); await call('entries/entry-a','DELETE');shared=(await call('state')).data;assert.deepEqual(shared.entries.map(e=>e.id),['entry-b']); assert.equal((await call('recipes','POST',{...a,id:'bad',image:'javascript:alert(1)'})).status,400); assert.equal((await call('entries','POST',{id:'bad',slot:'2026-2-30:1',recipeId:a.id})).status,400); assert.equal((await call('entries','POST',{id:'bad',slot,recipeId:'missing'})).status,404); assert.equal((await call('recipes','POST',{...a,id:'bad',name:''})).status,400); assert.equal((await call('recipes','POST',{...a,id:'big',image:'data:image/png;base64,'+Buffer.alloc(2*1024*1024+1).toString('base64')})).status,413); await stop();url=await start();assert.deepEqual((await call('state')).data,shared); const page=await fetch(url);assert.equal(page.status,200);assert.match(await page.text(),//); }finally{if(server?.listening)await stop();rmSync(dataDir,{recursive:true,force:true});} });