// Preserve partial stdout records across WASI writes; ordinary prompts are // flushed on stdin requests even when printf did not end with a newline. export function createRaceProtocol({ configure, speed, go, winner, output }) { let pending = ''; function line(text) { const value = text.trim(); let match; if ((match = /^course (\d+) distance ([\d.eE+-]+)$/.exec(value))) configure(Number(match[1]), Number(match[2])); else if ((match = /^microduck (\d+) vitesse ([\d.eE+-]+)$/.exec(value))) speed(Number(match[1]), Number(match[2])); else if (/^1\s*,\s*2\s*,\s*3\s*,\s*partez\s*!?$/i.test(value)) { go(); output(text); } else if ((match = /^le vainqueur est microduck (\d+)$/i.exec(value))) { if (winner(Number(match[1])) !== false) output(text); } else output(text); } return { write(text) { pending += text; let n; while ((n = pending.indexOf('\n')) >= 0) { const record = pending.slice(0, n + 1); pending = pending.slice(n + 1); line(record); } }, flush() { if (pending) { line(pending); pending = ''; } }, }; }