lnsocket.js (69070B)
1 2 var Module = (function() { 3 var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; 4 5 return ( 6 function(Module) { 7 Module = Module || {}; 8 9 10 11 // The Module object: Our interface to the outside world. We import 12 // and export values on it. There are various ways Module can be used: 13 // 1. Not defined. We create it here 14 // 2. A function parameter, function(Module) { ..generated code.. } 15 // 3. pre-run appended it, var Module = {}; ..generated code.. 16 // 4. External script tag defines var Module. 17 // We need to check if Module already exists (e.g. case 3 above). 18 // Substitution will be replaced with actual code on later stage of the build, 19 // this way Closure Compiler will not mangle it (e.g. case 4. above). 20 // Note that if you want to run closure, and also to use Module 21 // after the generated code, you will need to define var Module = {}; 22 // before the code. Then that object will be used in the code, and you 23 // can continue to use Module afterwards as well. 24 var Module = typeof Module !== 'undefined' ? Module : {}; 25 26 // Set up the promise that indicates the Module is initialized 27 var readyPromiseResolve, readyPromiseReject; 28 Module['ready'] = new Promise(function(resolve, reject) { 29 readyPromiseResolve = resolve; 30 readyPromiseReject = reject; 31 }); 32 33 // --pre-jses are emitted after the Module integration code, so that they can 34 // refer to Module (if they choose; they can also define Module) 35 Module.getRandomValue = (function() { 36 const window_ = "object" === typeof window ? window : self 37 const crypto_ = typeof window_.crypto !== "undefined" ? window_.crypto : window_.msCrypto; 38 39 function randomValuesStandard() { 40 var buf = new Uint32Array(1); 41 crypto_.getRandomValues(buf); 42 return buf[0] >>> 0; 43 }; 44 45 return randomValuesStandard 46 })() 47 48 49 50 // Sometimes an existing Module object exists with properties 51 // meant to overwrite the default module functionality. Here 52 // we collect those properties and reapply _after_ we configure 53 // the current environment's defaults to avoid having to be so 54 // defensive during initialization. 55 var moduleOverrides = {}; 56 var key; 57 for (key in Module) { 58 if (Module.hasOwnProperty(key)) { 59 moduleOverrides[key] = Module[key]; 60 } 61 } 62 63 var arguments_ = []; 64 var thisProgram = './this.program'; 65 var quit_ = function(status, toThrow) { 66 throw toThrow; 67 }; 68 69 // Determine the runtime environment we are in. You can customize this by 70 // setting the ENVIRONMENT setting at compile time (see settings.js). 71 72 var ENVIRONMENT_IS_WEB = true; 73 var ENVIRONMENT_IS_WORKER = false; 74 var ENVIRONMENT_IS_NODE = false; 75 var ENVIRONMENT_IS_SHELL = false; 76 77 // `/` should be present at the end if `scriptDirectory` is not empty 78 var scriptDirectory = ''; 79 function locateFile(path) { 80 if (Module['locateFile']) { 81 return Module['locateFile'](path, scriptDirectory); 82 } 83 return scriptDirectory + path; 84 } 85 86 // Hooks that are implemented differently in different runtime environments. 87 var read_, 88 readAsync, 89 readBinary, 90 setWindowTitle; 91 92 // Note that this includes Node.js workers when relevant (pthreads is enabled). 93 // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and 94 // ENVIRONMENT_IS_NODE. 95 if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { 96 if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled 97 scriptDirectory = self.location.href; 98 } else if (typeof document !== 'undefined' && document.currentScript) { // web 99 scriptDirectory = document.currentScript.src; 100 } 101 // When MODULARIZE, this JS may be executed later, after document.currentScript 102 // is gone, so we saved it, and we use it here instead of any other info. 103 if (_scriptDir) { 104 scriptDirectory = _scriptDir; 105 } 106 // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them. 107 // otherwise, slice off the final part of the url to find the script directory. 108 // if scriptDirectory does not contain a slash, lastIndexOf will return -1, 109 // and scriptDirectory will correctly be replaced with an empty string. 110 if (scriptDirectory.indexOf('blob:') !== 0) { 111 scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1); 112 } else { 113 scriptDirectory = ''; 114 } 115 116 // Differentiate the Web Worker from the Node Worker case, as reading must 117 // be done differently. 118 { 119 120 // include: web_or_worker_shell_read.js 121 122 123 read_ = function(url) { 124 var xhr = new XMLHttpRequest(); 125 xhr.open('GET', url, false); 126 xhr.send(null); 127 return xhr.responseText; 128 }; 129 130 if (ENVIRONMENT_IS_WORKER) { 131 readBinary = function(url) { 132 var xhr = new XMLHttpRequest(); 133 xhr.open('GET', url, false); 134 xhr.responseType = 'arraybuffer'; 135 xhr.send(null); 136 return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response)); 137 }; 138 } 139 140 readAsync = function(url, onload, onerror) { 141 var xhr = new XMLHttpRequest(); 142 xhr.open('GET', url, true); 143 xhr.responseType = 'arraybuffer'; 144 xhr.onload = function() { 145 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0 146 onload(xhr.response); 147 return; 148 } 149 onerror(); 150 }; 151 xhr.onerror = onerror; 152 xhr.send(null); 153 }; 154 155 // end include: web_or_worker_shell_read.js 156 } 157 158 setWindowTitle = function(title) { document.title = title }; 159 } else 160 { 161 } 162 163 // Set up the out() and err() hooks, which are how we can print to stdout or 164 // stderr, respectively. 165 var out = Module['print'] || console.log.bind(console); 166 var err = Module['printErr'] || console.warn.bind(console); 167 168 // Merge back in the overrides 169 for (key in moduleOverrides) { 170 if (moduleOverrides.hasOwnProperty(key)) { 171 Module[key] = moduleOverrides[key]; 172 } 173 } 174 // Free the object hierarchy contained in the overrides, this lets the GC 175 // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array. 176 moduleOverrides = null; 177 178 // Emit code to handle expected values on the Module object. This applies Module.x 179 // to the proper local x. This has two benefits: first, we only emit it if it is 180 // expected to arrive, and second, by using a local everywhere else that can be 181 // minified. 182 183 if (Module['arguments']) arguments_ = Module['arguments']; 184 185 if (Module['thisProgram']) thisProgram = Module['thisProgram']; 186 187 if (Module['quit']) quit_ = Module['quit']; 188 189 // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message 190 191 192 193 194 var STACK_ALIGN = 16; 195 196 function getNativeTypeSize(type) { 197 switch (type) { 198 case 'i1': case 'i8': return 1; 199 case 'i16': return 2; 200 case 'i32': return 4; 201 case 'i64': return 8; 202 case 'float': return 4; 203 case 'double': return 8; 204 default: { 205 if (type[type.length-1] === '*') { 206 return 4; // A pointer 207 } else if (type[0] === 'i') { 208 var bits = Number(type.substr(1)); 209 assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type); 210 return bits / 8; 211 } else { 212 return 0; 213 } 214 } 215 } 216 } 217 218 function warnOnce(text) { 219 if (!warnOnce.shown) warnOnce.shown = {}; 220 if (!warnOnce.shown[text]) { 221 warnOnce.shown[text] = 1; 222 err(text); 223 } 224 } 225 226 // include: runtime_functions.js 227 228 229 // Wraps a JS function as a wasm function with a given signature. 230 function convertJsFunctionToWasm(func, sig) { 231 232 // If the type reflection proposal is available, use the new 233 // "WebAssembly.Function" constructor. 234 // Otherwise, construct a minimal wasm module importing the JS function and 235 // re-exporting it. 236 if (typeof WebAssembly.Function === "function") { 237 var typeNames = { 238 'i': 'i32', 239 'j': 'i64', 240 'f': 'f32', 241 'd': 'f64' 242 }; 243 var type = { 244 parameters: [], 245 results: sig[0] == 'v' ? [] : [typeNames[sig[0]]] 246 }; 247 for (var i = 1; i < sig.length; ++i) { 248 type.parameters.push(typeNames[sig[i]]); 249 } 250 return new WebAssembly.Function(type, func); 251 } 252 253 // The module is static, with the exception of the type section, which is 254 // generated based on the signature passed in. 255 var typeSection = [ 256 0x01, // id: section, 257 0x00, // length: 0 (placeholder) 258 0x01, // count: 1 259 0x60, // form: func 260 ]; 261 var sigRet = sig.slice(0, 1); 262 var sigParam = sig.slice(1); 263 var typeCodes = { 264 'i': 0x7f, // i32 265 'j': 0x7e, // i64 266 'f': 0x7d, // f32 267 'd': 0x7c, // f64 268 }; 269 270 // Parameters, length + signatures 271 typeSection.push(sigParam.length); 272 for (var i = 0; i < sigParam.length; ++i) { 273 typeSection.push(typeCodes[sigParam[i]]); 274 } 275 276 // Return values, length + signatures 277 // With no multi-return in MVP, either 0 (void) or 1 (anything else) 278 if (sigRet == 'v') { 279 typeSection.push(0x00); 280 } else { 281 typeSection = typeSection.concat([0x01, typeCodes[sigRet]]); 282 } 283 284 // Write the overall length of the type section back into the section header 285 // (excepting the 2 bytes for the section id and length) 286 typeSection[1] = typeSection.length - 2; 287 288 // Rest of the module is static 289 var bytes = new Uint8Array([ 290 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm") 291 0x01, 0x00, 0x00, 0x00, // version: 1 292 ].concat(typeSection, [ 293 0x02, 0x07, // import section 294 // (import "e" "f" (func 0 (type 0))) 295 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00, 296 0x07, 0x05, // export section 297 // (export "f" (func 0 (type 0))) 298 0x01, 0x01, 0x66, 0x00, 0x00, 299 ])); 300 301 // We can compile this wasm module synchronously because it is very small. 302 // This accepts an import (at "e.f"), that it reroutes to an export (at "f") 303 var module = new WebAssembly.Module(bytes); 304 var instance = new WebAssembly.Instance(module, { 305 'e': { 306 'f': func 307 } 308 }); 309 var wrappedFunc = instance.exports['f']; 310 return wrappedFunc; 311 } 312 313 var freeTableIndexes = []; 314 315 // Weak map of functions in the table to their indexes, created on first use. 316 var functionsInTableMap; 317 318 function getEmptyTableSlot() { 319 // Reuse a free index if there is one, otherwise grow. 320 if (freeTableIndexes.length) { 321 return freeTableIndexes.pop(); 322 } 323 // Grow the table 324 try { 325 wasmTable.grow(1); 326 } catch (err) { 327 if (!(err instanceof RangeError)) { 328 throw err; 329 } 330 throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.'; 331 } 332 return wasmTable.length - 1; 333 } 334 335 // Add a wasm function to the table. 336 function addFunctionWasm(func, sig) { 337 // Check if the function is already in the table, to ensure each function 338 // gets a unique index. First, create the map if this is the first use. 339 if (!functionsInTableMap) { 340 functionsInTableMap = new WeakMap(); 341 for (var i = 0; i < wasmTable.length; i++) { 342 var item = wasmTable.get(i); 343 // Ignore null values. 344 if (item) { 345 functionsInTableMap.set(item, i); 346 } 347 } 348 } 349 if (functionsInTableMap.has(func)) { 350 return functionsInTableMap.get(func); 351 } 352 353 // It's not in the table, add it now. 354 355 var ret = getEmptyTableSlot(); 356 357 // Set the new value. 358 try { 359 // Attempting to call this with JS function will cause of table.set() to fail 360 wasmTable.set(ret, func); 361 } catch (err) { 362 if (!(err instanceof TypeError)) { 363 throw err; 364 } 365 var wrapped = convertJsFunctionToWasm(func, sig); 366 wasmTable.set(ret, wrapped); 367 } 368 369 functionsInTableMap.set(func, ret); 370 371 return ret; 372 } 373 374 function removeFunction(index) { 375 functionsInTableMap.delete(wasmTable.get(index)); 376 freeTableIndexes.push(index); 377 } 378 379 // 'sig' parameter is required for the llvm backend but only when func is not 380 // already a WebAssembly function. 381 function addFunction(func, sig) { 382 383 return addFunctionWasm(func, sig); 384 } 385 386 // end include: runtime_functions.js 387 // include: runtime_debug.js 388 389 390 // end include: runtime_debug.js 391 var tempRet0 = 0; 392 393 var setTempRet0 = function(value) { 394 tempRet0 = value; 395 }; 396 397 var getTempRet0 = function() { 398 return tempRet0; 399 }; 400 401 402 403 // === Preamble library stuff === 404 405 // Documentation for the public APIs defined in this file must be updated in: 406 // site/source/docs/api_reference/preamble.js.rst 407 // A prebuilt local version of the documentation is available at: 408 // site/build/text/docs/api_reference/preamble.js.txt 409 // You can also build docs locally as HTML or other formats in site/ 410 // An online HTML version (which may be of a different version of Emscripten) 411 // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html 412 413 var wasmBinary; 414 if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']; 415 var noExitRuntime = Module['noExitRuntime'] || true; 416 417 if (typeof WebAssembly !== 'object') { 418 abort('no native wasm support detected'); 419 } 420 421 // include: runtime_safe_heap.js 422 423 424 // In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking. 425 // In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties) 426 427 /** @param {number} ptr 428 @param {number} value 429 @param {string} type 430 @param {number|boolean=} noSafe */ 431 function setValue(ptr, value, type, noSafe) { 432 type = type || 'i8'; 433 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit 434 switch (type) { 435 case 'i1': HEAP8[((ptr)>>0)] = value; break; 436 case 'i8': HEAP8[((ptr)>>0)] = value; break; 437 case 'i16': HEAP16[((ptr)>>1)] = value; break; 438 case 'i32': HEAP32[((ptr)>>2)] = value; break; 439 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; 440 case 'float': HEAPF32[((ptr)>>2)] = value; break; 441 case 'double': HEAPF64[((ptr)>>3)] = value; break; 442 default: abort('invalid type for setValue: ' + type); 443 } 444 } 445 446 /** @param {number} ptr 447 @param {string} type 448 @param {number|boolean=} noSafe */ 449 function getValue(ptr, type, noSafe) { 450 type = type || 'i8'; 451 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit 452 switch (type) { 453 case 'i1': return HEAP8[((ptr)>>0)]; 454 case 'i8': return HEAP8[((ptr)>>0)]; 455 case 'i16': return HEAP16[((ptr)>>1)]; 456 case 'i32': return HEAP32[((ptr)>>2)]; 457 case 'i64': return HEAP32[((ptr)>>2)]; 458 case 'float': return HEAPF32[((ptr)>>2)]; 459 case 'double': return HEAPF64[((ptr)>>3)]; 460 default: abort('invalid type for getValue: ' + type); 461 } 462 return null; 463 } 464 465 // end include: runtime_safe_heap.js 466 // Wasm globals 467 468 var wasmMemory; 469 470 //======================================== 471 // Runtime essentials 472 //======================================== 473 474 // whether we are quitting the application. no code should run after this. 475 // set in exit() and abort() 476 var ABORT = false; 477 478 // set by exit() and abort(). Passed to 'onExit' handler. 479 // NOTE: This is also used as the process return code code in shell environments 480 // but only when noExitRuntime is false. 481 var EXITSTATUS; 482 483 /** @type {function(*, string=)} */ 484 function assert(condition, text) { 485 if (!condition) { 486 abort('Assertion failed: ' + text); 487 } 488 } 489 490 // Returns the C function with a specified identifier (for C++, you need to do manual name mangling) 491 function getCFunc(ident) { 492 var func = Module['_' + ident]; // closure exported function 493 assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported'); 494 return func; 495 } 496 497 // C calling interface. 498 /** @param {string|null=} returnType 499 @param {Array=} argTypes 500 @param {Arguments|Array=} args 501 @param {Object=} opts */ 502 function ccall(ident, returnType, argTypes, args, opts) { 503 // For fast lookup of conversion functions 504 var toC = { 505 'string': function(str) { 506 var ret = 0; 507 if (str !== null && str !== undefined && str !== 0) { // null string 508 // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0' 509 var len = (str.length << 2) + 1; 510 ret = stackAlloc(len); 511 stringToUTF8(str, ret, len); 512 } 513 return ret; 514 }, 515 'array': function(arr) { 516 var ret = stackAlloc(arr.length); 517 writeArrayToMemory(arr, ret); 518 return ret; 519 } 520 }; 521 522 function convertReturnValue(ret) { 523 if (returnType === 'string') return UTF8ToString(ret); 524 if (returnType === 'boolean') return Boolean(ret); 525 return ret; 526 } 527 528 var func = getCFunc(ident); 529 var cArgs = []; 530 var stack = 0; 531 if (args) { 532 for (var i = 0; i < args.length; i++) { 533 var converter = toC[argTypes[i]]; 534 if (converter) { 535 if (stack === 0) stack = stackSave(); 536 cArgs[i] = converter(args[i]); 537 } else { 538 cArgs[i] = args[i]; 539 } 540 } 541 } 542 var ret = func.apply(null, cArgs); 543 function onDone(ret) { 544 if (stack !== 0) stackRestore(stack); 545 return convertReturnValue(ret); 546 } 547 548 ret = onDone(ret); 549 return ret; 550 } 551 552 /** @param {string=} returnType 553 @param {Array=} argTypes 554 @param {Object=} opts */ 555 function cwrap(ident, returnType, argTypes, opts) { 556 argTypes = argTypes || []; 557 // When the function takes numbers and returns a number, we can just return 558 // the original function 559 var numericArgs = argTypes.every(function(type){ return type === 'number'}); 560 var numericRet = returnType !== 'string'; 561 if (numericRet && numericArgs && !opts) { 562 return getCFunc(ident); 563 } 564 return function() { 565 return ccall(ident, returnType, argTypes, arguments, opts); 566 } 567 } 568 569 var ALLOC_NORMAL = 0; // Tries to use _malloc() 570 var ALLOC_STACK = 1; // Lives for the duration of the current function call 571 572 // allocate(): This is for internal use. You can use it yourself as well, but the interface 573 // is a little tricky (see docs right below). The reason is that it is optimized 574 // for multiple syntaxes to save space in generated code. So you should 575 // normally not use allocate(), and instead allocate memory using _malloc(), 576 // initialize it with setValue(), and so forth. 577 // @slab: An array of data. 578 // @allocator: How to allocate memory, see ALLOC_* 579 /** @type {function((Uint8Array|Array<number>), number)} */ 580 function allocate(slab, allocator) { 581 var ret; 582 583 if (allocator == ALLOC_STACK) { 584 ret = stackAlloc(slab.length); 585 } else { 586 ret = _malloc(slab.length); 587 } 588 589 if (slab.subarray || slab.slice) { 590 HEAPU8.set(/** @type {!Uint8Array} */(slab), ret); 591 } else { 592 HEAPU8.set(new Uint8Array(slab), ret); 593 } 594 return ret; 595 } 596 597 // include: runtime_strings.js 598 599 600 // runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime. 601 602 // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns 603 // a copy of that string as a Javascript String object. 604 605 var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined; 606 607 /** 608 * @param {number} idx 609 * @param {number=} maxBytesToRead 610 * @return {string} 611 */ 612 function UTF8ArrayToString(heap, idx, maxBytesToRead) { 613 var endIdx = idx + maxBytesToRead; 614 var endPtr = idx; 615 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. 616 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. 617 // (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity) 618 while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr; 619 620 if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) { 621 return UTF8Decoder.decode(heap.subarray(idx, endPtr)); 622 } else { 623 var str = ''; 624 // If building with TextDecoder, we have already computed the string length above, so test loop end condition against that 625 while (idx < endPtr) { 626 // For UTF8 byte structure, see: 627 // http://en.wikipedia.org/wiki/UTF-8#Description 628 // https://www.ietf.org/rfc/rfc2279.txt 629 // https://tools.ietf.org/html/rfc3629 630 var u0 = heap[idx++]; 631 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } 632 var u1 = heap[idx++] & 63; 633 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } 634 var u2 = heap[idx++] & 63; 635 if ((u0 & 0xF0) == 0xE0) { 636 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; 637 } else { 638 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63); 639 } 640 641 if (u0 < 0x10000) { 642 str += String.fromCharCode(u0); 643 } else { 644 var ch = u0 - 0x10000; 645 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); 646 } 647 } 648 } 649 return str; 650 } 651 652 // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a 653 // copy of that string as a Javascript String object. 654 // maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit 655 // this parameter to scan the string until the first \0 byte. If maxBytesToRead is 656 // passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the 657 // middle, then the string will cut short at that byte index (i.e. maxBytesToRead will 658 // not produce a string of exact length [ptr, ptr+maxBytesToRead[) 659 // N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may 660 // throw JS JIT optimizations off, so it is worth to consider consistently using one 661 // style or the other. 662 /** 663 * @param {number} ptr 664 * @param {number=} maxBytesToRead 665 * @return {string} 666 */ 667 function UTF8ToString(ptr, maxBytesToRead) { 668 return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; 669 } 670 671 // Copies the given Javascript String object 'str' to the given byte array at address 'outIdx', 672 // encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP. 673 // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. 674 // Parameters: 675 // str: the Javascript string to copy. 676 // heap: the array to copy to. Each index in this array is assumed to be one 8-byte element. 677 // outIdx: The starting offset in the array to begin the copying. 678 // maxBytesToWrite: The maximum number of bytes this function can write to the array. 679 // This count should include the null terminator, 680 // i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else. 681 // maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator. 682 // Returns the number of bytes written, EXCLUDING the null terminator. 683 684 function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { 685 if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes. 686 return 0; 687 688 var startIdx = outIdx; 689 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator. 690 for (var i = 0; i < str.length; ++i) { 691 // 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. 692 // See http://unicode.org/faq/utf_bom.html#utf16-3 693 // 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 694 var u = str.charCodeAt(i); // possibly a lead surrogate 695 if (u >= 0xD800 && u <= 0xDFFF) { 696 var u1 = str.charCodeAt(++i); 697 u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); 698 } 699 if (u <= 0x7F) { 700 if (outIdx >= endIdx) break; 701 heap[outIdx++] = u; 702 } else if (u <= 0x7FF) { 703 if (outIdx + 1 >= endIdx) break; 704 heap[outIdx++] = 0xC0 | (u >> 6); 705 heap[outIdx++] = 0x80 | (u & 63); 706 } else if (u <= 0xFFFF) { 707 if (outIdx + 2 >= endIdx) break; 708 heap[outIdx++] = 0xE0 | (u >> 12); 709 heap[outIdx++] = 0x80 | ((u >> 6) & 63); 710 heap[outIdx++] = 0x80 | (u & 63); 711 } else { 712 if (outIdx + 3 >= endIdx) break; 713 heap[outIdx++] = 0xF0 | (u >> 18); 714 heap[outIdx++] = 0x80 | ((u >> 12) & 63); 715 heap[outIdx++] = 0x80 | ((u >> 6) & 63); 716 heap[outIdx++] = 0x80 | (u & 63); 717 } 718 } 719 // Null-terminate the pointer to the buffer. 720 heap[outIdx] = 0; 721 return outIdx - startIdx; 722 } 723 724 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 725 // null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP. 726 // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. 727 // Returns the number of bytes written, EXCLUDING the null terminator. 728 729 function stringToUTF8(str, outPtr, maxBytesToWrite) { 730 return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite); 731 } 732 733 // Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte. 734 function lengthBytesUTF8(str) { 735 var len = 0; 736 for (var i = 0; i < str.length; ++i) { 737 // 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. 738 // See http://unicode.org/faq/utf_bom.html#utf16-3 739 var u = str.charCodeAt(i); // possibly a lead surrogate 740 if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF); 741 if (u <= 0x7F) ++len; 742 else if (u <= 0x7FF) len += 2; 743 else if (u <= 0xFFFF) len += 3; 744 else len += 4; 745 } 746 return len; 747 } 748 749 // end include: runtime_strings.js 750 // include: runtime_strings_extra.js 751 752 753 // runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime. 754 755 // Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns 756 // a copy of that string as a Javascript String object. 757 758 function AsciiToString(ptr) { 759 var str = ''; 760 while (1) { 761 var ch = HEAPU8[((ptr++)>>0)]; 762 if (!ch) return str; 763 str += String.fromCharCode(ch); 764 } 765 } 766 767 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 768 // null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP. 769 770 function stringToAscii(str, outPtr) { 771 return writeAsciiToMemory(str, outPtr, false); 772 } 773 774 // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns 775 // a copy of that string as a Javascript String object. 776 777 var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined; 778 779 function UTF16ToString(ptr, maxBytesToRead) { 780 var endPtr = ptr; 781 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. 782 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. 783 var idx = endPtr >> 1; 784 var maxIdx = idx + maxBytesToRead / 2; 785 // If maxBytesToRead is not passed explicitly, it will be undefined, and this 786 // will always evaluate to true. This saves on code size. 787 while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx; 788 endPtr = idx << 1; 789 790 if (endPtr - ptr > 32 && UTF16Decoder) { 791 return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)); 792 } else { 793 var str = ''; 794 795 // If maxBytesToRead is not passed explicitly, it will be undefined, and the for-loop's condition 796 // will always evaluate to true. The loop is then terminated on the first null char. 797 for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { 798 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)]; 799 if (codeUnit == 0) break; 800 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through. 801 str += String.fromCharCode(codeUnit); 802 } 803 804 return str; 805 } 806 } 807 808 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 809 // null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP. 810 // Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write. 811 // Parameters: 812 // str: the Javascript string to copy. 813 // outPtr: Byte address in Emscripten HEAP where to write the string to. 814 // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null 815 // terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else. 816 // maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator. 817 // Returns the number of bytes written, EXCLUDING the null terminator. 818 819 function stringToUTF16(str, outPtr, maxBytesToWrite) { 820 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. 821 if (maxBytesToWrite === undefined) { 822 maxBytesToWrite = 0x7FFFFFFF; 823 } 824 if (maxBytesToWrite < 2) return 0; 825 maxBytesToWrite -= 2; // Null terminator. 826 var startPtr = outPtr; 827 var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length; 828 for (var i = 0; i < numCharsToWrite; ++i) { 829 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP. 830 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate 831 HEAP16[((outPtr)>>1)] = codeUnit; 832 outPtr += 2; 833 } 834 // Null-terminate the pointer to the HEAP. 835 HEAP16[((outPtr)>>1)] = 0; 836 return outPtr - startPtr; 837 } 838 839 // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte. 840 841 function lengthBytesUTF16(str) { 842 return str.length*2; 843 } 844 845 function UTF32ToString(ptr, maxBytesToRead) { 846 var i = 0; 847 848 var str = ''; 849 // If maxBytesToRead is not passed explicitly, it will be undefined, and this 850 // will always evaluate to true. This saves on code size. 851 while (!(i >= maxBytesToRead / 4)) { 852 var utf32 = HEAP32[(((ptr)+(i*4))>>2)]; 853 if (utf32 == 0) break; 854 ++i; 855 // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing. 856 // See http://unicode.org/faq/utf_bom.html#utf16-3 857 if (utf32 >= 0x10000) { 858 var ch = utf32 - 0x10000; 859 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); 860 } else { 861 str += String.fromCharCode(utf32); 862 } 863 } 864 return str; 865 } 866 867 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 868 // null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP. 869 // Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write. 870 // Parameters: 871 // str: the Javascript string to copy. 872 // outPtr: Byte address in Emscripten HEAP where to write the string to. 873 // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null 874 // terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else. 875 // maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator. 876 // Returns the number of bytes written, EXCLUDING the null terminator. 877 878 function stringToUTF32(str, outPtr, maxBytesToWrite) { 879 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. 880 if (maxBytesToWrite === undefined) { 881 maxBytesToWrite = 0x7FFFFFFF; 882 } 883 if (maxBytesToWrite < 4) return 0; 884 var startPtr = outPtr; 885 var endPtr = startPtr + maxBytesToWrite - 4; 886 for (var i = 0; i < str.length; ++i) { 887 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap. 888 // See http://unicode.org/faq/utf_bom.html#utf16-3 889 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate 890 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) { 891 var trailSurrogate = str.charCodeAt(++i); 892 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF); 893 } 894 HEAP32[((outPtr)>>2)] = codeUnit; 895 outPtr += 4; 896 if (outPtr + 4 > endPtr) break; 897 } 898 // Null-terminate the pointer to the HEAP. 899 HEAP32[((outPtr)>>2)] = 0; 900 return outPtr - startPtr; 901 } 902 903 // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte. 904 905 function lengthBytesUTF32(str) { 906 var len = 0; 907 for (var i = 0; i < str.length; ++i) { 908 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap. 909 // See http://unicode.org/faq/utf_bom.html#utf16-3 910 var codeUnit = str.charCodeAt(i); 911 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate. 912 len += 4; 913 } 914 915 return len; 916 } 917 918 // Allocate heap space for a JS string, and write it there. 919 // It is the responsibility of the caller to free() that memory. 920 function allocateUTF8(str) { 921 var size = lengthBytesUTF8(str) + 1; 922 var ret = _malloc(size); 923 if (ret) stringToUTF8Array(str, HEAP8, ret, size); 924 return ret; 925 } 926 927 // Allocate stack space for a JS string, and write it there. 928 function allocateUTF8OnStack(str) { 929 var size = lengthBytesUTF8(str) + 1; 930 var ret = stackAlloc(size); 931 stringToUTF8Array(str, HEAP8, ret, size); 932 return ret; 933 } 934 935 // Deprecated: This function should not be called because it is unsafe and does not provide 936 // a maximum length limit of how many bytes it is allowed to write. Prefer calling the 937 // function stringToUTF8Array() instead, which takes in a maximum length that can be used 938 // to be secure from out of bounds writes. 939 /** @deprecated 940 @param {boolean=} dontAddNull */ 941 function writeStringToMemory(string, buffer, dontAddNull) { 942 warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!'); 943 944 var /** @type {number} */ lastChar, /** @type {number} */ end; 945 if (dontAddNull) { 946 // stringToUTF8Array always appends null. If we don't want to do that, remember the 947 // character that existed at the location where the null will be placed, and restore 948 // that after the write (below). 949 end = buffer + lengthBytesUTF8(string); 950 lastChar = HEAP8[end]; 951 } 952 stringToUTF8(string, buffer, Infinity); 953 if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character. 954 } 955 956 function writeArrayToMemory(array, buffer) { 957 HEAP8.set(array, buffer); 958 } 959 960 /** @param {boolean=} dontAddNull */ 961 function writeAsciiToMemory(str, buffer, dontAddNull) { 962 for (var i = 0; i < str.length; ++i) { 963 HEAP8[((buffer++)>>0)] = str.charCodeAt(i); 964 } 965 // Null-terminate the pointer to the HEAP. 966 if (!dontAddNull) HEAP8[((buffer)>>0)] = 0; 967 } 968 969 // end include: runtime_strings_extra.js 970 // Memory management 971 972 function alignUp(x, multiple) { 973 if (x % multiple > 0) { 974 x += multiple - (x % multiple); 975 } 976 return x; 977 } 978 979 var HEAP, 980 /** @type {ArrayBuffer} */ 981 buffer, 982 /** @type {Int8Array} */ 983 HEAP8, 984 /** @type {Uint8Array} */ 985 HEAPU8, 986 /** @type {Int16Array} */ 987 HEAP16, 988 /** @type {Uint16Array} */ 989 HEAPU16, 990 /** @type {Int32Array} */ 991 HEAP32, 992 /** @type {Uint32Array} */ 993 HEAPU32, 994 /** @type {Float32Array} */ 995 HEAPF32, 996 /** @type {Float64Array} */ 997 HEAPF64; 998 999 function updateGlobalBufferAndViews(buf) { 1000 buffer = buf; 1001 Module['HEAP8'] = HEAP8 = new Int8Array(buf); 1002 Module['HEAP16'] = HEAP16 = new Int16Array(buf); 1003 Module['HEAP32'] = HEAP32 = new Int32Array(buf); 1004 Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf); 1005 Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf); 1006 Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf); 1007 Module['HEAPF32'] = HEAPF32 = new Float32Array(buf); 1008 Module['HEAPF64'] = HEAPF64 = new Float64Array(buf); 1009 } 1010 1011 var TOTAL_STACK = 5242880; 1012 1013 var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216; 1014 1015 // include: runtime_init_table.js 1016 // In regular non-RELOCATABLE mode the table is exported 1017 // from the wasm module and this will be assigned once 1018 // the exports are available. 1019 var wasmTable; 1020 1021 // end include: runtime_init_table.js 1022 // include: runtime_stack_check.js 1023 1024 1025 // end include: runtime_stack_check.js 1026 // include: runtime_assertions.js 1027 1028 1029 // end include: runtime_assertions.js 1030 var __ATPRERUN__ = []; // functions called before the runtime is initialized 1031 var __ATINIT__ = []; // functions called during startup 1032 var __ATEXIT__ = []; // functions called during shutdown 1033 var __ATPOSTRUN__ = []; // functions called after the main() is called 1034 1035 var runtimeInitialized = false; 1036 var runtimeExited = false; 1037 var runtimeKeepaliveCounter = 0; 1038 1039 function keepRuntimeAlive() { 1040 return noExitRuntime || runtimeKeepaliveCounter > 0; 1041 } 1042 1043 function preRun() { 1044 1045 if (Module['preRun']) { 1046 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; 1047 while (Module['preRun'].length) { 1048 addOnPreRun(Module['preRun'].shift()); 1049 } 1050 } 1051 1052 callRuntimeCallbacks(__ATPRERUN__); 1053 } 1054 1055 function initRuntime() { 1056 runtimeInitialized = true; 1057 1058 1059 callRuntimeCallbacks(__ATINIT__); 1060 } 1061 1062 function exitRuntime() { 1063 runtimeExited = true; 1064 } 1065 1066 function postRun() { 1067 1068 if (Module['postRun']) { 1069 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; 1070 while (Module['postRun'].length) { 1071 addOnPostRun(Module['postRun'].shift()); 1072 } 1073 } 1074 1075 callRuntimeCallbacks(__ATPOSTRUN__); 1076 } 1077 1078 function addOnPreRun(cb) { 1079 __ATPRERUN__.unshift(cb); 1080 } 1081 1082 function addOnInit(cb) { 1083 __ATINIT__.unshift(cb); 1084 } 1085 1086 function addOnExit(cb) { 1087 } 1088 1089 function addOnPostRun(cb) { 1090 __ATPOSTRUN__.unshift(cb); 1091 } 1092 1093 // include: runtime_math.js 1094 1095 1096 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul 1097 1098 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround 1099 1100 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 1101 1102 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc 1103 1104 // end include: runtime_math.js 1105 // A counter of dependencies for calling run(). If we need to 1106 // do asynchronous work before running, increment this and 1107 // decrement it. Incrementing must happen in a place like 1108 // Module.preRun (used by emcc to add file preloading). 1109 // Note that you can add dependencies in preRun, even though 1110 // it happens right before run - run will be postponed until 1111 // the dependencies are met. 1112 var runDependencies = 0; 1113 var runDependencyWatcher = null; 1114 var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled 1115 1116 function getUniqueRunDependency(id) { 1117 return id; 1118 } 1119 1120 function addRunDependency(id) { 1121 runDependencies++; 1122 1123 if (Module['monitorRunDependencies']) { 1124 Module['monitorRunDependencies'](runDependencies); 1125 } 1126 1127 } 1128 1129 function removeRunDependency(id) { 1130 runDependencies--; 1131 1132 if (Module['monitorRunDependencies']) { 1133 Module['monitorRunDependencies'](runDependencies); 1134 } 1135 1136 if (runDependencies == 0) { 1137 if (runDependencyWatcher !== null) { 1138 clearInterval(runDependencyWatcher); 1139 runDependencyWatcher = null; 1140 } 1141 if (dependenciesFulfilled) { 1142 var callback = dependenciesFulfilled; 1143 dependenciesFulfilled = null; 1144 callback(); // can add another dependenciesFulfilled 1145 } 1146 } 1147 } 1148 1149 Module["preloadedImages"] = {}; // maps url to image data 1150 Module["preloadedAudios"] = {}; // maps url to audio data 1151 1152 /** @param {string|number=} what */ 1153 function abort(what) { 1154 if (Module['onAbort']) { 1155 Module['onAbort'](what); 1156 } 1157 1158 what += ''; 1159 err(what); 1160 1161 ABORT = true; 1162 EXITSTATUS = 1; 1163 1164 what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'; 1165 1166 // Use a wasm runtime error, because a JS error might be seen as a foreign 1167 // exception, which means we'd run destructors on it. We need the error to 1168 // simply make the program stop. 1169 var e = new WebAssembly.RuntimeError(what); 1170 1171 readyPromiseReject(e); 1172 // Throw the error whether or not MODULARIZE is set because abort is used 1173 // in code paths apart from instantiation where an exception is expected 1174 // to be thrown when abort is called. 1175 throw e; 1176 } 1177 1178 // {{MEM_INITIALIZER}} 1179 1180 // include: memoryprofiler.js 1181 1182 1183 // end include: memoryprofiler.js 1184 // include: URIUtils.js 1185 1186 1187 // Prefix of data URIs emitted by SINGLE_FILE and related options. 1188 var dataURIPrefix = 'data:application/octet-stream;base64,'; 1189 1190 // Indicates whether filename is a base64 data URI. 1191 function isDataURI(filename) { 1192 // Prefix of data URIs emitted by SINGLE_FILE and related options. 1193 return filename.startsWith(dataURIPrefix); 1194 } 1195 1196 // Indicates whether filename is delivered via file protocol (as opposed to http/https) 1197 function isFileURI(filename) { 1198 return filename.startsWith('file://'); 1199 } 1200 1201 // end include: URIUtils.js 1202 var wasmBinaryFile; 1203 wasmBinaryFile = 'lnsocket_module.wasm'; 1204 if (!isDataURI(wasmBinaryFile)) { 1205 wasmBinaryFile = locateFile(wasmBinaryFile); 1206 } 1207 1208 function getBinary(file) { 1209 try { 1210 if (file == wasmBinaryFile && wasmBinary) { 1211 return new Uint8Array(wasmBinary); 1212 } 1213 if (readBinary) { 1214 return readBinary(file); 1215 } else { 1216 throw "both async and sync fetching of the wasm failed"; 1217 } 1218 } 1219 catch (err) { 1220 abort(err); 1221 } 1222 } 1223 1224 function getBinaryPromise() { 1225 // If we don't have the binary yet, try to to load it asynchronously. 1226 // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url. 1227 // See https://github.com/github/fetch/pull/92#issuecomment-140665932 1228 // Cordova or Electron apps are typically loaded from a file:// url. 1229 // So use fetch if it is available and the url is not a file, otherwise fall back to XHR. 1230 if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { 1231 if (typeof fetch === 'function' 1232 ) { 1233 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) { 1234 if (!response['ok']) { 1235 throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; 1236 } 1237 return response['arrayBuffer'](); 1238 }).catch(function () { 1239 return getBinary(wasmBinaryFile); 1240 }); 1241 } 1242 } 1243 1244 // Otherwise, getBinary should be able to get it synchronously 1245 return Promise.resolve().then(function() { return getBinary(wasmBinaryFile); }); 1246 } 1247 1248 // Create the wasm instance. 1249 // Receives the wasm imports, returns the exports. 1250 function createWasm() { 1251 // prepare imports 1252 var info = { 1253 'env': asmLibraryArg, 1254 'wasi_snapshot_preview1': asmLibraryArg, 1255 }; 1256 // Load the wasm module and create an instance of using native support in the JS engine. 1257 // handle a generated wasm instance, receiving its exports and 1258 // performing other necessary setup 1259 /** @param {WebAssembly.Module=} module*/ 1260 function receiveInstance(instance, module) { 1261 var exports = instance.exports; 1262 1263 Module['asm'] = exports; 1264 1265 wasmMemory = Module['asm']['memory']; 1266 updateGlobalBufferAndViews(wasmMemory.buffer); 1267 1268 wasmTable = Module['asm']['__indirect_function_table']; 1269 1270 addOnInit(Module['asm']['__wasm_call_ctors']); 1271 1272 removeRunDependency('wasm-instantiate'); 1273 } 1274 // we can't run yet (except in a pthread, where we have a custom sync instantiator) 1275 addRunDependency('wasm-instantiate'); 1276 1277 // Prefer streaming instantiation if available. 1278 function receiveInstantiationResult(result) { 1279 // 'result' is a ResultObject object which has both the module and instance. 1280 // receiveInstance() will swap in the exports (to Module.asm) so they can be called 1281 // 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. 1282 // When the regression is fixed, can restore the above USE_PTHREADS-enabled path. 1283 receiveInstance(result['instance']); 1284 } 1285 1286 function instantiateArrayBuffer(receiver) { 1287 return getBinaryPromise().then(function(binary) { 1288 return WebAssembly.instantiate(binary, info); 1289 }).then(function (instance) { 1290 return instance; 1291 }).then(receiver, function(reason) { 1292 err('failed to asynchronously prepare wasm: ' + reason); 1293 1294 abort(reason); 1295 }); 1296 } 1297 1298 function instantiateAsync() { 1299 if (!wasmBinary && 1300 typeof WebAssembly.instantiateStreaming === 'function' && 1301 !isDataURI(wasmBinaryFile) && 1302 typeof fetch === 'function') { 1303 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) { 1304 var result = WebAssembly.instantiateStreaming(response, info); 1305 1306 return result.then( 1307 receiveInstantiationResult, 1308 function(reason) { 1309 // We expect the most common failure cause to be a bad MIME type for the binary, 1310 // in which case falling back to ArrayBuffer instantiation should work. 1311 err('wasm streaming compile failed: ' + reason); 1312 err('falling back to ArrayBuffer instantiation'); 1313 return instantiateArrayBuffer(receiveInstantiationResult); 1314 }); 1315 }); 1316 } else { 1317 return instantiateArrayBuffer(receiveInstantiationResult); 1318 } 1319 } 1320 1321 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback 1322 // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel 1323 // to any other async startup actions they are performing. 1324 if (Module['instantiateWasm']) { 1325 try { 1326 var exports = Module['instantiateWasm'](info, receiveInstance); 1327 return exports; 1328 } catch(e) { 1329 err('Module.instantiateWasm callback failed with error: ' + e); 1330 return false; 1331 } 1332 } 1333 1334 // If instantiation fails, reject the module ready promise. 1335 instantiateAsync().catch(readyPromiseReject); 1336 return {}; // no exports yet; we'll fill them in later 1337 } 1338 1339 // Globals used by JS i64 conversions (see makeSetValue) 1340 var tempDouble; 1341 var tempI64; 1342 1343 // === Body === 1344 1345 var ASM_CONSTS = { 1346 70824: function() {return Module.getRandomValue();}, 1347 70860: function() {if (Module.getRandomValue === undefined) { try { var window_ = 'object' === typeof window ? window : self; var crypto_ = typeof window_.crypto !== 'undefined' ? window_.crypto : window_.msCrypto; var randomValuesStandard = function() { var buf = new Uint32Array(1); crypto_.getRandomValues(buf); return buf[0] >>> 0; }; randomValuesStandard(); Module.getRandomValue = randomValuesStandard; } catch (e) { try { var crypto = require('crypto'); var randomValueNodeJS = function() { var buf = crypto.randomBytes(4); return (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]) >>> 0; }; randomValueNodeJS(); Module.getRandomValue = randomValueNodeJS; } catch (e) { throw 'No secure random number generator found'; } } }} 1348 }; 1349 1350 1351 1352 1353 1354 1355 function callRuntimeCallbacks(callbacks) { 1356 while (callbacks.length > 0) { 1357 var callback = callbacks.shift(); 1358 if (typeof callback == 'function') { 1359 callback(Module); // Pass the module as the first argument. 1360 continue; 1361 } 1362 var func = callback.func; 1363 if (typeof func === 'number') { 1364 if (callback.arg === undefined) { 1365 wasmTable.get(func)(); 1366 } else { 1367 wasmTable.get(func)(callback.arg); 1368 } 1369 } else { 1370 func(callback.arg === undefined ? null : callback.arg); 1371 } 1372 } 1373 } 1374 1375 function demangle(func) { 1376 return func; 1377 } 1378 1379 function demangleAll(text) { 1380 var regex = 1381 /\b_Z[\w\d_]+/g; 1382 return text.replace(regex, 1383 function(x) { 1384 var y = demangle(x); 1385 return x === y ? x : (y + ' [' + x + ']'); 1386 }); 1387 } 1388 1389 function jsStackTrace() { 1390 var error = new Error(); 1391 if (!error.stack) { 1392 // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown, 1393 // so try that as a special-case. 1394 try { 1395 throw new Error(); 1396 } catch(e) { 1397 error = e; 1398 } 1399 if (!error.stack) { 1400 return '(no stack trace available)'; 1401 } 1402 } 1403 return error.stack.toString(); 1404 } 1405 1406 function stackTrace() { 1407 var js = jsStackTrace(); 1408 if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace'](); 1409 return demangleAll(js); 1410 } 1411 1412 function ___assert_fail(condition, filename, line, func) { 1413 abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']); 1414 } 1415 1416 function _abort() { 1417 abort(); 1418 } 1419 1420 var readAsmConstArgsArray = []; 1421 function readAsmConstArgs(sigPtr, buf) { 1422 readAsmConstArgsArray.length = 0; 1423 var ch; 1424 // Most arguments are i32s, so shift the buffer pointer so it is a plain 1425 // index into HEAP32. 1426 buf >>= 2; 1427 while (ch = HEAPU8[sigPtr++]) { 1428 // A double takes two 32-bit slots, and must also be aligned - the backend 1429 // will emit padding to avoid that. 1430 var double = ch < 105; 1431 if (double && (buf & 1)) buf++; 1432 readAsmConstArgsArray.push(double ? HEAPF64[buf++ >> 1] : HEAP32[buf]); 1433 ++buf; 1434 } 1435 return readAsmConstArgsArray; 1436 } 1437 function _emscripten_asm_const_int(code, sigPtr, argbuf) { 1438 var args = readAsmConstArgs(sigPtr, argbuf); 1439 return ASM_CONSTS[code].apply(null, args); 1440 } 1441 1442 function _emscripten_memcpy_big(dest, src, num) { 1443 HEAPU8.copyWithin(dest, src, src + num); 1444 } 1445 1446 function abortOnCannotGrowMemory(requestedSize) { 1447 abort('OOM'); 1448 } 1449 function _emscripten_resize_heap(requestedSize) { 1450 var oldSize = HEAPU8.length; 1451 requestedSize = requestedSize >>> 0; 1452 abortOnCannotGrowMemory(requestedSize); 1453 } 1454 1455 var SYSCALLS = {mappings:{},buffers:[null,[],[]],printChar:function(stream, curr) { 1456 var buffer = SYSCALLS.buffers[stream]; 1457 if (curr === 0 || curr === 10) { 1458 (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)); 1459 buffer.length = 0; 1460 } else { 1461 buffer.push(curr); 1462 } 1463 },varargs:undefined,get:function() { 1464 SYSCALLS.varargs += 4; 1465 var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)]; 1466 return ret; 1467 },getStr:function(ptr) { 1468 var ret = UTF8ToString(ptr); 1469 return ret; 1470 },get64:function(low, high) { 1471 return low; 1472 }}; 1473 function _fd_close(fd) { 1474 return 0; 1475 } 1476 1477 function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { 1478 } 1479 1480 function flush_NO_FILESYSTEM() { 1481 // flush anything remaining in the buffers during shutdown 1482 if (typeof _fflush !== 'undefined') _fflush(0); 1483 var buffers = SYSCALLS.buffers; 1484 if (buffers[1].length) SYSCALLS.printChar(1, 10); 1485 if (buffers[2].length) SYSCALLS.printChar(2, 10); 1486 } 1487 function _fd_write(fd, iov, iovcnt, pnum) { 1488 // hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=0 1489 var num = 0; 1490 for (var i = 0; i < iovcnt; i++) { 1491 var ptr = HEAP32[(((iov)+(i*8))>>2)]; 1492 var len = HEAP32[(((iov)+(i*8 + 4))>>2)]; 1493 for (var j = 0; j < len; j++) { 1494 SYSCALLS.printChar(fd, HEAPU8[ptr+j]); 1495 } 1496 num += len; 1497 } 1498 HEAP32[((pnum)>>2)] = num 1499 return 0; 1500 } 1501 1502 function _setTempRet0(val) { 1503 setTempRet0(val); 1504 } 1505 var ASSERTIONS = false; 1506 1507 1508 1509 /** @type {function(string, boolean=, number=)} */ 1510 function intArrayFromString(stringy, dontAddNull, length) { 1511 var len = length > 0 ? length : lengthBytesUTF8(stringy)+1; 1512 var u8array = new Array(len); 1513 var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); 1514 if (dontAddNull) u8array.length = numBytesWritten; 1515 return u8array; 1516 } 1517 1518 function intArrayToString(array) { 1519 var ret = []; 1520 for (var i = 0; i < array.length; i++) { 1521 var chr = array[i]; 1522 if (chr > 0xFF) { 1523 if (ASSERTIONS) { 1524 assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.'); 1525 } 1526 chr &= 0xFF; 1527 } 1528 ret.push(String.fromCharCode(chr)); 1529 } 1530 return ret.join(''); 1531 } 1532 1533 1534 var asmLibraryArg = { 1535 "__assert_fail": ___assert_fail, 1536 "abort": _abort, 1537 "emscripten_asm_const_int": _emscripten_asm_const_int, 1538 "emscripten_memcpy_big": _emscripten_memcpy_big, 1539 "emscripten_resize_heap": _emscripten_resize_heap, 1540 "fd_close": _fd_close, 1541 "fd_seek": _fd_seek, 1542 "fd_write": _fd_write, 1543 "setTempRet0": _setTempRet0 1544 }; 1545 var asm = createWasm(); 1546 /** @type {function(...*):?} */ 1547 var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { 1548 return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["__wasm_call_ctors"]).apply(null, arguments); 1549 }; 1550 1551 /** @type {function(...*):?} */ 1552 var _malloc = Module["_malloc"] = function() { 1553 return (_malloc = Module["_malloc"] = Module["asm"]["malloc"]).apply(null, arguments); 1554 }; 1555 1556 /** @type {function(...*):?} */ 1557 var _free = Module["_free"] = function() { 1558 return (_free = Module["_free"] = Module["asm"]["free"]).apply(null, arguments); 1559 }; 1560 1561 /** @type {function(...*):?} */ 1562 var ___errno_location = Module["___errno_location"] = function() { 1563 return (___errno_location = Module["___errno_location"] = Module["asm"]["__errno_location"]).apply(null, arguments); 1564 }; 1565 1566 /** @type {function(...*):?} */ 1567 var _lnsocket_make_default_initmsg = Module["_lnsocket_make_default_initmsg"] = function() { 1568 return (_lnsocket_make_default_initmsg = Module["_lnsocket_make_default_initmsg"] = Module["asm"]["lnsocket_make_default_initmsg"]).apply(null, arguments); 1569 }; 1570 1571 /** @type {function(...*):?} */ 1572 var _lnsocket_decrypt = Module["_lnsocket_decrypt"] = function() { 1573 return (_lnsocket_decrypt = Module["_lnsocket_decrypt"] = Module["asm"]["lnsocket_decrypt"]).apply(null, arguments); 1574 }; 1575 1576 /** @type {function(...*):?} */ 1577 var _lnsocket_make_ping_msg = Module["_lnsocket_make_ping_msg"] = function() { 1578 return (_lnsocket_make_ping_msg = Module["_lnsocket_make_ping_msg"] = Module["asm"]["lnsocket_make_ping_msg"]).apply(null, arguments); 1579 }; 1580 1581 /** @type {function(...*):?} */ 1582 var _lnsocket_msgbuf = Module["_lnsocket_msgbuf"] = function() { 1583 return (_lnsocket_msgbuf = Module["_lnsocket_msgbuf"] = Module["asm"]["lnsocket_msgbuf"]).apply(null, arguments); 1584 }; 1585 1586 /** @type {function(...*):?} */ 1587 var _lnsocket_encrypt = Module["_lnsocket_encrypt"] = function() { 1588 return (_lnsocket_encrypt = Module["_lnsocket_encrypt"] = Module["asm"]["lnsocket_encrypt"]).apply(null, arguments); 1589 }; 1590 1591 /** @type {function(...*):?} */ 1592 var _lnsocket_create = Module["_lnsocket_create"] = function() { 1593 return (_lnsocket_create = Module["_lnsocket_create"] = Module["asm"]["lnsocket_create"]).apply(null, arguments); 1594 }; 1595 1596 /** @type {function(...*):?} */ 1597 var _lnsocket_destroy = Module["_lnsocket_destroy"] = function() { 1598 return (_lnsocket_destroy = Module["_lnsocket_destroy"] = Module["asm"]["lnsocket_destroy"]).apply(null, arguments); 1599 }; 1600 1601 /** @type {function(...*):?} */ 1602 var _lnsocket_secp = Module["_lnsocket_secp"] = function() { 1603 return (_lnsocket_secp = Module["_lnsocket_secp"] = Module["asm"]["lnsocket_secp"]).apply(null, arguments); 1604 }; 1605 1606 /** @type {function(...*):?} */ 1607 var _lnsocket_genkey = Module["_lnsocket_genkey"] = function() { 1608 return (_lnsocket_genkey = Module["_lnsocket_genkey"] = Module["asm"]["lnsocket_genkey"]).apply(null, arguments); 1609 }; 1610 1611 /** @type {function(...*):?} */ 1612 var _lnsocket_print_errors = Module["_lnsocket_print_errors"] = function() { 1613 return (_lnsocket_print_errors = Module["_lnsocket_print_errors"] = Module["asm"]["lnsocket_print_errors"]).apply(null, arguments); 1614 }; 1615 1616 /** @type {function(...*):?} */ 1617 var _lnsocket_act_two = Module["_lnsocket_act_two"] = function() { 1618 return (_lnsocket_act_two = Module["_lnsocket_act_two"] = Module["asm"]["lnsocket_act_two"]).apply(null, arguments); 1619 }; 1620 1621 /** @type {function(...*):?} */ 1622 var _commando_make_rpc_msg = Module["_commando_make_rpc_msg"] = function() { 1623 return (_commando_make_rpc_msg = Module["_commando_make_rpc_msg"] = Module["asm"]["commando_make_rpc_msg"]).apply(null, arguments); 1624 }; 1625 1626 /** @type {function(...*):?} */ 1627 var _lnsocket_act_one = Module["_lnsocket_act_one"] = function() { 1628 return (_lnsocket_act_one = Module["_lnsocket_act_one"] = Module["asm"]["lnsocket_act_one"]).apply(null, arguments); 1629 }; 1630 1631 /** @type {function(...*):?} */ 1632 var _htonl = Module["_htonl"] = function() { 1633 return (_htonl = Module["_htonl"] = Module["asm"]["htonl"]).apply(null, arguments); 1634 }; 1635 1636 /** @type {function(...*):?} */ 1637 var _htons = Module["_htons"] = function() { 1638 return (_htons = Module["_htons"] = Module["asm"]["htons"]).apply(null, arguments); 1639 }; 1640 1641 /** @type {function(...*):?} */ 1642 var _ntohs = Module["_ntohs"] = function() { 1643 return (_ntohs = Module["_ntohs"] = Module["asm"]["ntohs"]).apply(null, arguments); 1644 }; 1645 1646 /** @type {function(...*):?} */ 1647 var stackSave = Module["stackSave"] = function() { 1648 return (stackSave = Module["stackSave"] = Module["asm"]["stackSave"]).apply(null, arguments); 1649 }; 1650 1651 /** @type {function(...*):?} */ 1652 var stackRestore = Module["stackRestore"] = function() { 1653 return (stackRestore = Module["stackRestore"] = Module["asm"]["stackRestore"]).apply(null, arguments); 1654 }; 1655 1656 /** @type {function(...*):?} */ 1657 var stackAlloc = Module["stackAlloc"] = function() { 1658 return (stackAlloc = Module["stackAlloc"] = Module["asm"]["stackAlloc"]).apply(null, arguments); 1659 }; 1660 1661 /** @type {function(...*):?} */ 1662 var _memalign = Module["_memalign"] = function() { 1663 return (_memalign = Module["_memalign"] = Module["asm"]["memalign"]).apply(null, arguments); 1664 }; 1665 1666 /** @type {function(...*):?} */ 1667 var dynCall_iiiji = Module["dynCall_iiiji"] = function() { 1668 return (dynCall_iiiji = Module["dynCall_iiiji"] = Module["asm"]["dynCall_iiiji"]).apply(null, arguments); 1669 }; 1670 1671 /** @type {function(...*):?} */ 1672 var dynCall_iiij = Module["dynCall_iiij"] = function() { 1673 return (dynCall_iiij = Module["dynCall_iiij"] = Module["asm"]["dynCall_iiij"]).apply(null, arguments); 1674 }; 1675 1676 /** @type {function(...*):?} */ 1677 var dynCall_iijii = Module["dynCall_iijii"] = function() { 1678 return (dynCall_iijii = Module["dynCall_iijii"] = Module["asm"]["dynCall_iijii"]).apply(null, arguments); 1679 }; 1680 1681 /** @type {function(...*):?} */ 1682 var dynCall_iiijiji = Module["dynCall_iiijiji"] = function() { 1683 return (dynCall_iiijiji = Module["dynCall_iiijiji"] = Module["asm"]["dynCall_iiijiji"]).apply(null, arguments); 1684 }; 1685 1686 /** @type {function(...*):?} */ 1687 var dynCall_iiijiii = Module["dynCall_iiijiii"] = function() { 1688 return (dynCall_iiijiii = Module["dynCall_iiijiii"] = Module["asm"]["dynCall_iiijiii"]).apply(null, arguments); 1689 }; 1690 1691 /** @type {function(...*):?} */ 1692 var dynCall_jiji = Module["dynCall_jiji"] = function() { 1693 return (dynCall_jiji = Module["dynCall_jiji"] = Module["asm"]["dynCall_jiji"]).apply(null, arguments); 1694 }; 1695 1696 1697 1698 1699 1700 // === Auto-generated postamble setup entry stuff === 1701 1702 Module["ccall"] = ccall; 1703 Module["cwrap"] = cwrap; 1704 1705 var calledRun; 1706 1707 /** 1708 * @constructor 1709 * @this {ExitStatus} 1710 */ 1711 function ExitStatus(status) { 1712 this.name = "ExitStatus"; 1713 this.message = "Program terminated with exit(" + status + ")"; 1714 this.status = status; 1715 } 1716 1717 var calledMain = false; 1718 1719 dependenciesFulfilled = function runCaller() { 1720 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false) 1721 if (!calledRun) run(); 1722 if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled 1723 }; 1724 1725 /** @type {function(Array=)} */ 1726 function run(args) { 1727 args = args || arguments_; 1728 1729 if (runDependencies > 0) { 1730 return; 1731 } 1732 1733 preRun(); 1734 1735 // a preRun added a dependency, run will be called later 1736 if (runDependencies > 0) { 1737 return; 1738 } 1739 1740 function doRun() { 1741 // run may have just been called through dependencies being fulfilled just in this very frame, 1742 // or while the async setStatus time below was happening 1743 if (calledRun) return; 1744 calledRun = true; 1745 Module['calledRun'] = true; 1746 1747 if (ABORT) return; 1748 1749 initRuntime(); 1750 1751 readyPromiseResolve(Module); 1752 if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); 1753 1754 postRun(); 1755 } 1756 1757 if (Module['setStatus']) { 1758 Module['setStatus']('Running...'); 1759 setTimeout(function() { 1760 setTimeout(function() { 1761 Module['setStatus'](''); 1762 }, 1); 1763 doRun(); 1764 }, 1); 1765 } else 1766 { 1767 doRun(); 1768 } 1769 } 1770 Module['run'] = run; 1771 1772 /** @param {boolean|number=} implicit */ 1773 function exit(status, implicit) { 1774 EXITSTATUS = status; 1775 1776 if (keepRuntimeAlive()) { 1777 } else { 1778 exitRuntime(); 1779 } 1780 1781 procExit(status); 1782 } 1783 1784 function procExit(code) { 1785 EXITSTATUS = code; 1786 if (!keepRuntimeAlive()) { 1787 if (Module['onExit']) Module['onExit'](code); 1788 ABORT = true; 1789 } 1790 quit_(code, new ExitStatus(code)); 1791 } 1792 1793 if (Module['preInit']) { 1794 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']]; 1795 while (Module['preInit'].length > 0) { 1796 Module['preInit'].pop()(); 1797 } 1798 } 1799 1800 run(); 1801 1802 1803 1804 1805 1806 1807 1808 return Module.ready 1809 } 1810 ); 1811 })(); 1812 if (typeof exports === 'object' && typeof module === 'object') 1813 module.exports = Module; 1814 else if (typeof define === 'function' && define['amd']) 1815 define([], function() { return Module; }); 1816 else if (typeof exports === 'object') 1817 exports["Module"] = Module; 1818 1819 async function lnsocket_init() { 1820 const module = await Module() 1821 1822 const ACT_ONE_SIZE = 50 1823 const ACT_TWO_SIZE = 50 1824 const ACT_THREE_SIZE = 66 1825 const DEFAULT_TIMEOUT = 3000 1826 1827 const COMMANDO_REPLY_CONTINUES = 0x594b 1828 const COMMANDO_REPLY_TERM = 0x594d 1829 1830 const lnsocket_create = module.cwrap("lnsocket_create", "number") 1831 const lnsocket_encrypt = module.cwrap("lnsocket_encrypt", "number", ["int", "array", "int", "int"]) 1832 const lnsocket_decrypt = module.cwrap("lnsocket_decrypt", "number", ["int", "array", "int"]) 1833 const lnsocket_msgbuf = module.cwrap("lnsocket_msgbuf", "number", ["int"]) 1834 const lnsocket_act_one = module.cwrap("lnsocket_act_one", "number", ["number", "string"]) 1835 const lnsocket_act_two = module.cwrap("lnsocket_act_two", "number", ["number", "array"]) 1836 const lnsocket_print_errors = module.cwrap("lnsocket_print_errors", "int") 1837 const lnsocket_genkey = module.cwrap("lnsocket_genkey", "int") 1838 const lnsocket_make_default_initmsg = module.cwrap("lnsocket_make_default_initmsg", "int", ["int", "int"]) 1839 const lnsocket_make_ping_msg = module.cwrap("lnsocket_make_ping_msg", "int", ["int", "int", "int", "int"]) 1840 const commando_make_rpc_msg = module.cwrap("commando_make_rpc_msg", "int", ["string", "string", "string", "number", "int", "int"]) 1841 1842 function concat_u8_arrays(arrays) { 1843 // sum of individual array lengths 1844 let totalLength = arrays.reduce((acc, value) => acc + value.length, 0); 1845 1846 if (!arrays.length) return null; 1847 1848 let result = new Uint8Array(totalLength); 1849 1850 let length = 0; 1851 for (let array of arrays) { 1852 result.set(array, length); 1853 length += array.length; 1854 } 1855 1856 return result; 1857 } 1858 1859 function queue_recv(queue) { 1860 return new Promise((resolve, reject) => { 1861 const checker = setInterval(() => { 1862 const val = queue.shift() 1863 if (val) { 1864 clearInterval(checker) 1865 resolve(val) 1866 } 1867 }, 5); 1868 }) 1869 } 1870 1871 function parse_msgtype(buf) { 1872 return buf[0] << 8 | buf[1] 1873 } 1874 1875 function wasm_mem(ptr, size) { 1876 return new Uint8Array(module.HEAPU8.buffer, ptr, size); 1877 } 1878 1879 function LNSocket(opts) { 1880 if (!(this instanceof LNSocket)) 1881 return new LNSocket(opts) 1882 1883 this.opts = opts || { 1884 timeout: DEFAULT_TIMEOUT 1885 } 1886 this.queue = [] 1887 this.ln = lnsocket_create() 1888 } 1889 1890 LNSocket.prototype.print_errors = function _lnsocket_print_errors() { 1891 lnsocket_print_errors(this.ln) 1892 } 1893 1894 LNSocket.prototype.genkey = function _lnsocket_genkey() { 1895 lnsocket_genkey(this.ln) 1896 } 1897 1898 LNSocket.prototype.act_one_data = function _lnsocket_act_one(node_id) { 1899 const act_one_ptr = lnsocket_act_one(this.ln, node_id) 1900 if (act_one_ptr === 0) 1901 return null 1902 return wasm_mem(act_one_ptr, ACT_ONE_SIZE) 1903 } 1904 1905 LNSocket.prototype.act_two = function _lnsocket_act_two(act2) { 1906 const act_three_ptr = lnsocket_act_two(this.ln, new Uint8Array(act2)) 1907 if (act_three_ptr === 0) { 1908 this.print_errors() 1909 return null 1910 } 1911 return wasm_mem(act_three_ptr, ACT_THREE_SIZE) 1912 } 1913 1914 LNSocket.prototype.connect = async function lnsocket_connect(node_id, host) { 1915 await handle_connect(this, node_id, host) 1916 1917 const act1 = this.act_one_data(node_id) 1918 this.ws.send(act1) 1919 const act2 = await this.read_clear() 1920 if (act2.byteLength != ACT_TWO_SIZE) { 1921 throw new Error(`expected act2 to be ${ACT_TWO_SIZE} long, got ${act2.length}`) 1922 } 1923 const act3 = this.act_two(act2) 1924 this.ws.send(act3) 1925 } 1926 1927 LNSocket.prototype.connect_and_init = async function _connect_and_init(node_id, host) { 1928 await this.connect(node_id, host) 1929 await this.perform_init() 1930 } 1931 1932 LNSocket.prototype.rpc = async function lnsocket_rpc(opts) { 1933 const msg = this.make_commando_msg(opts) 1934 this.write(msg) 1935 return JSON.parse(await this.read_all_rpc()) 1936 } 1937 1938 LNSocket.prototype.recv = async function lnsocket_recv() { 1939 const msg = await this.read() 1940 console.log("recv", msg) 1941 const msgtype = parse_msgtype(msg.slice(0,2)) 1942 return [msgtype, msg.slice(2)] 1943 } 1944 1945 LNSocket.prototype.read_all_rpc = async function read_all_rpc() { 1946 let chunks = [] 1947 while (true) { 1948 const [typ, msg] = await this.recv() 1949 switch (typ) { 1950 case COMMANDO_REPLY_TERM: 1951 chunks.push(msg.slice(8)) 1952 return new TextDecoder().decode(concat_u8_arrays(chunks)); 1953 case COMMANDO_REPLY_CONTINUES: 1954 chunks.push(msg.slice(8)) 1955 break 1956 default: 1957 console.log("got unknown type", typ) 1958 continue 1959 } 1960 } 1961 } 1962 1963 LNSocket.prototype.make_commando_msg = function _lnsocket_make_commando_msg(opts) { 1964 const buflen = 4096 1965 let len = 0; 1966 const buf = module._malloc(buflen); 1967 module.HEAPU8.set(Uint8Array, buf); 1968 1969 const params = JSON.stringify(opts.params||{}) 1970 if (!(len = commando_make_rpc_msg(opts.method, params, opts.rune, 1971 0, buf, buflen))) { 1972 throw new Error("couldn't make commando msg"); 1973 } 1974 1975 const dat = wasm_mem(buf, len) 1976 module._free(buf); 1977 return dat 1978 } 1979 1980 LNSocket.prototype.make_ping_msg = function _lnsocket_make_ping_msg(num_pong_bytes=1, ignored_bytes=1) { 1981 const buflen = 32 1982 let len = 0; 1983 const buf = module._malloc(buflen); 1984 module.HEAPU8.set(Uint8Array, buf); 1985 1986 if (!(len = lnsocket_make_ping_msg(buf, buflen, num_pong_bytes, ignored_bytes))) 1987 throw new Error("couldn't make ping msg"); 1988 1989 const dat = wasm_mem(buf, len) 1990 module._free(buf); 1991 return dat 1992 } 1993 1994 LNSocket.prototype.encrypt = function _lnsocket_encrypt(dat) { 1995 const len = lnsocket_encrypt(this.ln, dat, dat.length) 1996 if (len === 0) { 1997 this.print_errors() 1998 throw new Error("encrypt error") 1999 } 2000 const enc = wasm_mem(lnsocket_msgbuf(this.ln), len) 2001 return enc 2002 } 2003 2004 LNSocket.prototype.decrypt = function _lnsocket_decrypt(dat) { 2005 const len = lnsocket_decrypt(this.ln, dat, dat.length) 2006 if (len === 0) { 2007 this.print_errors() 2008 throw new Error("decrypt error") 2009 } 2010 return wasm_mem(lnsocket_msgbuf(this.ln), len) 2011 } 2012 2013 LNSocket.prototype.write = function _lnsocket_write(dat) { 2014 this.ws.send(this.encrypt(dat)) 2015 } 2016 2017 LNSocket.prototype.read_clear = async function _lnsocket_read() { 2018 return (await queue_recv(this.queue)) 2019 } 2020 2021 LNSocket.prototype.read = async function _lnsocket_read() { 2022 const enc = await this.read_clear() 2023 return this.decrypt(new Uint8Array(enc)) 2024 } 2025 2026 LNSocket.prototype.make_default_initmsg = function _lnsocket_make_default_initmsg() { 2027 const buflen = 1024 2028 let len = 0; 2029 const buf = module._malloc(buflen); 2030 module.HEAPU8.set(Uint8Array, buf); 2031 2032 if (!(len = lnsocket_make_default_initmsg(buf, buflen))) 2033 throw new Error("couldn't make initmsg"); 2034 2035 const dat = wasm_mem(buf, len) 2036 module._free(buf); 2037 return dat 2038 } 2039 2040 LNSocket.prototype.perform_init = async function lnsocket_connect() { 2041 await this.read() 2042 const our_init = this.make_default_initmsg() 2043 console.log("our_init", our_init) 2044 this.write(our_init) 2045 } 2046 2047 LNSocket.prototype.ping_pong = async function lnsocket_ping_pong() { 2048 const pingmsg = this.make_ping_msg() 2049 console.log("ping", pingmsg) 2050 this.write(pingmsg) 2051 return await this.read() 2052 } 2053 2054 function handle_connect(ln, node_id, host) { 2055 const ws = new WebSocket(`ws://${host}`) 2056 return new Promise((resolve, reject) => { 2057 ws.onmessage = (v) => { 2058 ln.queue.push(v.data.arrayBuffer()) 2059 } 2060 2061 ws.addEventListener('open', function(ev) { 2062 ln.ws = ws 2063 resolve(ws) 2064 }); 2065 2066 ws.addEventListener('close', function(ev) { 2067 reject() 2068 }); 2069 2070 const timeout = ln.opts.timeout || DEFAULT_TIMEOUT 2071 setTimeout(reject, timeout); 2072 }) 2073 } 2074 2075 return LNSocket 2076 } 2077 2078 Module.init = lnsocket_init