summaryrefslogtreecommitdiffstats
path: root/internal/warpc/js/common.js
blob: 61c535fb7719e6c1b9276c6ca19ae9d45bfc2c2c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Read JSONL from stdin.
export function readInput(handle) {
	const buffSize = 1024;
	let currentLine = [];
	const buffer = new Uint8Array(buffSize);

	// These are not implemented by QuickJS.
	console.warn = (value) => {
		console.log(value);
	};

	console.error = (value) => {
		throw new Error(value);
	};

	// Read all the available bytes
	while (true) {
		// Stdin file descriptor
		const fd = 0;
		let bytesRead = 0;
		try {
			bytesRead = Javy.IO.readSync(fd, buffer);
		} catch (e) {
			// IO.readSync fails with os error 29 when stdin closes.
			if (e.message.includes('os error 29')) {
				break;
			}
			throw new Error('Error reading from stdin');
		}

		if (bytesRead < 0) {
			throw new Error('Error reading from stdin');
			break;
		}

		if (bytesRead === 0) {
			break;
		}

		currentLine = [...currentLine, ...buffer.subarray(0, bytesRead)];

		// Check for newline. If not, we need to read more data.
		if (!currentLine.includes(10)) {
			continue;
		}

		// Split array into chunks by newline.
		let i = 0;
		for (let j = 0; i < currentLine.length; i++) {
			if (currentLine[i] === 10) {
				const chunk = currentLine.splice(j, i + 1);
				const arr = new Uint8Array(chunk);
				let message;
				try {
					message = JSON.parse(new TextDecoder().decode(arr));
				} catch (e) {
					throw new Error(`Error parsing JSON '${new TextDecoder().decode(arr)}' from stdin: ${e.message}`);
				}

				try {
					handle(message);
				} catch (e) {
					let header = message.header;
					header.err = e.message;
					writeOutput({ header: header });
				}

				j = i + 1;
			}
		}
		// Remove processed data.
		currentLine = currentLine.slice(i);
	}
}

// Write JSONL to stdout
export function writeOutput(output) {
	const encodedOutput = new TextEncoder().encode(JSON.stringify(output) + '\n');
	const buffer = new Uint8Array(encodedOutput);
	// Stdout file descriptor
	const fd = 1;
	Javy.IO.writeSync(fd, buffer);
}