@wasm-fmt/clang-format
Version:
A wasm based clang-format
1,522 lines • 130 kB
JavaScript
#!/usr/bin/env node
var Module = typeof Module != 'undefined' ? Module : {};
var ENVIRONMENT_IS_WORKER = false;
var ENVIRONMENT_IS_NODE = true;
if (ENVIRONMENT_IS_NODE) {
}
var moduleOverrides = Object.assign({}, Module);
var arguments_ = [];
var thisProgram = './this.program';
var quit_ = (status, toThrow) => {
throw toThrow
};
var scriptDirectory = '';
function locateFile(path) {
if (Module['locateFile']) {
return Module['locateFile'](path, scriptDirectory)
}
return scriptDirectory + path
}
var readAsync, readBinary;
if (ENVIRONMENT_IS_NODE) {
var fs = require('fs');
var nodePath = require('path');
scriptDirectory = __dirname + '/';
readBinary = filename => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
var ret = fs.readFileSync(filename);
return ret
};
readAsync = (filename, binary = true) => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
return new Promise((resolve, reject) => {fs.readFile(filename, binary ? undefined : 'utf8', (err, data) => {
if (err)
reject(err);
else
resolve(binary ? data.buffer : data)
})})
};
if (!Module['thisProgram'] && process.argv.length > 1) {
thisProgram = process.argv[1].replace(/\\/g, '/')
}
arguments_ = process.argv.slice(2);
if (typeof module != 'undefined') {
module['exports'] = Module
}
quit_ = (status, toThrow) => {
process.exitCode = status;
throw toThrow
}
} else {
}
var out = Module['print'] || console.log.bind(console);
var err = Module['printErr'] || console.error.bind(console);
Object.assign(Module, moduleOverrides);
moduleOverrides = null;
if (Module['arguments']) arguments_ = Module['arguments'];
if (Module['thisProgram']) thisProgram = Module['thisProgram'];
var wasmBinary = Module['wasmBinary'];
var wasmMemory;
var ABORT = false;
var EXITSTATUS;
var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
function updateMemoryViews() {
var b = wasmMemory.buffer;
Module['HEAP8'] = HEAP8 = new Int8Array(b);
Module['HEAP16'] = HEAP16 = new Int16Array(b);
Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
Module['HEAP32'] = HEAP32 = new Int32Array(b);
Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
Module['HEAPF64'] = HEAPF64 = new Float64Array(b)
}
var __ATPRERUN__ = [];
var __ATINIT__ = [];
var __ATMAIN__ = [];
var __ATPOSTRUN__ = [];
var runtimeInitialized = false;
function preRun() {
if (Module['preRun']) {
if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
while (Module['preRun'].length) {
addOnPreRun(Module['preRun'].shift())
}
}
callRuntimeCallbacks(__ATPRERUN__)
}
function initRuntime() {
runtimeInitialized = true;
if (!Module['noFSInit'] && !FS.initialized) FS.init();
FS.ignorePermissions = false;
TTY.init();
callRuntimeCallbacks(__ATINIT__)
}
function preMain() {
callRuntimeCallbacks(__ATMAIN__)
}
function postRun() {
if (Module['postRun']) {
if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
while (Module['postRun'].length) {
addOnPostRun(Module['postRun'].shift())
}
}
callRuntimeCallbacks(__ATPOSTRUN__)
}
function addOnPreRun(cb) {
__ATPRERUN__.unshift(cb)
}
function addOnInit(cb) {
__ATINIT__.unshift(cb)
}
function addOnPostRun(cb) {
__ATPOSTRUN__.unshift(cb)
}
var runDependencies = 0;
var runDependencyWatcher = null;
var dependenciesFulfilled = null;
function getUniqueRunDependency(id) {
return id
}
function addRunDependency(id) {
runDependencies++;
Module['monitorRunDependencies']?.(runDependencies)
}
function removeRunDependency(id) {
runDependencies--;
Module['monitorRunDependencies']?.(runDependencies);
if (runDependencies == 0) {
if (runDependencyWatcher !== null) {
clearInterval(runDependencyWatcher);
runDependencyWatcher = null
}
if (dependenciesFulfilled) {
var callback = dependenciesFulfilled;
dependenciesFulfilled = null;
callback()
}
}
}
function abort(what) {
Module['onAbort']?.(what);
what = 'Aborted(' + what + ')';
err(what);
ABORT = true;
what += '. Build with -sASSERTIONS for more info.';
var e = new WebAssembly.RuntimeError(what);
throw e
}
var dataURIPrefix = 'data:application/octet-stream;base64,';
var isDataURI = filename => filename.startsWith(dataURIPrefix);
var isFileURI = filename => filename.startsWith('file://');
function findWasmBinary() {
var f = 'clang-format-cli.wasm';
if (!isDataURI(f)) {
return locateFile(f)
}
return f
}
var wasmBinaryFile;
function getBinarySync(file) {
if (file == wasmBinaryFile && wasmBinary) {
return new Uint8Array(wasmBinary)
}
if (readBinary) {
return readBinary(file)
}
throw 'both async and sync fetching of the wasm failed'
}
function getBinaryPromise(binaryFile) {
if (!wasmBinary) {
return readAsync(binaryFile).then(response => new Uint8Array(response), () => getBinarySync(binaryFile))
}
return Promise.resolve().then(() => getBinarySync(binaryFile))
}
function instantiateArrayBuffer(binaryFile, imports, receiver) {
return getBinaryPromise(binaryFile)
.then(binary => WebAssembly.instantiate(binary, imports))
.then(receiver, reason => {
err(`failed to asynchronously prepare wasm: ${reason}`);
abort(reason)
})
}
function instantiateAsync(binary, binaryFile, imports, callback) {
if (!binary && typeof WebAssembly.instantiateStreaming == 'function' && !isDataURI(binaryFile) &&
!ENVIRONMENT_IS_NODE && typeof fetch == 'function') {
return fetch(binaryFile, {credentials: 'same-origin'}).then(response => {
var result = WebAssembly.instantiateStreaming(response, imports);
return result.then(callback, function(reason) {
err(`wasm streaming compile failed: ${reason}`);
err('falling back to ArrayBuffer instantiation');
return instantiateArrayBuffer(binaryFile, imports, callback)
})
})
}
return instantiateArrayBuffer(binaryFile, imports, callback)
}
function getWasmImports() {
return {
a: wasmImports
}
}
function createWasm() {
function receiveInstance(instance, module) {
wasmExports = instance.exports;
wasmMemory = wasmExports['Q'];
updateMemoryViews();
wasmTable = wasmExports['S'];
addOnInit(wasmExports['R']);
removeRunDependency('wasm-instantiate');
return wasmExports
}
addRunDependency('wasm-instantiate');
function receiveInstantiationResult(result) {
receiveInstance(result['instance'])
}
var info = getWasmImports();
if (Module['instantiateWasm']) {
try {
return Module['instantiateWasm'](info, receiveInstance)
} catch (e) {
err(`Module.instantiateWasm callback failed with error: ${e}`);
return false
}
}
wasmBinaryFile ??= findWasmBinary();
instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult);
return {
}
}
var tempDouble;
var tempI64;
class ExitStatus {
name = 'ExitStatus';
constructor(status) {
this.message = `Program terminated with exit(${status})`;
this.status = status
}
}
var callRuntimeCallbacks = callbacks => {
while (callbacks.length > 0) {
callbacks.shift()(Module)
}
};
var noExitRuntime = Module['noExitRuntime'] || true;
var wasmTable;
var getWasmTableEntry = funcPtr => wasmTable.get(funcPtr);
var ___call_sighandler = (fp, sig) => getWasmTableEntry(fp)(sig);
class ExceptionInfo {
constructor(excPtr) {
this.excPtr = excPtr;
this.ptr = excPtr - 24
}
set_type(type) {
HEAPU32[this.ptr + 4 >> 2] = type
}
get_type() {
return HEAPU32[this.ptr + 4 >> 2]
}
set_destructor(destructor) {
HEAPU32[this.ptr + 8 >> 2] = destructor
}
get_destructor() {
return HEAPU32[this.ptr + 8 >> 2]
}
set_caught(caught) {
caught = caught ? 1 : 0;
HEAP8[this.ptr + 12] = caught
}
get_caught() {
return HEAP8[this.ptr + 12] != 0
}
set_rethrown(rethrown) {
rethrown = rethrown ? 1 : 0;
HEAP8[this.ptr + 13] = rethrown
}
get_rethrown() {
return HEAP8[this.ptr + 13] != 0
}
init(type, destructor) {
this.set_adjusted_ptr(0);
this.set_type(type);
this.set_destructor(destructor)
}
set_adjusted_ptr(adjustedPtr) {
HEAPU32[this.ptr + 16 >> 2] = adjustedPtr
}
get_adjusted_ptr() {
return HEAPU32[this.ptr + 16 >> 2]
}
}
var exceptionLast = 0;
var uncaughtExceptionCount = 0;
var ___cxa_throw = (ptr, type, destructor) => {
var info = new ExceptionInfo(ptr);
info.init(type, destructor);
exceptionLast = ptr;
uncaughtExceptionCount++;
throw exceptionLast
};
var PATH = {
isAbs: path => nodePath['isAbsolute'](path),
normalize: path => nodePath['normalize'](path),
dirname: path => nodePath['dirname'](path),
basename: path => nodePath['basename'](path),
join: (...args) => nodePath['join'](...args),
join2: (l, r) => nodePath['join'](l, r)
};
var initRandomFill = () => {
if (typeof crypto == 'object' && typeof crypto['getRandomValues'] == 'function') {
return view => crypto.getRandomValues(view)
} else if (ENVIRONMENT_IS_NODE) {
try {
var crypto_module = require('crypto');
var randomFillSync = crypto_module['randomFillSync'];
if (randomFillSync) {
return view => crypto_module['randomFillSync'](view)
}
var randomBytes = crypto_module['randomBytes'];
return view => (view.set(randomBytes(view.byteLength)), view)
} catch (e) {
}
}
abort('initRandomDevice')
};
var randomFill = view => (randomFill = initRandomFill())(view);
var PATH_FS = {
resolve: (...paths) => {
paths.unshift(FS.cwd());
return nodePath['posix']['resolve'](...paths)
},
relative: (from, to) => nodePath['posix']['relative'](from || FS.cwd(), to || FS.cwd())
};
var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder : undefined;
var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
var endIdx = idx + maxBytesToRead;
var endPtr = idx;
while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr))
}
var str = '';
while (idx < endPtr) {
var u0 = heapOrArray[idx++];
if (!(u0 & 128)) {
str += String.fromCharCode(u0);
continue
}
var u1 = heapOrArray[idx++] & 63;
if ((u0 & 224) == 192) {
str += String.fromCharCode((u0 & 31) << 6 | u1);
continue
}
var u2 = heapOrArray[idx++] & 63;
if ((u0 & 240) == 224) {
u0 = (u0 & 15) << 12 | u1 << 6 | u2
} else {
u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63
}
if (u0 < 65536) {
str += String.fromCharCode(u0)
} else {
var ch = u0 - 65536;
str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023)
}
}
return str
};
var FS_stdin_getChar_buffer = [];
var lengthBytesUTF8 = str => {
var len = 0;
for (var i = 0; i < str.length; ++i) {
var c = str.charCodeAt(i);
if (c <= 127) {
len++
} else if (c <= 2047) {
len += 2
} else if (c >= 55296 && c <= 57343) {
len += 4;
++i
} else {
len += 3
}
}
return len
};
var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
if (!(maxBytesToWrite > 0)) return 0;
var startIdx = outIdx;
var endIdx = outIdx + maxBytesToWrite - 1;
for (var i = 0; i < str.length; ++i) {
var u = str.charCodeAt(i);
if (u >= 55296 && u <= 57343) {
var u1 = str.charCodeAt(++i);
u = 65536 + ((u & 1023) << 10) | u1 & 1023
}
if (u <= 127) {
if (outIdx >= endIdx) break;
heap[outIdx++] = u
} else if (u <= 2047) {
if (outIdx + 1 >= endIdx) break;
heap[outIdx++] = 192 | u >> 6;
heap[outIdx++] = 128 | u & 63
} else if (u <= 65535) {
if (outIdx + 2 >= endIdx) break;
heap[outIdx++] = 224 | u >> 12;
heap[outIdx++] = 128 | u >> 6 & 63;
heap[outIdx++] = 128 | u & 63
} else {
if (outIdx + 3 >= endIdx) break;
heap[outIdx++] = 240 | u >> 18;
heap[outIdx++] = 128 | u >> 12 & 63;
heap[outIdx++] = 128 | u >> 6 & 63;
heap[outIdx++] = 128 | u & 63
}
}
heap[outIdx] = 0;
return outIdx - startIdx
};
function intArrayFromString(stringy, dontAddNull, length) {
var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
var u8array = new Array(len);
var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
if (dontAddNull) u8array.length = numBytesWritten;
return u8array
}
var FS_stdin_getChar = () => {
if (!FS_stdin_getChar_buffer.length) {
var result = null;
if (ENVIRONMENT_IS_NODE) {
var BUFSIZE = 256;
var buf = Buffer.alloc(BUFSIZE);
var bytesRead = 0;
var fd = process.stdin.fd;
try {
bytesRead = fs.readSync(fd, buf, 0, BUFSIZE)
} catch (e) {
if (e.toString().includes('EOF'))
bytesRead = 0;
else
throw e
}
if (bytesRead > 0) {
result = buf.slice(0, bytesRead).toString('utf-8')
}
} else {
}
if (!result) {
return null
}
FS_stdin_getChar_buffer = intArrayFromString(result, true)
}
return FS_stdin_getChar_buffer.shift()
};
var TTY = {
ttys: [],
init() {},
shutdown() {},
register(dev, ops) {
TTY.ttys[dev] = {input: [], output: [], ops};
FS.registerDevice(dev, TTY.stream_ops)
},
stream_ops: {
open(stream) {
var tty = TTY.ttys[stream.node.rdev];
if (!tty) {
throw new FS.ErrnoError(43)
}
stream.tty = tty;
stream.seekable = false
},
close(stream) {
stream.tty.ops.fsync(stream.tty)
},
fsync(stream) {
stream.tty.ops.fsync(stream.tty)
},
read(stream, buffer, offset, length, pos) {
if (!stream.tty || !stream.tty.ops.get_char) {
throw new FS.ErrnoError(60)
}
var bytesRead = 0;
for (var i = 0; i < length; i++) {
var result;
try {
result = stream.tty.ops.get_char(stream.tty)
} catch (e) {
throw new FS.ErrnoError(29)
}
if (result === undefined && bytesRead === 0) {
throw new FS.ErrnoError(6)
}
if (result === null || result === undefined) break;
bytesRead++;
buffer[offset + i] = result
}
if (bytesRead) {
stream.node.timestamp = Date.now()
}
return bytesRead
},
write(stream, buffer, offset, length, pos) {
if (!stream.tty || !stream.tty.ops.put_char) {
throw new FS.ErrnoError(60)
}
try {
for (var i = 0; i < length; i++) {
stream.tty.ops.put_char(stream.tty, buffer[offset + i])
}
} catch (e) {
throw new FS.ErrnoError(29)
}
if (length) {
stream.node.timestamp = Date.now()
}
return i
}
},
default_tty_ops: {
get_char(tty) {
return FS_stdin_getChar()
},
put_char(tty, val) {
if (val === null || val === 10) {
out(UTF8ArrayToString(tty.output));
tty.output = []
} else {
if (val != 0) tty.output.push(val)
}
},
fsync(tty) {
if (tty.output && tty.output.length > 0) {
out(UTF8ArrayToString(tty.output));
tty.output = []
}
},
ioctl_tcgets(tty) {
return {
c_iflag: 25856, c_oflag: 5, c_cflag: 191, c_lflag: 35387, c_cc: [
3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]
}
},
ioctl_tcsets(tty, optional_actions, data) {
return 0
},
ioctl_tiocgwinsz(tty) {
return [24, 80]
}
},
default_tty1_ops: {
put_char(tty, val) {
if (val === null || val === 10) {
err(UTF8ArrayToString(tty.output));
tty.output = []
} else {
if (val != 0) tty.output.push(val)
}
},
fsync(tty) {
if (tty.output && tty.output.length > 0) {
err(UTF8ArrayToString(tty.output));
tty.output = []
}
}
}
};
var zeroMemory = (address, size) => {
HEAPU8.fill(0, address, address + size)
};
var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;
var mmapAlloc = size => {
size = alignMemory(size, 65536);
var ptr = _emscripten_builtin_memalign(65536, size);
if (ptr) zeroMemory(ptr, size);
return ptr
};
var MEMFS = {
ops_table: null,
mount(mount) {
return MEMFS.createNode(null, '/', 16384 | 511, 0)
},
createNode(parent, name, mode, dev) {
if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
throw new FS.ErrnoError(63)
}
MEMFS.ops_table ||= {
dir: {
node: {
getattr: MEMFS.node_ops.getattr,
setattr: MEMFS.node_ops.setattr,
lookup: MEMFS.node_ops.lookup,
mknod: MEMFS.node_ops.mknod,
rename: MEMFS.node_ops.rename,
unlink: MEMFS.node_ops.unlink,
rmdir: MEMFS.node_ops.rmdir,
readdir: MEMFS.node_ops.readdir,
symlink: MEMFS.node_ops.symlink
},
stream: {llseek: MEMFS.stream_ops.llseek}
},
file: {
node: {getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr},
stream: {
llseek: MEMFS.stream_ops.llseek,
read: MEMFS.stream_ops.read,
write: MEMFS.stream_ops.write,
allocate: MEMFS.stream_ops.allocate,
mmap: MEMFS.stream_ops.mmap,
msync: MEMFS.stream_ops.msync
}
},
link: {
node: {
getattr: MEMFS.node_ops.getattr,
setattr: MEMFS.node_ops.setattr,
readlink: MEMFS.node_ops.readlink
},
stream: {}
},
chrdev:
{node: {getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr}, stream: FS.chrdev_stream_ops}
};
var node = FS.createNode(parent, name, mode, dev);
if (FS.isDir(node.mode)) {
node.node_ops = MEMFS.ops_table.dir.node;
node.stream_ops = MEMFS.ops_table.dir.stream;
node.contents = {}
} else if (FS.isFile(node.mode)) {
node.node_ops = MEMFS.ops_table.file.node;
node.stream_ops = MEMFS.ops_table.file.stream;
node.usedBytes = 0;
node.contents = null
} else if (FS.isLink(node.mode)) {
node.node_ops = MEMFS.ops_table.link.node;
node.stream_ops = MEMFS.ops_table.link.stream
} else if (FS.isChrdev(node.mode)) {
node.node_ops = MEMFS.ops_table.chrdev.node;
node.stream_ops = MEMFS.ops_table.chrdev.stream
}
node.timestamp = Date.now();
if (parent) {
parent.contents[name] = node;
parent.timestamp = node.timestamp
}
return node
},
getFileDataAsTypedArray(node) {
if (!node.contents) return new Uint8Array(0);
if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
return new Uint8Array(node.contents)
},
expandFileStorage(node, newCapacity) {
var prevCapacity = node.contents ? node.contents.length : 0;
if (prevCapacity >= newCapacity) return;
var CAPACITY_DOUBLING_MAX = 1024 * 1024;
newCapacity = Math.max(newCapacity, prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0);
if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
var oldContents = node.contents;
node.contents = new Uint8Array(newCapacity);
if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0)
},
resizeFileStorage(node, newSize) {
if (node.usedBytes == newSize) return;
if (newSize == 0) {
node.contents = null;
node.usedBytes = 0
} else {
var oldContents = node.contents;
node.contents = new Uint8Array(newSize);
if (oldContents) {
node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)))
}
node.usedBytes = newSize
}
},
node_ops: {
getattr(node) {
var attr = {};
attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
attr.ino = node.id;
attr.mode = node.mode;
attr.nlink = 1;
attr.uid = 0;
attr.gid = 0;
attr.rdev = node.rdev;
if (FS.isDir(node.mode)) {
attr.size = 4096
} else if (FS.isFile(node.mode)) {
attr.size = node.usedBytes
} else if (FS.isLink(node.mode)) {
attr.size = node.link.length
} else {
attr.size = 0
}
attr.atime = new Date(node.timestamp);
attr.mtime = new Date(node.timestamp);
attr.ctime = new Date(node.timestamp);
attr.blksize = 4096;
attr.blocks = Math.ceil(attr.size / attr.blksize);
return attr
},
setattr(node, attr) {
if (attr.mode !== undefined) {
node.mode = attr.mode
}
if (attr.timestamp !== undefined) {
node.timestamp = attr.timestamp
}
if (attr.size !== undefined) {
MEMFS.resizeFileStorage(node, attr.size)
}
},
lookup(parent, name) {
throw MEMFS.doesNotExistError
},
mknod(parent, name, mode, dev) {
return MEMFS.createNode(parent, name, mode, dev)
},
rename(old_node, new_dir, new_name) {
if (FS.isDir(old_node.mode)) {
var new_node;
try {
new_node = FS.lookupNode(new_dir, new_name)
} catch (e) {
}
if (new_node) {
for (var i in new_node.contents) {
throw new FS.ErrnoError(55)
}
}
}
delete old_node.parent.contents[old_node.name];
old_node.parent.timestamp = Date.now();
old_node.name = new_name;
new_dir.contents[new_name] = old_node;
new_dir.timestamp = old_node.parent.timestamp
},
unlink(parent, name) {
delete parent.contents[name];
parent.timestamp = Date.now()
},
rmdir(parent, name) {
var node = FS.lookupNode(parent, name);
for (var i in node.contents) {
throw new FS.ErrnoError(55)
}
delete parent.contents[name];
parent.timestamp = Date.now()
},
readdir(node) {
var entries = ['.', '..'];
for (var key of Object.keys(node.contents)) {
entries.push(key)
}
return entries
},
symlink(parent, newname, oldpath) {
var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
node.link = oldpath;
return node
},
readlink(node) {
if (!FS.isLink(node.mode)) {
throw new FS.ErrnoError(28)
}
return node.link
}
},
stream_ops: {
read(stream, buffer, offset, length, position) {
var contents = stream.node.contents;
if (position >= stream.node.usedBytes) return 0;
var size = Math.min(stream.node.usedBytes - position, length);
if (size > 8 && contents.subarray) {
buffer.set(contents.subarray(position, position + size), offset)
} else {
for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i]
}
return size
},
write(stream, buffer, offset, length, position, canOwn) {
if (buffer.buffer === HEAP8.buffer) {
canOwn = false
}
if (!length) return 0;
var node = stream.node;
node.timestamp = Date.now();
if (buffer.subarray && (!node.contents || node.contents.subarray)) {
if (canOwn) {
node.contents = buffer.subarray(offset, offset + length);
node.usedBytes = length;
return length
} else if (node.usedBytes === 0 && position === 0) {
node.contents = buffer.slice(offset, offset + length);
node.usedBytes = length;
return length
} else if (position + length <= node.usedBytes) {
node.contents.set(buffer.subarray(offset, offset + length), position);
return length
}
}
MEMFS.expandFileStorage(node, position + length);
if (node.contents.subarray && buffer.subarray) {
node.contents.set(buffer.subarray(offset, offset + length), position)
} else {
for (var i = 0; i < length; i++) {
node.contents[position + i] = buffer[offset + i]
}
}
node.usedBytes = Math.max(node.usedBytes, position + length);
return length
},
llseek(stream, offset, whence) {
var position = offset;
if (whence === 1) {
position += stream.position
} else if (whence === 2) {
if (FS.isFile(stream.node.mode)) {
position += stream.node.usedBytes
}
}
if (position < 0) {
throw new FS.ErrnoError(28)
}
return position
},
allocate(stream, offset, length) {
MEMFS.expandFileStorage(stream.node, offset + length);
stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length)
},
mmap(stream, length, position, prot, flags) {
if (!FS.isFile(stream.node.mode)) {
throw new FS.ErrnoError(43)
}
var ptr;
var allocated;
var contents = stream.node.contents;
if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
allocated = false;
ptr = contents.byteOffset
} else {
allocated = true;
ptr = mmapAlloc(length);
if (!ptr) {
throw new FS.ErrnoError(48)
}
if (contents) {
if (position > 0 || position + length < contents.length) {
if (contents.subarray) {
contents = contents.subarray(position, position + length)
} else {
contents = Array.prototype.slice.call(contents, position, position + length)
}
}
HEAP8.set(contents, ptr)
}
}
return {
ptr, allocated
}
},
msync(stream, buffer, offset, length, mmapFlags) {
MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
return 0
}
}
};
var asyncLoad = (url, onload, onerror, noRunDep) => {
var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : '';
readAsync(url).then(
arrayBuffer => {
onload(new Uint8Array(arrayBuffer));
if (dep) removeRunDependency(dep)
},
err => {
if (onerror) {
onerror()
} else {
throw `Loading data file "${url}" failed.`
}
});
if (dep) addRunDependency(dep)
};
var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn)
};
var preloadPlugins = Module['preloadPlugins'] || [];
var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
if (typeof Browser != 'undefined') Browser.init();
var handled = false;
preloadPlugins.forEach(plugin => {
if (handled) return;
if (plugin['canHandle'](fullname)) {
plugin['handle'](byteArray, fullname, finish, onerror);
handled = true
}
});
return handled
};
var FS_createPreloadedFile =
(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
var dep = getUniqueRunDependency(`cp ${fullname}`);
function processData(byteArray) {
function finish(byteArray) {
preFinish?.();
if (!dontCreateFile) {
FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn)
}
onload?.();
removeRunDependency(dep)
}
if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
onerror?.();
removeRunDependency(dep)
})) {
return
}
finish(byteArray)
}
addRunDependency(dep);
if (typeof url == 'string') {
asyncLoad(url, processData, onerror)
} else {
processData(url)
}
};
var FS_modeStringToFlags = str => {
var flagModes = {r: 0, 'r+': 2, w: 512 | 64 | 1, 'w+': 512 | 64 | 2, a: 1024 | 64 | 1, 'a+': 1024 | 64 | 2};
var flags = flagModes[str];
if (typeof flags == 'undefined') {
throw new Error(`Unknown file open mode: ${str}`)
}
return flags
};
var FS_getMode = (canRead, canWrite) => {
var mode = 0;
if (canRead) mode |= 292 | 73;
if (canWrite) mode |= 146;
return mode
};
var ERRNO_CODES = {
EPERM: 63,
ENOENT: 44,
ESRCH: 71,
EINTR: 27,
EIO: 29,
ENXIO: 60,
E2BIG: 1,
ENOEXEC: 45,
EBADF: 8,
ECHILD: 12,
EAGAIN: 6,
EWOULDBLOCK: 6,
ENOMEM: 48,
EACCES: 2,
EFAULT: 21,
ENOTBLK: 105,
EBUSY: 10,
EEXIST: 20,
EXDEV: 75,
ENODEV: 43,
ENOTDIR: 54,
EISDIR: 31,
EINVAL: 28,
ENFILE: 41,
EMFILE: 33,
ENOTTY: 59,
ETXTBSY: 74,
EFBIG: 22,
ENOSPC: 51,
ESPIPE: 70,
EROFS: 69,
EMLINK: 34,
EPIPE: 64,
EDOM: 18,
ERANGE: 68,
ENOMSG: 49,
EIDRM: 24,
ECHRNG: 106,
EL2NSYNC: 156,
EL3HLT: 107,
EL3RST: 108,
ELNRNG: 109,
EUNATCH: 110,
ENOCSI: 111,
EL2HLT: 112,
EDEADLK: 16,
ENOLCK: 46,
EBADE: 113,
EBADR: 114,
EXFULL: 115,
ENOANO: 104,
EBADRQC: 103,
EBADSLT: 102,
EDEADLOCK: 16,
EBFONT: 101,
ENOSTR: 100,
ENODATA: 116,
ETIME: 117,
ENOSR: 118,
ENONET: 119,
ENOPKG: 120,
EREMOTE: 121,
ENOLINK: 47,
EADV: 122,
ESRMNT: 123,
ECOMM: 124,
EPROTO: 65,
EMULTIHOP: 36,
EDOTDOT: 125,
EBADMSG: 9,
ENOTUNIQ: 126,
EBADFD: 127,
EREMCHG: 128,
ELIBACC: 129,
ELIBBAD: 130,
ELIBSCN: 131,
ELIBMAX: 132,
ELIBEXEC: 133,
ENOSYS: 52,
ENOTEMPTY: 55,
ENAMETOOLONG: 37,
ELOOP: 32,
EOPNOTSUPP: 138,
EPFNOSUPPORT: 139,
ECONNRESET: 15,
ENOBUFS: 42,
EAFNOSUPPORT: 5,
EPROTOTYPE: 67,
ENOTSOCK: 57,
ENOPROTOOPT: 50,
ESHUTDOWN: 140,
ECONNREFUSED: 14,
EADDRINUSE: 3,
ECONNABORTED: 13,
ENETUNREACH: 40,
ENETDOWN: 38,
ETIMEDOUT: 73,
EHOSTDOWN: 142,
EHOSTUNREACH: 23,
EINPROGRESS: 26,
EALREADY: 7,
EDESTADDRREQ: 17,
EMSGSIZE: 35,
EPROTONOSUPPORT: 66,
ESOCKTNOSUPPORT: 137,
EADDRNOTAVAIL: 4,
ENETRESET: 39,
EISCONN: 30,
ENOTCONN: 53,
ETOOMANYREFS: 141,
EUSERS: 136,
EDQUOT: 19,
ESTALE: 72,
ENOTSUP: 138,
ENOMEDIUM: 148,
EILSEQ: 25,
EOVERFLOW: 61,
ECANCELED: 11,
ENOTRECOVERABLE: 56,
EOWNERDEAD: 62,
ESTRPIPE: 135
};
var NODEFS = {
isWindows: false,
staticInit() {
NODEFS.isWindows = !!process.platform.match(/^win/);
var flags = process.binding('constants');
if (flags['fs']) {
flags = flags['fs']
}
NODEFS.flagsForNodeMap = {
1024: flags['O_APPEND'],
64: flags['O_CREAT'],
128: flags['O_EXCL'],
256: flags['O_NOCTTY'],
0: flags['O_RDONLY'],
2: flags['O_RDWR'],
4096: flags['O_SYNC'],
512: flags['O_TRUNC'],
1: flags['O_WRONLY'],
131072: flags['O_NOFOLLOW']
}
},
convertNodeCode(e) {
var code = e.code;
return ERRNO_CODES[code]
},
tryFSOperation(f) {
try {
return f()
} catch (e) {
if (!e.code) throw e;
if (e.code === 'UNKNOWN') throw new FS.ErrnoError(28);
throw new FS.ErrnoError(NODEFS.convertNodeCode(e))
}
},
mount(mount) {
return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0)
},
createNode(parent, name, mode, dev) {
if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
throw new FS.ErrnoError(28)
}
var node = FS.createNode(parent, name, mode);
node.node_ops = NODEFS.node_ops;
node.stream_ops = NODEFS.stream_ops;
return node
},
getMode(path) {
var stat;
return NODEFS.tryFSOperation(() => {
stat = fs.lstatSync(path);
if (NODEFS.isWindows) {
stat.mode |= (stat.mode & 292) >> 2
}
return stat.mode
})
},
realPath(node) {
var parts = [];
while (node.parent !== node) {
parts.push(node.name);
node = node.parent
}
parts.push(node.mount.opts.root);
parts.reverse();
return PATH.join(...parts)
},
flagsForNode(flags) {
flags &= ~2097152;
flags &= ~2048;
flags &= ~32768;
flags &= ~524288;
flags &= ~65536;
var newFlags = 0;
for (var k in NODEFS.flagsForNodeMap) {
if (flags & k) {
newFlags |= NODEFS.flagsForNodeMap[k];
flags ^= k
}
}
if (flags) {
throw new FS.ErrnoError(28)
}
return newFlags
},
node_ops: {
getattr(node) {
var path = NODEFS.realPath(node);
var stat;
NODEFS.tryFSOperation(() => stat = fs.lstatSync(path));
if (NODEFS.isWindows) {
if (!stat.blksize) {
stat.blksize = 4096
}
if (!stat.blocks) {
stat.blocks = (stat.size + stat.blksize - 1) / stat.blksize | 0
}
stat.mode |= (stat.mode & 292) >> 2
}
return {
dev: stat.dev, ino: stat.ino, mode: stat.mode, nlink: stat.nlink, uid: stat.uid, gid: stat.gid,
rdev: stat.rdev, size: stat.size, atime: stat.atime, mtime: stat.mtime, ctime: stat.ctime,
blksize: stat.blksize, blocks: stat.blocks
}
},
setattr(node, attr) {
var path = NODEFS.realPath(node);
NODEFS.tryFSOperation(() => {
if (attr.mode !== undefined) {
fs.chmodSync(path, attr.mode);
node.mode = attr.mode
}
if (attr.timestamp !== undefined) {
var date = new Date(attr.timestamp);
fs.utimesSync(path, date, date)
}
if (attr.size !== undefined) {
fs.truncateSync(path, attr.size)
}
})
},
lookup(parent, name) {
var path = PATH.join2(NODEFS.realPath(parent), name);
var mode = NODEFS.getMode(path);
return NODEFS.createNode(parent, name, mode)
},
mknod(parent, name, mode, dev) {
var node = NODEFS.createNode(parent, name, mode, dev);
var path = NODEFS.realPath(node);
NODEFS.tryFSOperation(() => {
if (FS.isDir(node.mode)) {
fs.mkdirSync(path, node.mode)
} else {
fs.writeFileSync(path, '', {mode: node.mode})
}
});
return node
},
rename(oldNode, newDir, newName) {
var oldPath = NODEFS.realPath(oldNode);
var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
NODEFS.tryFSOperation(() => fs.renameSync(oldPath, newPath));
oldNode.name = newName
},
unlink(parent, name) {
var path = PATH.join2(NODEFS.realPath(parent), name);
NODEFS.tryFSOperation(() => fs.unlinkSync(path))
},
rmdir(parent, name) {
var path = PATH.join2(NODEFS.realPath(parent), name);
NODEFS.tryFSOperation(() => fs.rmdirSync(path))
},
readdir(node) {
var path = NODEFS.realPath(node);
return NODEFS.tryFSOperation(() => fs.readdirSync(path))
},
symlink(parent, newName, oldPath) {
var newPath = PATH.join2(NODEFS.realPath(parent), newName);
NODEFS.tryFSOperation(() => fs.symlinkSync(oldPath, newPath))
},
readlink(node) {
var path = NODEFS.realPath(node);
return NODEFS.tryFSOperation(() => fs.readlinkSync(path))
}
},
stream_ops: {
open(stream) {
var path = NODEFS.realPath(stream.node);
NODEFS.tryFSOperation(() => {
if (FS.isFile(stream.node.mode)) {
stream.shared.refcount = 1;
stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags))
}
})
},
close(stream) {
NODEFS.tryFSOperation(() => {
if (FS.isFile(stream.node.mode) && stream.nfd && --stream.shared.refcount === 0) {
fs.closeSync(stream.nfd)
}
})
},
dup(stream) {
stream.shared.refcount++
},
read(stream, buffer, offset, length, position) {
if (length === 0) return 0;
return NODEFS.tryFSOperation(
() => fs.readSync(stream.nfd, new Int8Array(buffer.buffer, offset, length), 0, length, position))
},
write(stream, buffer, offset, length, position) {
return NODEFS.tryFSOperation(
() => fs.writeSync(stream.nfd, new Int8Array(buffer.buffer, offset, length), 0, length, position))
},
llseek(stream, offset, whence) {
var position = offset;
if (whence === 1) {
position += stream.position
} else if (whence === 2) {
if (FS.isFile(stream.node.mode)) {
NODEFS.tryFSOperation(() => {
var stat = fs.fstatSync(stream.nfd);
position += stat.size
})
}
}
if (position < 0) {
throw new FS.ErrnoError(28)
}
return position
},
mmap(stream, length, position, prot, flags) {
if (!FS.isFile(stream.node.mode)) {
throw new FS.ErrnoError(43)
}
var ptr = mmapAlloc(length);
NODEFS.stream_ops.read(stream, HEAP8, ptr, length, position);
return {
ptr, allocated: true
}
},
msync(stream, buffer, offset, length, mmapFlags) {
NODEFS.stream_ops.write(stream, buffer, 0, length, offset, false);
return 0
}
}
};
var NODERAWFS = {
lookup(parent, name) {
return FS.lookupPath(`${parent.path}/${name}`).node
},
lookupPath(path, opts = {}) {
if (opts.parent) {
path = nodePath.dirname(path)
}
var st = fs.lstatSync(path);
var mode = NODEFS.getMode(path);
return {
path, node: {id: st.ino, mode, node_ops: NODERAWFS, path}
}
},
createStandardStreams() {
FS.createStream({nfd: 0, position: 0, path: '', flags: 0, tty: true, seekable: false}, 0);
for (var i = 1; i < 3; i++) {
FS.createStream({nfd: i, position: 0, path: '', flags: 577, tty: true, seekable: false}, i)
}
},
cwd() {
return process.cwd()
},
chdir(...args) {
process.chdir(...args)
},
mknod(path, mode) {
if (FS.isDir(path)) {
fs.mkdirSync(path, mode)
} else {
fs.writeFileSync(path, '', {mode})
}
},
mkdir(...args) {
fs.mkdirSync(...args)
},
symlink(...args) {
fs.symlinkSync(...args)
},
rename(...args) {
fs.renameSync(...args)
},
rmdir(...args) {
fs.rmdirSync(...args)
},
readdir(...args) {
return ['.', '..'].concat(fs.readdirSync(...args))
},
unlink(...args) {
fs.unlinkSync(...args)
},
readlink(...args) {
return fs.readlinkSync(...args)
},
stat(...args) {
return fs.statSync(...args)
},
lstat(...args) {
return fs.lstatSync(...args)
},
chmod(...args) {
fs.chmodSync(...args)
},
fchmod(fd, mode) {
var stream = FS.getStreamChecked(fd);
fs.fchmodSync(stream.nfd, mode)
},
chown(...args) {
fs.chownSync(...args)
},
fchown(fd, owner, group) {
var stream = FS.getStreamChecked(fd);
fs.fchownSync(stream.nfd, owner, group)
},
truncate(...args) {
fs.truncateSync(...args)
},
ftruncate(fd, len) {
if (len < 0) {
throw new FS.ErrnoError(28)
}
var stream = FS.getStreamChecked(fd);
fs.ftruncateSync(stream.nfd, len)
},
utime(path, atime, mtime) {
if (atime == -1 || mtime == -1) {
var st = fs.statSync(path);
if (atime == -1) atime = st.atimeMs;
if (mtime == -1) mtime = st.mtimeMs
}
fs.utimesSync(path, atime / 1e3, mtime / 1e3)
},
open(path, flags, mode) {
if (typeof flags == 'string') {
flags = FS_modeStringToFlags(flags)
}
var pathTruncated = path.split('/').map(s => s.substr(0, 255)).join('/');
var nfd = fs.openSync(pathTruncated, NODEFS.flagsForNode(flags), mode);
var st = fs.fstatSync(nfd);
if (flags & 65536 && !st.isDirectory()) {
fs.closeSync(nfd);
throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR)
}
var newMode = NODEFS.getMode(pathTruncated);
var node = {id: st.ino, mode: newMode, node_ops: NODERAWFS, path};
return FS.createStream({nfd, position: 0, path, flags, node, seekable: true})
},
createStream(stream, fd) {
var rtn = VFS.createStream(stream, fd);
if (typeof rtn.shared.refcnt == 'undefined') {
rtn.shared.refcnt = 1
} else {
rtn.shared.refcnt++
}
return rtn
},
close(stream) {
VFS.closeStream(stream.fd);
if (!stream.stream_ops && --stream.shared.refcnt === 0) {
fs.closeSync(stream.nfd)
}
},
llseek(stream, offset, whence) {
if (stream.stream_ops) {
return VFS.llseek(stream, offset, whence)
}
var position = offset;
if (whence === 1) {
position += stream.position
} else if (whence === 2) {
position += fs.fstatSync(stream.nfd).size
} else if (whence !== 0) {
throw new FS.ErrnoError(28)
}
if (position < 0) {
throw new FS.ErrnoError(28)
}
stream.position = position;
return position
},
read(stream, buffer, offset, length, position) {
if (stream.stream_ops) {
return VFS.read(stream, buffer, offset, length, position)
}
var seeking = typeof position != 'undefined';
if (!seeking && stream.seekable) position = stream.position;
var bytesRead = fs.readSync(stream.nfd, new Int8Array(buffer.buffer, offset, length), 0, length, position);
if (!seeking) stream.position += bytesRead;
return bytesRead
},
write(stream, buffer, offset, length, position) {
if (stream.stream_ops) {
return VFS.write(stream, buffer, offset, length, position)
}
if (stream.flags & +'1024') {
FS.llseek(stream, 0, +'2')
}
var seeking = typeof position != 'undefined';
if (!seeking && stream.seekable) position = stream.position;
var bytesWritten = fs.writeSync(stream.nfd, new Int8Array(buffer.buffer, offset, length), 0, length, position);
if (!seeking) stream.position += bytesWritten;
return bytesWritten
},
allocate() {
throw new FS.ErrnoError(138)
},
mmap(stream, length, position, prot, flags) {
if (!length) {
throw new FS.ErrnoError(28)
}
if (stream.stream_ops) {
return VFS.mmap(stream, length, position, prot, flags)
}
var ptr = mmapAlloc(length);
FS.read(stream, HEAP8, ptr, length, position);
return {
ptr, allocated: true
}
},
msync(stream, buffer, offset, length, mmapFlags) {
if (stream.stream_ops) {
return VFS.msync(stream, buffer, offset, length, mmapFlags)
}
FS.write(stream, buffer, 0, length, offset);
return 0
},
ioctl() {
throw new FS.ErrnoError(59)
}
};
var FS = {
root: null,
mounts: [],
devices: {},
streams: [],
nextInode: 1,
nameTable: null,
currentPath: '/',
initialized: false,
ignorePermissions: true,
ErrnoError: class {
name = 'ErrnoError';
constructor(errno) {
this.errno = errno
}
},
filesystems: null,
syncFSRequests: 0,
readFiles: {},
FSStream: class {
shared = {};
get object() {
return this.node
}
set object(val) {
this.node = val
}
get isRead() {
return (this.flags & 2097155) !== 1
}
get isWrite() {
return (this.flags & 2097155) !== 0
}
get isAppend() {
return this.flags & 1024
}
get flags() {
return this.shared.flags
}
se