-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
68 lines (56 loc) · 2.14 KB
/
index.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
import { readFile } from 'fs/promises';
import path from 'path';
import { readFileSync, writeFileSync } from 'fs';
const wasmModule = require('./funcfiftlib.js');
const copyToCString = (mod: any, str: string) => {
const len = mod.lengthBytesUTF8(str) + 1;
const ptr = mod._malloc(len);
mod.stringToUTF8(str, ptr, len);
return ptr;
};
const copyToCStringPtr = (mod: any, str: string, ptr: any) => {
const allocated = copyToCString(mod, str);
mod.setValue(ptr, allocated, '*');
return allocated;
};
const copyFromCString = (mod: any, ptr: any) => {
return mod.UTF8ToString(ptr);
};
async function main() {
const bin = await readFile('funcfiftlib.wasm');
const mod = await wasmModule({
wasmBinary: new Uint8Array(bin),
});
const callbackPtr = mod.addFunction((_kind: any, _data: any, contents: any, error: any) => {
const kind: string = copyFromCString(mod, _kind);
const data: string = copyFromCString(mod, _data);
switch (kind) {
case 'readfile':
try {
const fc = readFileSync(path.join(process.cwd(), data));
copyToCStringPtr(mod, JSON.stringify({ path: data, data: fc.toString('base64') }), contents);
} catch (e) {
copyToCStringPtr(mod, 'could not read file ' + data, error);
}
return;
case 'writefile':
const req = JSON.parse(data);
try {
writeFileSync(req.filename, Buffer.from(req.data, 'base64'));
copyToCStringPtr(mod, JSON.stringify({ ok: true }), contents);
} catch (e) {
copyToCStringPtr(mod, JSON.stringify({ ok: false, error: 'could not write file ' + req.filename }), contents);
}
return;
}
}, 'viiii');
const cfg = {
include_paths: ['/', '/lib'],
args: [],
};
const cfgPtr = copyToCString(mod, JSON.stringify(cfg));
const r = mod._run_fift_callback(cfgPtr, callbackPtr);
const resp = JSON.parse(copyFromCString(mod, r));
console.log(resp);
}
main();