-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (50 loc) · 1.4 KB
/
index.js
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
/**
* Artistic Style (AStyle) JavaScript Wrapper
*
* Copyright (C) 2019, 2020, Uri Shaked
*/
const libastyle = require('./dist/libastyle.js');
const AStyleMain = libastyle.cwrap('AStyleMain', 'string', [
'string',
'string',
'number',
'number'
]);
let mallocList = [];
const malloc = libastyle.addFunction((numBytes) => {
const result = libastyle._malloc(numBytes);
mallocList.push(result);
return result;
}, 'ii');
// This has to be a global function since emscripten doesn't support removeFunction()
// with WASM, and we have a limited number of entries in the callback table, so we
// can't create a new function for every function call
let activeOutputCallback = null;
const outputHandler = libastyle.addFunction((code, msg) => {
if (activeOutputCallback) {
activeOutputCallback(code, libastyle.UTF8ToString(msg));
}
}, 'vii');
let libReadyCallback;
const ready = new Promise((resolve) => {
libReadyCallback = resolve;
});
async function format(code, options = '', outputCallback) {
await ready;
activeOutputCallback = outputCallback;
try {
return AStyleMain(code, options, outputHandler, malloc);
} finally {
activeOutputCallback = null;
// Free all memory allocation by AStyle
for (const item of mallocList) {
libastyle._free(item);
}
mallocList = [];
}
}
module.exports = {
format,
ready
};
libastyle.onRuntimeInitialized = libReadyCallback;