-
Notifications
You must be signed in to change notification settings - Fork 245
/
in-out.ts
75 lines (59 loc) · 1.62 KB
/
in-out.ts
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
import { api } from '@jsii/kernel';
import { SyncStdio } from './sync-stdio';
export type Output =
| { hello: string }
| { ok: api.KernelResponse }
| { callback: api.Callback }
| { pending: true }
| { error: string; stack?: string };
export type Input =
| ({ api: string } & api.KernelRequest)
| { complete: api.CompleteRequest };
export type Exit = { exit: number };
/**
* An IO provider for jsii API exchanges.
*/
export interface IInputOutput {
/**
* Writes a message to the jsii API host.
* @param message the message to be sent.
*/
write(message: Output): void;
/**
* Wait for a message from the jsii API host, then return it.
*
* @returns the received message, or `undefined` if the API host has no more
* requests to send.
*/
read(): Input | Exit | undefined;
}
export class InputOutput implements IInputOutput {
public debug = false;
public constructor(private readonly stdio: SyncStdio) {}
public write(obj: Output) {
const output = JSON.stringify(obj);
this.stdio.writeLine(output);
if (this.debug) {
this.stdio.writeErrorLine(`< ${output}`);
}
}
public read(): Input | undefined {
let reqLine = this.stdio.readLine();
if (!reqLine) {
return undefined;
}
// skip recorded responses
if (reqLine.startsWith('< ')) {
return this.read();
}
// stip "> " from recorded requests
if (reqLine.startsWith('> ')) {
reqLine = reqLine.slice(2);
}
const input = JSON.parse(reqLine);
if (this.debug) {
this.stdio.writeErrorLine(`> ${JSON.stringify(input)}`);
}
return input;
}
}