yongbo-7z-wasm
Version:
7-Zip for JavaScript environments, compiled to WASM
1,321 lines (1,193 loc) • 308 kB
JavaScript
/* eslint-disable */
var SevenZip = (function () {
var _scriptDir = import.meta.url;
return function (SevenZip) {
SevenZip = SevenZip || {};
// The Module object: Our interface to the outside world. We import
// and export values on it. There are various ways Module can be used:
// 1. Not defined. We create it here
// 2. A function parameter, function(Module) { ..generated code.. }
// 3. pre-run appended it, var Module = {}; ..generated code..
// 4. External script tag defines var Module.
// We need to check if Module already exists (e.g. case 3 above).
// Substitution will be replaced with actual code on later stage of the build,
// this way Closure Compiler will not mangle it (e.g. case 4. above).
// Note that if you want to run closure, and also to use Module
// after the generated code, you will need to define var Module = {};
// before the code. Then that object will be used in the code, and you
// can continue to use Module afterwards as well.
var Module = typeof SevenZip !== 'undefined' ? SevenZip : {};
// Set up the promise that indicates the Module is initialized
var readyPromiseResolve, readyPromiseReject;
Module['ready'] = new Promise(function (resolve, reject) {
readyPromiseResolve = resolve;
readyPromiseReject = reject;
});
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_main')) {
Object.defineProperty(Module['ready'], '_main', {
configurable: true,
get: function () {
abort(
'You are getting _main on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_main', {
configurable: true,
set: function () {
abort(
'You are setting _main on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_emscripten_stack_get_end')) {
Object.defineProperty(Module['ready'], '_emscripten_stack_get_end', {
configurable: true,
get: function () {
abort(
'You are getting _emscripten_stack_get_end on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_emscripten_stack_get_end', {
configurable: true,
set: function () {
abort(
'You are setting _emscripten_stack_get_end on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_emscripten_stack_get_free')) {
Object.defineProperty(Module['ready'], '_emscripten_stack_get_free', {
configurable: true,
get: function () {
abort(
'You are getting _emscripten_stack_get_free on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_emscripten_stack_get_free', {
configurable: true,
set: function () {
abort(
'You are setting _emscripten_stack_get_free on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_emscripten_stack_init')) {
Object.defineProperty(Module['ready'], '_emscripten_stack_init', {
configurable: true,
get: function () {
abort(
'You are getting _emscripten_stack_init on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_emscripten_stack_init', {
configurable: true,
set: function () {
abort(
'You are setting _emscripten_stack_init on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_stackSave')) {
Object.defineProperty(Module['ready'], '_stackSave', {
configurable: true,
get: function () {
abort(
'You are getting _stackSave on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_stackSave', {
configurable: true,
set: function () {
abort(
'You are setting _stackSave on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_stackRestore')) {
Object.defineProperty(Module['ready'], '_stackRestore', {
configurable: true,
get: function () {
abort(
'You are getting _stackRestore on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_stackRestore', {
configurable: true,
set: function () {
abort(
'You are setting _stackRestore on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_stackAlloc')) {
Object.defineProperty(Module['ready'], '_stackAlloc', {
configurable: true,
get: function () {
abort(
'You are getting _stackAlloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_stackAlloc', {
configurable: true,
set: function () {
abort(
'You are setting _stackAlloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '___wasm_call_ctors')) {
Object.defineProperty(Module['ready'], '___wasm_call_ctors', {
configurable: true,
get: function () {
abort(
'You are getting ___wasm_call_ctors on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '___wasm_call_ctors', {
configurable: true,
set: function () {
abort(
'You are setting ___wasm_call_ctors on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_fflush')) {
Object.defineProperty(Module['ready'], '_fflush', {
configurable: true,
get: function () {
abort(
'You are getting _fflush on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_fflush', {
configurable: true,
set: function () {
abort(
'You are setting _fflush on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '___errno_location')) {
Object.defineProperty(Module['ready'], '___errno_location', {
configurable: true,
get: function () {
abort(
'You are getting ___errno_location on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '___errno_location', {
configurable: true,
set: function () {
abort(
'You are setting ___errno_location on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '_malloc')) {
Object.defineProperty(Module['ready'], '_malloc', {
configurable: true,
get: function () {
abort(
'You are getting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '_malloc', {
configurable: true,
set: function () {
abort(
'You are setting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '__get_tzname')) {
Object.defineProperty(Module['ready'], '__get_tzname', {
configurable: true,
get: function () {
abort(
'You are getting __get_tzname on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '__get_tzname', {
configurable: true,
set: function () {
abort(
'You are setting __get_tzname on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '__get_daylight')) {
Object.defineProperty(Module['ready'], '__get_daylight', {
configurable: true,
get: function () {
abort(
'You are getting __get_daylight on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '__get_daylight', {
configurable: true,
set: function () {
abort(
'You are setting __get_daylight on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], '__get_timezone')) {
Object.defineProperty(Module['ready'], '__get_timezone', {
configurable: true,
get: function () {
abort(
'You are getting __get_timezone on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], '__get_timezone', {
configurable: true,
set: function () {
abort(
'You are setting __get_timezone on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module['ready'], 'onRuntimeInitialized')) {
Object.defineProperty(Module['ready'], 'onRuntimeInitialized', {
configurable: true,
get: function () {
abort(
'You are getting onRuntimeInitialized on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
Object.defineProperty(Module['ready'], 'onRuntimeInitialized', {
configurable: true,
set: function () {
abort(
'You are setting onRuntimeInitialized on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js',
);
},
});
}
// --pre-jses are emitted after the Module integration code, so that they can
// refer to Module (if they choose; they can also define Module)
Module.noInitialRun = true;
// Sometimes an existing Module object exists with properties
// meant to overwrite the default module functionality. Here
// we collect those properties and reapply _after_ we configure
// the current environment's defaults to avoid having to be so
// defensive during initialization.
var moduleOverrides = {};
var key;
for (key in Module) {
if (Module.hasOwnProperty(key)) {
moduleOverrides[key] = Module[key];
}
}
var arguments_ = [];
var thisProgram = './this.program';
var quit_ = function (status, toThrow) {
throw toThrow;
};
// Determine the runtime environment we are in. You can customize this by
// setting the ENVIRONMENT setting at compile time (see settings.js).
// Attempt to auto-detect the environment
var ENVIRONMENT_IS_WEB = typeof window === 'object';
var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
// N.b. Electron.js environment is simultaneously a NODE-environment, but
// also a web environment.
var ENVIRONMENT_IS_NODE =
typeof process === 'object' &&
typeof process.versions === 'object' &&
typeof process.versions.node === 'string';
var ENVIRONMENT_IS_SHELL =
!ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
if (Module['ENVIRONMENT']) {
throw new Error(
'Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)',
);
}
// `/` should be present at the end if `scriptDirectory` is not empty
var scriptDirectory = '';
function locateFile(path) {
if (Module['locateFile']) {
return Module['locateFile'](path, scriptDirectory);
}
return scriptDirectory + path;
}
// Hooks that are implemented differently in different runtime environments.
var read_, readAsync, readBinary, setWindowTitle;
var nodeFS;
var nodePath;
if (ENVIRONMENT_IS_NODE) {
if (!(typeof process === 'object' && typeof require === 'function'))
throw new Error(
'not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)',
);
if (ENVIRONMENT_IS_WORKER) {
scriptDirectory = require('path').dirname(scriptDirectory) + '/';
} else {
scriptDirectory = __dirname + '/';
}
// include: node_shell_read.js
read_ = function shell_read(filename, binary) {
if (!nodeFS) nodeFS = require('fs');
if (!nodePath) nodePath = require('path');
filename = nodePath['normalize'](filename);
return nodeFS['readFileSync'](filename, binary ? null : 'utf8');
};
readBinary = function readBinary(filename) {
var ret = read_(filename, true);
if (!ret.buffer) {
ret = new Uint8Array(ret);
}
assert(ret.buffer);
return ret;
};
readAsync = function readAsync(filename, onload, onerror) {
if (!nodeFS) nodeFS = require('fs');
if (!nodePath) nodePath = require('path');
filename = nodePath['normalize'](filename);
nodeFS['readFile'](filename, function (err, data) {
if (err) onerror(err);
else onload(data.buffer);
});
};
// end include: node_shell_read.js
if (process['argv'].length > 1) {
thisProgram = process['argv'][1].replace(/\\/g, '/');
}
arguments_ = process['argv'].slice(2);
// MODULARIZE will export the module in the proper place outside, we don't need to export here
process['on']('uncaughtException', function (ex) {
// suppress ExitStatus exceptions from showing an error
if (!(ex instanceof ExitStatus)) {
throw ex;
}
});
process['on']('unhandledRejection', abort);
quit_ = function (status, toThrow) {
if (keepRuntimeAlive()) {
process['exitCode'] = status;
throw toThrow;
}
process['exit'](status);
};
Module['inspect'] = function () {
return '[Emscripten Module object]';
};
} else if (ENVIRONMENT_IS_SHELL) {
if (
(typeof process === 'object' && typeof require === 'function') ||
typeof window === 'object' ||
typeof importScripts === 'function'
)
throw new Error(
'not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)',
);
if (typeof read != 'undefined') {
read_ = function shell_read(f) {
return read(f);
};
}
readBinary = function readBinary(f) {
var data;
if (typeof readbuffer === 'function') {
return new Uint8Array(readbuffer(f));
}
data = read(f, 'binary');
assert(typeof data === 'object');
return data;
};
readAsync = function readAsync(f, onload, onerror) {
setTimeout(function () {
onload(readBinary(f));
}, 0);
};
if (typeof scriptArgs != 'undefined') {
arguments_ = scriptArgs;
} else if (typeof arguments != 'undefined') {
arguments_ = arguments;
}
if (typeof quit === 'function') {
quit_ = function (status) {
quit(status);
};
}
if (typeof print !== 'undefined') {
// Prefer to use print/printErr where they exist, as they usually work better.
if (typeof console === 'undefined') console = /** @type{!Console} */ ({});
console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (
typeof printErr !== 'undefined' ? printErr : print
);
}
}
// Note that this includes Node.js workers when relevant (pthreads is enabled).
// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
// ENVIRONMENT_IS_NODE.
else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
if (ENVIRONMENT_IS_WORKER) {
// Check worker, not web, since window could be polyfilled
scriptDirectory = self.location.href;
} else if (typeof document !== 'undefined' && document.currentScript) {
// web
scriptDirectory = document.currentScript.src;
}
// When MODULARIZE, this JS may be executed later, after document.currentScript
// is gone, so we saved it, and we use it here instead of any other info.
if (_scriptDir) {
scriptDirectory = _scriptDir;
}
// blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
// otherwise, slice off the final part of the url to find the script directory.
// if scriptDirectory does not contain a slash, lastIndexOf will return -1,
// and scriptDirectory will correctly be replaced with an empty string.
if (scriptDirectory.indexOf('blob:') !== 0) {
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/') + 1);
} else {
scriptDirectory = '';
}
if (!(typeof window === 'object' || typeof importScripts === 'function'))
throw new Error(
'not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)',
);
// Differentiate the Web Worker from the Node Worker case, as reading must
// be done differently.
{
// include: web_or_worker_shell_read.js
read_ = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);
return xhr.responseText;
};
if (ENVIRONMENT_IS_WORKER) {
readBinary = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'arraybuffer';
xhr.send(null);
return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));
};
}
readAsync = function (url, onload, onerror) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {
// file URLs can return 0
onload(xhr.response);
return;
}
onerror();
};
xhr.onerror = onerror;
xhr.send(null);
};
// end include: web_or_worker_shell_read.js
}
setWindowTitle = function (title) {
document.title = title;
};
} else {
throw new Error('environment detection error');
}
// Set up the out() and err() hooks, which are how we can print to stdout or
// stderr, respectively.
var out = Module['print'] || console.log.bind(console);
var err = Module['printErr'] || console.warn.bind(console);
// Merge back in the overrides
for (key in moduleOverrides) {
if (moduleOverrides.hasOwnProperty(key)) {
Module[key] = moduleOverrides[key];
}
}
// Free the object hierarchy contained in the overrides, this lets the GC
// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
moduleOverrides = null;
// Emit code to handle expected values on the Module object. This applies Module.x
// to the proper local x. This has two benefits: first, we only emit it if it is
// expected to arrive, and second, by using a local everywhere else that can be
// minified.
if (Module['arguments']) arguments_ = Module['arguments'];
if (!Object.getOwnPropertyDescriptor(Module, 'arguments')) {
Object.defineProperty(Module, 'arguments', {
configurable: true,
get: function () {
abort(
'Module.arguments has been replaced with plain arguments_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (Module['thisProgram']) thisProgram = Module['thisProgram'];
if (!Object.getOwnPropertyDescriptor(Module, 'thisProgram')) {
Object.defineProperty(Module, 'thisProgram', {
configurable: true,
get: function () {
abort(
'Module.thisProgram has been replaced with plain thisProgram (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (Module['quit']) quit_ = Module['quit'];
if (!Object.getOwnPropertyDescriptor(Module, 'quit')) {
Object.defineProperty(Module, 'quit', {
configurable: true,
get: function () {
abort(
'Module.quit has been replaced with plain quit_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
// Assertions on removed incoming Module JS APIs.
assert(
typeof Module['memoryInitializerPrefixURL'] === 'undefined',
'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead',
);
assert(
typeof Module['pthreadMainPrefixURL'] === 'undefined',
'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead',
);
assert(
typeof Module['cdInitializerPrefixURL'] === 'undefined',
'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead',
);
assert(
typeof Module['filePackagePrefixURL'] === 'undefined',
'Module.filePackagePrefixURL option was removed, use Module.locateFile instead',
);
assert(
typeof Module['read'] === 'undefined',
'Module.read option was removed (modify read_ in JS)',
);
assert(
typeof Module['readAsync'] === 'undefined',
'Module.readAsync option was removed (modify readAsync in JS)',
);
assert(
typeof Module['readBinary'] === 'undefined',
'Module.readBinary option was removed (modify readBinary in JS)',
);
assert(
typeof Module['setWindowTitle'] === 'undefined',
'Module.setWindowTitle option was removed (modify setWindowTitle in JS)',
);
assert(
typeof Module['TOTAL_MEMORY'] === 'undefined',
'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY',
);
if (!Object.getOwnPropertyDescriptor(Module, 'read')) {
Object.defineProperty(Module, 'read', {
configurable: true,
get: function () {
abort(
'Module.read has been replaced with plain read_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module, 'readAsync')) {
Object.defineProperty(Module, 'readAsync', {
configurable: true,
get: function () {
abort(
'Module.readAsync has been replaced with plain readAsync (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module, 'readBinary')) {
Object.defineProperty(Module, 'readBinary', {
configurable: true,
get: function () {
abort(
'Module.readBinary has been replaced with plain readBinary (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (!Object.getOwnPropertyDescriptor(Module, 'setWindowTitle')) {
Object.defineProperty(Module, 'setWindowTitle', {
configurable: true,
get: function () {
abort(
'Module.setWindowTitle has been replaced with plain setWindowTitle (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
assert(
!ENVIRONMENT_IS_SHELL,
"shell environment detected but not enabled at build time. Add 'shell' to `-s ENVIRONMENT` to enable.",
);
var STACK_ALIGN = 16;
function getNativeTypeSize(type) {
switch (type) {
case 'i1':
case 'i8':
return 1;
case 'i16':
return 2;
case 'i32':
return 4;
case 'i64':
return 8;
case 'float':
return 4;
case 'double':
return 8;
default: {
if (type[type.length - 1] === '*') {
return 4; // A pointer
} else if (type[0] === 'i') {
var bits = Number(type.substr(1));
assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
return bits / 8;
} else {
return 0;
}
}
}
}
function warnOnce(text) {
if (!warnOnce.shown) warnOnce.shown = {};
if (!warnOnce.shown[text]) {
warnOnce.shown[text] = 1;
err(text);
}
}
// include: runtime_functions.js
// Wraps a JS function as a wasm function with a given signature.
function convertJsFunctionToWasm(func, sig) {
// If the type reflection proposal is available, use the new
// "WebAssembly.Function" constructor.
// Otherwise, construct a minimal wasm module importing the JS function and
// re-exporting it.
if (typeof WebAssembly.Function === 'function') {
var typeNames = {
i: 'i32',
j: 'i64',
f: 'f32',
d: 'f64',
};
var type = {
parameters: [],
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]],
};
for (var i = 1; i < sig.length; ++i) {
type.parameters.push(typeNames[sig[i]]);
}
return new WebAssembly.Function(type, func);
}
// The module is static, with the exception of the type section, which is
// generated based on the signature passed in.
var typeSection = [
0x01, // id: section,
0x00, // length: 0 (placeholder)
0x01, // count: 1
0x60, // form: func
];
var sigRet = sig.slice(0, 1);
var sigParam = sig.slice(1);
var typeCodes = {
i: 0x7f, // i32
j: 0x7e, // i64
f: 0x7d, // f32
d: 0x7c, // f64
};
// Parameters, length + signatures
typeSection.push(sigParam.length);
for (var i = 0; i < sigParam.length; ++i) {
typeSection.push(typeCodes[sigParam[i]]);
}
// Return values, length + signatures
// With no multi-return in MVP, either 0 (void) or 1 (anything else)
if (sigRet == 'v') {
typeSection.push(0x00);
} else {
typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
}
// Write the overall length of the type section back into the section header
// (excepting the 2 bytes for the section id and length)
typeSection[1] = typeSection.length - 2;
// Rest of the module is static
var bytes = new Uint8Array(
[
0x00,
0x61,
0x73,
0x6d, // magic ("\0asm")
0x01,
0x00,
0x00,
0x00, // version: 1
].concat(typeSection, [
0x02,
0x07, // import section
// (import "e" "f" (func 0 (type 0)))
0x01,
0x01,
0x65,
0x01,
0x66,
0x00,
0x00,
0x07,
0x05, // export section
// (export "f" (func 0 (type 0)))
0x01,
0x01,
0x66,
0x00,
0x00,
]),
);
// We can compile this wasm module synchronously because it is very small.
// This accepts an import (at "e.f"), that it reroutes to an export (at "f")
var module = new WebAssembly.Module(bytes);
var instance = new WebAssembly.Instance(module, {
e: {
f: func,
},
});
var wrappedFunc = instance.exports['f'];
return wrappedFunc;
}
var freeTableIndexes = [];
// Weak map of functions in the table to their indexes, created on first use.
var functionsInTableMap;
function getEmptyTableSlot() {
// Reuse a free index if there is one, otherwise grow.
if (freeTableIndexes.length) {
return freeTableIndexes.pop();
}
// Grow the table
try {
wasmTable.grow(1);
} catch (err) {
if (!(err instanceof RangeError)) {
throw err;
}
throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
}
return wasmTable.length - 1;
}
// Add a wasm function to the table.
function addFunctionWasm(func, sig) {
// Check if the function is already in the table, to ensure each function
// gets a unique index. First, create the map if this is the first use.
if (!functionsInTableMap) {
functionsInTableMap = new WeakMap();
for (var i = 0; i < wasmTable.length; i++) {
var item = wasmTable.get(i);
// Ignore null values.
if (item) {
functionsInTableMap.set(item, i);
}
}
}
if (functionsInTableMap.has(func)) {
return functionsInTableMap.get(func);
}
// It's not in the table, add it now.
var ret = getEmptyTableSlot();
// Set the new value.
try {
// Attempting to call this with JS function will cause of table.set() to fail
wasmTable.set(ret, func);
} catch (err) {
if (!(err instanceof TypeError)) {
throw err;
}
assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction: ' + func);
var wrapped = convertJsFunctionToWasm(func, sig);
wasmTable.set(ret, wrapped);
}
functionsInTableMap.set(func, ret);
return ret;
}
function removeFunction(index) {
functionsInTableMap.delete(wasmTable.get(index));
freeTableIndexes.push(index);
}
// 'sig' parameter is required for the llvm backend but only when func is not
// already a WebAssembly function.
function addFunction(func, sig) {
assert(typeof func !== 'undefined');
return addFunctionWasm(func, sig);
}
// end include: runtime_functions.js
// include: runtime_debug.js
// end include: runtime_debug.js
var tempRet0 = 0;
var setTempRet0 = function (value) {
tempRet0 = value;
};
var getTempRet0 = function () {
return tempRet0;
};
// === Preamble library stuff ===
// Documentation for the public APIs defined in this file must be updated in:
// site/source/docs/api_reference/preamble.js.rst
// A prebuilt local version of the documentation is available at:
// site/build/text/docs/api_reference/preamble.js.txt
// You can also build docs locally as HTML or other formats in site/
// An online HTML version (which may be of a different version of Emscripten)
// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
var wasmBinary;
if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
if (!Object.getOwnPropertyDescriptor(Module, 'wasmBinary')) {
Object.defineProperty(Module, 'wasmBinary', {
configurable: true,
get: function () {
abort(
'Module.wasmBinary has been replaced with plain wasmBinary (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
var noExitRuntime = Module['noExitRuntime'] || true;
if (!Object.getOwnPropertyDescriptor(Module, 'noExitRuntime')) {
Object.defineProperty(Module, 'noExitRuntime', {
configurable: true,
get: function () {
abort(
'Module.noExitRuntime has been replaced with plain noExitRuntime (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)',
);
},
});
}
if (typeof WebAssembly !== 'object') {
abort('no native wasm support detected');
}
// include: runtime_safe_heap.js
// In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
// In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
/** @param {number} ptr
@param {number} value
@param {string} type
@param {number|boolean=} noSafe */
function setValue(ptr, value, type, noSafe) {
type = type || 'i8';
if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
switch (type) {
case 'i1':
HEAP8[ptr >> 0] = value;
break;
case 'i8':
HEAP8[ptr >> 0] = value;
break;
case 'i16':
HEAP16[ptr >> 1] = value;
break;
case 'i32':
HEAP32[ptr >> 2] = value;
break;
case 'i64':
(tempI64 = [
value >>> 0,
((tempDouble = value),
+Math.abs(tempDouble) >= 1.0
? tempDouble > 0.0
? (Math.min(+Math.floor(tempDouble / 4294967296.0), 4294967295.0) | 0) >>> 0
: ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0) >>> 0
: 0),
]),
(HEAP32[ptr >> 2] = tempI64[0]),
(HEAP32[(ptr + 4) >> 2] = tempI64[1]);
break;
case 'float':
HEAPF32[ptr >> 2] = value;
break;
case 'double':
HEAPF64[ptr >> 3] = value;
break;
default:
abort('invalid type for setValue: ' + type);
}
}
/** @param {number} ptr
@param {string} type
@param {number|boolean=} noSafe */
function getValue(ptr, type, noSafe) {
type = type || 'i8';
if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
switch (type) {
case 'i1':
return HEAP8[ptr >> 0];
case 'i8':
return HEAP8[ptr >> 0];
case 'i16':
return HEAP16[ptr >> 1];
case 'i32':
return HEAP32[ptr >> 2];
case 'i64':
return HEAP32[ptr >> 2];
case 'float':
return HEAPF32[ptr >> 2];
case 'double':
return HEAPF64[ptr >> 3];
default:
abort('invalid type for getValue: ' + type);
}
return null;
}
// end include: runtime_safe_heap.js
// Wasm globals
var wasmMemory;
//========================================
// Runtime essentials
//========================================
// whether we are quitting the application. no code should run after this.
// set in exit() and abort()
var ABORT = false;
// set by exit() and abort(). Passed to 'onExit' handler.
// NOTE: This is also used as the process return code code in shell environments
// but only when noExitRuntime is false.
var EXITSTATUS;
/** @type {function(*, string=)} */
function assert(condition, text) {
if (!condition) {
abort('Assertion failed: ' + text);
}
}
// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
function getCFunc(ident) {
var func = Module['_' + ident]; // closure exported function
assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
return func;
}
// C calling interface.
/** @param {string|null=} returnType
@param {Array=} argTypes
@param {Arguments|Array=} args
@param {Object=} opts */
function ccall(ident, returnType, argTypes, args, opts) {
// For fast lookup of conversion functions
var toC = {
string: function (str) {
var ret = 0;
if (str !== null && str !== undefined && str !== 0) {
// null string
// at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
var len = (str.length << 2) + 1;
ret = stackAlloc(len);
stringToUTF8(str, ret, len);
}
return ret;
},
array: function (arr) {
var ret = stackAlloc(arr.length);
writeArrayToMemory(arr, ret);
return ret;
},
};
function convertReturnValue(ret) {
if (returnType === 'string') return UTF8ToString(ret);
if (returnType === 'boolean') return Boolean(ret);
return ret;
}
var func = getCFunc(ident);
var cArgs = [];
var stack = 0;
assert(returnType !== 'array', 'Return type should not be "array".');
if (args) {
for (var i = 0; i < args.length; i++) {
var converter = toC[argTypes[i]];
if (converter) {
if (stack === 0) stack = stackSave();
cArgs[i] = converter(args[i]);
} else {
cArgs[i] = args[i];
}
}
}
var ret = func.apply(null, cArgs);
function onDone(ret) {
if (stack !== 0) stackRestore(stack);
return convertReturnValue(ret);
}
ret = onDone(ret);
return ret;
}
/** @param {string=} returnType
@param {Array=} argTypes
@param {Object=} opts */
function cwrap(ident, returnType, argTypes, opts) {
return function () {
return ccall(ident, returnType, argTypes, arguments, opts);
};
}
// We used to include malloc/free by default in the past. Show a helpful error in
// builds with assertions.
function _free() {
// Show a helpful error since we used to include free by default in the past.
abort("free() called but not included in the build - add '_free' to EXPORTED_FUNCTIONS");
}
var ALLOC_NORMAL = 0; // Tries to use _malloc()
var ALLOC_STACK = 1; // Lives for the duration of the current function call
// allocate(): This is for internal use. You can use it yourself as well, but the interface
// is a little tricky (see docs right below). The reason is that it is optimized
// for multiple syntaxes to save space in generated code. So you should
// normally not use allocate(), and instead allocate memory using _malloc(),
// initialize it with setValue(), and so forth.
// @slab: An array of data.
// @allocator: How to allocate memory, see ALLOC_*
/** @type {function((Uint8Array|Array<number>), number)} */
function allocate(slab, allocator) {
var ret;
assert(typeof allocator === 'number', 'allocate no longer takes a type argument');
assert(typeof slab !== 'number', 'allocate no longer takes a number as arg0');
if (allocator == ALLOC_STACK) {
ret = stackAlloc(slab.length);
} else {
ret = _malloc(slab.length);
}
if (slab.subarray || slab.slice) {
HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
} else {
HEAPU8.set(new Uint8Array(slab), ret);
}
return ret;
}
// include: runtime_strings.js
// runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime.
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
// a copy of that string as a Javascript String object.
var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
/**
* @param {number} idx
* @param {number=} maxBytesToRead
* @return {string}
*/
function UTF8ArrayToString(heap, idx, maxBytesToRead) {
var endIdx = idx + maxBytesToRead;
var endPtr = idx;
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
// (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr;
if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) {
return UTF8Decoder.decode(heap.subarray(idx, endPtr));
} else {
var str = '';
// If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
while (idx < endPtr) {
// For UTF8 byte structure, see:
// http://en.wikipedia.org/wiki/UTF-8#Description
// https://www.ietf.org/rfc/rfc2279.txt
// https://tools.ietf.org/html/rfc3629
var u0 = heap[idx++];
if (!(u0 & 0x80)) {
str += String.fromCharCode(u0);
continue;
}
var u1 = heap[idx++] & 63;
if ((u0 & 0xe0) == 0xc0) {
str += String.fromCharCode(((u0 & 31) << 6) | u1);
continue;
}
var u2 = heap[idx++] & 63;
if ((u0 & 0xf0) == 0xe0) {
u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
} else {
if ((u0 & 0xf8) != 0xf0)
warnOnce(
'Invalid UTF-8 leading byte 0x' +
u0.toString(16) +
' encountered when deserializing a UTF-8 string in wasm memory to a JS string!',
);
u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63);
}
if (u0 < 0x10000) {
str += String.fromCharCode(u0);
} else {
var ch = u0 - 0x10000;
str += String.fromCharCode(0xd800 | (ch >> 10), 0xdc00 | (ch & 0x3ff));
}
}
}
return str;
}
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
// copy of that string as a Javascript String object.
// maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
// this parameter to scan the string until the first \0 byte. If maxBytesToRead is
// passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
// middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
// not produce a string of exact length [ptr, ptr+maxBytesToRead[)
// N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
// throw JS JIT optimizations off, so it is worth to consider consistently using one
// style or the other.
/**
* @param {number} ptr
* @param {number=} maxBytesToRead
* @return {string}
*/
function UTF8ToString(ptr, maxBytesToRead) {
return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
}
// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
// Parameters:
// str: the Javascript string to copy.
// heap: the array to copy to. Each index in this array is assumed to be one 8-byte element.
// outIdx: The starting offset in the array to begin the copying.
// maxBytesToWrite: The maximum number of bytes this function can write to the array.
// This count should include the null terminator,
// i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
// Returns the number of bytes written, EXCLUDING the null terminator.
function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
if (!(maxBytesToWrite > 0))
// Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
return 0;
var startIdx = outIdx;
var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
for (var i = 0; i < str.length; ++i) {
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
// See http://unicode.org/faq/utf_bom.html#utf16-3
// For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
var u = str.charCodeAt(i); // possibly a lead surrogate
if (u >= 0xd800 && u <= 0xdfff) {
var u1 = str.charCodeAt(++i);
u = (0x10000 + ((u & 0x3ff) << 10)) | (u1 & 0x3ff);
}
if (u <= 0x7f) {
if (outIdx >= endIdx) break;
heap[outIdx++] = u;
} else if (u <= 0x7ff) {
if (outIdx + 1 >=