This repository has been archived by the owner on Jan 17, 2022. It is now read-only.
/
wasm_exec_wrapper.ts
91 lines (83 loc) · 2.35 KB
/
wasm_exec_wrapper.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @ignore
* @packageDocumentation
*/
import WasmHooks from './WasmHooks'
import WasmData, { IGoWasm } from '../types/Wasm'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const goWasm = require('./wasm_exec')
let GoInstance: IGoWasm | undefined
let isClosed = false
/**
* Loads the Go wasm instance.
*
* @returns A promise of the Go wasm instance.
* @internal
*/
export const goWasmInit = async (): Promise<IGoWasm> => {
if (!GoInstance) {
GoInstance = await goWasm.GoWasm.init()
}
return GoInstance as IGoWasm
}
/**
* Calls a function from the Go wasm.
*
* @param goHook The name of the function which should be called.
* @param args The arguments for the function call put into an array.
* @returns A promise of the Go wasms function call.
* @internal
*/
const goWasmExec = <T>(
goHook: WasmHooks,
args?: Array<string | number | boolean>
): Promise<T> =>
goWasmInit()
.then((wasm) => wasm.execWasmFn(goHook, args))
.catch((e) => {
// catches unresolved wasm calls despite calling goWasmClose
if (isClosed) {
process.exit(0)
}
throw e
})
// eslint-disable-next-line jsdoc/require-returns
/**
* Closes the Go wasm channel.
*
* @internal
*/
export const goWasmClose = async (): Promise<void> => {
isClosed = true
const wasm = GoInstance
if (wasm) wasm.close()
// closes Go channel
return goWasmExec<void>(WasmHooks.closeWasm)
}
/**
* A wrapper function to stringify an instance of [[WasmData]] or a dictionary.
*
* Reason: When shallow cloning OR deserializing a serialized instance of [[WasmData]],
* the `[[WasmData.toString]]` method does not exist anymore or it might be overwritten by [[Object.toString]].
*
* @param arg The argument which should be stringified.
* @returns A stringified version of the argument.
*/
export const wasmStringify = (
arg: Record<string, unknown> | WasmData | string
): string => {
// already stringified
if (typeof arg === 'string') {
return arg
}
// the instance we actually want
if (arg instanceof WasmData) {
return arg.toString()
}
return 'wasmData' in arg && typeof arg.wasmData === 'string'
? // due to deserialization of a serialized instance of WasmData is lost s.t. `toString()` does not exist
arg.wasmData
: // input was never an instance of WasmData
JSON.stringify(arg)
}
export default goWasmExec