Capycap-AI/CaptchaSolve-Demo
1
1// This code implements the `-sMODULARIZE` settings by taking the generated2// JS program code (INNER_JS_CODE) and wrapping it in a factory function.3 4// Single threaded MINIMAL_RUNTIME programs do not need access to5// document.currentScript, so a simple export declaration is enough.6var createGameModule = (() => {7 // When MODULARIZE this JS may be executed later,8 // after document.currentScript is gone, so we save it.9 // In EXPORT_ES6 mode we can just use 'import.meta.url'.10 var _scriptName = globalThis.document?.currentScript?.src;11 return async function(moduleArg = {}) {12 var moduleRtn;13 14// include: shell.js15// include: minimum_runtime_check.js16(function() {17 // "30.0.0" -> 30000018 function humanReadableVersionToPacked(str) {19 str = str.split('-')[0]; // Remove any trailing part from e.g. "12.53.3-alpha"20 var vers = str.split('.').slice(0, 3);21 while(vers.length < 3) vers.push('00');22 vers = vers.map((n, i, arr) => n.padStart(2, '0'));23 return vers.join('');24 }25 // 300000 -> "30.0.0"26 var packedVersionToHumanReadable = n => [n / 10000 | 0, (n / 100 | 0) % 100, n % 100].join('.');27 28 var TARGET_NOT_SUPPORTED = 2147483647;29 30 // Note: We use a typeof check here instead of optional chaining using31 // globalThis because older browsers might not have globalThis defined.32 var currentNodeVersion = typeof process !== 'undefined' && process.versions?.node ? humanReadableVersionToPacked(process.versions.node) : TARGET_NOT_SUPPORTED;33 if (currentNodeVersion < 160000) {34 throw new Error(`This emscripten-generated code requires node v${ packedVersionToHumanReadable(160000) } (detected v${packedVersionToHumanReadable(currentNodeVersion)})`);35 }36 37 var userAgent = typeof navigator !== 'undefined' && navigator.userAgent;38 if (!userAgent) {39 return;40 }41 42 var currentSafariVersion = userAgent.includes("Safari/") && userAgent.match(/Version\/(\d+\.?\d*\.?\d*)/) ? humanReadableVersionToPacked(userAgent.match(/Version\/(\d+\.?\d*\.?\d*)/)[1]) : TARGET_NOT_SUPPORTED;43 if (currentSafariVersion < 150000) {44 throw new Error(`This emscripten-generated code requires Safari v${ packedVersionToHumanReadable(150000) } (detected v${currentSafariVersion})`);45 }46 47 var currentFirefoxVersion = userAgent.match(/Firefox\/(\d+(?:\.\d+)?)/) ? parseFloat(userAgent.match(/Firefox\/(\d+(?:\.\d+)?)/)[1]) : TARGET_NOT_SUPPORTED;48 if (currentFirefoxVersion < 79) {49 throw new Error(`This emscripten-generated code requires Firefox v79 (detected v${currentFirefoxVersion})`);50 }51 52 var currentChromeVersion = userAgent.match(/Chrome\/(\d+(?:\.\d+)?)/) ? parseFloat(userAgent.match(/Chrome\/(\d+(?:\.\d+)?)/)[1]) : TARGET_NOT_SUPPORTED;53 if (currentChromeVersion < 85) {54 throw new Error(`This emscripten-generated code requires Chrome v85 (detected v${currentChromeVersion})`);55 }56})();57 58// end include: minimum_runtime_check.js59// The Module object: Our interface to the outside world. We import60// and export values on it. There are various ways Module can be used:61// 1. Not defined. We create it here62// 2. A function parameter, function(moduleArg) => Promise<Module>63// 3. pre-run appended it, var Module = {}; ..generated code..64// 4. External script tag defines var Module.65// We need to check if Module already exists (e.g. case 3 above).66// Substitution will be replaced with actual code on later stage of the build,67// this way Closure Compiler will not mangle it (e.g. case 4. above).68// Note that if you want to run closure, and also to use Module69// after the generated code, you will need to define var Module = {};70// before the code. Then that object will be used in the code, and you71// can continue to use Module afterwards as well.72var Module = moduleArg;73 74// Determine the runtime environment we are in. You can customize this by75// setting the ENVIRONMENT setting at compile time (see settings.js).76 77// Attempt to auto-detect the environment78var ENVIRONMENT_IS_WEB = !!globalThis.window;79var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;80// N.b. Electron.js environment is simultaneously a NODE-environment, but81// also a web environment.82var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != 'renderer';83var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;84 85// --pre-jses are emitted after the Module integration code, so that they can86// refer to Module (if they choose; they can also define Module)87 88 89var arguments_ = [];90var thisProgram = './this.program';91var quit_ = (status, toThrow) => {92 throw toThrow;93};94 95if (typeof __filename != 'undefined') { // Node96 _scriptName = __filename;97} else98if (ENVIRONMENT_IS_WORKER) {99 _scriptName = self.location.href;100}101 102// `/` should be present at the end if `scriptDirectory` is not empty103var scriptDirectory = '';104function locateFile(path) {105 if (Module['locateFile']) {106 return Module['locateFile'](path, scriptDirectory);107 }108 return scriptDirectory + path;109}110 111// Hooks that are implemented differently in different runtime environments.112var readAsync, readBinary;113 114if (ENVIRONMENT_IS_NODE) {115 const isNode = globalThis.process?.versions?.node && globalThis.process?.type != 'renderer';116 if (!isNode) 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?)');117 118 // These modules will usually be used on Node.js. Load them eagerly to avoid119 // the complexity of lazy-loading.120 var fs = require('fs');121 122 scriptDirectory = __dirname + '/';123 124// include: node_shell_read.js125readBinary = (filename) => {126 // We need to re-wrap `file://` strings to URLs.127 filename = isFileURI(filename) ? new URL(filename) : filename;128 var ret = fs.readFileSync(filename);129 assert(Buffer.isBuffer(ret));130 return ret;131};132 133readAsync = async (filename, binary = true) => {134 // See the comment in the `readBinary` function.135 filename = isFileURI(filename) ? new URL(filename) : filename;136 var ret = fs.readFileSync(filename, binary ? undefined : 'utf8');137 assert(binary ? Buffer.isBuffer(ret) : typeof ret == 'string');138 return ret;139};140// end include: node_shell_read.js141 if (process.argv.length > 1) {142 thisProgram = process.argv[1].replace(/\\/g, '/');143 }144 145 arguments_ = process.argv.slice(2);146 147 quit_ = (status, toThrow) => {148 process.exitCode = status;149 throw toThrow;150 };151 152} else153if (ENVIRONMENT_IS_SHELL) {154 155} else156 157// Note that this includes Node.js workers when relevant (pthreads is enabled).158// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and159// ENVIRONMENT_IS_NODE.160if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {161 try {162 scriptDirectory = new URL('.', _scriptName).href; // includes trailing slash163 } catch {164 // Must be a `blob:` or `data:` URL (e.g. `blob:http://site.com/etc/etc`), we cannot165 // infer anything from them.166 }167 168 if (!(globalThis.window || globalThis.WorkerGlobalScope)) 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?)');169 170 {171// include: web_or_worker_shell_read.js172if (ENVIRONMENT_IS_WORKER) {173 readBinary = (url) => {174 var xhr = new XMLHttpRequest();175 xhr.open('GET', url, false);176 xhr.responseType = 'arraybuffer';177 xhr.send(null);178 return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));179 };180 }181 182 readAsync = async (url) => {183 // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.184 // See https://github.com/github/fetch/pull/92#issuecomment-140665932185 // Cordova or Electron apps are typically loaded from a file:// url.186 // So use XHR on webview if URL is a file URL.187 if (isFileURI(url)) {188 return new Promise((resolve, reject) => {189 var xhr = new XMLHttpRequest();190 xhr.open('GET', url, true);191 xhr.responseType = 'arraybuffer';192 xhr.onload = () => {193 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0194 resolve(xhr.response);195 return;196 }197 reject(xhr.status);198 };199 xhr.onerror = reject;200 xhr.send(null);201 });202 }203 var response = await fetch(url, { credentials: 'same-origin' });204 if (response.ok) {205 return response.arrayBuffer();206 }207 throw new Error(response.status + ' : ' + response.url);208 };209// end include: web_or_worker_shell_read.js210 }211} else212{213 throw new Error('environment detection error');214}215 216var out = console.log.bind(console);217var err = console.error.bind(console);218 219var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';220var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';221var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';222var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js';223var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js';224var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js';225var OPFS = 'OPFS is no longer included by default; build with -lopfs.js';226 227var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';228 229// perform assertions in shell.js after we set up out() and err(), as otherwise230// if an assertion fails it cannot print the message231 232assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.');233 234// end include: shell.js235 236// include: preamble.js237// === Preamble library stuff ===238 239// Documentation for the public APIs defined in this file must be updated in:240// site/source/docs/api_reference/preamble.js.rst241// A prebuilt local version of the documentation is available at:242// site/build/text/docs/api_reference/preamble.js.txt243// You can also build docs locally as HTML or other formats in site/244// An online HTML version (which may be of a different version of Emscripten)245// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html246 247var wasmBinary;248 249if (!globalThis.WebAssembly) {250 err('no native wasm support detected');251}252 253// Wasm globals254 255//========================================256// Runtime essentials257//========================================258 259// whether we are quitting the application. no code should run after this.260// set in exit() and abort()261var ABORT = false;262 263// set by exit() and abort(). Passed to 'onExit' handler.264// NOTE: This is also used as the process return code code in shell environments265// but only when noExitRuntime is false.266var EXITSTATUS;267 268// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we269// don't define it at all in release modes. This matches the behaviour of270// MINIMAL_RUNTIME.271// TODO(sbc): Make this the default even without STRICT enabled.272/** @type {function(*, string=)} */273function assert(condition, text) {274 if (!condition) {275 abort('Assertion failed' + (text ? ': ' + text : ''));276 }277}278 279// We used to include malloc/free by default in the past. Show a helpful error in280// builds with assertions.281 282/**283 * Indicates whether filename is delivered via file protocol (as opposed to http/https)284 * @noinline285 */286var isFileURI = (filename) => filename.startsWith('file://');287 288// include: runtime_common.js289// include: runtime_stack_check.js290// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.291function writeStackCookie() {292 var max = _emscripten_stack_get_end();293 assert((max & 3) == 0);294 // If the stack ends at address zero we write our cookies 4 bytes into the295 // stack. This prevents interference with SAFE_HEAP and ASAN which also296 // monitor writes to address zero.297 if (max == 0) {298 max += 4;299 }300 // The stack grow downwards towards _emscripten_stack_get_end.301 // We write cookies to the final two words in the stack and detect if they are302 // ever overwritten.303 HEAPU32[((max)>>2)] = 0x02135467;304 HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE;305 // Also test the global address 0 for integrity.306 HEAPU32[((0)>>2)] = 1668509029;307}308 309function checkStackCookie() {310 if (ABORT) return;311 var max = _emscripten_stack_get_end();312 // See writeStackCookie().313 if (max == 0) {314 max += 4;315 }316 var cookie1 = HEAPU32[((max)>>2)];317 var cookie2 = HEAPU32[(((max)+(4))>>2)];318 if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {319 abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);320 }321 // Also test the global address 0 for integrity.322 if (HEAPU32[((0)>>2)] != 0x63736d65 /* 'emsc' */) {323 abort('Runtime error: The application has corrupted its heap memory area (address zero)!');324 }325}326// end include: runtime_stack_check.js327// include: runtime_exceptions.js328// end include: runtime_exceptions.js329// include: runtime_debug.js330var runtimeDebug = true; // Switch to false at runtime to disable logging at the right times331 332// Used by XXXXX_DEBUG settings to output debug messages.333function dbg(...args) {334 if (!runtimeDebug && typeof runtimeDebug != 'undefined') return;335 // TODO(sbc): Make this configurable somehow. Its not always convenient for336 // logging to show up as warnings.337 console.warn(...args);338}339 340// Endianness check341(() => {342 var h16 = new Int16Array(1);343 var h8 = new Int8Array(h16.buffer);344 h16[0] = 0x6373;345 if (h8[0] !== 0x73 || h8[1] !== 0x63) abort('Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)');346})();347 348function consumedModuleProp(prop) {349 if (!Object.getOwnPropertyDescriptor(Module, prop)) {350 Object.defineProperty(Module, prop, {351 configurable: true,352 set() {353 abort(`Attempt to set \`Module.${prop}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`);354 355 }356 });357 }358}359 360function makeInvalidEarlyAccess(name) {361 return () => assert(false, `call to '${name}' via reference taken before Wasm module initialization`);362 363}364 365function ignoredModuleProp(prop) {366 if (Object.getOwnPropertyDescriptor(Module, prop)) {367 abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`);368 }369}370 371// forcing the filesystem exports a few things by default372function isExportedByForceFilesystem(name) {373 return name === 'FS_createPath' ||374 name === 'FS_createDataFile' ||375 name === 'FS_createPreloadedFile' ||376 name === 'FS_preloadFile' ||377 name === 'FS_unlink' ||378 name === 'addRunDependency' ||379 // The old FS has some functionality that WasmFS lacks.380 name === 'FS_createLazyFile' ||381 name === 'FS_createDevice' ||382 name === 'removeRunDependency';383}384 385function missingLibrarySymbol(sym) {386 387 // Any symbol that is not included from the JS library is also (by definition)388 // not exported on the Module object.389 unexportedRuntimeSymbol(sym);390}391 392function unexportedRuntimeSymbol(sym) {393 if (!Object.getOwnPropertyDescriptor(Module, sym)) {394 Object.defineProperty(Module, sym, {395 configurable: true,396 get() {397 var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;398 if (isExportedByForceFilesystem(sym)) {399 msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';400 }401 abort(msg);402 },403 });404 }405}406 407// end include: runtime_debug.js408var readyPromiseResolve, readyPromiseReject;409 410// Memory management411var412/** @type {!Int8Array} */413 HEAP8,414/** @type {!Uint8Array} */415 HEAPU8,416/** @type {!Int16Array} */417 HEAP16,418/** @type {!Uint16Array} */419 HEAPU16,420/** @type {!Int32Array} */421 HEAP32,422/** @type {!Uint32Array} */423 HEAPU32,424/** @type {!Float32Array} */425 HEAPF32,426/** @type {!Float64Array} */427 HEAPF64;428 429// BigInt64Array type is not correctly defined in closure430var431/** not-@type {!BigInt64Array} */432 HEAP64,433/* BigUint64Array type is not correctly defined in closure434/** not-@type {!BigUint64Array} */435 HEAPU64;436 437var runtimeInitialized = false;438 439 440 441function updateMemoryViews() {442 var b = wasmMemory.buffer;443 HEAP8 = new Int8Array(b);444 HEAP16 = new Int16Array(b);445 Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);446 HEAPU16 = new Uint16Array(b);447 HEAP32 = new Int32Array(b);448 Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);449 Module['HEAPF32'] = HEAPF32 = new Float32Array(b);450 HEAPF64 = new Float64Array(b);451 HEAP64 = new BigInt64Array(b);452 HEAPU64 = new BigUint64Array(b);453}454 455// include: memoryprofiler.js456// end include: memoryprofiler.js457// end include: runtime_common.js458assert(globalThis.Int32Array && globalThis.Float64Array && Int32Array.prototype.subarray && Int32Array.prototype.set,459 'JS engine does not provide full typed array support');460 461function preRun() {462 if (Module['preRun']) {463 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];464 while (Module['preRun'].length) {465 addOnPreRun(Module['preRun'].shift());466 }467 }468 consumedModuleProp('preRun');469 // Begin ATPRERUNS hooks470 callRuntimeCallbacks(onPreRuns);471 // End ATPRERUNS hooks472}473 474function initRuntime() {475 assert(!runtimeInitialized);476 runtimeInitialized = true;477 478 checkStackCookie();479 480 // No ATINITS hooks481 482 wasmExports['__wasm_call_ctors']();483 484 // No ATPOSTCTORS hooks485}486 487function postRun() {488 checkStackCookie();489 // PThreads reuse the runtime from the main thread.490 491 if (Module['postRun']) {492 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];493 while (Module['postRun'].length) {494 addOnPostRun(Module['postRun'].shift());495 }496 }497 consumedModuleProp('postRun');498 499 // Begin ATPOSTRUNS hooks500 callRuntimeCallbacks(onPostRuns);501 // End ATPOSTRUNS hooks502}503 504/** @param {string|number=} what */505function abort(what) {506 Module['onAbort']?.(what);507 508 what = 'Aborted(' + what + ')';509 // TODO(sbc): Should we remove printing and leave it up to whoever510 // catches the exception?511 err(what);512 513 ABORT = true;514 515 // Use a wasm runtime error, because a JS error might be seen as a foreign516 // exception, which means we'd run destructors on it. We need the error to517 // simply make the program stop.518 // FIXME This approach does not work in Wasm EH because it currently does not assume519 // all RuntimeErrors are from traps; it decides whether a RuntimeError is from520 // a trap or not based on a hidden field within the object. So at the moment521 // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that522 // allows this in the wasm spec.523 524 // Suppress closure compiler warning here. Closure compiler's builtin extern525 // definition for WebAssembly.RuntimeError claims it takes no arguments even526 // though it can.527 // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.528 /** @suppress {checkTypes} */529 var e = new WebAssembly.RuntimeError(what);530 531 readyPromiseReject?.(e);532 // Throw the error whether or not MODULARIZE is set because abort is used533 // in code paths apart from instantiation where an exception is expected534 // to be thrown when abort is called.535 throw e;536}537 538// show errors on likely calls to FS when it was not included539var FS = {540 error() {541 abort('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');542 },543 init() { FS.error() },544 createDataFile() { FS.error() },545 createPreloadedFile() { FS.error() },546 createLazyFile() { FS.error() },547 open() { FS.error() },548 mkdev() { FS.error() },549 registerDevice() { FS.error() },550 analyzePath() { FS.error() },551 552 ErrnoError() { FS.error() },553};554 555 556function createExportWrapper(name, nargs) {557 return (...args) => {558 assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);559 var f = wasmExports[name];560 assert(f, `exported native function \`${name}\` not found`);561 // Only assert for too many arguments. Too few can be valid since the missing arguments will be zero filled.562 assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`);563 return f(...args);564 };565}566 567var wasmBinaryFile;568 569function findWasmBinary() {570 return locateFile('game.wasm');571}572 573function getBinarySync(file) {574 if (file == wasmBinaryFile && wasmBinary) {575 return new Uint8Array(wasmBinary);576 }577 if (readBinary) {578 return readBinary(file);579 }580 // Throwing a plain string here, even though it not normally adviables since581 // this gets turning into an `abort` in instantiateArrayBuffer.582 throw 'both async and sync fetching of the wasm failed';583}584 585async function getWasmBinary(binaryFile) {586 // If we don't have the binary yet, load it asynchronously using readAsync.587 if (!wasmBinary) {588 // Fetch the binary using readAsync589 try {590 var response = await readAsync(binaryFile);591 return new Uint8Array(response);592 } catch {593 // Fall back to getBinarySync below;594 }595 }596 597 // Otherwise, getBinarySync should be able to get it synchronously598 return getBinarySync(binaryFile);599}600 601async function instantiateArrayBuffer(binaryFile, imports) {602 try {603 var binary = await getWasmBinary(binaryFile);604 var instance = await WebAssembly.instantiate(binary, imports);605 return instance;606 } catch (reason) {607 err(`failed to asynchronously prepare wasm: ${reason}`);608 609 // Warn on some common problems.610 if (isFileURI(binaryFile)) {611 err(`warning: Loading from a file URI (${binaryFile}) 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`);612 }613 abort(reason);614 }615}616 617async function instantiateAsync(binary, binaryFile, imports) {618 if (!binary619 // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.620 && !isFileURI(binaryFile)621 // Avoid instantiateStreaming() on Node.js environment for now, as while622 // Node.js v18.1.0 implements it, it does not have a full fetch()623 // implementation yet.624 //625 // Reference:626 // https://github.com/emscripten-core/emscripten/pull/16917627 && !ENVIRONMENT_IS_NODE628 ) {629 try {630 var response = fetch(binaryFile, { credentials: 'same-origin' });631 var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);632 return instantiationResult;633 } catch (reason) {634 // We expect the most common failure cause to be a bad MIME type for the binary,635 // in which case falling back to ArrayBuffer instantiation should work.636 err(`wasm streaming compile failed: ${reason}`);637 err('falling back to ArrayBuffer instantiation');638 // fall back of instantiateArrayBuffer below639 };640 }641 return instantiateArrayBuffer(binaryFile, imports);642}643 644function getWasmImports() {645 // prepare imports646 var imports = {647 'env': wasmImports,648 'wasi_snapshot_preview1': wasmImports,649 };650 return imports;651}652 653// Create the wasm instance.654// Receives the wasm imports, returns the exports.655async function createWasm() {656 // Load the wasm module and create an instance of using native support in the JS engine.657 // handle a generated wasm instance, receiving its exports and658 // performing other necessary setup659 /** @param {WebAssembly.Module=} module*/660 function receiveInstance(instance, module) {661 wasmExports = instance.exports;662 663 assignWasmExports(wasmExports);664 665 updateMemoryViews();666 667 return wasmExports;668 }669 670 // Prefer streaming instantiation if available.671 // Async compilation can be confusing when an error on the page overwrites Module672 // (for example, if the order of elements is wrong, and the one defining Module is673 // later), so we save Module and check it later.674 var trueModule = Module;675 function receiveInstantiationResult(result) {676 // 'result' is a ResultObject object which has both the module and instance.677 // receiveInstance() will swap in the exports (to Module.asm) so they can be called678 assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');679 trueModule = null;680 // 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.681 // When the regression is fixed, can restore the above PTHREADS-enabled path.682 return receiveInstance(result['instance']);683 }684 685 var info = getWasmImports();686 687 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback688 // to manually instantiate the Wasm module themselves. This allows pages to689 // run the instantiation parallel to any other async startup actions they are690 // performing.691 // Also pthreads and wasm workers initialize the wasm instance through this692 // path.693 if (Module['instantiateWasm']) {694 return new Promise((resolve, reject) => {695 try {696 Module['instantiateWasm'](info, (inst, mod) => {697 resolve(receiveInstance(inst, mod));698 });699 } catch(e) {700 err(`Module.instantiateWasm callback failed with error: ${e}`);701 reject(e);702 }703 });704 }705 706 wasmBinaryFile ??= findWasmBinary();707 var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);708 var exports = receiveInstantiationResult(result);709 return exports;710}711 712// end include: preamble.js713 714// Begin JS library code715 716 717 class ExitStatus {718 name = 'ExitStatus';719 constructor(status) {720 this.message = `Program terminated with exit(${status})`;721 this.status = status;722 }723 }724 725 var callRuntimeCallbacks = (callbacks) => {726 while (callbacks.length > 0) {727 // Pass the module as the first argument.728 callbacks.shift()(Module);729 }730 };731 var onPostRuns = [];732 var addOnPostRun = (cb) => onPostRuns.push(cb);733 734 var onPreRuns = [];735 var addOnPreRun = (cb) => onPreRuns.push(cb);736 737 738 739 /**740 * @param {number} ptr741 * @param {string} type742 */743 function getValue(ptr, type = 'i8') {744 if (type.endsWith('*')) type = '*';745 switch (type) {746 case 'i1': return HEAP8[ptr];747 case 'i8': return HEAP8[ptr];748 case 'i16': return HEAP16[((ptr)>>1)];749 case 'i32': return HEAP32[((ptr)>>2)];750 case 'i64': return HEAP64[((ptr)>>3)];751 case 'float': return HEAPF32[((ptr)>>2)];752 case 'double': return HEAPF64[((ptr)>>3)];753 case '*': return HEAPU32[((ptr)>>2)];754 default: abort(`invalid type for getValue: ${type}`);755 }756 }757 758 var noExitRuntime = true;759 760 var ptrToString = (ptr) => {761 assert(typeof ptr === 'number', `ptrToString expects a number, got ${typeof ptr}`);762 // Convert to 32-bit unsigned value763 ptr >>>= 0;764 return '0x' + ptr.toString(16).padStart(8, '0');765 };766 767 768 /**769 * @param {number} ptr770 * @param {number} value771 * @param {string} type772 */773 function setValue(ptr, value, type = 'i8') {774 if (type.endsWith('*')) type = '*';775 switch (type) {776 case 'i1': HEAP8[ptr] = value; break;777 case 'i8': HEAP8[ptr] = value; break;778 case 'i16': HEAP16[((ptr)>>1)] = value; break;779 case 'i32': HEAP32[((ptr)>>2)] = value; break;780 case 'i64': HEAP64[((ptr)>>3)] = BigInt(value); break;781 case 'float': HEAPF32[((ptr)>>2)] = value; break;782 case 'double': HEAPF64[((ptr)>>3)] = value; break;783 case '*': HEAPU32[((ptr)>>2)] = value; break;784 default: abort(`invalid type for setValue: ${type}`);785 }786 }787 788 var stackRestore = (val) => __emscripten_stack_restore(val);789 790 var stackSave = () => _emscripten_stack_get_current();791 792 var warnOnce = (text) => {793 warnOnce.shown ||= {};794 if (!warnOnce.shown[text]) {795 warnOnce.shown[text] = 1;796 if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;797 err(text);798 }799 };800 801 802 803 var __abort_js = () =>804 abort('native code called abort()');805 806 var __emscripten_throw_longjmp = () => {807 throw Infinity;808 };809 810 var _emscripten_get_now = () => performance.now();811 812 var _emscripten_date_now = () => Date.now();813 814 var nowIsMonotonic = 1;815 816 var checkWasiClock = (clock_id) => clock_id >= 0 && clock_id <= 3;817 818 var INT53_MAX = 9007199254740992;819 820 var INT53_MIN = -9007199254740992;821 var bigintToI53Checked = (num) => (num < INT53_MIN || num > INT53_MAX) ? NaN : Number(num);822 function _clock_time_get(clk_id, ignored_precision, ptime) {823 ignored_precision = bigintToI53Checked(ignored_precision);824 825 826 if (!checkWasiClock(clk_id)) {827 return 28;828 }829 var now;830 // all wasi clocks but realtime are monotonic831 if (clk_id === 0) {832 now = _emscripten_date_now();833 } else if (nowIsMonotonic) {834 now = _emscripten_get_now();835 } else {836 return 52;837 }838 // "now" is in ms, and wasi times are in ns.839 var nsec = Math.round(now * 1000 * 1000);840 HEAP64[((ptime)>>3)] = BigInt(nsec);841 return 0;842 ;843 }844 845 846 var getHeapMax = () =>847 // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate848 // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side849 // for any code that deals with heap sizes, which would require special850 // casing all heap size related code to treat 0 specially.851 67108864;852 853 var alignMemory = (size, alignment) => {854 assert(alignment, "alignment argument is required");855 return Math.ceil(size / alignment) * alignment;856 };857 858 var growMemory = (size) => {859 var oldHeapSize = wasmMemory.buffer.byteLength;860 var pages = ((size - oldHeapSize + 65535) / 65536) | 0;861 try {862 // round size grow request up to wasm page size (fixed 64KB per spec)863 wasmMemory.grow(pages); // .grow() takes a delta compared to the previous size864 updateMemoryViews();865 return 1 /*success*/;866 } catch(e) {867 err(`growMemory: Attempted to grow heap from ${oldHeapSize} bytes to ${size} bytes, but got error: ${e}`);868 }869 // implicit 0 return to save code size (caller will cast "undefined" into 0870 // anyhow)871 };872 var _emscripten_resize_heap = (requestedSize) => {873 var oldSize = HEAPU8.length;874 // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.875 requestedSize >>>= 0;876 // With multithreaded builds, races can happen (another thread might increase the size877 // in between), so return a failure, and let the caller retry.878 assert(requestedSize > oldSize);879 880 // Memory resize rules:881 // 1. Always increase heap size to at least the requested size, rounded up882 // to next page multiple.883 // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap884 // geometrically: increase the heap size according to885 // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most886 // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).887 // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap888 // linearly: increase the heap size by at least889 // MEMORY_GROWTH_LINEAR_STEP bytes.890 // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by891 // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest892 // 4. If we were unable to allocate as much memory, it may be due to893 // over-eager decision to excessively reserve due to (3) above.894 // Hence if an allocation fails, cut down on the amount of excess895 // growth, in an attempt to succeed to perform a smaller allocation.896 897 // A limit is set for how much we can grow. We should not exceed that898 // (the wasm binary specifies it, so if we tried, we'd fail anyhow).899 var maxHeapSize = getHeapMax();900 if (requestedSize > maxHeapSize) {901 err(`Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`);902 return false;903 }904 905 // Loop through potential heap size increases. If we attempt a too eager906 // reservation that fails, cut down on the attempted size and reserve a907 // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)908 for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {909 var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); // ensure geometric growth910 // but limit overreserving (default to capping at +96MB overgrowth at most)911 overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 );912 913 var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));914 915 var replacement = growMemory(newSize);916 if (replacement) {917 918 return true;919 }920 }921 err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`);922 return false;923 };924 925 var UTF8Decoder = globalThis.TextDecoder && new TextDecoder();926 927 var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {928 var maxIdx = idx + maxBytesToRead;929 if (ignoreNul) return maxIdx;930 // TextDecoder needs to know the byte length in advance, it doesn't stop on931 // null terminator by itself.932 // As a tiny code save trick, compare idx against maxIdx using a negation,933 // so that maxBytesToRead=undefined/NaN means Infinity.934 while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;935 return idx;936 };937 938 939 /**940 * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given941 * array that contains uint8 values, returns a copy of that string as a942 * Javascript String object.943 * heapOrArray is either a regular array, or a JavaScript typed array view.944 * @param {number=} idx945 * @param {number=} maxBytesToRead946 * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.947 * @return {string}948 */949 var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {950 951 var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);952 953 // When using conditional TextDecoder, skip it for short strings as the overhead of the native call is not worth it.954 if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {955 return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));956 }957 var str = '';958 while (idx < endPtr) {959 // For UTF8 byte structure, see:960 // http://en.wikipedia.org/wiki/UTF-8#Description961 // https://www.ietf.org/rfc/rfc2279.txt962 // https://tools.ietf.org/html/rfc3629963 var u0 = heapOrArray[idx++];964 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }965 var u1 = heapOrArray[idx++] & 63;966 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }967 var u2 = heapOrArray[idx++] & 63;968 if ((u0 & 0xF0) == 0xE0) {969 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;970 } else {971 if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');972 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);973 }974 975 if (u0 < 0x10000) {976 str += String.fromCharCode(u0);977 } else {978 var ch = u0 - 0x10000;979 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));980 }981 }982 return str;983 };984 985 /**986 * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the987 * emscripten HEAP, returns a copy of that string as a Javascript String object.988 *989 * @param {number} ptr990 * @param {number=} maxBytesToRead - An optional length that specifies the991 * maximum number of bytes to read. You can omit this parameter to scan the992 * string until the first 0 byte. If maxBytesToRead is passed, and the string993 * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the994 * string will cut short at that byte index.995 * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.996 * @return {string}997 */998 var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {999 assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`);1000 return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead, ignoreNul) : '';1001 };1002 var SYSCALLS = {1003 varargs:undefined,1004 getStr(ptr) {1005 var ret = UTF8ToString(ptr);1006 return ret;1007 },1008 };1009 var _fd_close = (fd) => {1010 abort('fd_close called without SYSCALLS_REQUIRE_FILESYSTEM');1011 };1012 1013 function _fd_seek(fd, offset, whence, newOffset) {1014 offset = bigintToI53Checked(offset);1015 1016 1017 return 70;1018 ;1019 }1020 1021 var printCharBuffers = [null,[],[]];1022 1023 var printChar = (stream, curr) => {1024 var buffer = printCharBuffers[stream];1025 assert(buffer);1026 if (curr === 0 || curr === 10) {1027 (stream === 1 ? out : err)(UTF8ArrayToString(buffer));1028 buffer.length = 0;1029 } else {1030 buffer.push(curr);1031 }1032 };1033 1034 var flush_NO_FILESYSTEM = () => {1035 // flush anything remaining in the buffers during shutdown1036 _fflush(0);1037 if (printCharBuffers[1].length) printChar(1, 10);1038 if (printCharBuffers[2].length) printChar(2, 10);1039 };1040 1041 1042 var _fd_write = (fd, iov, iovcnt, pnum) => {1043 // hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=01044 var num = 0;1045 for (var i = 0; i < iovcnt; i++) {1046 var ptr = HEAPU32[((iov)>>2)];1047 var len = HEAPU32[(((iov)+(4))>>2)];1048 iov += 8;1049 for (var j = 0; j < len; j++) {1050 printChar(fd, HEAPU8[ptr+j]);1051 }1052 num += len;1053 }1054 HEAPU32[((pnum)>>2)] = num;1055 return 0;1056 };1057 1058 var wasmTableMirror = [];1059 1060 1061 var getWasmTableEntry = (funcPtr) => {1062 var func = wasmTableMirror[funcPtr];1063 if (!func) {1064 /** @suppress {checkTypes} */1065 wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);1066 }1067 /** @suppress {checkTypes} */1068 assert(wasmTable.get(funcPtr) == func, 'JavaScript-side Wasm function table mirror is out of date!');1069 return func;1070 };1071 1072 var getCFunc = (ident) => {1073 var func = Module['_' + ident]; // closure exported function1074 assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');1075 return func;1076 };1077 1078 var writeArrayToMemory = (array, buffer) => {1079 assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')1080 HEAP8.set(array, buffer);1081 };1082 1083 var lengthBytesUTF8 = (str) => {1084 var len = 0;1085 for (var i = 0; i < str.length; ++i) {1086 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code1087 // unit, not a Unicode code point of the character! So decode1088 // UTF16->UTF32->UTF8.1089 // See http://unicode.org/faq/utf_bom.html#utf16-31090 var c = str.charCodeAt(i); // possibly a lead surrogate1091 if (c <= 0x7F) {1092 len++;1093 } else if (c <= 0x7FF) {1094 len += 2;1095 } else if (c >= 0xD800 && c <= 0xDFFF) {1096 len += 4; ++i;1097 } else {1098 len += 3;1099 }1100 }1101 return len;1102 };1103 1104 var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {1105 assert(typeof str === 'string', `stringToUTF8Array expects a string (got ${typeof str})`);1106 // Parameter maxBytesToWrite is not optional. Negative values, 0, null,1107 // undefined and false each don't write out any bytes.1108 if (!(maxBytesToWrite > 0))1109 return 0;1110 1111 var startIdx = outIdx;1112 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.1113 for (var i = 0; i < str.length; ++i) {1114 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description1115 // and https://www.ietf.org/rfc/rfc2279.txt1116 // and https://tools.ietf.org/html/rfc36291117 var u = str.codePointAt(i);1118 if (u <= 0x7F) {1119 if (outIdx >= endIdx) break;1120 heap[outIdx++] = u;1121 } else if (u <= 0x7FF) {1122 if (outIdx + 1 >= endIdx) break;1123 heap[outIdx++] = 0xC0 | (u >> 6);1124 heap[outIdx++] = 0x80 | (u & 63);1125 } else if (u <= 0xFFFF) {1126 if (outIdx + 2 >= endIdx) break;1127 heap[outIdx++] = 0xE0 | (u >> 12);1128 heap[outIdx++] = 0x80 | ((u >> 6) & 63);1129 heap[outIdx++] = 0x80 | (u & 63);1130 } else {1131 if (outIdx + 3 >= endIdx) break;1132 if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).');1133 heap[outIdx++] = 0xF0 | (u >> 18);1134 heap[outIdx++] = 0x80 | ((u >> 12) & 63);1135 heap[outIdx++] = 0x80 | ((u >> 6) & 63);1136 heap[outIdx++] = 0x80 | (u & 63);1137 // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.1138 // We need to manually skip over the second code unit for correct iteration.1139 i++;1140 }1141 }1142 // Null-terminate the pointer to the buffer.1143 heap[outIdx] = 0;1144 return outIdx - startIdx;1145 };1146 var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {1147 assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');1148 return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);1149 };1150 1151 var stackAlloc = (sz) => __emscripten_stack_alloc(sz);1152 var stringToUTF8OnStack = (str) => {1153 var size = lengthBytesUTF8(str) + 1;1154 var ret = stackAlloc(size);1155 stringToUTF8(str, ret, size);1156 return ret;1157 };1158 1159 1160 1161 1162 1163 /**1164 * @param {string|null=} returnType1165 * @param {Array=} argTypes1166 * @param {Array=} args1167 * @param {Object=} opts1168 */1169 var ccall = (ident, returnType, argTypes, args, opts) => {1170 // For fast lookup of conversion functions1171 var toC = {1172 'string': (str) => {1173 var ret = 0;1174 if (str !== null && str !== undefined && str !== 0) { // null string1175 ret = stringToUTF8OnStack(str);1176 }1177 return ret;1178 },1179 'array': (arr) => {1180 var ret = stackAlloc(arr.length);1181 writeArrayToMemory(arr, ret);1182 return ret;1183 }1184 };1185 1186 function convertReturnValue(ret) {1187 if (returnType === 'string') {1188 return UTF8ToString(ret);1189 }1190 if (returnType === 'boolean') return Boolean(ret);1191 return ret;1192 }1193 1194 var func = getCFunc(ident);1195 var cArgs = [];1196 var stack = 0;1197 assert(returnType !== 'array', 'Return type should not be "array".');1198 if (args) {1199 for (var i = 0; i < args.length; i++) {1200 var converter = toC[argTypes[i]];