UNPKG

@shutter-network/shutter-sdk

Version:

TypeScript SDK for interacting with the Shutter crypto library, providing encryption, decryption, and utilities.

1 lines 187 kB
{"version":3,"sources":["../src/crypto/blst/blst.js"],"sourcesContent":["// include: shell.js\n// The Module object: Our interface to the outside world. We import\n// and export values on it. There are various ways Module can be used:\n// 1. Not defined. We create it here\n// 2. A function parameter, function(moduleArg) => Promise<Module>\n// 3. pre-run appended it, var blst = {}; ..generated code..\n// 4. External script tag defines var blst.\n// We need to check if blst already exists (e.g. case 3 above).\n// Substitution will be replaced with actual code on later stage of the build,\n// this way Closure Compiler will not mangle it (e.g. case 4. above).\n// Note that if you want to run closure, and also to use blst\n// after the generated code, you will need to define var blst = {};\n// before the code. Then that object will be used in the code, and you\n// can continue to use blst afterwards as well.\nvar blst = typeof blst != 'undefined' ? blst : {};\n\n// Determine the runtime environment we are in. You can customize this by\n// setting the ENVIRONMENT setting at compile time (see settings.js).\n\n// Attempt to auto-detect the environment\nvar ENVIRONMENT_IS_WEB = typeof window == 'object';\nvar ENVIRONMENT_IS_WORKER = typeof importScripts == 'function';\n// N.b. Electron.js environment is simultaneously a NODE-environment, but\n// also a web environment.\nvar ENVIRONMENT_IS_NODE =\n typeof process == 'object' &&\n typeof process.versions == 'object' &&\n typeof process.versions.node == 'string';\nvar ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;\n\nif (blst['ENVIRONMENT']) {\n throw new Error(\n 'blst.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)',\n );\n}\n\nif (ENVIRONMENT_IS_NODE) {\n // `require()` is no-op in an ESM module, use `createRequire()` to construct\n // the require()` function. This is only necessary for multi-environment\n // builds, `-sENVIRONMENT=node` emits a static import declaration instead.\n // TODO: Swap all `require()`'s with `import()`'s?\n}\n\n// --pre-jses are emitted after the blst integration code, so that they can\n// refer to blst (if they choose; they can also define blst)\n\n// Sometimes an existing blst object exists with properties\n// meant to overwrite the default module functionality. Here\n// we collect those properties and reapply _after_ we configure\n// the current environment's defaults to avoid having to be so\n// defensive during initialization.\nvar moduleOverrides = Object.assign({}, blst);\n\nvar arguments_ = [];\nvar thisProgram = './this.program';\nvar quit_ = (status, toThrow) => {\n throw toThrow;\n};\n\n// `/` should be present at the end if `scriptDirectory` is not empty\nvar scriptDirectory = '';\nfunction locateFile(path) {\n if (blst['locateFile']) {\n return blst['locateFile'](path, scriptDirectory);\n }\n return scriptDirectory + path;\n}\n\n// Hooks that are implemented differently in different runtime environments.\nvar read_, readAsync, readBinary;\n\nif (ENVIRONMENT_IS_NODE) {\n if (typeof process == 'undefined' || !process.release || process.release.name !== 'node')\n throw new Error(\n '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?)',\n );\n\n var nodeVersion = process.versions.node;\n var numericVersion = nodeVersion.split('.').slice(0, 3);\n numericVersion =\n numericVersion[0] * 10000 + numericVersion[1] * 100 + numericVersion[2].split('-')[0] * 1;\n var minVersion = 160000;\n if (numericVersion < 160000) {\n throw new Error(\n 'This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')',\n );\n }\n\n // These modules will usually be used on Node.js. Load them eagerly to avoid\n // the complexity of lazy-loading.\n var fs = require('fs');\n var nodePath = require('path');\n\n scriptDirectory = __dirname + '/';\n\n // include: node_shell_read.js\n read_ = (filename, binary) => {\n // We need to re-wrap `file://` strings to URLs. Normalizing isn't\n // necessary in that case, the path should already be absolute.\n filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);\n return fs.readFileSync(filename, binary ? undefined : 'utf8');\n };\n\n readBinary = (filename) => {\n var ret = read_(filename, true);\n if (!ret.buffer) {\n ret = new Uint8Array(ret);\n }\n assert(ret.buffer);\n return ret;\n };\n\n readAsync = (filename, onload, onerror, binary = true) => {\n // See the comment in the `read_` function.\n filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);\n fs.readFile(filename, binary ? undefined : 'utf8', (err, data) => {\n if (err) onerror(err);\n else onload(binary ? data.buffer : data);\n });\n };\n // end include: node_shell_read.js\n if (!blst['thisProgram'] && process.argv.length > 1) {\n thisProgram = process.argv[1].replace(/\\\\/g, '/');\n }\n\n arguments_ = process.argv.slice(2);\n\n if (typeof module != 'undefined') {\n module['exports'] = blst;\n }\n\n process.on('uncaughtException', (ex) => {\n // suppress ExitStatus exceptions from showing an error\n if (ex !== 'unwind' && !(ex instanceof ExitStatus) && !(ex.context instanceof ExitStatus)) {\n throw ex;\n }\n });\n\n quit_ = (status, toThrow) => {\n process.exitCode = status;\n throw toThrow;\n };\n} else if (ENVIRONMENT_IS_SHELL) {\n if (\n (typeof process == 'object' && typeof require === 'function') ||\n typeof window == 'object' ||\n typeof importScripts == 'function'\n )\n throw new Error(\n '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?)',\n );\n}\n\n// Note that this includes Node.js workers when relevant (pthreads is enabled).\n// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and\n// ENVIRONMENT_IS_NODE.\nelse if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {\n if (ENVIRONMENT_IS_WORKER) {\n // Check worker, not web, since window could be polyfilled\n scriptDirectory = self.location.href;\n } else if (typeof document != 'undefined' && document.currentScript) {\n // web\n scriptDirectory = document.currentScript.src;\n }\n // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.\n // otherwise, slice off the final part of the url to find the script directory.\n // if scriptDirectory does not contain a slash, lastIndexOf will return -1,\n // and scriptDirectory will correctly be replaced with an empty string.\n // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),\n // they are removed because they could contain a slash.\n if (scriptDirectory.startsWith('blob:')) {\n scriptDirectory = '';\n } else {\n scriptDirectory = scriptDirectory.substr(\n 0,\n scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/') + 1,\n );\n }\n\n if (!(typeof window == 'object' || typeof importScripts == 'function'))\n throw new Error(\n '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?)',\n );\n\n {\n // include: web_or_worker_shell_read.js\n read_ = (url) => {\n var xhr = new XMLHttpRequest();\n xhr.open('GET', url, false);\n xhr.send(null);\n return xhr.responseText;\n };\n\n if (ENVIRONMENT_IS_WORKER) {\n readBinary = (url) => {\n var xhr = new XMLHttpRequest();\n xhr.open('GET', url, false);\n xhr.responseType = 'arraybuffer';\n xhr.send(null);\n return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));\n };\n }\n\n readAsync = (url, onload, onerror) => {\n // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.\n // See https://github.com/github/fetch/pull/92#issuecomment-140665932\n // Cordova or Electron apps are typically loaded from a file:// url.\n // So use XHR on webview if URL is a file URL.\n if (isFileURI(url)) {\n var xhr = new XMLHttpRequest();\n xhr.open('GET', url, true);\n xhr.responseType = 'arraybuffer';\n xhr.onload = () => {\n if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {\n // file URLs can return 0\n onload(xhr.response);\n return;\n }\n onerror();\n };\n xhr.onerror = onerror;\n xhr.send(null);\n return;\n }\n fetch(url, { credentials: 'same-origin' })\n .then((response) => {\n if (response.ok) {\n return response.arrayBuffer();\n }\n return Promise.reject(new Error(response.status + ' : ' + response.url));\n })\n .then(onload, onerror);\n };\n // end include: web_or_worker_shell_read.js\n }\n} else {\n throw new Error('environment detection error');\n}\n\nvar out = blst['print'] || console.log.bind(console);\nvar err = blst['printErr'] || console.error.bind(console);\n\n// Merge back in the overrides\nObject.assign(blst, moduleOverrides);\n// Free the object hierarchy contained in the overrides, this lets the GC\n// reclaim data used.\nmoduleOverrides = null;\ncheckIncomingModuleAPI();\n\n// Emit code to handle expected values on the blst object. This applies blst.x\n// to the proper local x. This has two benefits: first, we only emit it if it is\n// expected to arrive, and second, by using a local everywhere else that can be\n// minified.\n\nif (blst['arguments']) arguments_ = blst['arguments'];\nlegacyModuleProp('arguments', 'arguments_');\n\nif (blst['thisProgram']) thisProgram = blst['thisProgram'];\nlegacyModuleProp('thisProgram', 'thisProgram');\n\nif (blst['quit']) quit_ = blst['quit'];\nlegacyModuleProp('quit', 'quit_');\n\n// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message\n// Assertions on removed incoming blst JS APIs.\nassert(\n typeof blst['memoryInitializerPrefixURL'] == 'undefined',\n 'blst.memoryInitializerPrefixURL option was removed, use blst.locateFile instead',\n);\nassert(\n typeof blst['pthreadMainPrefixURL'] == 'undefined',\n 'blst.pthreadMainPrefixURL option was removed, use blst.locateFile instead',\n);\nassert(\n typeof blst['cdInitializerPrefixURL'] == 'undefined',\n 'blst.cdInitializerPrefixURL option was removed, use blst.locateFile instead',\n);\nassert(\n typeof blst['filePackagePrefixURL'] == 'undefined',\n 'blst.filePackagePrefixURL option was removed, use blst.locateFile instead',\n);\nassert(typeof blst['read'] == 'undefined', 'blst.read option was removed (modify read_ in JS)');\nassert(\n typeof blst['readAsync'] == 'undefined',\n 'blst.readAsync option was removed (modify readAsync in JS)',\n);\nassert(\n typeof blst['readBinary'] == 'undefined',\n 'blst.readBinary option was removed (modify readBinary in JS)',\n);\nassert(\n typeof blst['setWindowTitle'] == 'undefined',\n 'blst.setWindowTitle option was removed (modify emscripten_set_window_title in JS)',\n);\nassert(\n typeof blst['TOTAL_MEMORY'] == 'undefined',\n 'blst.TOTAL_MEMORY has been renamed blst.INITIAL_MEMORY',\n);\nlegacyModuleProp('asm', 'wasmExports');\nlegacyModuleProp('read', 'read_');\nlegacyModuleProp('readAsync', 'readAsync');\nlegacyModuleProp('readBinary', 'readBinary');\nlegacyModuleProp('setWindowTitle', 'setWindowTitle');\nvar IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';\nvar PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';\nvar WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';\nvar FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js';\nvar ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js';\nvar JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js';\nvar OPFS = 'OPFS is no longer included by default; build with -lopfs.js';\n\nvar NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';\n\nassert(\n !ENVIRONMENT_IS_SHELL,\n 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.',\n);\n\n// end include: shell.js\n\n// include: preamble.js\n// === Preamble library stuff ===\n\n// Documentation for the public APIs defined in this file must be updated in:\n// site/source/docs/api_reference/preamble.js.rst\n// A prebuilt local version of the documentation is available at:\n// site/build/text/docs/api_reference/preamble.js.txt\n// You can also build docs locally as HTML or other formats in site/\n// An online HTML version (which may be of a different version of Emscripten)\n// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html\n\nvar wasmBinary;\nif (blst['wasmBinary']) wasmBinary = blst['wasmBinary'];\nlegacyModuleProp('wasmBinary', 'wasmBinary');\n\nif (typeof WebAssembly != 'object') {\n err('no native wasm support detected');\n}\n\n// Wasm globals\n\nvar wasmMemory;\n\n//========================================\n// Runtime essentials\n//========================================\n\n// whether we are quitting the application. no code should run after this.\n// set in exit() and abort()\nvar ABORT = false;\n\n// set by exit() and abort(). Passed to 'onExit' handler.\n// NOTE: This is also used as the process return code code in shell environments\n// but only when noExitRuntime is false.\nvar EXITSTATUS;\n\n// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we\n// don't define it at all in release modes. This matches the behaviour of\n// MINIMAL_RUNTIME.\n// TODO(sbc): Make this the default even without STRICT enabled.\n/** @type {function(*, string=)} */\nfunction assert(condition, text) {\n if (!condition) {\n abort('Assertion failed' + (text ? ': ' + text : ''));\n }\n}\n\n// We used to include malloc/free by default in the past. Show a helpful error in\n// builds with assertions.\n\n// Memory management\n\nvar HEAP,\n /** @type {!Int8Array} */\n HEAP8,\n /** @type {!Uint8Array} */\n HEAPU8,\n /** @type {!Int16Array} */\n HEAP16,\n /** @type {!Uint16Array} */\n HEAPU16,\n /** @type {!Int32Array} */\n HEAP32,\n /** @type {!Uint32Array} */\n HEAPU32,\n /** @type {!Float32Array} */\n HEAPF32,\n /** @type {!Float64Array} */\n HEAPF64;\n\n// include: runtime_shared.js\nfunction updateMemoryViews() {\n var b = wasmMemory.buffer;\n blst['HEAP8'] = HEAP8 = new Int8Array(b);\n blst['HEAP16'] = HEAP16 = new Int16Array(b);\n blst['HEAPU8'] = HEAPU8 = new Uint8Array(b);\n blst['HEAPU16'] = HEAPU16 = new Uint16Array(b);\n blst['HEAP32'] = HEAP32 = new Int32Array(b);\n blst['HEAPU32'] = HEAPU32 = new Uint32Array(b);\n blst['HEAPF32'] = HEAPF32 = new Float32Array(b);\n blst['HEAPF64'] = HEAPF64 = new Float64Array(b);\n}\n// end include: runtime_shared.js\nassert(\n !blst['STACK_SIZE'],\n 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time',\n);\n\nassert(\n typeof Int32Array != 'undefined' &&\n typeof Float64Array !== 'undefined' &&\n Int32Array.prototype.subarray != undefined &&\n Int32Array.prototype.set != undefined,\n 'JS engine does not provide full typed array support',\n);\n\n// If memory is defined in wasm, the user can't provide it, or set INITIAL_MEMORY\nassert(\n !blst['wasmMemory'],\n 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally',\n);\nassert(\n !blst['INITIAL_MEMORY'],\n 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically',\n);\n\n// include: runtime_stack_check.js\n// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.\nfunction writeStackCookie() {\n var max = _emscripten_stack_get_end();\n assert((max & 3) == 0);\n // If the stack ends at address zero we write our cookies 4 bytes into the\n // stack. This prevents interference with SAFE_HEAP and ASAN which also\n // monitor writes to address zero.\n if (max == 0) {\n max += 4;\n }\n // The stack grow downwards towards _emscripten_stack_get_end.\n // We write cookies to the final two words in the stack and detect if they are\n // ever overwritten.\n HEAPU32[max >> 2] = 0x02135467;\n HEAPU32[(max + 4) >> 2] = 0x89bacdfe;\n // Also test the global address 0 for integrity.\n HEAPU32[0 >> 2] = 1668509029;\n}\n\nfunction checkStackCookie() {\n if (ABORT) return;\n var max = _emscripten_stack_get_end();\n // See writeStackCookie().\n if (max == 0) {\n max += 4;\n }\n var cookie1 = HEAPU32[max >> 2];\n var cookie2 = HEAPU32[(max + 4) >> 2];\n if (cookie1 != 0x02135467 || cookie2 != 0x89bacdfe) {\n abort(\n `Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`,\n );\n }\n // Also test the global address 0 for integrity.\n if (HEAPU32[0 >> 2] != 0x63736d65 /* 'emsc' */) {\n abort('Runtime error: The application has corrupted its heap memory area (address zero)!');\n }\n}\n// end include: runtime_stack_check.js\n// include: runtime_assertions.js\n// Endianness check\n(function () {\n var h16 = new Int16Array(1);\n var h8 = new Int8Array(h16.buffer);\n h16[0] = 0x6373;\n if (h8[0] !== 0x73 || h8[1] !== 0x63)\n throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)';\n})();\n\n// end include: runtime_assertions.js\nvar __ATPRERUN__ = []; // functions called before the runtime is initialized\nvar __ATINIT__ = []; // functions called during startup\nvar __ATEXIT__ = []; // functions called during shutdown\nvar __ATPOSTRUN__ = []; // functions called after the main() is called\n\nvar runtimeInitialized = false;\n\nfunction preRun() {\n if (blst['preRun']) {\n if (typeof blst['preRun'] == 'function') blst['preRun'] = [blst['preRun']];\n while (blst['preRun'].length) {\n addOnPreRun(blst['preRun'].shift());\n }\n }\n callRuntimeCallbacks(__ATPRERUN__);\n}\n\nfunction initRuntime() {\n assert(!runtimeInitialized);\n runtimeInitialized = true;\n\n checkStackCookie();\n\n callRuntimeCallbacks(__ATINIT__);\n}\n\nfunction postRun() {\n checkStackCookie();\n\n if (blst['postRun']) {\n if (typeof blst['postRun'] == 'function') blst['postRun'] = [blst['postRun']];\n while (blst['postRun'].length) {\n addOnPostRun(blst['postRun'].shift());\n }\n }\n\n callRuntimeCallbacks(__ATPOSTRUN__);\n}\n\nfunction addOnPreRun(cb) {\n __ATPRERUN__.unshift(cb);\n}\n\nfunction addOnInit(cb) {\n __ATINIT__.unshift(cb);\n}\n\nfunction addOnExit(cb) { }\n\nfunction addOnPostRun(cb) {\n __ATPOSTRUN__.unshift(cb);\n}\n\n// include: runtime_math.js\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc\n\nassert(\n Math.imul,\n 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill',\n);\nassert(\n Math.fround,\n 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill',\n);\nassert(\n Math.clz32,\n 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill',\n);\nassert(\n Math.trunc,\n 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill',\n);\n// end include: runtime_math.js\n// A counter of dependencies for calling run(). If we need to\n// do asynchronous work before running, increment this and\n// decrement it. Incrementing must happen in a place like\n// blst.preRun (used by emcc to add file preloading).\n// Note that you can add dependencies in preRun, even though\n// it happens right before run - run will be postponed until\n// the dependencies are met.\nvar runDependencies = 0;\nvar runDependencyWatcher = null;\nvar dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled\nvar runDependencyTracking = {};\n\nfunction getUniqueRunDependency(id) {\n var orig = id;\n while (1) {\n if (!runDependencyTracking[id]) return id;\n id = orig + Math.random();\n }\n}\n\nfunction addRunDependency(id) {\n runDependencies++;\n\n blst['monitorRunDependencies']?.(runDependencies);\n\n if (id) {\n assert(!runDependencyTracking[id]);\n runDependencyTracking[id] = 1;\n if (runDependencyWatcher === null && typeof setInterval != 'undefined') {\n // Check for missing dependencies every few seconds\n runDependencyWatcher = setInterval(() => {\n if (ABORT) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n return;\n }\n var shown = false;\n for (var dep in runDependencyTracking) {\n if (!shown) {\n shown = true;\n err('still waiting on run dependencies:');\n }\n err(`dependency: ${dep}`);\n }\n if (shown) {\n err('(end of list)');\n }\n }, 10000);\n }\n } else {\n err('warning: run dependency added without ID');\n }\n}\n\nfunction removeRunDependency(id) {\n runDependencies--;\n\n blst['monitorRunDependencies']?.(runDependencies);\n\n if (id) {\n assert(runDependencyTracking[id]);\n delete runDependencyTracking[id];\n } else {\n err('warning: run dependency removed without ID');\n }\n if (runDependencies == 0) {\n if (runDependencyWatcher !== null) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n }\n if (dependenciesFulfilled) {\n var callback = dependenciesFulfilled;\n dependenciesFulfilled = null;\n callback(); // can add another dependenciesFulfilled\n }\n }\n}\n\n/** @param {string|number=} what */\nfunction abort(what) {\n blst['onAbort']?.(what);\n\n what = 'Aborted(' + what + ')';\n // TODO(sbc): Should we remove printing and leave it up to whoever\n // catches the exception?\n err(what);\n\n ABORT = true;\n EXITSTATUS = 1;\n\n // Use a wasm runtime error, because a JS error might be seen as a foreign\n // exception, which means we'd run destructors on it. We need the error to\n // simply make the program stop.\n // FIXME This approach does not work in Wasm EH because it currently does not assume\n // all RuntimeErrors are from traps; it decides whether a RuntimeError is from\n // a trap or not based on a hidden field within the object. So at the moment\n // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that\n // allows this in the wasm spec.\n\n // Suppress closure compiler warning here. Closure compiler's builtin extern\n // definition for WebAssembly.RuntimeError claims it takes no arguments even\n // though it can.\n // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.\n /** @suppress {checkTypes} */\n var e = new WebAssembly.RuntimeError(what);\n\n // Throw the error whether or not MODULARIZE is set because abort is used\n // in code paths apart from instantiation where an exception is expected\n // to be thrown when abort is called.\n throw e;\n}\n\n// include: memoryprofiler.js\n// end include: memoryprofiler.js\n// show errors on likely calls to FS when it was not included\nvar FS = {\n error() {\n abort(\n 'Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM',\n );\n },\n init() {\n FS.error();\n },\n createDataFile() {\n FS.error();\n },\n createPreloadedFile() {\n FS.error();\n },\n createLazyFile() {\n FS.error();\n },\n open() {\n FS.error();\n },\n mkdev() {\n FS.error();\n },\n registerDevice() {\n FS.error();\n },\n analyzePath() {\n FS.error();\n },\n\n ErrnoError() {\n FS.error();\n },\n};\nblst['FS_createDataFile'] = FS.createDataFile;\nblst['FS_createPreloadedFile'] = FS.createPreloadedFile;\n\n// include: URIUtils.js\n// Prefix of data URIs emitted by SINGLE_FILE and related options.\nvar dataURIPrefix = 'data:application/octet-stream;base64,';\n\n/**\n * Indicates whether filename is a base64 data URI.\n * @noinline\n */\nvar isDataURI = (filename) => filename.startsWith(dataURIPrefix);\n\n/**\n * Indicates whether filename is delivered via file protocol (as opposed to http/https)\n * @noinline\n */\nvar isFileURI = (filename) => filename.startsWith('file://');\n// end include: URIUtils.js\nfunction createExportWrapper(name, nargs) {\n return (...args) => {\n assert(runtimeInitialized, `native function \\`${name}\\` called before runtime initialization`);\n var f = wasmExports[name];\n assert(f, `exported native function \\`${name}\\` not found`);\n // Only assert for too many arguments. Too few can be valid since the missing arguments will be zero filled.\n assert(\n args.length <= nargs,\n `native function \\`${name}\\` called with ${args.length} args but expects ${nargs}`,\n );\n return f(...args);\n };\n}\n\n// include: runtime_exceptions.js\n// Base Emscripten EH error class\nclass EmscriptenEH extends Error { }\n\nclass EmscriptenSjLj extends EmscriptenEH { }\n\nclass CppException extends EmscriptenEH {\n constructor(excPtr) {\n super(excPtr);\n this.excPtr = excPtr;\n const excInfo = getExceptionMessage(excPtr);\n this.name = excInfo[0];\n this.message = excInfo[1];\n }\n}\n// end include: runtime_exceptions.js\nfunction findWasmBinary() {\n var f = 'blst.wasm';\n if (!isDataURI(f)) {\n return locateFile(f);\n }\n return f;\n}\n\nvar wasmBinaryFile;\n\nfunction getBinarySync(file) {\n if (file == wasmBinaryFile && wasmBinary) {\n return new Uint8Array(wasmBinary);\n }\n if (readBinary) {\n return readBinary(file);\n }\n throw 'both async and sync fetching of the wasm failed';\n}\n\nfunction getBinaryPromise(binaryFile) {\n // If we don't have the binary yet, load it asynchronously using readAsync.\n if (!wasmBinary) {\n // Fetch the binary use readAsync\n return new Promise((resolve, reject) => {\n readAsync(\n binaryFile,\n (response) => resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))),\n (error) => {\n try {\n resolve(getBinarySync(binaryFile));\n } catch (e) {\n reject(e);\n }\n },\n );\n });\n }\n\n // Otherwise, getBinarySync should be able to get it synchronously\n return Promise.resolve().then(() => getBinarySync(binaryFile));\n}\n\nfunction instantiateArrayBuffer(binaryFile, imports, receiver) {\n return getBinaryPromise(binaryFile)\n .then((binary) => {\n return WebAssembly.instantiate(binary, imports);\n })\n .then(receiver, (reason) => {\n err(`failed to asynchronously prepare wasm: ${reason}`);\n\n // Warn on some common problems.\n if (isFileURI(wasmBinaryFile)) {\n err(\n `warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`,\n );\n }\n abort(reason);\n });\n}\n\nfunction instantiateAsync(binary, binaryFile, imports, callback) {\n if (\n !binary &&\n typeof WebAssembly.instantiateStreaming == 'function' &&\n !isDataURI(binaryFile) &&\n // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.\n !isFileURI(binaryFile) &&\n // Avoid instantiateStreaming() on Node.js environment for now, as while\n // Node.js v18.1.0 implements it, it does not have a full fetch()\n // implementation yet.\n //\n // Reference:\n // https://github.com/emscripten-core/emscripten/pull/16917\n !ENVIRONMENT_IS_NODE &&\n typeof fetch == 'function'\n ) {\n return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => {\n // Suppress closure warning here since the upstream definition for\n // instantiateStreaming only allows Promise<Repsponse> rather than\n // an actual Response.\n // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.\n /** @suppress {checkTypes} */\n var result = WebAssembly.instantiateStreaming(response, imports);\n\n return result.then(callback, function (reason) {\n // We expect the most common failure cause to be a bad MIME type for the binary,\n // in which case falling back to ArrayBuffer instantiation should work.\n err(`wasm streaming compile failed: ${reason}`);\n err('falling back to ArrayBuffer instantiation');\n return instantiateArrayBuffer(binaryFile, imports, callback);\n });\n });\n }\n return instantiateArrayBuffer(binaryFile, imports, callback);\n}\n\nfunction getWasmImports() {\n // prepare imports\n return {\n env: wasmImports,\n wasi_snapshot_preview1: wasmImports,\n };\n}\n\n// Create the wasm instance.\n// Receives the wasm imports, returns the exports.\nfunction createWasm() {\n var info = getWasmImports();\n // Load the wasm module and create an instance of using native support in the JS engine.\n // handle a generated wasm instance, receiving its exports and\n // performing other necessary setup\n /** @param {WebAssembly.blst=} module*/\n function receiveInstance(instance, module) {\n wasmExports = instance.exports;\n\n wasmMemory = wasmExports['memory'];\n\n assert(wasmMemory, 'memory not found in wasm exports');\n updateMemoryViews();\n\n wasmTable = wasmExports['__indirect_function_table'];\n\n assert(wasmTable, 'table not found in wasm exports');\n\n addOnInit(wasmExports['__wasm_call_ctors']);\n\n removeRunDependency('wasm-instantiate');\n return wasmExports;\n }\n // wait for the pthread pool (if any)\n addRunDependency('wasm-instantiate');\n\n // Prefer streaming instantiation if available.\n // Async compilation can be confusing when an error on the page overwrites blst\n // (for example, if the order of elements is wrong, and the one defining blst is\n // later), so we save blst and check it later.\n var trueModule = blst;\n function receiveInstantiationResult(result) {\n // 'result' is a ResultObject object which has both the module and instance.\n // receiveInstance() will swap in the exports (to blst.asm) so they can be called\n assert(\n blst === trueModule,\n 'the blst object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?',\n );\n trueModule = null;\n // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.\n // When the regression is fixed, can restore the above PTHREADS-enabled path.\n receiveInstance(result['instance']);\n }\n\n // User shell pages can write their own blst.instantiateWasm = function(imports, successCallback) callback\n // to manually instantiate the Wasm module themselves. This allows pages to\n // run the instantiation parallel to any other async startup actions they are\n // performing.\n // Also pthreads and wasm workers initialize the wasm instance through this\n // path.\n if (blst['instantiateWasm']) {\n try {\n return blst['instantiateWasm'](info, receiveInstance);\n } catch (e) {\n err(`blst.instantiateWasm callback failed with error: ${e}`);\n return false;\n }\n }\n\n if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary();\n\n instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult);\n return {}; // no exports yet; we'll fill them in later\n}\n\n// Globals used by JS i64 conversions (see makeSetValue)\nvar tempDouble;\nvar tempI64;\n\n// include: runtime_debug.js\nfunction legacyModuleProp(prop, newName, incoming = true) {\n if (!Object.getOwnPropertyDescriptor(blst, prop)) {\n Object.defineProperty(blst, prop, {\n configurable: true,\n get() {\n let extra = incoming\n ? ' (the initial value can be provided on blst, but after startup the value is only looked for on a local variable of that name)'\n : '';\n abort(`\\`blst.${prop}\\` has been replaced by \\`${newName}\\`` + extra);\n },\n });\n }\n}\n\nfunction ignoredModuleProp(prop) {\n if (Object.getOwnPropertyDescriptor(blst, prop)) {\n abort(`\\`blst.${prop}\\` was supplied but \\`${prop}\\` not included in INCOMING_MODULE_JS_API`);\n }\n}\n\n// forcing the filesystem exports a few things by default\nfunction isExportedByForceFilesystem(name) {\n return (\n name === 'FS_createPath' ||\n name === 'FS_createDataFile' ||\n name === 'FS_createPreloadedFile' ||\n name === 'FS_unlink' ||\n name === 'addRunDependency' ||\n // The old FS has some functionality that WasmFS lacks.\n name === 'FS_createLazyFile' ||\n name === 'FS_createDevice' ||\n name === 'removeRunDependency'\n );\n}\n\nfunction missingGlobal(sym, msg) {\n if (typeof globalThis != 'undefined') {\n Object.defineProperty(globalThis, sym, {\n configurable: true,\n get() {\n warnOnce(`\\`${sym}\\` is not longer defined by emscripten. ${msg}`);\n return undefined;\n },\n });\n }\n}\n\nmissingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer');\nmissingGlobal('asm', 'Please use wasmExports instead');\n\nfunction missingLibrarySymbol(sym) {\n if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) {\n Object.defineProperty(globalThis, sym, {\n configurable: true,\n get() {\n // Can't `abort()` here because it would break code that does runtime\n // checks. e.g. `if (typeof SDL === 'undefined')`.\n var msg = `\\`${sym}\\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`;\n // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in\n // library.js, which means $name for a JS name with no prefix, or name\n // for a JS name like _name.\n var librarySymbol = sym;\n if (!librarySymbol.startsWith('_')) {\n librarySymbol = '$' + sym;\n }\n msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;\n if (isExportedByForceFilesystem(sym)) {\n msg +=\n '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';\n }\n warnOnce(msg);\n return undefined;\n },\n });\n }\n // Any symbol that is not included from the JS library is also (by definition)\n // not exported on the blst object.\n unexportedRuntimeSymbol(sym);\n}\n\nfunction unexportedRuntimeSymbol(sym) {\n if (!Object.getOwnPropertyDescriptor(blst, sym)) {\n Object.defineProperty(blst, sym, {\n configurable: true,\n get() {\n var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;\n if (isExportedByForceFilesystem(sym)) {\n msg +=\n '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';\n }\n abort(msg);\n },\n });\n }\n}\n\n// Used by XXXXX_DEBUG settings to output debug messages.\nfunction dbg(...args) {\n // TODO(sbc): Make this configurable somehow. Its not always convenient for\n // logging to show up as warnings.\n console.warn(...args);\n}\n// end include: runtime_debug.js\n// === Body ===\n\nfunction blst_exception(code) {\n throw new Error(BLST_ERROR_str[code]);\n}\n\n// end include: preamble.js\n\n/** @constructor */\nfunction ExitStatus(status) {\n this.name = 'ExitStatus';\n this.message = `Program terminated with exit(${status})`;\n this.status = status;\n}\n\nvar callRuntimeCallbacks = (callbacks) => {\n while (callbacks.length > 0) {\n // Pass the module as the first argument.\n callbacks.shift()(blst);\n }\n};\n\n/**\n * @param {number} ptr\n * @param {string} type\n */\nfunction getValue(ptr, type = 'i8') {\n if (type.endsWith('*')) type = '*';\n switch (type) {\n case 'i1':\n return HEAP8[ptr];\n case 'i8':\n return HEAP8[ptr];\n case 'i16':\n return HEAP16[ptr >> 1];\n case 'i32':\n return HEAP32[ptr >> 2];\n case 'i64':\n abort('to do getValue(i64) use WASM_BIGINT');\n case 'float':\n return HEAPF32[ptr >> 2];\n case 'double':\n return HEAPF64[ptr >> 3];\n case '*':\n return HEAPU32[ptr >> 2];\n default:\n abort(`invalid type for getValue: ${type}`);\n }\n}\n\nvar lengthBytesUTF8 = (str) => {\n var len = 0;\n for (var i = 0; i < str.length; ++i) {\n // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code\n // unit, not a Unicode code point of the character! So decode\n // UTF16->UTF32->UTF8.\n // See http://unicode.org/faq/utf_bom.html#utf16-3\n var c = str.charCodeAt(i); // possibly a lead surrogate\n if (c <= 0x7f) {\n len++;\n } else if (c <= 0x7ff) {\n len += 2;\n } else if (c >= 0xd800 && c <= 0xdfff) {\n len += 4;\n ++i;\n } else {\n len += 3;\n }\n }\n return len;\n};\n\nvar stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {\n assert(typeof str === 'string', `stringToUTF8Array expects a string (got ${typeof str})`);\n // Parameter maxBytesToWrite is not optional. Negative values, 0, null,\n // undefined and false each don't write out any bytes.\n if (!(maxBytesToWrite > 0)) return 0;\n\n var startIdx = outIdx;\n var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.\n for (var i = 0; i < str.length; ++i) {\n // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code\n // unit, not a Unicode code point of the character! So decode\n // UTF16->UTF32->UTF8.\n // See http://unicode.org/faq/utf_bom.html#utf16-3\n // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description\n // and https://www.ietf.org/rfc/rfc2279.txt\n // and https://tools.ietf.org/html/rfc3629\n var u = str.charCodeAt(i); // possibly a lead surrogate\n if (u >= 0xd800 && u <= 0xdfff) {\n var u1 = str.charCodeAt(++i);\n u = (0x10000 + ((u & 0x3ff) << 10)) | (u1 & 0x3ff);\n }\n if (u <= 0x7f) {\n if (outIdx >= endIdx) break;\n heap[outIdx++] = u;\n } else if (u <= 0x7ff) {\n if (outIdx + 1 >= endIdx) break;\n heap[outIdx++] = 0xc0 | (u >> 6);\n heap[outIdx++] = 0x80 | (u & 63);\n } else if (u <= 0xffff) {\n if (outIdx + 2 >= endIdx) break;\n heap[outIdx++] = 0xe0 | (u >> 12);\n heap[outIdx++] = 0x80 | ((u >> 6) & 63);\n heap[outIdx++] = 0x80 | (u & 63);\n } else {\n if (outIdx + 3 >= endIdx) break;\n if (u > 0x10ffff)\n warnOnce(\n 'Invalid Unicode code point ' +\n ptrToString(u) +\n ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).',\n );\n heap[outIdx++] = 0xf0 | (u >> 18);\n heap[outIdx++] = 0x80 | ((u >> 12) & 63);\n heap[outIdx++] = 0x80 | ((u >> 6) & 63);\n heap[outIdx++] = 0x80 | (u & 63);\n }\n }\n // Null-terminate the pointer to the buffer.\n heap[outIdx] = 0;\n return outIdx - startIdx;\n};\n/** @type {function(string, boolean=, number=)} */\nfunction intArrayFromString(stringy, dontAddNull, length) {\n var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;\n var u8array = new Array(len);\n var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);\n if (dontAddNull) u8array.length = numBytesWritten;\n return u8array;\n}\n\nvar noExitRuntime = blst['noExitRuntime'] || true;\n\nvar ptrToString = (ptr) => {\n assert(typeof ptr === 'number');\n // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.\n ptr >>>= 0;\n return '0x' + ptr.toString(16).padStart(8, '0');\n};\n\n/**\n * @param {number} ptr\n * @param {number} value\n * @param {string} type\n */\nfunction setValue(ptr, value, type = 'i8') {\n if (type.endsWith('*')) type = '*';\n switch (type) {\n case 'i1':\n HEAP8[ptr] = value;\n break;\n case 'i8':\n HEAP8[ptr] = value;\n break;\n case 'i16':\n HEAP16[ptr >> 1] = value;\n break;\n case 'i32':\n HEAP32[ptr >> 2] = value;\n break;\n case 'i64':\n abort('to do setValue(i64) use WASM_BIGINT');\n case 'float':\n HEAPF32[ptr >> 2] = value;\n break;\n case 'double':\n HEAPF64[ptr >> 3] = value;\n break;\n case '*':\n HEAPU32[ptr >> 2] = value;\n break;\n default:\n abort(`invalid type for setValue: ${type}`);\n }\n}\n\nvar stackRestore = (val) => __emscripten_stack_restore(val);\n\nvar stackSave = () => _emscripten_stack_get_current();\n\nvar warnOnce = (text) => {\n warnOnce.shown ||= {};\n if (!warnOnce.shown[text]) {\n warnOnce.shown[text] = 1;\n if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;\n err(text);\n }\n};\n\nvar UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;\n\n/**\n * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given\n * array that contains uint8 values, returns a copy of that string as a\n * Javascript String object.\n * heapOrArray is either a regular array, or a JavaScript typed array view.\n * @param {number} idx\n * @param {number=} maxBytesToRead\n * @return {string}\n */\nvar UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => {\n var endIdx = idx + maxBytesToRead;\n var endPtr = idx;\n // TextDecoder needs to know the byte length in advance, it doesn't stop on\n // null terminator by itself. Also, use the length info to avoid running tiny\n // strings through TextDecoder, since .subarray() allocates garbage.\n // (As a tiny code save trick, compare endPtr against endIdx using a negation,\n // so that undefined means Infinity)\n while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;\n\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n var str = '';\n // If building with TextDecoder, we have already computed the string length\n // above, so test loop end condition against that\n while (idx < endPtr) {\n // For UTF8 byte structure, see:\n // http://en.wikipedia.org/wiki/UTF-8#Description\n // https://www.ietf.org/rfc/rfc2279.txt\n // https://tools.ietf.org/html/rfc3629\n var u0 = heapOrArray[idx++];\n if (!(u0 & 0x80)) {\n str += String.fromCharCode(u0);\n continue;\n }\n var u1 = heapOrArray[idx++] & 63;\n if ((u0 & 0xe0) == 0xc0) {\n str += String.fromCharCode(((u0 & 31) << 6) | u1);\n continue;\n }\n var u2 = heapOrArray[idx++] & 63;\n if ((u0 & 0xf0) == 0xe0) {\n u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;\n } else {\n if ((u0 & 0xf8) != 0xf0)\n warnOnce(\n 'Invalid UTF-8 leading byte ' +\n ptrToString(u0) +\n ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!',\n );\n u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);\n }\n\n if (u0 < 0x10000) {\n str += String.fromCharCode(u0);\n } else {\n var ch = u0 - 0x10000;\n str += String.fromCharCode(0xd800 | (ch >> 10), 0xdc00 | (ch & 0x3ff));\n }\n }\n return str;\n};\n\n/**\n * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the\n * emscripten HEAP, returns a copy of that string as a Javascript String object.\n *\n * @param {number} ptr\n * @param {number=} maxBytesToRead - An optional length that specifies the\n * maximum number of bytes to read. You can omit this parameter to scan the\n * string until the first 0 byte. If maxBytesToRead is passed, and the string\n * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the\n * string will cut short at that byte index (i.e. maxBytesToRead will not\n * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing\n * frequent uses of UTF8ToString() with and without maxBytesToRead may throw\n * JS JIT optimizations off, so it is worth to consider consistently using one\n * @return {string}\n */\nvar UTF8ToString = (ptr, maxBytesToRead) => {\n assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`);\n return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';\n};\nvar ___assert_fail = (condition, filename, line, func) => {\n abort(\n `Assertion failed: ${UTF8ToString(condition)}, at: ` +\n [\n filename ? UTF8ToString(filename) : 'unknown filename',\n line,\n func ? UTF8ToString(func) : 'unknown function',\n ],\n );\n};\n\nvar exceptionCaught = [];\n\nvar uncaughtExceptionCount = 0;\nvar ___cxa_begin_catch = (ptr) => {\n var info = new ExceptionInfo(ptr);\n if (!info.get_caught()) {\n info.set_caught(true);\n uncaughtExceptionCount--;\n }\n info.set_rethrown(false);\n exceptionCaught.push(info);\n ___cxa_increment_exception_refcount(info.excPtr);\n return info.get_exception_ptr();\n};\n\nvar exceptionLast = 0;\n\nvar ___cxa_end_catch = () => {\n // Clear state flag.\n