This commit is contained in:
kl3z00
2026-10-26 14:16:09 +00:00
commit 6db0460adc
20 changed files with 8111 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {mkdtempSync,rmSync} from 'node:fs';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {createApp} from './server.mjs';
import {applyShoppingOverrides} from '../src/shopping.ts';
test('upgrade old database preserves recipes and plans, edits and weekly products survive restart',async()=>{
const dir=mkdtempSync(join(tmpdir(),'amesa-upgrade-'));
const old=new DatabaseSync(join(dir,'amesa.sqlite'));
old.exec(`CREATE TABLE recipes(id TEXT PRIMARY KEY,name TEXT NOT NULL,image TEXT NOT NULL,ingredients TEXT NOT NULL,preparation TEXT NOT NULL);
CREATE TABLE entries(id TEXT PRIMARY KEY,slot TEXT NOT NULL,recipeId TEXT NOT NULL REFERENCES recipes(id));
CREATE TABLE metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);INSERT INTO metadata VALUES('seeded','1');`);
const r={id:'mine',name:'Receita guardada',image:'https://example.com/image.jpg',ingredients:'100 g de arroz',preparation:'Cozer.'};
old.prepare('INSERT INTO recipes VALUES(?,?,?,?,?)').run(...Object.values(r));
old.prepare('INSERT INTO entries VALUES(?,?,?)').run('planned','2026-9-7:1','mine');old.close();
let app,url;
const start=async()=>{app=createApp({dataDir:dir});await new Promise(r=>app.listen(0,'127.0.0.1',r));url=`http://127.0.0.1:${app.address().port}/api/`;};
const stop=()=>new Promise(r=>app.close(r));
const call=async(path,method='GET',data)=>{const response=await fetch(url+path,{method,headers:{'Content-Type':'application/json'},body:data?JSON.stringify(data):undefined});return {status:response.status,data:await response.json()};};
try{
await start();let state=(await call('state')).data;
assert.deepEqual(state.recipes,[r]);assert.equal(state.entries[0].recipeId,'mine');
const changed={...r,name:'Receita editada',ingredients:'200 g de arroz'};
assert.equal((await call('recipes/mine','PUT',{...changed,previous:r})).status,200);
assert.equal((await call('recipes/mine','PUT',{...r,previous:r})).status,409);
assert.equal((await call('recipes/mine','PUT',{...changed,name:'',previous:changed})).status,400);
const product={week:'2026-9-7',key:'arroz|g',name:'arroz',quantity:300,unit:'g',removed:false};
const manual={...product,key:'manual:milk',name:'leite',unit:'l',quantity:2};
assert.equal((await call('shopping','PUT',product)).status,200);
assert.equal((await call('shopping','PUT',manual)).status,200);
assert.equal((await call('shopping','PUT',{...product,quantity:-2})).status,400);
assert.equal((await call('shopping','PUT',{...product,week:'2026-9-8'})).status,400);
await call('shopping','PUT',{...product,week:'2026-9-14',removed:true});
await stop();await start();state=(await call('state')).data;
assert.deepEqual(state.recipes,[changed]);assert.equal(state.entries.length,1);assert.equal(state.shoppingOverrides.length,3);
const base=[{key:'arroz|g',name:'arroz',unit:'g',quantity:200,occurrences:1,recipes:['Receita editada']}];
const rows=applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-7');
assert.equal(rows.find(r=>r.name==='arroz').quantity,300);assert.equal(rows.find(r=>r.name==='leite').quantity,2);
assert.deepEqual(applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-14'),[]);
assert.equal((await call('shopping','DELETE',product)).status,200);
state=(await call('state')).data;
assert.equal(applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-7').find(r=>r.name==='arroz').quantity,200);
}finally{if(app?.listening)await stop();rmSync(dir,{recursive:true,force:true});}
});
+44
View File
@@ -0,0 +1,44 @@
[
{
"id": "1",
"name": "Tosta de abacate e ovo",
"image": "https://images.unsplash.com/photo-1525351484163-7529414344d8?auto=format&fit=crop&w=600&q=80",
"ingredients": "1 fatia de pão\n½ abacate\n1 ovo\nSal e pimenta",
"preparation": "Torre o pão. Esmague o abacate e tempere. Cozinhe o ovo numa frigideira e coloque sobre a tosta com o abacate."
},
{
"id": "2",
"name": "Bowl de iogurte e frutos",
"image": "https://images.unsplash.com/photo-1511690743698-d9d85f2fbf38?auto=format&fit=crop&w=600&q=80",
"ingredients": "150 g de iogurte natural\n3 colheres de granola\nFrutos vermelhos\n1 colher de mel",
"preparation": "Coloque o iogurte numa taça. Acrescente a granola e os frutos lavados. Finalize com um fio de mel."
},
{
"id": "3",
"name": "Salada mediterrânica",
"image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=600&q=80",
"ingredients": "Alface\nTomate cherry\nPepino\nQueijo feta\nAzeite e limão",
"preparation": "Lave e corte os vegetais. Misture numa taça com o queijo. Tempere com azeite e sumo de limão antes de servir."
},
{
"id": "4",
"name": "Salmão com legumes",
"image": "https://images.unsplash.com/photo-1467003909585-2f8a72700288?auto=format&fit=crop&w=600&q=80",
"ingredients": "1 lombo de salmão\nBrócolos\nCenoura\nAzeite\nLimão e sal",
"preparation": "Aqueça o forno a 200 °C. Coloque o salmão e os legumes num tabuleiro, tempere e regue com azeite. Asse durante cerca de 20 minutos, até estar cozinhado."
},
{
"id": "5",
"name": "Massa com tomate e manjericão",
"image": "https://images.unsplash.com/photo-1473093295043-cdd812d0e601?auto=format&fit=crop&w=600&q=80",
"ingredients": "100 g de massa\n150 g de tomate\n1 dente de alho\nManjericão\nAzeite",
"preparation": "Coza a massa. Salteie o alho e o tomate em azeite. Envolva a massa no molho e termine com manjericão fresco."
},
{
"id": "6",
"name": "Panquecas de banana",
"image": "https://images.unsplash.com/photo-1528207776546-365bb710ee93?auto=format&fit=crop&w=600&q=80",
"ingredients": "1 banana\n1 ovo\n3 colheres de aveia\nCanela",
"preparation": "Esmague a banana e misture com o ovo, a aveia e a canela. Cozinhe pequenas porções numa frigideira antiaderente, dos dois lados."
}
]
+133
View File
@@ -0,0 +1,133 @@
import http from 'node:http';
import { DatabaseSync } from 'node:sqlite';
import { mkdirSync, readFileSync, existsSync, statSync } from 'node:fs';
import { resolve, extname, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const fail = (status, message) => Object.assign(new Error(message), { status });
export function createApp({ dataDir = process.env.DATA_DIR || './data', staticDir = './dist/a-mesa/browser' } = {}) {
mkdirSync(dataDir, { recursive: true });
const db = new DatabaseSync(resolve(dataDir, 'amesa.sqlite'));
db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS recipes (id TEXT PRIMARY KEY, name TEXT NOT NULL, image TEXT NOT NULL, ingredients TEXT NOT NULL, preparation TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS entries (id TEXT PRIMARY KEY, slot TEXT NOT NULL, recipeId TEXT NOT NULL REFERENCES recipes(id));
CREATE INDEX IF NOT EXISTS entries_slot ON entries(slot);
CREATE TABLE IF NOT EXISTS shopping_overrides (week TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(week, key));
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);`);
const insert = db.prepare('INSERT INTO recipes VALUES (?, ?, ?, ?, ?)');
if (!db.prepare("SELECT value FROM metadata WHERE key='seeded'").get()) {
const seed = JSON.parse(readFileSync(new URL('./seed.json', import.meta.url), 'utf8'));
db.exec('BEGIN');
try {
for (const r of seed) insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
db.prepare('INSERT INTO metadata VALUES (?, ?)').run('seeded', '1');
db.exec('COMMIT');
} catch (error) { db.exec('ROLLBACK'); throw error; }
}
function state() {
return { recipes: db.prepare('SELECT * FROM recipes ORDER BY rowid').all(), entries: db.prepare('SELECT * FROM entries ORDER BY rowid').all(), shoppingOverrides: db.prepare('SELECT * FROM shopping_overrides').all().map(r => ({week:r.week,key:r.key,...JSON.parse(r.value)})) };
}
function recipe(input) {
if (!input || typeof input !== 'object') throw fail(400, 'Receita inválida.');
const result = {};
for (const [key, max] of Object.entries({ id: 100, name: 100, image: 2900000, ingredients: 20000, preparation: 30000 })) {
if (typeof input[key] !== 'string' || !input[key].trim() || input[key].length > max) throw fail(400, `Campo inválido: ${key}.`);
result[key] = input[key].trim();
}
if (!/^[a-zA-Z0-9-]+$/.test(result.id)) throw fail(400, 'Identificador inválido.');
const data = result.image.match(/^data:image\/(png|jpeg|gif|webp);base64,([A-Za-z0-9+/]+={0,2})$/);
if (data) {
if (Buffer.from(data[2], 'base64').length > 2 * 1024 * 1024) throw fail(413, 'A imagem deve ter menos de 2 MB.');
} else {
let url; try { url = new URL(result.image); } catch { throw fail(400, 'Imagem inválida.'); }
if (!['http:', 'https:'].includes(url.protocol) || result.image.length > 4096) throw fail(400, 'Utilize uma imagem PNG, JPEG, GIF, WebP ou um URL HTTP/HTTPS.');
}
return result;
}
async function body(req) {
if (!req.headers['content-type']?.startsWith('application/json')) throw fail(415, 'Envie dados JSON.');
const chunks = []; let size = 0;
const limit = req.method === 'PUT' && req.url?.startsWith('/api/recipes/') ? 6000000 : 3000000;
for await (const chunk of req) { size += chunk.length; if (size > limit) throw fail(413, 'Pedido demasiado grande.'); chunks.push(chunk); }
try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw fail(400, 'JSON inválido.'); }
}
function json(res, status, value) { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); }
const root = resolve(staticDir);
const server = http.createServer(async (req, res) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
try {
const path = new URL(req.url, 'http://localhost').pathname;
if (path === '/api/health' && req.method === 'GET') return json(res, 200, { ok: true });
if (path === '/api/state' && req.method === 'GET') return json(res, 200, state());
if (path.startsWith('/api/recipes/') && req.method === 'PUT') {
const input = await body(req), r = recipe(input), previous = recipe(input.previous);
if (r.id !== decodeURIComponent(path.slice('/api/recipes/'.length)) || previous.id !== r.id) throw fail(400, 'Identificador inválido.');
const result = db.prepare('UPDATE recipes SET name=?, image=?, ingredients=?, preparation=? WHERE id=? AND name=? AND image=? AND ingredients=? AND preparation=?').run(r.name,r.image,r.ingredients,r.preparation,r.id,previous.name,previous.image,previous.ingredients,previous.preparation);
if (!result.changes) throw fail(409, 'Esta receita foi alterada entretanto. Feche e volte a abrir a receita para editar a versão atual.');
return json(res, 200, r);
}
if (path === '/api/shopping' && ['PUT','DELETE'].includes(req.method)) {
const input = await body(req);
if (!input || typeof input.week !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}$/.test(input.week) || typeof input.key !== 'string' || !input.key.trim() || input.key.length > 21000) throw fail(400,'Lista inválida.');
const [y,m,d] = input.week.split('-').map(Number), date = new Date(Date.UTC(y,m-1,d));
if (date.getUTCFullYear()!==y || date.getUTCMonth()!==m-1 || date.getUTCDate()!==d || date.getUTCDay()!==1) throw fail(400,'Semana inválida.');
if (req.method === 'DELETE') {
db.prepare('DELETE FROM shopping_overrides WHERE week=? AND key=?').run(input.week,input.key);
} else {
if(typeof input.name!=='string'||!input.name.trim()||input.name.length>20000||typeof input.unit!=='string'||input.unit.length>100||typeof input.removed!=='boolean'||(input.quantity!==null&&(typeof input.quantity!=='number'||!Number.isFinite(input.quantity)||input.quantity<0||input.quantity>1e9))) throw fail(400,'Produto ou quantidade inválidos.');
const value=JSON.stringify({name:input.name.trim(),unit:input.unit.trim(),quantity:input.quantity,removed:input.removed});
db.prepare('INSERT INTO shopping_overrides VALUES (?,?,?) ON CONFLICT(week,key) DO UPDATE SET value=excluded.value').run(input.week,input.key,value);
}
return json(res,200,{ok:true});
}
if (path === '/api/recipes' && req.method === 'POST') {
const r = recipe(await body(req));
const existing = db.prepare('SELECT * FROM recipes WHERE id=?').get(r.id);
if (existing) {
if (Object.keys(r).some(key => r[key] !== existing[key])) throw fail(409, 'Já existe uma receita diferente com este identificador.');
return json(res, 200, existing);
}
insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
return json(res, 201, r);
}
if (path === '/api/entries' && req.method === 'POST') {
const data = await body(req);
if (!data || typeof data.slot !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}:[012]$/.test(data.slot)) throw fail(400, 'Dia ou refeição inválidos.');
const [year, month, day] = data.slot.split(':')[0].split('-').map(Number);
const date = new Date(Date.UTC(year, month - 1, day));
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) throw fail(400, 'Data inválida.');
if (typeof data.recipeId !== 'string' || !db.prepare('SELECT id FROM recipes WHERE id=?').get(data.recipeId)) throw fail(404, 'Receita não encontrada.');
if (typeof data.id !== 'string' || !/^[a-zA-Z0-9-]{1,100}$/.test(data.id)) throw fail(400, 'Identificador inválido.');
const existing = db.prepare('SELECT * FROM entries WHERE id=?').get(data.id);
if (existing && (existing.slot !== data.slot || existing.recipeId !== data.recipeId)) throw fail(409, 'Identificador já utilizado.');
if (!existing) db.prepare('INSERT INTO entries VALUES (?, ?, ?)').run(data.id, data.slot, data.recipeId);
return json(res, existing ? 200 : 201, { id: data.id, slot: data.slot, recipeId: data.recipeId });
}
if (path.startsWith('/api/entries/') && req.method === 'DELETE') {
db.prepare('DELETE FROM entries WHERE id=?').run(decodeURIComponent(path.slice('/api/entries/'.length)));
return json(res, 200, { ok: true });
}
if (path.startsWith('/api/')) throw fail(404, 'Operação não encontrada.');
if (!['GET', 'HEAD'].includes(req.method)) throw fail(405, 'Método não permitido.');
let file = resolve(root, '.' + decodeURIComponent(path));
if (file !== root && !file.startsWith(root + sep)) throw fail(403, 'Caminho inválido.');
if (!existsSync(file) || statSync(file).isDirectory()) file = resolve(root, 'index.html');
if (!existsSync(file)) throw fail(404, 'Compile a aplicação com npm run build.');
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
res.writeHead(200, { 'Content-Type': types[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
res.end(req.method === 'HEAD' ? undefined : readFileSync(file));
} catch (error) {
if (!error.status) console.error(error);
if (!res.headersSent) json(res, error.status || 500, { error: error.status ? error.message : 'Não foi possível guardar os dados. Tente novamente.' });
else res.end();
}
});
server.on('close', () => db.close());
return server;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const server = createApp();
const port = Number(process.env.PORT || 3000);
server.listen(port, '0.0.0.0', () => console.log(`À Mesa disponível na porta ${port}`));
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => server.close());
}
+36
View File
@@ -0,0 +1,36 @@
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(),/<app-root>/);
}finally{if(server?.listening)await stop();rmSync(dataDir,{recursive:true,force:true});}
});
+23
View File
@@ -0,0 +1,23 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { shoppingList, quantityLabel } from '../src/shopping.ts';
test('weekly totals include repeated recipes and compatible quantities only',()=>{
const recipes=[{id:'a',name:'A',ingredients:'150 g de arroz\n1 ovo\n½ abacate\nSal\n1 colher de sopa de azeite'},{id:'b',name:'B',ingredients:'0,5 kg de arroz\n2 ovos\n1/2 abacate\nSal\n20 ml de azeite'}];
const entries=[{slot:'week',recipeId:'a'},{slot:'week',recipeId:'a'},{slot:'week',recipeId:'b'},{slot:'other',recipeId:'b'}];
const rows=shoppingList(recipes,entries,['week']);
assert.equal(rows.find(r=>r.name==='arroz').quantity,800);
assert.equal(rows.find(r=>r.name==='ovo').quantity,4);
assert.equal(rows.find(r=>r.name==='abacate').quantity,1.5);
assert.equal(rows.find(r=>r.name==='Sal').quantity,null);
assert.equal(rows.find(r=>r.name==='Sal').occurrences,3);
assert.equal(rows.filter(r=>r.name==='azeite').length,2);
assert.deepEqual(shoppingList(recipes,entries,['empty']),[]);
});
test('fractions, unit conversions, ambiguous quantities and line breaks',()=>{
const rows=shoppingList([{id:'r',name:'Receita',ingredients:'1½ l de água\r\n250ml de água\n1 1/2 kg de farinha\n500 g de farinha\n1 a 2 ovos\n1/0 ovos\n\n- 2 bananas'}],[{slot:'s',recipeId:'r'}],['s']);
assert.equal(rows.find(r=>r.name==='água').quantity,1750);
assert.equal(quantityLabel(rows.find(r=>r.name==='farinha')),'2 kg');
assert.equal(rows.find(r=>r.name==='1 a 2 ovos').quantity,null);
assert.equal(rows.find(r=>r.name==='1/0 ovos').quantity,null);
assert.equal(rows.find(r=>r.name==='banana').quantity,2);
});