| 1 |
// Read JSONL from stdin. |
| 2 |
export function readInput(handle) { |
| 3 |
const buffSize = 1024; |
| 4 |
let currentLine = []; |
| 5 |
const buffer = new Uint8Array(buffSize); |
| 6 |
|
| 7 |
// These are not implemented by QuickJS. |
| 8 |
console.warn = (value) => { |
| 9 |
console.log(value); |
| 10 |
}; |
| 11 |
|
| 12 |
console.error = (value) => { |
| 13 |
throw new Error(value); |
| 14 |
}; |
| 15 |
|
| 16 |
// Read all the available bytes |
| 17 |
while (true) { |
| 18 |
// Stdin file descriptor |
| 19 |
const fd = 0; |
| 20 |
let bytesRead = 0; |
| 21 |
try { |
| 22 |
bytesRead = Javy.IO.readSync(fd, buffer); |
| 23 |
} catch (e) { |
| 24 |
// IO.readSync fails with os error 29 when stdin closes. |
| 25 |
if (e.message.includes('os error 29')) { |
| 26 |
break; |
| 27 |
} |
| 28 |
throw new Error('Error reading from stdin'); |
| 29 |
} |
| 30 |
|
| 31 |
if (bytesRead < 0) { |
| 32 |
throw new Error('Error reading from stdin'); |
| 33 |
break; |
| 34 |
} |
| 35 |
|
| 36 |
if (bytesRead === 0) { |
| 37 |
break; |
| 38 |
} |
| 39 |
|
| 40 |
currentLine = [...currentLine, ...buffer.subarray(0, bytesRead)]; |
| 41 |
|
| 42 |
// Check for newline. If not, we need to read more data. |
| 43 |
if (!currentLine.includes(10)) { |
| 44 |
continue; |
| 45 |
} |
| 46 |
|
| 47 |
// Split array into chunks by newline. |
| 48 |
let i = 0; |
| 49 |
for (let j = 0; i < currentLine.length; i++) { |
| 50 |
if (currentLine[i] === 10) { |
| 51 |
const chunk = currentLine.splice(j, i + 1); |
| 52 |
const arr = new Uint8Array(chunk); |
| 53 |
let message; |
| 54 |
try { |
| 55 |
message = JSON.parse(new TextDecoder().decode(arr)); |
| 56 |
} catch (e) { |
| 57 |
throw new Error(`Error parsing JSON '${new TextDecoder().decode(arr)}' from stdin: ${e.message}`); |
| 58 |
} |
| 59 |
|
| 60 |
try { |
| 61 |
handle(message); |
| 62 |
} catch (e) { |
| 63 |
let header = message.header; |
| 64 |
header.err = e.message; |
| 65 |
writeOutput({ header: header }); |
| 66 |
} |
| 67 |
|
| 68 |
j = i + 1; |
| 69 |
} |
| 70 |
} |
| 71 |
// Remove processed data. |
| 72 |
currentLine = currentLine.slice(i); |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
// Write JSONL to stdout |
| 77 |
export function writeOutput(output) { |
| 78 |
const encodedOutput = new TextEncoder().encode(JSON.stringify(output) + '\n'); |
| 79 |
const buffer = new Uint8Array(encodedOutput); |
| 80 |
// Stdout file descriptor |
| 81 |
const fd = 1; |
| 82 |
Javy.IO.writeSync(fd, buffer); |
| 83 |
} |