export function createDesk() { const stock = new Map([ [701, 3], [702, 2], ]); const receipts = new Map(); return { inventory() { return [...stock].map(([id, available]) => ({ id, available })); }, checkout(input) { if (!input || typeof input !== 'object' || Array.isArray(input)) throw Object.assign(new Error('Invalid request'), { status: 422 }); const { key, kitId, quantity } = input; if ( typeof key !== 'string' || !/^[a-z0-9-]{1,40}$/.test(key) || !Number.isSafeInteger(kitId) || !Number.isSafeInteger(quantity) || quantity < 1 || quantity > 20 ) throw Object.assign(new Error('Invalid request'), { status: 422 }); const signature = JSON.stringify({ kitId, quantity }); if (receipts.has(key)) { const previous = receipts.get(key); if (previous.signature !== signature) throw Object.assign(new Error('Key conflict'), { status: 409 }); return { ...previous.receipt, replayed: true }; } if (!stock.has(kitId)) throw Object.assign(new Error('Unknown kit'), { status: 404 }); if (quantity > stock.get(kitId)) throw Object.assign(new Error('Unavailable'), { status: 409 }); if (receipts.size >= 1000) throw Object.assign(new Error('Demo receipt capacity reached'), { status: 503, }); stock.set(kitId, stock.get(kitId) - quantity); const receipt = { kitId, quantity, available: stock.get(kitId), replayed: false, persistent: false, }; receipts.set(key, { signature, receipt }); return { ...receipt }; }, }; }