summaryrefslogtreecommitdiff
path: root/os.ts
blob: 4952609f21b8a8d03d911a193173a6a90f45993d (plain)
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
import { main as pb } from "./msg.pb";
import { TextDecoder } from "text-encoding";

// TODO move this to types.ts
type TypedArray = Uint8Array | Float32Array | Int32Array;

export function exit(code = 0): void {
  sendMsgFromObject({
    kind: pb.Msg.MsgKind.EXIT,
    code
  });
}

export function sourceCodeFetch(
  filename: string
): { sourceCode: string; outputCode: string } {
  const res = sendMsgFromObject({
    kind: pb.Msg.MsgKind.SOURCE_CODE_FETCH,
    sourceCodeFetch: { filename }
  });
  const { sourceCode, outputCode } = res.sourceCodeFetchRes;
  return { sourceCode, outputCode };
}

export function sourceCodeCache(
  filename: string,
  sourceCode: string,
  outputCode: string
): void {
  const res = sendMsgFromObject({
    kind: pb.Msg.MsgKind.SOURCE_CODE_CACHE,
    sourceCodeCache: { filename, sourceCode, outputCode }
  });
  throwOnError(res);
}

export function readFileSync(filename: string): string {
  const res = sendMsgFromObject({
    kind: pb.Msg.MsgKind.READ_FILE_SYNC,
    path: filename
  });
  const decoder = new TextDecoder("utf8");
  return decoder.decode(res.data);
}

function typedArrayToArrayBuffer(ta: TypedArray): ArrayBuffer {
  const ab = ta.buffer.slice(ta.byteOffset, ta.byteOffset + ta.byteLength);
  return ab as ArrayBuffer;
}

function sendMsgFromObject(obj: pb.IMsg): null | pb.Msg {
  const msg = pb.Msg.fromObject(obj);
  const ui8 = pb.Msg.encode(msg).finish();
  const ab = typedArrayToArrayBuffer(ui8);
  const resBuf = V8Worker2.send(ab);
  if (resBuf != null && resBuf.byteLength > 0) {
    const res = pb.Msg.decode(new Uint8Array(resBuf));
    throwOnError(res);
    return res;
  } else {
    return null;
  }
}

function throwOnError(res: pb.Msg) {
  if (res != null && res.error != null && res.error.length > 0) {
    throw Error(res.error);
  }
}