frameos-wasm 2026.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4208 @@
1
+ // This code implements the `-sMODULARIZE` settings by taking the generated
2
+ // JS program code (INNER_JS_CODE) and wrapping it in a factory function.
3
+
4
+ // When targeting node and ES6 we use `await import ..` in the generated code
5
+ // so the outer function needs to be marked as async.
6
+ async function createFrameOS(moduleArg = {}) {
7
+ var Module = moduleArg;
8
+ // include: shell.js
9
+ // include: minimum_runtime_check.js
10
+ // end include: minimum_runtime_check.js
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(moduleArg) => Promise<Module>
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
+
25
+ // Determine the runtime environment we are in. You can customize this by
26
+ // setting the ENVIRONMENT setting at compile time (see settings.js).
27
+
28
+ // Attempt to auto-detect the environment
29
+ var ENVIRONMENT_IS_WEB = !!globalThis.window;
30
+ var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;
31
+ // N.b. Electron.js environment is simultaneously a NODE-environment, but
32
+ // also a web environment.
33
+ var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != 'renderer';
34
+ var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
35
+
36
+ // --pre-jses are emitted after the Module integration code, so that they can
37
+ // refer to Module (if they choose; they can also define Module)
38
+
39
+
40
+ var programArgs = [];
41
+ var thisProgram = './this.program';
42
+ var quit_ = (status, toThrow) => {
43
+ throw toThrow;
44
+ };
45
+
46
+ var _scriptName = import.meta.url;
47
+
48
+ // `/` should be present at the end if `scriptDirectory` is not empty
49
+ var scriptDirectory = '';
50
+ function locateFile(path) {
51
+ if (Module['locateFile']) {
52
+ return Module['locateFile'](path, scriptDirectory);
53
+ }
54
+ return scriptDirectory + path;
55
+ }
56
+
57
+ // Hooks that are implemented differently in different runtime environments.
58
+ var readAsync, readBinary;
59
+
60
+ // Note that this includes Node.js workers when relevant (pthreads is enabled).
61
+ // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
62
+ // ENVIRONMENT_IS_NODE.
63
+ if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
64
+ try {
65
+ scriptDirectory = new URL('.', _scriptName).href; // includes trailing slash
66
+ } catch {
67
+ // Must be a `blob:` or `data:` URL (e.g. `blob:http://site.com/etc/etc`), we cannot
68
+ // infer anything from them.
69
+ }
70
+
71
+ {
72
+ // include: web_or_worker_shell_read.js
73
+ if (ENVIRONMENT_IS_WORKER) {
74
+ readBinary = (url) => {
75
+ var xhr = new XMLHttpRequest();
76
+ xhr.open('GET', url, false);
77
+ xhr.responseType = 'arraybuffer';
78
+ xhr.send(null);
79
+ return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
80
+ };
81
+ }
82
+
83
+ readAsync = async (url) => {
84
+ var response = await fetch(url, { credentials: 'same-origin' });
85
+ if (response.ok) {
86
+ return response.arrayBuffer();
87
+ }
88
+ throw new Error(response.status + ' : ' + response.url);
89
+ };
90
+ // end include: web_or_worker_shell_read.js
91
+ }
92
+ } else
93
+ {
94
+ }
95
+
96
+ var out = console.log.bind(console);
97
+ var err = console.error.bind(console);
98
+
99
+ // end include: shell.js
100
+
101
+ // include: preamble.js
102
+ // === Preamble library stuff ===
103
+
104
+ // Documentation for the public APIs defined in this file must be updated in:
105
+ // site/source/docs/api_reference/preamble.js.rst
106
+ // A prebuilt local version of the documentation is available at:
107
+ // site/build/text/docs/api_reference/preamble.js.txt
108
+ // You can also build docs locally as HTML or other formats in site/
109
+ // An online HTML version (which may be of a different version of Emscripten)
110
+ // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
111
+
112
+ var wasmBinary;
113
+
114
+ // Wasm globals
115
+
116
+ //========================================
117
+ // Runtime essentials
118
+ //========================================
119
+
120
+ // whether we are quitting the application. no code should run after this.
121
+ // set in exit() and abort()
122
+ var ABORT = false;
123
+
124
+ // set by exit() and abort(). Passed to 'onExit' handler.
125
+ // NOTE: This is also used as the process return code in shell environments
126
+ // but only when noExitRuntime is false.
127
+ var EXITSTATUS;
128
+
129
+ // In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we
130
+ // don't define it at all in release modes. This matches the behaviour of
131
+ // MINIMAL_RUNTIME.
132
+ // TODO(sbc): Make this the default even without STRICT enabled.
133
+ /** @type {function(*, string=)} */
134
+ function assert(condition, text) {
135
+ if (!condition) {
136
+ // This build was created without ASSERTIONS defined. `assert()` should not
137
+ // ever be called in this configuration but in case there are callers in
138
+ // the wild leave this simple abort() implementation here for now.
139
+ abort(text);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Indicates whether filename is delivered via file protocol (as opposed to http/https)
145
+ * @noinline
146
+ */
147
+ var isFileURI = (filename) => filename.startsWith('file://');
148
+
149
+ // include: runtime_common.js
150
+ // include: runtime_stack_check.js
151
+ // end include: runtime_stack_check.js
152
+ // include: runtime_exceptions.js
153
+ // Base Emscripten EH error class
154
+ class EmscriptenEH {}
155
+
156
+ class EmscriptenSjLj extends EmscriptenEH {}
157
+
158
+ // end include: runtime_exceptions.js
159
+ // include: runtime_debug.js
160
+ // end include: runtime_debug.js
161
+ // Memory management
162
+
163
+ var runtimeInitialized = false;
164
+
165
+
166
+
167
+ // When ALLOW_MEMORY_GROWTH is enabled, the conversion from Wasm
168
+ // memory to ArrayBuffer requires some additional logic.
169
+ function getMemoryBuffer() {
170
+ return wasmMemory.buffer;
171
+ }
172
+
173
+ function updateMemoryViews() {
174
+ // If we already have a heap that is resizeable/growable buffer we don't
175
+ // need to do anything in updateMemoryViews.
176
+ if (HEAP8?.buffer?.resizable) return;
177
+ var b = getMemoryBuffer();
178
+ HEAP8 = new Int8Array(b);
179
+ HEAP16 = new Int16Array(b);
180
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
181
+ HEAPU16 = new Uint16Array(b);
182
+ HEAP32 = new Int32Array(b);
183
+ HEAPU32 = new Uint32Array(b);
184
+ HEAPF32 = new Float32Array(b);
185
+ HEAPF64 = new Float64Array(b);
186
+ HEAP64 = new BigInt64Array(b);
187
+ HEAPU64 = new BigUint64Array(b);
188
+ }
189
+
190
+ // include: memoryprofiler.js
191
+ // end include: memoryprofiler.js
192
+ // end include: runtime_common.js
193
+ function preRun() {
194
+ // No ATPRERUNS hooks
195
+ }
196
+
197
+ function initRuntime() {
198
+ runtimeInitialized = true;
199
+
200
+ // Begin ATINITS hooks
201
+ if (!Module['noFSInit'] && !FS.initialized) FS.init();
202
+ TTY.init();
203
+ // End ATINITS hooks
204
+
205
+ wasmExports['__wasm_call_ctors']();
206
+
207
+ // Begin ATPOSTCTORS hooks
208
+ FS.ignorePermissions = false;
209
+ // End ATPOSTCTORS hooks
210
+
211
+ }
212
+
213
+ function postRun() {
214
+
215
+ // No ATPOSTRUNS hooks
216
+ }
217
+
218
+ /**
219
+ * @param {string|number=} what
220
+ */
221
+ function abort(what) {
222
+ Module['onAbort']?.(what);
223
+
224
+ what = `Aborted(${what})`;
225
+ // TODO(sbc): Should we remove printing and leave it up to whoever
226
+ // catches the exception?
227
+ err(what);
228
+
229
+ ABORT = true;
230
+
231
+ what += '. Build with -sASSERTIONS for more info.';
232
+
233
+ // Use a wasm runtime error, because a JS error might be seen as a foreign
234
+ // exception, which means we'd run destructors on it. We need the error to
235
+ // simply make the program stop.
236
+ // FIXME This approach does not work in Wasm EH because it currently does not assume
237
+ // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
238
+ // a trap or not based on a hidden field within the object. So at the moment
239
+ // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
240
+ // allows this in the wasm spec.
241
+
242
+ // Suppress closure compiler warning here. Closure compiler's builtin extern
243
+ // definition for WebAssembly.RuntimeError claims it takes no arguments even
244
+ // though it can.
245
+ // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
246
+ /** @suppress {checkTypes} */
247
+ var e = new WebAssembly.RuntimeError(what);
248
+
249
+ // Throw the error whether or not MODULARIZE is set because abort is used
250
+ // in code paths apart from instantiation where an exception is expected
251
+ // to be thrown when abort is called.
252
+ throw e;
253
+ }
254
+
255
+ var wasmBinaryFile;
256
+
257
+ function findWasmBinary() {
258
+
259
+ if (Module['locateFile']) {
260
+ return locateFile('frameos.wasm');
261
+ }
262
+
263
+ // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too.
264
+ return new URL('frameos.wasm', import.meta.url).href;
265
+
266
+ }
267
+
268
+ function getBinarySync(file) {
269
+ if (file == wasmBinaryFile && wasmBinary) {
270
+ return new Uint8Array(wasmBinary);
271
+ }
272
+ if (readBinary) {
273
+ return readBinary(file);
274
+ }
275
+ // Throwing a plain string here, even though it not normally advisable since
276
+ // this gets turning into an `abort` in instantiateArrayBuffer.
277
+ throw 'both async and sync fetching of the wasm failed';
278
+ }
279
+
280
+ async function getWasmBinary(binaryFile) {
281
+ // If we don't have the binary yet, load it asynchronously using readAsync.
282
+ if (!wasmBinary) {
283
+ // Fetch the binary using readAsync
284
+ try {
285
+ var response = await readAsync(binaryFile);
286
+ return new Uint8Array(response);
287
+ } catch {
288
+ // Fall back to getBinarySync below;
289
+ }
290
+ }
291
+
292
+ // Otherwise, getBinarySync should be able to get it synchronously
293
+ return getBinarySync(binaryFile);
294
+ }
295
+
296
+ async function instantiateArrayBuffer(binaryFile, imports) {
297
+ try {
298
+ var binary = await getWasmBinary(binaryFile);
299
+ var instance = await WebAssembly.instantiate(binary, imports);
300
+ return instance;
301
+ } catch (reason) {
302
+ err(`failed to asynchronously prepare wasm: ${reason}`);
303
+
304
+ abort(reason);
305
+ }
306
+ }
307
+
308
+ async function instantiateAsync(binary, binaryFile, imports) {
309
+ if (!binary
310
+ ) {
311
+ try {
312
+ var response = fetch(binaryFile, { credentials: 'same-origin' });
313
+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
314
+ return instantiationResult;
315
+ } catch (reason) {
316
+ // We expect the most common failure cause to be a bad MIME type for the binary,
317
+ // in which case falling back to ArrayBuffer instantiation should work.
318
+ err(`wasm streaming compile failed: ${reason}`);
319
+ err('falling back to ArrayBuffer instantiation');
320
+ // fall back of instantiateArrayBuffer below
321
+ };
322
+ }
323
+ return instantiateArrayBuffer(binaryFile, imports);
324
+ }
325
+
326
+ function getWasmImports() {
327
+ // prepare imports
328
+ var imports = {
329
+ 'env': wasmImports,
330
+ 'wasi_snapshot_preview1': wasmImports,
331
+ };
332
+ return imports;
333
+ }
334
+
335
+ // Create the wasm instance.
336
+ // Receives the wasm imports, returns the exports.
337
+ async function createWasm() {
338
+ // Load the wasm module and create an instance of using native support in the JS engine.
339
+ // handle a generated wasm instance, receiving its exports and
340
+ // performing other necessary setup
341
+ function receiveInstance(instance) {
342
+ wasmExports = instance.exports;
343
+
344
+ assignWasmExports(wasmExports);
345
+
346
+ updateMemoryViews();
347
+
348
+ return wasmExports;
349
+ }
350
+
351
+ // Prefer streaming instantiation if available.
352
+ function receiveInstantiationResult(result) {
353
+ // 'result' is a ResultObject object which has both the module and instance.
354
+ // receiveInstance() will swap in the exports (to Module.asm) so they can be called
355
+ // 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.
356
+ // When the regression is fixed, can restore the above PTHREADS-enabled path.
357
+ return receiveInstance(result['instance']);
358
+ }
359
+
360
+ var info = getWasmImports();
361
+
362
+ wasmBinaryFile ??= findWasmBinary();
363
+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
364
+ var exports = receiveInstantiationResult(result);
365
+ return exports;
366
+ }
367
+
368
+ // end include: preamble.js
369
+
370
+ // Begin JS library code
371
+
372
+
373
+ class ExitStatus {
374
+ name = 'ExitStatus';
375
+ constructor(status) {
376
+ this.message = `Program terminated with exit(${status})`;
377
+ this.status = status;
378
+ }
379
+ }
380
+
381
+ /** @type {!Int16Array} */
382
+ var HEAP16;
383
+
384
+ /** @type {!Int32Array} */
385
+ var HEAP32;
386
+
387
+ /** not-@type {!BigInt64Array} */
388
+ var HEAP64;
389
+
390
+ /** @type {!Int8Array} */
391
+ var HEAP8;
392
+
393
+ /** @type {!Float32Array} */
394
+ var HEAPF32;
395
+
396
+ /** @type {!Float64Array} */
397
+ var HEAPF64;
398
+
399
+ /** @type {!Uint16Array} */
400
+ var HEAPU16;
401
+
402
+ /** @type {!Uint32Array} */
403
+ var HEAPU32;
404
+
405
+ /** not-@type {!BigUint64Array} */
406
+ var HEAPU64;
407
+
408
+ /** @type {!Uint8Array} */
409
+ var HEAPU8;
410
+
411
+ var callRuntimeCallbacks = (callbacks) => {
412
+ while (callbacks.length > 0) {
413
+ // Pass the module as the first argument.
414
+ callbacks.shift()(Module);
415
+ }
416
+ };
417
+
418
+
419
+ /**
420
+ * @param {number} ptr
421
+ * @param {string} type
422
+ */
423
+ function getValue(ptr, type = 'i8') {
424
+ if (type.endsWith('*')) type = '*';
425
+ switch (type) {
426
+ case 'i1': return HEAP8[ptr];
427
+ case 'i8': return HEAP8[ptr];
428
+ case 'i16': return HEAP16[((ptr)>>1)];
429
+ case 'i32': return HEAP32[((ptr)>>2)];
430
+ case 'i64': return HEAP64[((ptr)>>3)];
431
+ case 'float': return HEAPF32[((ptr)>>2)];
432
+ case 'double': return HEAPF64[((ptr)>>3)];
433
+ case '*': return HEAPU32[((ptr)>>2)];
434
+ default: abort(`invalid type for getValue: ${type}`);
435
+ }
436
+ }
437
+
438
+
439
+ /**
440
+ * @param {number} ptr
441
+ * @param {number} value
442
+ * @param {string} type
443
+ */
444
+ function setValue(ptr, value, type = 'i8') {
445
+ if (type.endsWith('*')) type = '*';
446
+ switch (type) {
447
+ case 'i1': HEAP8[ptr] = value; break;
448
+ case 'i8': HEAP8[ptr] = value; break;
449
+ case 'i16': HEAP16[((ptr)>>1)] = value; break;
450
+ case 'i32': HEAP32[((ptr)>>2)] = value; break;
451
+ case 'i64': HEAP64[((ptr)>>3)] = BigInt(value); break;
452
+ case 'float': HEAPF32[((ptr)>>2)] = value; break;
453
+ case 'double': HEAPF64[((ptr)>>3)] = value; break;
454
+ case '*': HEAPU32[((ptr)>>2)] = value; break;
455
+ default: abort(`invalid type for setValue: ${type}`);
456
+ }
457
+ }
458
+
459
+ var stackRestore = (val) => __emscripten_stack_restore(val);
460
+
461
+ var stackSave = () => _emscripten_stack_get_current();
462
+
463
+
464
+
465
+ var UTF8Decoder = globalThis.TextDecoder && new TextDecoder();
466
+
467
+
468
+ /**
469
+ * heapOrArray is either a regular array, or a JavaScript typed array view.
470
+ * @param {number} idx
471
+ * @param {number=} maxBytesToRead
472
+ * @param {boolean=} ignoreNul
473
+ * @return {number}
474
+ */
475
+ var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {
476
+ var maxIdx = idx + maxBytesToRead;
477
+ if (ignoreNul) return maxIdx;
478
+ // TextDecoder needs to know the byte length in advance, it doesn't stop on
479
+ // null terminator by itself.
480
+ // As a tiny code save trick, compare idx against maxIdx using a negation,
481
+ // so that maxBytesToRead=undefined/NaN means Infinity.
482
+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;
483
+ return idx;
484
+ };
485
+
486
+ /**
487
+ * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given
488
+ * array that contains uint8 values, returns a copy of that string as a
489
+ * Javascript String object.
490
+ * heapOrArray is either a regular array, or a JavaScript typed array view.
491
+ * @param {number=} idx
492
+ * @param {number=} maxBytesToRead
493
+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.
494
+ * @return {string}
495
+ */
496
+ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {
497
+
498
+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);
499
+
500
+ // When using conditional TextDecoder, skip it for short strings as the overhead of the native call is not worth it.
501
+ if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
502
+ return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
503
+ }
504
+ var str = '';
505
+ while (idx < endPtr) {
506
+ // For UTF8 byte structure, see:
507
+ // http://en.wikipedia.org/wiki/UTF-8#Description
508
+ // https://www.ietf.org/rfc/rfc2279.txt
509
+ // https://tools.ietf.org/html/rfc3629
510
+ var u0 = heapOrArray[idx++];
511
+ if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
512
+ var u1 = heapOrArray[idx++] & 63;
513
+ if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
514
+ var u2 = heapOrArray[idx++] & 63;
515
+ if ((u0 & 0xF0) == 0xE0) {
516
+ u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
517
+ } else {
518
+ u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
519
+ }
520
+
521
+ if (u0 < 0x10000) {
522
+ str += String.fromCharCode(u0);
523
+ } else {
524
+ var ch = u0 - 0x10000;
525
+ str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
526
+ }
527
+ }
528
+ return str;
529
+ };
530
+
531
+ /**
532
+ * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the
533
+ * emscripten HEAP, returns a copy of that string as a Javascript String object.
534
+ *
535
+ * @param {number} ptr
536
+ * @param {number=} maxBytesToRead - An optional length that specifies the
537
+ * maximum number of bytes to read. You can omit this parameter to scan the
538
+ * string until the first 0 byte. If maxBytesToRead is passed, and the string
539
+ * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the
540
+ * string will cut short at that byte index.
541
+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.
542
+ * @return {string}
543
+ */
544
+ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {
545
+ return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead, ignoreNul) : '';
546
+ };
547
+ var ___assert_fail = (condition, filename, line, func) =>
548
+ abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
549
+
550
+ var syscallGetVarargI = () => {
551
+ // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.
552
+ var ret = HEAP32[((+SYSCALLS.varargs)>>2)];
553
+ SYSCALLS.varargs += 4;
554
+ return ret;
555
+ };
556
+ var syscallGetVarargP = syscallGetVarargI;
557
+
558
+
559
+ var PATH = {
560
+ isAbs:(path) => path.charAt(0) === '/',
561
+ splitPath:(filename) => {
562
+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
563
+ return splitPathRe.exec(filename).slice(1);
564
+ },
565
+ normalizeArray:(parts, allowAboveRoot) => {
566
+ // if the path tries to go above the root, `up` ends up > 0
567
+ var up = 0;
568
+ for (var i = parts.length - 1; i >= 0; i--) {
569
+ var last = parts[i];
570
+ if (last === '.') {
571
+ parts.splice(i, 1);
572
+ } else if (last === '..') {
573
+ parts.splice(i, 1);
574
+ up++;
575
+ } else if (up) {
576
+ parts.splice(i, 1);
577
+ up--;
578
+ }
579
+ }
580
+ // if the path is allowed to go above the root, restore leading ..s
581
+ if (allowAboveRoot) {
582
+ for (; up; up--) {
583
+ parts.unshift('..');
584
+ }
585
+ }
586
+ return parts;
587
+ },
588
+ normalize:(path) => {
589
+ var isAbsolute = PATH.isAbs(path),
590
+ trailingSlash = path.slice(-1) === '/';
591
+ // Normalize the path
592
+ path = PATH.normalizeArray(path.split('/').filter((p) => !!p), !isAbsolute).join('/');
593
+ if (!path && !isAbsolute) {
594
+ path = '.';
595
+ }
596
+ if (path && trailingSlash) {
597
+ path += '/';
598
+ }
599
+ return (isAbsolute ? '/' : '') + path;
600
+ },
601
+ dirname:(path) => {
602
+ var result = PATH.splitPath(path),
603
+ root = result[0],
604
+ dir = result[1];
605
+ if (!root && !dir) {
606
+ // No dirname whatsoever
607
+ return '.';
608
+ }
609
+ if (dir) {
610
+ // It has a dirname, strip trailing slash
611
+ dir = dir.slice(0, -1);
612
+ }
613
+ return root + dir;
614
+ },
615
+ basename:(path) => path && path.match(/([^\/]+|\/)\/*$/)[1],
616
+ join:(...paths) => PATH.normalize(paths.join('/')),
617
+ join2:(l, r) => PATH.normalize(l + '/' + r),
618
+ };
619
+
620
+ var initRandomFill = () => {
621
+
622
+ return (view) => (crypto.getRandomValues(view), 0);
623
+ };
624
+ var randomFill = (view) => (randomFill = initRandomFill())(view);
625
+
626
+
627
+
628
+ var PATH_FS = {
629
+ resolve:(...args) => {
630
+ var resolvedPath = '',
631
+ resolvedAbsolute = false;
632
+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
633
+ var path = (i >= 0) ? args[i] : FS.cwd();
634
+ // Skip empty and invalid entries
635
+ if (typeof path != 'string') {
636
+ throw new TypeError('Arguments to path.resolve must be strings');
637
+ } else if (!path) {
638
+ return ''; // an invalid portion invalidates the whole thing
639
+ }
640
+ resolvedPath = path + '/' + resolvedPath;
641
+ resolvedAbsolute = PATH.isAbs(path);
642
+ }
643
+ // At this point the path should be resolved to a full absolute path, but
644
+ // handle relative paths to be safe (might happen when process.cwd() fails)
645
+ resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter((p) => !!p), !resolvedAbsolute).join('/');
646
+ return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
647
+ },
648
+ relative:(from, to) => {
649
+ from = PATH_FS.resolve(from).slice(1);
650
+ to = PATH_FS.resolve(to).slice(1);
651
+ function trim(arr) {
652
+ var start = 0;
653
+ for (; start < arr.length; start++) {
654
+ if (arr[start] !== '') break;
655
+ }
656
+ var end = arr.length - 1;
657
+ for (; end >= 0; end--) {
658
+ if (arr[end] !== '') break;
659
+ }
660
+ if (start > end) return [];
661
+ return arr.slice(start, end - start + 1);
662
+ }
663
+ var fromParts = trim(from.split('/'));
664
+ var toParts = trim(to.split('/'));
665
+ var length = Math.min(fromParts.length, toParts.length);
666
+ var samePartsLength = length;
667
+ for (var i = 0; i < length; i++) {
668
+ if (fromParts[i] !== toParts[i]) {
669
+ samePartsLength = i;
670
+ break;
671
+ }
672
+ }
673
+ var outputParts = [];
674
+ for (var i = samePartsLength; i < fromParts.length; i++) {
675
+ outputParts.push('..');
676
+ }
677
+ outputParts = outputParts.concat(toParts.slice(samePartsLength));
678
+ return outputParts.join('/');
679
+ },
680
+ };
681
+
682
+
683
+
684
+ var FS_stdin_getChar_buffer = [];
685
+
686
+ var lengthBytesUTF8 = (str) => {
687
+ var len = 0;
688
+ for (var i = 0; i < str.length; ++i) {
689
+ // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
690
+ // unit, not a Unicode code point of the character! So decode
691
+ // UTF16->UTF32->UTF8.
692
+ // See http://unicode.org/faq/utf_bom.html#utf16-3
693
+ var c = str.charCodeAt(i); // possibly a lead surrogate
694
+ if (c <= 0x7F) {
695
+ len++;
696
+ } else if (c <= 0x7FF) {
697
+ len += 2;
698
+ } else if (c >= 0xD800 && c <= 0xDFFF) {
699
+ len += 4; ++i;
700
+ } else {
701
+ len += 3;
702
+ }
703
+ }
704
+ return len;
705
+ };
706
+
707
+ var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
708
+ // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
709
+ // undefined and false each don't write out any bytes.
710
+ if (!(maxBytesToWrite > 0))
711
+ return 0;
712
+
713
+ var startIdx = outIdx;
714
+ var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
715
+ for (var i = 0; i < str.length; ++i) {
716
+ // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
717
+ // and https://www.ietf.org/rfc/rfc2279.txt
718
+ // and https://tools.ietf.org/html/rfc3629
719
+ var u = str.codePointAt(i);
720
+ if (u <= 0x7F) {
721
+ if (outIdx >= endIdx) break;
722
+ heap[outIdx++] = u;
723
+ } else if (u <= 0x7FF) {
724
+ if (outIdx + 1 >= endIdx) break;
725
+ heap[outIdx++] = 0xC0 | (u >> 6);
726
+ heap[outIdx++] = 0x80 | (u & 63);
727
+ } else if (u <= 0xFFFF) {
728
+ if (outIdx + 2 >= endIdx) break;
729
+ heap[outIdx++] = 0xE0 | (u >> 12);
730
+ heap[outIdx++] = 0x80 | ((u >> 6) & 63);
731
+ heap[outIdx++] = 0x80 | (u & 63);
732
+ } else {
733
+ if (outIdx + 3 >= endIdx) break;
734
+ heap[outIdx++] = 0xF0 | (u >> 18);
735
+ heap[outIdx++] = 0x80 | ((u >> 12) & 63);
736
+ heap[outIdx++] = 0x80 | ((u >> 6) & 63);
737
+ heap[outIdx++] = 0x80 | (u & 63);
738
+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.
739
+ // We need to manually skip over the second code unit for correct iteration.
740
+ i++;
741
+ }
742
+ }
743
+ // Null-terminate the pointer to the buffer.
744
+ heap[outIdx] = 0;
745
+ return outIdx - startIdx;
746
+ };
747
+ /** @type {function(string, boolean=, number=)} */
748
+ var intArrayFromString = (stringy, dontAddNull, length) => {
749
+ var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
750
+ var u8array = new Array(len);
751
+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
752
+ if (dontAddNull) u8array.length = numBytesWritten;
753
+ return u8array;
754
+ };
755
+ var FS_stdin_getChar = () => {
756
+ if (!FS_stdin_getChar_buffer.length) {
757
+ var result = null;
758
+ if (globalThis.window?.prompt) {
759
+ // Browser.
760
+ result = window.prompt('Input: '); // returns null on cancel
761
+ if (result !== null) {
762
+ result += '\n';
763
+ }
764
+ } else
765
+ {}
766
+ if (!result) {
767
+ return null;
768
+ }
769
+ FS_stdin_getChar_buffer = intArrayFromString(result, true);
770
+ }
771
+ return FS_stdin_getChar_buffer.shift();
772
+ };
773
+ var TTY = {
774
+ ttys:[],
775
+ init() {
776
+ // https://github.com/emscripten-core/emscripten/pull/1555
777
+ // if (ENVIRONMENT_IS_NODE) {
778
+ // // currently, FS.init does not distinguish if process.stdin is a file or TTY
779
+ // // device, it always assumes it's a TTY device. because of this, we're forcing
780
+ // // process.stdin to UTF8 encoding to at least make stdin reading compatible
781
+ // // with text files until FS.init can be refactored.
782
+ // process.stdin.setEncoding('utf8');
783
+ // }
784
+ },
785
+ shutdown() {
786
+ // https://github.com/emscripten-core/emscripten/pull/1555
787
+ // if (ENVIRONMENT_IS_NODE) {
788
+ // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
789
+ // // isaacs: because now it's reading from the stream, you've expressed interest in it, so that read() kicks off a _read() which creates a ReadReq operation
790
+ // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
791
+ // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
792
+ // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
793
+ // process.stdin.pause();
794
+ // }
795
+ },
796
+ register(dev, ops) {
797
+ TTY.ttys[dev] = { input: [], output: [], ops: ops };
798
+ FS.registerDevice(dev, TTY.stream_ops);
799
+ },
800
+ stream_ops:{
801
+ open(stream) {
802
+ var tty = TTY.ttys[stream.node.rdev];
803
+ if (!tty) {
804
+ throw new FS.ErrnoError(43);
805
+ }
806
+ stream.tty = tty;
807
+ stream.seekable = false;
808
+ },
809
+ close(stream) {
810
+ // flush any pending line data
811
+ stream.tty.ops.fsync(stream.tty);
812
+ },
813
+ fsync(stream) {
814
+ stream.tty.ops.fsync(stream.tty);
815
+ },
816
+ read(stream, buffer, offset, length, pos /* ignored */) {
817
+ if (!stream.tty || !stream.tty.ops.get_char) {
818
+ throw new FS.ErrnoError(60);
819
+ }
820
+ var bytesRead = 0;
821
+ for (var i = 0; i < length; i++) {
822
+ var result;
823
+ try {
824
+ result = stream.tty.ops.get_char(stream.tty);
825
+ } catch (e) {
826
+ throw new FS.ErrnoError(29);
827
+ }
828
+ if (result === undefined && bytesRead === 0) {
829
+ throw new FS.ErrnoError(6);
830
+ }
831
+ if (result === null || result === undefined) break;
832
+ bytesRead++;
833
+ buffer[offset+i] = result;
834
+ }
835
+ if (bytesRead) {
836
+ stream.node.atime = Date.now();
837
+ }
838
+ return bytesRead;
839
+ },
840
+ write(stream, buffer, offset, length, pos) {
841
+ if (!stream.tty || !stream.tty.ops.put_char) {
842
+ throw new FS.ErrnoError(60);
843
+ }
844
+ try {
845
+ for (var i = 0; i < length; i++) {
846
+ stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
847
+ }
848
+ } catch (e) {
849
+ throw new FS.ErrnoError(29);
850
+ }
851
+ if (length) {
852
+ stream.node.mtime = stream.node.ctime = Date.now();
853
+ }
854
+ return i;
855
+ },
856
+ },
857
+ default_tty_ops:{
858
+ get_char(tty) {
859
+ return FS_stdin_getChar();
860
+ },
861
+ put_char(tty, val) {
862
+ if (val === null || val === 10) {
863
+ out(UTF8ArrayToString(tty.output));
864
+ tty.output = [];
865
+ } else {
866
+ if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
867
+ }
868
+ },
869
+ fsync(tty) {
870
+ if (tty.output?.length > 0) {
871
+ out(UTF8ArrayToString(tty.output));
872
+ tty.output = [];
873
+ }
874
+ },
875
+ ioctl_tcgets(tty) {
876
+ // typical setting
877
+ return {
878
+ c_iflag: 25856,
879
+ c_oflag: 5,
880
+ c_cflag: 191,
881
+ c_lflag: 35387,
882
+ c_cc: [
883
+ 0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00,
884
+ 0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
885
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
886
+ ]
887
+ };
888
+ },
889
+ ioctl_tcsets(tty, optional_actions, data) {
890
+ // currently just ignore
891
+ return 0;
892
+ },
893
+ ioctl_tiocgwinsz(tty) {
894
+ return [24, 80];
895
+ },
896
+ },
897
+ default_tty1_ops:{
898
+ put_char(tty, val) {
899
+ if (val === null || val === 10) {
900
+ err(UTF8ArrayToString(tty.output));
901
+ tty.output = [];
902
+ } else {
903
+ if (val != 0) tty.output.push(val);
904
+ }
905
+ },
906
+ fsync(tty) {
907
+ if (tty.output?.length > 0) {
908
+ err(UTF8ArrayToString(tty.output));
909
+ tty.output = [];
910
+ }
911
+ },
912
+ },
913
+ };
914
+
915
+
916
+ var mmapAlloc = (size) => {
917
+ abort();
918
+ };
919
+ var MEMFS = {
920
+ ops_table:null,
921
+ mount(mount) {
922
+ return MEMFS.createNode(null, '/', 16895, 0);
923
+ },
924
+ createNode(parent, name, mode, dev) {
925
+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
926
+ // not supported
927
+ throw new FS.ErrnoError(63);
928
+ }
929
+ MEMFS.ops_table ||= {
930
+ dir: {
931
+ node: {
932
+ getattr: MEMFS.node_ops.getattr,
933
+ setattr: MEMFS.node_ops.setattr,
934
+ lookup: MEMFS.node_ops.lookup,
935
+ mknod: MEMFS.node_ops.mknod,
936
+ rename: MEMFS.node_ops.rename,
937
+ unlink: MEMFS.node_ops.unlink,
938
+ rmdir: MEMFS.node_ops.rmdir,
939
+ readdir: MEMFS.node_ops.readdir,
940
+ symlink: MEMFS.node_ops.symlink
941
+ },
942
+ stream: {
943
+ llseek: MEMFS.stream_ops.llseek
944
+ }
945
+ },
946
+ file: {
947
+ node: {
948
+ getattr: MEMFS.node_ops.getattr,
949
+ setattr: MEMFS.node_ops.setattr
950
+ },
951
+ stream: {
952
+ llseek: MEMFS.stream_ops.llseek,
953
+ read: MEMFS.stream_ops.read,
954
+ write: MEMFS.stream_ops.write,
955
+ mmap: MEMFS.stream_ops.mmap,
956
+ msync: MEMFS.stream_ops.msync
957
+ }
958
+ },
959
+ link: {
960
+ node: {
961
+ getattr: MEMFS.node_ops.getattr,
962
+ setattr: MEMFS.node_ops.setattr,
963
+ readlink: MEMFS.node_ops.readlink
964
+ },
965
+ stream: {}
966
+ },
967
+ chrdev: {
968
+ node: {
969
+ getattr: MEMFS.node_ops.getattr,
970
+ setattr: MEMFS.node_ops.setattr
971
+ },
972
+ stream: FS.chrdev_stream_ops
973
+ }
974
+ };
975
+ var node = FS.createNode(parent, name, mode, dev);
976
+ if (FS.isDir(node.mode)) {
977
+ node.node_ops = MEMFS.ops_table.dir.node;
978
+ node.stream_ops = MEMFS.ops_table.dir.stream;
979
+ node.contents = {};
980
+ } else if (FS.isFile(node.mode)) {
981
+ node.node_ops = MEMFS.ops_table.file.node;
982
+ node.stream_ops = MEMFS.ops_table.file.stream;
983
+ // The actual number of bytes used in the typed array, as opposed to
984
+ // contents.length which gives the whole capacity.
985
+ node.usedBytes = 0;
986
+ // The byte data of the file is stored in a typed array.
987
+ // Note: typed arrays are not resizable like normal JS arrays are, so
988
+ // there is a small penalty involved for appending file writes that
989
+ // continuously grow a file similar to std::vector capacity vs used.
990
+ node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0);
991
+ } else if (FS.isLink(node.mode)) {
992
+ node.node_ops = MEMFS.ops_table.link.node;
993
+ node.stream_ops = MEMFS.ops_table.link.stream;
994
+ } else if (FS.isChrdev(node.mode)) {
995
+ node.node_ops = MEMFS.ops_table.chrdev.node;
996
+ node.stream_ops = MEMFS.ops_table.chrdev.stream;
997
+ }
998
+ node.atime = node.mtime = node.ctime = Date.now();
999
+ // add the new node to the parent
1000
+ if (parent) {
1001
+ parent.contents[name] = node;
1002
+ parent.atime = parent.mtime = parent.ctime = node.atime;
1003
+ }
1004
+ return node;
1005
+ },
1006
+ getFileDataAsTypedArray(node) {
1007
+ return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
1008
+ },
1009
+ expandFileStorage(node, newCapacity) {
1010
+ var prevCapacity = node.contents.length;
1011
+ if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
1012
+ // Don't expand strictly to the given requested limit if it's only a very
1013
+ // small increase, but instead geometrically grow capacity.
1014
+ // For small filesizes (<1MB), perform size*2 geometric increase, but for
1015
+ // large sizes, do a much more conservative size*1.125 increase to avoid
1016
+ // overshooting the allocation cap by a very large margin.
1017
+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;
1018
+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>> 0);
1019
+ if (prevCapacity) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
1020
+ var oldContents = MEMFS.getFileDataAsTypedArray(node);
1021
+ node.contents = new Uint8Array(newCapacity); // Allocate new storage.
1022
+ node.contents.set(oldContents);
1023
+ },
1024
+ resizeFileStorage(node, newSize) {
1025
+ if (node.usedBytes == newSize) return;
1026
+ var oldContents = node.contents;
1027
+ node.contents = new Uint8Array(newSize); // Allocate new storage.
1028
+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
1029
+ node.usedBytes = newSize;
1030
+ },
1031
+ node_ops:{
1032
+ getattr(node) {
1033
+ var attr = {};
1034
+ // device numbers reuse inode numbers.
1035
+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1036
+ attr.ino = node.id;
1037
+ attr.mode = node.mode;
1038
+ attr.nlink = 1;
1039
+ attr.uid = 0;
1040
+ attr.gid = 0;
1041
+ attr.rdev = node.rdev;
1042
+ if (FS.isDir(node.mode)) {
1043
+ attr.size = 4096;
1044
+ } else if (FS.isFile(node.mode)) {
1045
+ attr.size = node.usedBytes;
1046
+ } else if (FS.isLink(node.mode)) {
1047
+ attr.size = node.link.length;
1048
+ } else {
1049
+ attr.size = 0;
1050
+ }
1051
+ attr.atime = new Date(node.atime);
1052
+ attr.mtime = new Date(node.mtime);
1053
+ attr.ctime = new Date(node.ctime);
1054
+ // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
1055
+ // but this is not required by the standard.
1056
+ attr.blksize = 4096;
1057
+ attr.blocks = Math.ceil(attr.size / attr.blksize);
1058
+ return attr;
1059
+ },
1060
+ setattr(node, attr) {
1061
+ for (const key of ["mode", "atime", "mtime", "ctime"]) {
1062
+ if (attr[key] != null) {
1063
+ node[key] = attr[key];
1064
+ }
1065
+ }
1066
+ if (attr.size !== undefined) {
1067
+ MEMFS.resizeFileStorage(node, attr.size);
1068
+ }
1069
+ },
1070
+ lookup(parent, name) {
1071
+ // This error may happen quite a bit. To avoid overhead we reuse it (and
1072
+ // suffer a lack of stack info).
1073
+ if (!MEMFS.doesNotExistError) {
1074
+ MEMFS.doesNotExistError = new FS.ErrnoError(44);
1075
+ /** @suppress {checkTypes} */
1076
+ MEMFS.doesNotExistError.stack = '<generic error, no stack>';
1077
+ }
1078
+ throw MEMFS.doesNotExistError;
1079
+ },
1080
+ mknod(parent, name, mode, dev) {
1081
+ return MEMFS.createNode(parent, name, mode, dev);
1082
+ },
1083
+ rename(old_node, new_dir, new_name) {
1084
+ var new_node;
1085
+ try {
1086
+ new_node = FS.lookupNode(new_dir, new_name);
1087
+ } catch (e) {}
1088
+ if (new_node) {
1089
+ if (FS.isDir(old_node.mode)) {
1090
+ // if we're overwriting a directory at new_name, make sure it's empty.
1091
+ for (var i in new_node.contents) {
1092
+ throw new FS.ErrnoError(55);
1093
+ }
1094
+ }
1095
+ FS.hashRemoveNode(new_node);
1096
+ }
1097
+ // do the internal rewiring
1098
+ delete old_node.parent.contents[old_node.name];
1099
+ new_dir.contents[new_name] = old_node;
1100
+ old_node.name = new_name;
1101
+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();
1102
+ },
1103
+ unlink(parent, name) {
1104
+ delete parent.contents[name];
1105
+ parent.ctime = parent.mtime = Date.now();
1106
+ },
1107
+ rmdir(parent, name) {
1108
+ var node = FS.lookupNode(parent, name);
1109
+ for (var i in node.contents) {
1110
+ throw new FS.ErrnoError(55);
1111
+ }
1112
+ delete parent.contents[name];
1113
+ parent.ctime = parent.mtime = Date.now();
1114
+ },
1115
+ readdir(node) {
1116
+ return ['.', '..', ...Object.keys(node.contents)];
1117
+ },
1118
+ symlink(parent, newname, oldpath) {
1119
+ var node = MEMFS.createNode(parent, newname, 0o777 | 40960, 0);
1120
+ node.link = oldpath;
1121
+ return node;
1122
+ },
1123
+ readlink(node) {
1124
+ if (!FS.isLink(node.mode)) {
1125
+ throw new FS.ErrnoError(28);
1126
+ }
1127
+ return node.link;
1128
+ },
1129
+ },
1130
+ stream_ops:{
1131
+ read(stream, buffer, offset, length, position) {
1132
+ var contents = stream.node.contents;
1133
+ if (position >= stream.node.usedBytes) return 0;
1134
+ var size = Math.min(stream.node.usedBytes - position, length);
1135
+ buffer.set(contents.subarray(position, position + size), offset);
1136
+ return size;
1137
+ },
1138
+ write(stream, buffer, offset, length, position, canOwn) {
1139
+ // If the buffer is located in main memory (HEAP), and if
1140
+ // memory can grow, we can't hold on to references of the
1141
+ // memory buffer, as they may get invalidated. That means we
1142
+ // need to copy its contents.
1143
+ if (buffer.buffer === HEAP8.buffer) {
1144
+ canOwn = false;
1145
+ }
1146
+
1147
+ if (!length) return 0;
1148
+ var node = stream.node;
1149
+ node.mtime = node.ctime = Date.now();
1150
+
1151
+ if (canOwn) {
1152
+ node.contents = buffer.subarray(offset, offset + length);
1153
+ node.usedBytes = length;
1154
+ } else if (node.usedBytes === 0 && position === 0) { // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
1155
+ node.contents = buffer.slice(offset, offset + length);
1156
+ node.usedBytes = length;
1157
+ } else {
1158
+ MEMFS.expandFileStorage(node, position+length);
1159
+ // Use typed array write which is available.
1160
+ node.contents.set(buffer.subarray(offset, offset + length), position);
1161
+ node.usedBytes = Math.max(node.usedBytes, position + length);
1162
+ }
1163
+ return length;
1164
+ },
1165
+ llseek(stream, offset, whence) {
1166
+ var position = offset;
1167
+ if (whence === 1) {
1168
+ position += stream.position;
1169
+ } else if (whence === 2) {
1170
+ if (FS.isFile(stream.node.mode)) {
1171
+ position += stream.node.usedBytes;
1172
+ }
1173
+ }
1174
+ if (position < 0) {
1175
+ throw new FS.ErrnoError(28);
1176
+ }
1177
+ return position;
1178
+ },
1179
+ mmap(stream, length, position, prot, flags) {
1180
+ if (!FS.isFile(stream.node.mode)) {
1181
+ throw new FS.ErrnoError(43);
1182
+ }
1183
+ var ptr;
1184
+ var allocated;
1185
+ var contents = stream.node.contents;
1186
+ // Only make a new copy when MAP_PRIVATE is specified.
1187
+ if (!(flags & 2) && contents.buffer === HEAP8.buffer) {
1188
+ // We can't emulate MAP_SHARED when the file is not backed by the
1189
+ // buffer we're mapping to (e.g. the HEAP buffer).
1190
+ allocated = false;
1191
+ ptr = contents.byteOffset;
1192
+ } else {
1193
+ allocated = true;
1194
+ ptr = mmapAlloc(length);
1195
+ if (!ptr) {
1196
+ throw new FS.ErrnoError(48);
1197
+ }
1198
+ if (contents) {
1199
+ // Try to avoid unnecessary slices.
1200
+ if (position > 0 || position + length < contents.length) {
1201
+ if (contents.subarray) {
1202
+ contents = contents.subarray(position, position + length);
1203
+ } else {
1204
+ contents = Array.prototype.slice.call(contents, position, position + length);
1205
+ }
1206
+ }
1207
+ HEAP8.set(contents, ptr);
1208
+ }
1209
+ }
1210
+ return { ptr, allocated };
1211
+ },
1212
+ msync(stream, buffer, offset, length, mmapFlags) {
1213
+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
1214
+ // should we check if bytesWritten and length are the same?
1215
+ return 0;
1216
+ },
1217
+ },
1218
+ };
1219
+
1220
+ var FS_modeStringToFlags = (str) => {
1221
+ if (typeof str != 'string') return str;
1222
+ var flagModes = {
1223
+ 'r': 0,
1224
+ 'r+': 2,
1225
+ 'w': 512 | 64 | 1,
1226
+ 'w+': 512 | 64 | 2,
1227
+ 'a': 1024 | 64 | 1,
1228
+ 'a+': 1024 | 64 | 2,
1229
+ };
1230
+ var flags = flagModes[str];
1231
+ if (typeof flags == 'undefined') {
1232
+ throw new Error(`Unknown file open mode: ${str}`);
1233
+ }
1234
+ return flags;
1235
+ };
1236
+
1237
+ var FS_fileDataToTypedArray = (data) => {
1238
+ if (typeof data == 'string') {
1239
+ data = intArrayFromString(data, true);
1240
+ }
1241
+ if (!data.subarray) {
1242
+ data = new Uint8Array(data);
1243
+ }
1244
+ return data;
1245
+ };
1246
+
1247
+ var FS_getMode = (canRead, canWrite) => {
1248
+ var mode = 0;
1249
+ if (canRead) mode |= 292 | 73;
1250
+ if (canWrite) mode |= 146;
1251
+ return mode;
1252
+ };
1253
+
1254
+
1255
+ var asyncLoad = async (url) => {
1256
+ var arrayBuffer = await readAsync(url);
1257
+ return new Uint8Array(arrayBuffer);
1258
+ };
1259
+
1260
+
1261
+ var FS_createDataFile = (...args) => FS.createDataFile(...args);
1262
+
1263
+ var getUniqueRunDependency = (id) => {
1264
+ return id;
1265
+ };
1266
+
1267
+ var dependenciesPromise = null;
1268
+ var resolveRunDependencies = async () => dependenciesPromise;
1269
+ var runDependencies = 0;
1270
+
1271
+
1272
+ var removeRunDependency = (id) => {
1273
+ runDependencies--;
1274
+
1275
+ if (!runDependencies) {
1276
+ dependenciesPromise.resolve();
1277
+ }
1278
+ };
1279
+
1280
+ var addRunDependency = (id) => {
1281
+ if (!runDependencies) {
1282
+ var resolve;
1283
+ dependenciesPromise = new Promise((r) => resolve = r);
1284
+ dependenciesPromise.resolve = resolve;
1285
+ }
1286
+ runDependencies++;
1287
+
1288
+ };
1289
+
1290
+
1291
+ var preloadPlugins = [];
1292
+ var FS_handledByPreloadPlugin = async (byteArray, fullname) => {
1293
+ // Ensure plugins are ready.
1294
+ if (typeof Browser != 'undefined') Browser.init();
1295
+
1296
+ for (var plugin of preloadPlugins) {
1297
+ if (plugin['canHandle'](fullname)) {
1298
+ return plugin['handle'](byteArray, fullname);
1299
+ }
1300
+ }
1301
+ // If no plugin handled this file then return the original/unmodified
1302
+ // byteArray.
1303
+ return byteArray;
1304
+ };
1305
+ var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {
1306
+ // TODO we should allow people to just pass in a complete filename instead
1307
+ // of parent and name being that we just join them anyways
1308
+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
1309
+ var dep = getUniqueRunDependency(`cp ${fullname}`); // might have several active requests for the same fullname
1310
+ addRunDependency(dep);
1311
+
1312
+ try {
1313
+ var byteArray = url;
1314
+ if (typeof url == 'string') {
1315
+ byteArray = await asyncLoad(url);
1316
+ }
1317
+
1318
+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);
1319
+ preFinish?.();
1320
+ if (!dontCreateFile) {
1321
+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
1322
+ }
1323
+ } finally {
1324
+ removeRunDependency(dep);
1325
+ }
1326
+ };
1327
+ var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
1328
+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);
1329
+ };
1330
+ var FS = {
1331
+ root:null,
1332
+ mounts:[],
1333
+ devices:{
1334
+ },
1335
+ streams:[],
1336
+ nextInode:1,
1337
+ nameTable:null,
1338
+ currentPath:"/",
1339
+ initialized:false,
1340
+ ignorePermissions:true,
1341
+ filesystems:null,
1342
+ syncFSRequests:0,
1343
+ ErrnoError:class {
1344
+ name = 'ErrnoError';
1345
+ // We set the `name` property to be able to identify `FS.ErrnoError`
1346
+ // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.
1347
+ // - when using PROXYFS, an error can come from an underlying FS
1348
+ // as different FS objects have their own FS.ErrnoError each,
1349
+ // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.
1350
+ // we'll use the reliable test `err.name == "ErrnoError"` instead
1351
+ constructor(errno) {
1352
+ this.errno = errno;
1353
+ }
1354
+ },
1355
+ FSStream:class {
1356
+ shared = {};
1357
+ get object() {
1358
+ return this.node;
1359
+ }
1360
+ set object(val) {
1361
+ this.node = val;
1362
+ }
1363
+ get isRead() {
1364
+ return (this.flags & 2097155) !== 1;
1365
+ }
1366
+ get isWrite() {
1367
+ return (this.flags & 2097155) !== 0;
1368
+ }
1369
+ get isAppend() {
1370
+ return (this.flags & 1024);
1371
+ }
1372
+ get flags() {
1373
+ return this.shared.flags;
1374
+ }
1375
+ set flags(val) {
1376
+ this.shared.flags = val;
1377
+ }
1378
+ get position() {
1379
+ return this.shared.position;
1380
+ }
1381
+ set position(val) {
1382
+ this.shared.position = val;
1383
+ }
1384
+ },
1385
+ FSNode:class {
1386
+ node_ops = {};
1387
+ stream_ops = {};
1388
+ readMode = 292 | 73;
1389
+ writeMode = 146;
1390
+ mounted = null;
1391
+ constructor(parent, name, mode, rdev) {
1392
+ if (!parent) {
1393
+ parent = this; // root node sets parent to itself
1394
+ }
1395
+ this.parent = parent;
1396
+ this.mount = parent.mount;
1397
+ this.id = FS.nextInode++;
1398
+ this.name = name;
1399
+ this.mode = mode;
1400
+ this.rdev = rdev;
1401
+ this.atime = this.mtime = this.ctime = Date.now();
1402
+ }
1403
+ get read() {
1404
+ return (this.mode & this.readMode) === this.readMode;
1405
+ }
1406
+ set read(val) {
1407
+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
1408
+ }
1409
+ get write() {
1410
+ return (this.mode & this.writeMode) === this.writeMode;
1411
+ }
1412
+ set write(val) {
1413
+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
1414
+ }
1415
+ get isFolder() {
1416
+ return FS.isDir(this.mode);
1417
+ }
1418
+ get isDevice() {
1419
+ return FS.isChrdev(this.mode);
1420
+ }
1421
+ },
1422
+ lookupPath(path, opts = {}) {
1423
+ if (!path) {
1424
+ throw new FS.ErrnoError(44);
1425
+ }
1426
+ opts.follow_mount ??= true
1427
+
1428
+ if (!PATH.isAbs(path)) {
1429
+ path = FS.cwd() + '/' + path;
1430
+ }
1431
+
1432
+ // limit max consecutive symlinks to SYMLOOP_MAX.
1433
+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {
1434
+ // split the absolute path
1435
+ var parts = path.split('/').filter((p) => !!p);
1436
+
1437
+ // start at the root
1438
+ var current = FS.root;
1439
+ var current_path = '/';
1440
+
1441
+ for (var i = 0; i < parts.length; i++) {
1442
+ var islast = (i === parts.length-1);
1443
+ if (islast && opts.parent) {
1444
+ // stop resolving
1445
+ break;
1446
+ }
1447
+
1448
+ if (parts[i] === '.') {
1449
+ continue;
1450
+ }
1451
+
1452
+ if (parts[i] === '..') {
1453
+ current_path = PATH.dirname(current_path);
1454
+ if (FS.isRoot(current)) {
1455
+ path = current_path + '/' + parts.slice(i + 1).join('/');
1456
+ // We're making progress here, don't let many consecutive ..'s
1457
+ // lead to ELOOP
1458
+ nlinks--;
1459
+ continue linkloop;
1460
+ } else {
1461
+ current = current.parent;
1462
+ }
1463
+ continue;
1464
+ }
1465
+
1466
+ current_path = PATH.join2(current_path, parts[i]);
1467
+ try {
1468
+ current = FS.lookupNode(current, parts[i]);
1469
+ } catch (e) {
1470
+ // if noent_okay is true, suppress a ENOENT in the last component
1471
+ // and return an object with an undefined node. This is needed for
1472
+ // resolving symlinks in the path when creating a file.
1473
+ if ((e?.errno === 44) && islast && opts.noent_okay) {
1474
+ return { path: current_path };
1475
+ }
1476
+ throw e;
1477
+ }
1478
+
1479
+ // jump to the mount's root node if this is a mountpoint
1480
+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {
1481
+ current = current.mounted.root;
1482
+ }
1483
+
1484
+ // by default, lookupPath will not follow a symlink if it is the final path component.
1485
+ // setting opts.follow = true will override this behavior.
1486
+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {
1487
+ if (!current.node_ops.readlink) {
1488
+ throw new FS.ErrnoError(52);
1489
+ }
1490
+ var link = current.node_ops.readlink(current);
1491
+ if (!PATH.isAbs(link)) {
1492
+ link = PATH.dirname(current_path) + '/' + link;
1493
+ }
1494
+ path = link + '/' + parts.slice(i + 1).join('/');
1495
+ continue linkloop;
1496
+ }
1497
+ }
1498
+ return { path: current_path, node: current };
1499
+ }
1500
+ throw new FS.ErrnoError(32);
1501
+ },
1502
+ getPath(node) {
1503
+ var path;
1504
+ while (true) {
1505
+ if (FS.isRoot(node)) {
1506
+ var mount = node.mount.mountpoint;
1507
+ if (!path) return mount;
1508
+ return mount[mount.length-1] !== '/' ? `${mount}/${path}` : mount + path;
1509
+ }
1510
+ path = path ? `${node.name}/${path}` : node.name;
1511
+ node = node.parent;
1512
+ }
1513
+ },
1514
+ hashName(parentid, name) {
1515
+ var hash = 0;
1516
+
1517
+ for (var i = 0; i < name.length; i++) {
1518
+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
1519
+ }
1520
+ return ((parentid + hash) >>> 0) % FS.nameTable.length;
1521
+ },
1522
+ hashAddNode(node) {
1523
+ var hash = FS.hashName(node.parent.id, node.name);
1524
+ node.name_next = FS.nameTable[hash];
1525
+ FS.nameTable[hash] = node;
1526
+ },
1527
+ hashRemoveNode(node) {
1528
+ var hash = FS.hashName(node.parent.id, node.name);
1529
+ if (FS.nameTable[hash] === node) {
1530
+ FS.nameTable[hash] = node.name_next;
1531
+ } else {
1532
+ var current = FS.nameTable[hash];
1533
+ while (current) {
1534
+ if (current.name_next === node) {
1535
+ current.name_next = node.name_next;
1536
+ break;
1537
+ }
1538
+ current = current.name_next;
1539
+ }
1540
+ }
1541
+ },
1542
+ lookupNode(parent, name) {
1543
+ var errCode = FS.mayLookup(parent);
1544
+ if (errCode) {
1545
+ throw new FS.ErrnoError(errCode);
1546
+ }
1547
+ var hash = FS.hashName(parent.id, name);
1548
+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {
1549
+ var nodeName = node.name;
1550
+ if (node.parent.id === parent.id && nodeName === name) {
1551
+ return node;
1552
+ }
1553
+ }
1554
+ // if we failed to find it in the cache, call into the VFS
1555
+ return FS.lookup(parent, name);
1556
+ },
1557
+ createNode(parent, name, mode, rdev) {
1558
+ var node = new FS.FSNode(parent, name, mode, rdev);
1559
+
1560
+ FS.hashAddNode(node);
1561
+
1562
+ return node;
1563
+ },
1564
+ destroyNode(node) {
1565
+ FS.hashRemoveNode(node);
1566
+ },
1567
+ isRoot(node) {
1568
+ return node === node.parent;
1569
+ },
1570
+ isMountpoint(node) {
1571
+ return !!node.mounted;
1572
+ },
1573
+ isFile(mode) {
1574
+ return (mode & 61440) === 32768;
1575
+ },
1576
+ isDir(mode) {
1577
+ return (mode & 61440) === 16384;
1578
+ },
1579
+ isLink(mode) {
1580
+ return (mode & 61440) === 40960;
1581
+ },
1582
+ isChrdev(mode) {
1583
+ return (mode & 61440) === 8192;
1584
+ },
1585
+ isBlkdev(mode) {
1586
+ return (mode & 61440) === 24576;
1587
+ },
1588
+ isFIFO(mode) {
1589
+ return (mode & 61440) === 4096;
1590
+ },
1591
+ isSocket(mode) {
1592
+ return (mode & 49152) === 49152;
1593
+ },
1594
+ flagsToPermissionString(flag) {
1595
+ var perms = ['r', 'w', 'rw'][flag & 3];
1596
+ if ((flag & 512)) {
1597
+ perms += 'w';
1598
+ }
1599
+ return perms;
1600
+ },
1601
+ nodePermissions(node, perms) {
1602
+ if (FS.ignorePermissions) {
1603
+ return 0;
1604
+ }
1605
+ // return 0 if any user, group or owner bits are set.
1606
+ if (perms.includes('r') && !(node.mode & 292)) {
1607
+ return 2;
1608
+ }
1609
+ if (perms.includes('w') && !(node.mode & 146)) {
1610
+ return 2;
1611
+ }
1612
+ if (perms.includes('x') && !(node.mode & 73)) {
1613
+ return 2;
1614
+ }
1615
+ return 0;
1616
+ },
1617
+ mayLookup(dir) {
1618
+ if (!FS.isDir(dir.mode)) return 54;
1619
+ var errCode = FS.nodePermissions(dir, 'x');
1620
+ if (errCode) return errCode;
1621
+ if (!dir.node_ops.lookup) return 2;
1622
+ return 0;
1623
+ },
1624
+ mayCreate(dir, name) {
1625
+ if (!FS.isDir(dir.mode)) {
1626
+ return 54;
1627
+ }
1628
+ try {
1629
+ var node = FS.lookupNode(dir, name);
1630
+ return 20;
1631
+ } catch (e) {
1632
+ }
1633
+ return FS.nodePermissions(dir, 'wx');
1634
+ },
1635
+ mayDelete(dir, name, isdir) {
1636
+ var node;
1637
+ try {
1638
+ node = FS.lookupNode(dir, name);
1639
+ } catch (e) {
1640
+ return e.errno;
1641
+ }
1642
+ var errCode = FS.nodePermissions(dir, 'wx');
1643
+ if (errCode) {
1644
+ return errCode;
1645
+ }
1646
+ if (isdir) {
1647
+ if (!FS.isDir(node.mode)) {
1648
+ return 54;
1649
+ }
1650
+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
1651
+ return 10;
1652
+ }
1653
+ } else if (FS.isDir(node.mode)) {
1654
+ return 31;
1655
+ }
1656
+ return 0;
1657
+ },
1658
+ mayOpen(node, flags) {
1659
+ if (!node) {
1660
+ return 44;
1661
+ }
1662
+ if (FS.isLink(node.mode)) {
1663
+ return 32;
1664
+ }
1665
+ var mode = FS.flagsToPermissionString(flags);
1666
+ if (FS.isDir(node.mode)) {
1667
+ // opening for write
1668
+ // TODO: check for O_SEARCH? (== search for dir only)
1669
+ if (mode !== 'r' || (flags & (512 | 64))) {
1670
+ return 31;
1671
+ }
1672
+ }
1673
+ return FS.nodePermissions(node, mode);
1674
+ },
1675
+ checkOpExists(op, err) {
1676
+ if (!op) {
1677
+ throw new FS.ErrnoError(err);
1678
+ }
1679
+ return op;
1680
+ },
1681
+ MAX_OPEN_FDS:4096,
1682
+ nextfd() {
1683
+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
1684
+ if (!FS.streams[fd]) {
1685
+ return fd;
1686
+ }
1687
+ }
1688
+ throw new FS.ErrnoError(33);
1689
+ },
1690
+ getStreamChecked(fd) {
1691
+ var stream = FS.getStream(fd);
1692
+ if (!stream) {
1693
+ throw new FS.ErrnoError(8);
1694
+ }
1695
+ return stream;
1696
+ },
1697
+ getStream:(fd) => FS.streams[fd],
1698
+ createStream(stream, fd = -1) {
1699
+
1700
+ // clone it, so we can return an instance of FSStream
1701
+ stream = Object.assign(new FS.FSStream(), stream);
1702
+ if (fd == -1) {
1703
+ fd = FS.nextfd();
1704
+ }
1705
+ stream.fd = fd;
1706
+ FS.streams[fd] = stream;
1707
+ return stream;
1708
+ },
1709
+ closeStream(fd) {
1710
+ FS.streams[fd] = null;
1711
+ },
1712
+ dupStream(origStream, fd = -1) {
1713
+ var stream = FS.createStream(origStream, fd);
1714
+ stream.stream_ops?.dup?.(stream);
1715
+ return stream;
1716
+ },
1717
+ doSetAttr(stream, node, attr) {
1718
+ var setattr = stream?.stream_ops.setattr;
1719
+ var arg = setattr ? stream : node;
1720
+ setattr ??= node.node_ops.setattr;
1721
+ FS.checkOpExists(setattr, 63)
1722
+ try {
1723
+ setattr(arg, attr);
1724
+ } catch (e) {
1725
+ if (e instanceof RangeError) {
1726
+ throw new FS.ErrnoError(22);
1727
+ }
1728
+ throw e;
1729
+ }
1730
+ },
1731
+ chrdev_stream_ops:{
1732
+ open(stream) {
1733
+ var device = FS.getDevice(stream.node.rdev);
1734
+ // override node's stream ops with the device's
1735
+ stream.stream_ops = device.stream_ops;
1736
+ // forward the open call
1737
+ stream.stream_ops.open?.(stream);
1738
+ },
1739
+ llseek() {
1740
+ throw new FS.ErrnoError(70);
1741
+ },
1742
+ },
1743
+ major:(dev) => ((dev) >> 8),
1744
+ minor:(dev) => ((dev) & 0xff),
1745
+ makedev:(ma, mi) => ((ma) << 8 | (mi)),
1746
+ registerDevice(dev, ops) {
1747
+ FS.devices[dev] = { stream_ops: ops };
1748
+ },
1749
+ getDevice:(dev) => FS.devices[dev],
1750
+ getMounts(mount) {
1751
+ var mounts = [];
1752
+ var check = [mount];
1753
+
1754
+ while (check.length) {
1755
+ var m = check.pop();
1756
+
1757
+ mounts.push(m);
1758
+
1759
+ check.push(...m.mounts);
1760
+ }
1761
+
1762
+ return mounts;
1763
+ },
1764
+ syncfs(populate, callback) {
1765
+ if (typeof populate == 'function') {
1766
+ callback = populate;
1767
+ populate = false;
1768
+ }
1769
+
1770
+ FS.syncFSRequests++;
1771
+
1772
+ if (FS.syncFSRequests > 1) {
1773
+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);
1774
+ }
1775
+
1776
+ var mounts = FS.getMounts(FS.root.mount);
1777
+ var completed = 0;
1778
+
1779
+ function doCallback(errCode) {
1780
+ FS.syncFSRequests--;
1781
+ return callback(errCode);
1782
+ }
1783
+
1784
+ function done(errCode) {
1785
+ if (errCode) {
1786
+ if (!done.errored) {
1787
+ done.errored = true;
1788
+ return doCallback(errCode);
1789
+ }
1790
+ return;
1791
+ }
1792
+ if (++completed >= mounts.length) {
1793
+ doCallback(null);
1794
+ }
1795
+ };
1796
+
1797
+ // sync all mounts
1798
+ for (var mount of mounts) {
1799
+ if (mount.type.syncfs) {
1800
+ mount.type.syncfs(mount, populate, done);
1801
+ } else {
1802
+ done(null);
1803
+ }
1804
+ }
1805
+ },
1806
+ mount(type, opts, mountpoint) {
1807
+ var root = mountpoint === '/';
1808
+ var pseudo = !mountpoint;
1809
+ var node;
1810
+
1811
+ if (root && FS.root) {
1812
+ throw new FS.ErrnoError(10);
1813
+ } else if (!root && !pseudo) {
1814
+ var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
1815
+
1816
+ mountpoint = lookup.path; // use the absolute path
1817
+ node = lookup.node;
1818
+
1819
+ if (FS.isMountpoint(node)) {
1820
+ throw new FS.ErrnoError(10);
1821
+ }
1822
+
1823
+ if (!FS.isDir(node.mode)) {
1824
+ throw new FS.ErrnoError(54);
1825
+ }
1826
+ }
1827
+
1828
+ var mount = {
1829
+ type,
1830
+ opts,
1831
+ mountpoint,
1832
+ mounts: []
1833
+ };
1834
+
1835
+ // create a root node for the fs
1836
+ var mountRoot = type.mount(mount);
1837
+ mountRoot.mount = mount;
1838
+ mount.root = mountRoot;
1839
+
1840
+ if (root) {
1841
+ FS.root = mountRoot;
1842
+ } else if (node) {
1843
+ // set as a mountpoint
1844
+ node.mounted = mount;
1845
+
1846
+ // add the new mount to the current mount's children
1847
+ if (node.mount) {
1848
+ node.mount.mounts.push(mount);
1849
+ }
1850
+ }
1851
+
1852
+ return mountRoot;
1853
+ },
1854
+ unmount(mountpoint) {
1855
+ var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
1856
+
1857
+ if (!FS.isMountpoint(lookup.node)) {
1858
+ throw new FS.ErrnoError(28);
1859
+ }
1860
+
1861
+ // destroy the nodes for this mount, and all its child mounts
1862
+ var node = lookup.node;
1863
+ var mount = node.mounted;
1864
+ var mounts = FS.getMounts(mount);
1865
+
1866
+ for (var [hash, current] of Object.entries(FS.nameTable)) {
1867
+ while (current) {
1868
+ var next = current.name_next;
1869
+
1870
+ if (mounts.includes(current.mount)) {
1871
+ FS.destroyNode(current);
1872
+ }
1873
+
1874
+ current = next;
1875
+ }
1876
+ }
1877
+
1878
+ // no longer a mountpoint
1879
+ node.mounted = null;
1880
+
1881
+ // remove this mount from the child mounts
1882
+ var idx = node.mount.mounts.indexOf(mount);
1883
+ node.mount.mounts.splice(idx, 1);
1884
+ },
1885
+ lookup(parent, name) {
1886
+ return parent.node_ops.lookup(parent, name);
1887
+ },
1888
+ mknod(path, mode, dev) {
1889
+ var lookup = FS.lookupPath(path, { parent: true });
1890
+ var parent = lookup.node;
1891
+ var name = PATH.basename(path);
1892
+ if (!name) {
1893
+ throw new FS.ErrnoError(28);
1894
+ }
1895
+ if (name === '.' || name === '..') {
1896
+ throw new FS.ErrnoError(20);
1897
+ }
1898
+ var errCode = FS.mayCreate(parent, name);
1899
+ if (errCode) {
1900
+ throw new FS.ErrnoError(errCode);
1901
+ }
1902
+ if (!parent.node_ops.mknod) {
1903
+ throw new FS.ErrnoError(63);
1904
+ }
1905
+ return parent.node_ops.mknod(parent, name, mode, dev);
1906
+ },
1907
+ statfs(path) {
1908
+ return FS.statfsNode(FS.lookupPath(path, {follow: true}).node);
1909
+ },
1910
+ statfsStream(stream) {
1911
+ // We keep a separate statfsStream function because noderawfs overrides
1912
+ // it. In noderawfs, stream.node is sometimes null. Instead, we need to
1913
+ // look at stream.path.
1914
+ return FS.statfsNode(stream.node);
1915
+ },
1916
+ statfsNode(node) {
1917
+ // NOTE: None of the defaults here are true. We're just returning safe and
1918
+ // sane values. Currently nodefs and rawfs replace these defaults,
1919
+ // other file systems leave them alone.
1920
+ var rtn = {
1921
+ bsize: 4096,
1922
+ frsize: 4096,
1923
+ blocks: 1e6,
1924
+ bfree: 5e5,
1925
+ bavail: 5e5,
1926
+ files: FS.nextInode,
1927
+ ffree: FS.nextInode - 1,
1928
+ fsid: 42,
1929
+ flags: 2,
1930
+ namelen: 255,
1931
+ };
1932
+
1933
+ if (node.node_ops.statfs) {
1934
+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));
1935
+ }
1936
+ return rtn;
1937
+ },
1938
+ create(path, mode = 0o666) {
1939
+ mode &= 4095;
1940
+ mode |= 32768;
1941
+ return FS.mknod(path, mode, 0);
1942
+ },
1943
+ mkdir(path, mode = 0o777) {
1944
+ mode &= 511 | 512;
1945
+ mode |= 16384;
1946
+ return FS.mknod(path, mode, 0);
1947
+ },
1948
+ mkdirTree(path, mode) {
1949
+ var dirs = path.split('/');
1950
+ var d = '';
1951
+ for (var dir of dirs) {
1952
+ if (!dir) continue;
1953
+ if (d || PATH.isAbs(path)) d += '/';
1954
+ d += dir;
1955
+ try {
1956
+ FS.mkdir(d, mode);
1957
+ } catch(e) {
1958
+ if (e.errno != 20) throw e;
1959
+ }
1960
+ }
1961
+ },
1962
+ mkdev(path, mode, dev) {
1963
+ if (typeof dev == 'undefined') {
1964
+ dev = mode;
1965
+ mode = 0o666;
1966
+ }
1967
+ mode |= 8192;
1968
+ return FS.mknod(path, mode, dev);
1969
+ },
1970
+ symlink(oldpath, newpath) {
1971
+ if (!PATH_FS.resolve(oldpath)) {
1972
+ throw new FS.ErrnoError(44);
1973
+ }
1974
+ var lookup = FS.lookupPath(newpath, { parent: true });
1975
+ var parent = lookup.node;
1976
+ if (!parent) {
1977
+ throw new FS.ErrnoError(44);
1978
+ }
1979
+ var newname = PATH.basename(newpath);
1980
+ var errCode = FS.mayCreate(parent, newname);
1981
+ if (errCode) {
1982
+ throw new FS.ErrnoError(errCode);
1983
+ }
1984
+ if (!parent.node_ops.symlink) {
1985
+ throw new FS.ErrnoError(63);
1986
+ }
1987
+ return parent.node_ops.symlink(parent, newname, oldpath);
1988
+ },
1989
+ rename(old_path, new_path) {
1990
+ var old_dirname = PATH.dirname(old_path);
1991
+ var new_dirname = PATH.dirname(new_path);
1992
+ var old_name = PATH.basename(old_path);
1993
+ var new_name = PATH.basename(new_path);
1994
+ // parents must exist
1995
+ var lookup, old_dir, new_dir;
1996
+
1997
+ // let the errors from non existent directories percolate up
1998
+ lookup = FS.lookupPath(old_path, { parent: true });
1999
+ old_dir = lookup.node;
2000
+ lookup = FS.lookupPath(new_path, { parent: true });
2001
+ new_dir = lookup.node;
2002
+
2003
+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
2004
+ // need to be part of the same mount
2005
+ if (old_dir.mount !== new_dir.mount) {
2006
+ throw new FS.ErrnoError(75);
2007
+ }
2008
+ // source must exist
2009
+ var old_node = FS.lookupNode(old_dir, old_name);
2010
+ // old path should not be an ancestor of the new path
2011
+ var relative = PATH_FS.relative(old_path, new_dirname);
2012
+ if (relative.charAt(0) !== '.') {
2013
+ throw new FS.ErrnoError(28);
2014
+ }
2015
+ // new path should not be an ancestor of the old path
2016
+ relative = PATH_FS.relative(new_path, old_dirname);
2017
+ if (relative.charAt(0) !== '.') {
2018
+ throw new FS.ErrnoError(55);
2019
+ }
2020
+ // see if the new path already exists
2021
+ var new_node;
2022
+ try {
2023
+ new_node = FS.lookupNode(new_dir, new_name);
2024
+ } catch (e) {
2025
+ // not fatal
2026
+ }
2027
+ // early out if nothing needs to change
2028
+ if (old_node === new_node) {
2029
+ return;
2030
+ }
2031
+ // we'll need to delete the old entry
2032
+ var isdir = FS.isDir(old_node.mode);
2033
+ var errCode = FS.mayDelete(old_dir, old_name, isdir);
2034
+ if (errCode) {
2035
+ throw new FS.ErrnoError(errCode);
2036
+ }
2037
+ // need delete permissions if we'll be overwriting.
2038
+ // need create permissions if new doesn't already exist.
2039
+ errCode = new_node ?
2040
+ FS.mayDelete(new_dir, new_name, isdir) :
2041
+ FS.mayCreate(new_dir, new_name);
2042
+ if (errCode) {
2043
+ throw new FS.ErrnoError(errCode);
2044
+ }
2045
+ if (!old_dir.node_ops.rename) {
2046
+ throw new FS.ErrnoError(63);
2047
+ }
2048
+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
2049
+ throw new FS.ErrnoError(10);
2050
+ }
2051
+ // if we are going to change the parent, check write permissions
2052
+ if (new_dir !== old_dir) {
2053
+ errCode = FS.nodePermissions(old_dir, 'w');
2054
+ if (errCode) {
2055
+ throw new FS.ErrnoError(errCode);
2056
+ }
2057
+ }
2058
+ // remove the node from the lookup hash
2059
+ FS.hashRemoveNode(old_node);
2060
+ // do the underlying fs rename
2061
+ try {
2062
+ old_dir.node_ops.rename(old_node, new_dir, new_name);
2063
+ // update old node (we do this here to avoid each backend
2064
+ // needing to)
2065
+ old_node.parent = new_dir;
2066
+ } catch (e) {
2067
+ throw e;
2068
+ } finally {
2069
+ // add the node back to the hash (in case node_ops.rename
2070
+ // changed its name)
2071
+ FS.hashAddNode(old_node);
2072
+ }
2073
+ },
2074
+ rmdir(path) {
2075
+ var lookup = FS.lookupPath(path, { parent: true });
2076
+ var parent = lookup.node;
2077
+ var name = PATH.basename(path);
2078
+ var node = FS.lookupNode(parent, name);
2079
+ var errCode = FS.mayDelete(parent, name, true);
2080
+ if (errCode) {
2081
+ throw new FS.ErrnoError(errCode);
2082
+ }
2083
+ if (!parent.node_ops.rmdir) {
2084
+ throw new FS.ErrnoError(63);
2085
+ }
2086
+ if (FS.isMountpoint(node)) {
2087
+ throw new FS.ErrnoError(10);
2088
+ }
2089
+ parent.node_ops.rmdir(parent, name);
2090
+ FS.destroyNode(node);
2091
+ },
2092
+ readdir(path) {
2093
+ var lookup = FS.lookupPath(path, { follow: true });
2094
+ var node = lookup.node;
2095
+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);
2096
+ return readdir(node);
2097
+ },
2098
+ unlink(path) {
2099
+ var lookup = FS.lookupPath(path, { parent: true });
2100
+ var parent = lookup.node;
2101
+ if (!parent) {
2102
+ throw new FS.ErrnoError(44);
2103
+ }
2104
+ var name = PATH.basename(path);
2105
+ var node = FS.lookupNode(parent, name);
2106
+ var errCode = FS.mayDelete(parent, name, false);
2107
+ if (errCode) {
2108
+ // According to POSIX, we should map EISDIR to EPERM, but
2109
+ // we instead do what Linux does (and we must, as we use
2110
+ // the musl linux libc).
2111
+ throw new FS.ErrnoError(errCode);
2112
+ }
2113
+ if (!parent.node_ops.unlink) {
2114
+ throw new FS.ErrnoError(63);
2115
+ }
2116
+ if (FS.isMountpoint(node)) {
2117
+ throw new FS.ErrnoError(10);
2118
+ }
2119
+ parent.node_ops.unlink(parent, name);
2120
+ FS.destroyNode(node);
2121
+ },
2122
+ readlink(path) {
2123
+ var lookup = FS.lookupPath(path);
2124
+ var link = lookup.node;
2125
+ if (!link) {
2126
+ throw new FS.ErrnoError(44);
2127
+ }
2128
+ if (!link.node_ops.readlink) {
2129
+ throw new FS.ErrnoError(28);
2130
+ }
2131
+ return link.node_ops.readlink(link);
2132
+ },
2133
+ stat(path, dontFollow) {
2134
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
2135
+ var node = lookup.node;
2136
+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);
2137
+ return getattr(node);
2138
+ },
2139
+ fstat(fd) {
2140
+ var stream = FS.getStreamChecked(fd);
2141
+ var node = stream.node;
2142
+ var getattr = stream.stream_ops.getattr;
2143
+ var arg = getattr ? stream : node;
2144
+ getattr ??= node.node_ops.getattr;
2145
+ FS.checkOpExists(getattr, 63)
2146
+ return getattr(arg);
2147
+ },
2148
+ lstat(path) {
2149
+ return FS.stat(path, true);
2150
+ },
2151
+ doChmod(stream, node, mode, dontFollow) {
2152
+ FS.doSetAttr(stream, node, {
2153
+ mode: (mode & 4095) | (node.mode & ~4095),
2154
+ ctime: Date.now(),
2155
+ dontFollow
2156
+ });
2157
+ },
2158
+ chmod(path, mode, dontFollow) {
2159
+ var node;
2160
+ if (typeof path == 'string') {
2161
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
2162
+ node = lookup.node;
2163
+ } else {
2164
+ node = path;
2165
+ }
2166
+ FS.doChmod(null, node, mode, dontFollow);
2167
+ },
2168
+ lchmod(path, mode) {
2169
+ FS.chmod(path, mode, true);
2170
+ },
2171
+ fchmod(fd, mode) {
2172
+ var stream = FS.getStreamChecked(fd);
2173
+ FS.doChmod(stream, stream.node, mode, false);
2174
+ },
2175
+ doChown(stream, node, dontFollow) {
2176
+ FS.doSetAttr(stream, node, {
2177
+ timestamp: Date.now(),
2178
+ dontFollow
2179
+ // we ignore the uid / gid for now
2180
+ });
2181
+ },
2182
+ chown(path, uid, gid, dontFollow) {
2183
+ var node;
2184
+ if (typeof path == 'string') {
2185
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
2186
+ node = lookup.node;
2187
+ } else {
2188
+ node = path;
2189
+ }
2190
+ FS.doChown(null, node, dontFollow);
2191
+ },
2192
+ lchown(path, uid, gid) {
2193
+ FS.chown(path, uid, gid, true);
2194
+ },
2195
+ fchown(fd, uid, gid) {
2196
+ var stream = FS.getStreamChecked(fd);
2197
+ FS.doChown(stream, stream.node, false);
2198
+ },
2199
+ doTruncate(stream, node, len) {
2200
+ if (FS.isDir(node.mode)) {
2201
+ throw new FS.ErrnoError(31);
2202
+ }
2203
+ if (!FS.isFile(node.mode)) {
2204
+ throw new FS.ErrnoError(28);
2205
+ }
2206
+ var errCode = FS.nodePermissions(node, 'w');
2207
+ if (errCode) {
2208
+ throw new FS.ErrnoError(errCode);
2209
+ }
2210
+ FS.doSetAttr(stream, node, {
2211
+ size: len,
2212
+ timestamp: Date.now()
2213
+ });
2214
+ },
2215
+ truncate(path, len) {
2216
+ if (len < 0) {
2217
+ throw new FS.ErrnoError(28);
2218
+ }
2219
+ var node;
2220
+ if (typeof path == 'string') {
2221
+ var lookup = FS.lookupPath(path, { follow: true });
2222
+ node = lookup.node;
2223
+ } else {
2224
+ node = path;
2225
+ }
2226
+ FS.doTruncate(null, node, len);
2227
+ },
2228
+ ftruncate(fd, len) {
2229
+ var stream = FS.getStreamChecked(fd);
2230
+ if (len < 0 || (stream.flags & 2097155) === 0) {
2231
+ throw new FS.ErrnoError(28);
2232
+ }
2233
+ FS.doTruncate(stream, stream.node, len);
2234
+ },
2235
+ utime(path, atime, mtime) {
2236
+ var lookup = FS.lookupPath(path, { follow: true });
2237
+ var node = lookup.node;
2238
+ var setattr = FS.checkOpExists(node.node_ops.setattr, 63);
2239
+ setattr(node, {
2240
+ atime: atime,
2241
+ mtime: mtime
2242
+ });
2243
+ },
2244
+ open(path, flags, mode = 0o666) {
2245
+ if (path === "") {
2246
+ throw new FS.ErrnoError(44);
2247
+ }
2248
+ flags = FS_modeStringToFlags(flags);
2249
+ if ((flags & 64)) {
2250
+ mode = (mode & 4095) | 32768;
2251
+ } else {
2252
+ mode = 0;
2253
+ }
2254
+ var node;
2255
+ var isDirPath;
2256
+ if (typeof path == 'object') {
2257
+ node = path;
2258
+ } else {
2259
+ isDirPath = path.endsWith("/");
2260
+ // noent_okay makes it so that if the final component of the path
2261
+ // doesn't exist, lookupPath returns `node: undefined`. `path` will be
2262
+ // updated to point to the target of all symlinks.
2263
+ var lookup = FS.lookupPath(path, {
2264
+ follow: !(flags & 131072),
2265
+ noent_okay: true
2266
+ });
2267
+ node = lookup.node;
2268
+ path = lookup.path;
2269
+ }
2270
+ // perhaps we need to create the node
2271
+ var created = false;
2272
+ if ((flags & 64)) {
2273
+ if (node) {
2274
+ // if O_CREAT and O_EXCL are set, error out if the node already exists
2275
+ if ((flags & 128)) {
2276
+ throw new FS.ErrnoError(20);
2277
+ }
2278
+ } else if (isDirPath) {
2279
+ throw new FS.ErrnoError(31);
2280
+ } else {
2281
+ // node doesn't exist, try to create it
2282
+ // Ignore the permission bits here to ensure we can `open` this new
2283
+ // file below. We use chmod below to apply the permissions once the
2284
+ // file is open.
2285
+ node = FS.mknod(path, mode | 0o777, 0);
2286
+ created = true;
2287
+ }
2288
+ }
2289
+ if (!node) {
2290
+ throw new FS.ErrnoError(44);
2291
+ }
2292
+ // can't truncate a device
2293
+ if (FS.isChrdev(node.mode)) {
2294
+ flags &= ~512;
2295
+ }
2296
+ // if asked only for a directory, then this must be one
2297
+ if ((flags & 65536) && !FS.isDir(node.mode)) {
2298
+ throw new FS.ErrnoError(54);
2299
+ }
2300
+ // check permissions, if this is not a file we just created now (it is ok to
2301
+ // create and write to a file with read-only permissions; it is read-only
2302
+ // for later use)
2303
+ if (!created) {
2304
+ var errCode = FS.mayOpen(node, flags);
2305
+ if (errCode) {
2306
+ throw new FS.ErrnoError(errCode);
2307
+ }
2308
+ }
2309
+ // do truncation if necessary
2310
+ if ((flags & 512) && !created) {
2311
+ FS.truncate(node, 0);
2312
+ }
2313
+ // we've already handled these, don't pass down to the underlying vfs
2314
+ flags &= ~(128 | 512 | 131072);
2315
+
2316
+ // register the stream with the filesystem
2317
+ var stream = FS.createStream({
2318
+ node,
2319
+ path: FS.getPath(node), // we want the absolute path to the node
2320
+ flags,
2321
+ seekable: true,
2322
+ position: 0,
2323
+ stream_ops: node.stream_ops,
2324
+ // used by the file family libc calls (fopen, fwrite, ferror, etc.)
2325
+ ungotten: [],
2326
+ error: false
2327
+ });
2328
+ // call the new stream's open function
2329
+ if (stream.stream_ops.open) {
2330
+ stream.stream_ops.open(stream);
2331
+ }
2332
+ if (created) {
2333
+ FS.chmod(node, mode & 0o777);
2334
+ }
2335
+ return stream;
2336
+ },
2337
+ close(stream) {
2338
+ if (FS.isClosed(stream)) {
2339
+ throw new FS.ErrnoError(8);
2340
+ }
2341
+ if (stream.getdents) stream.getdents = null; // free readdir state
2342
+ try {
2343
+ if (stream.stream_ops.close) {
2344
+ stream.stream_ops.close(stream);
2345
+ }
2346
+ } catch (e) {
2347
+ throw e;
2348
+ } finally {
2349
+ FS.closeStream(stream.fd);
2350
+ }
2351
+ stream.fd = null;
2352
+ },
2353
+ isClosed(stream) {
2354
+ return stream.fd === null;
2355
+ },
2356
+ llseek(stream, offset, whence) {
2357
+ if (FS.isClosed(stream)) {
2358
+ throw new FS.ErrnoError(8);
2359
+ }
2360
+ if (!stream.seekable || !stream.stream_ops.llseek) {
2361
+ throw new FS.ErrnoError(70);
2362
+ }
2363
+ if (whence != 0 && whence != 1 && whence != 2) {
2364
+ throw new FS.ErrnoError(28);
2365
+ }
2366
+ stream.position = stream.stream_ops.llseek(stream, offset, whence);
2367
+ stream.ungotten = [];
2368
+ return stream.position;
2369
+ },
2370
+ read(stream, buffer, offset, length, position) {
2371
+ if (length < 0 || position < 0) {
2372
+ throw new FS.ErrnoError(28);
2373
+ }
2374
+ if (FS.isClosed(stream)) {
2375
+ throw new FS.ErrnoError(8);
2376
+ }
2377
+ if ((stream.flags & 2097155) === 1) {
2378
+ throw new FS.ErrnoError(8);
2379
+ }
2380
+ if (FS.isDir(stream.node.mode)) {
2381
+ throw new FS.ErrnoError(31);
2382
+ }
2383
+ if (!stream.stream_ops.read) {
2384
+ throw new FS.ErrnoError(28);
2385
+ }
2386
+ var seeking = typeof position != 'undefined';
2387
+ if (!seeking) {
2388
+ position = stream.position;
2389
+ } else if (!stream.seekable) {
2390
+ throw new FS.ErrnoError(70);
2391
+ }
2392
+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
2393
+ if (!seeking) stream.position += bytesRead;
2394
+ return bytesRead;
2395
+ },
2396
+ write(stream, buffer, offset, length, position, canOwn) {
2397
+ if (length < 0 || position < 0) {
2398
+ throw new FS.ErrnoError(28);
2399
+ }
2400
+ if (FS.isClosed(stream)) {
2401
+ throw new FS.ErrnoError(8);
2402
+ }
2403
+ if ((stream.flags & 2097155) === 0) {
2404
+ throw new FS.ErrnoError(8);
2405
+ }
2406
+ if (FS.isDir(stream.node.mode)) {
2407
+ throw new FS.ErrnoError(31);
2408
+ }
2409
+ if (!stream.stream_ops.write) {
2410
+ throw new FS.ErrnoError(28);
2411
+ }
2412
+ if (stream.seekable && stream.flags & 1024) {
2413
+ // seek to the end before writing in append mode
2414
+ FS.llseek(stream, 0, 2);
2415
+ }
2416
+ var seeking = typeof position != 'undefined';
2417
+ if (!seeking) {
2418
+ position = stream.position;
2419
+ } else if (!stream.seekable) {
2420
+ throw new FS.ErrnoError(70);
2421
+ }
2422
+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
2423
+ if (!seeking) stream.position += bytesWritten;
2424
+ return bytesWritten;
2425
+ },
2426
+ mmap(stream, length, position, prot, flags) {
2427
+ // User requests writing to file (prot & PROT_WRITE != 0).
2428
+ // Checking if we have permissions to write to the file unless
2429
+ // MAP_PRIVATE flag is set. According to POSIX spec it is possible
2430
+ // to write to file opened in read-only mode with MAP_PRIVATE flag,
2431
+ // as all modifications will be visible only in the memory of
2432
+ // the current process.
2433
+ if ((prot & 2) !== 0
2434
+ && (flags & 2) === 0
2435
+ && (stream.flags & 2097155) !== 2) {
2436
+ throw new FS.ErrnoError(2);
2437
+ }
2438
+ if ((stream.flags & 2097155) === 1) {
2439
+ throw new FS.ErrnoError(2);
2440
+ }
2441
+ if (!stream.stream_ops.mmap) {
2442
+ throw new FS.ErrnoError(43);
2443
+ }
2444
+ if (!length) {
2445
+ throw new FS.ErrnoError(28);
2446
+ }
2447
+ return stream.stream_ops.mmap(stream, length, position, prot, flags);
2448
+ },
2449
+ msync(stream, buffer, offset, length, mmapFlags) {
2450
+ if (!stream.stream_ops.msync) {
2451
+ return 0;
2452
+ }
2453
+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
2454
+ },
2455
+ ioctl(stream, cmd, arg) {
2456
+ if (!stream.stream_ops.ioctl) {
2457
+ throw new FS.ErrnoError(59);
2458
+ }
2459
+ return stream.stream_ops.ioctl(stream, cmd, arg);
2460
+ },
2461
+ readFile(path, opts = {}) {
2462
+ opts.flags = opts.flags ?? 0;
2463
+ opts.encoding = opts.encoding ?? 'binary';
2464
+ if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
2465
+ abort(`Invalid encoding type "${opts.encoding}"`);
2466
+ }
2467
+ var stream = FS.open(path, opts.flags);
2468
+ var stat = FS.stat(path);
2469
+ var length = stat.size;
2470
+ var buf = new Uint8Array(length);
2471
+ FS.read(stream, buf, 0, length, 0);
2472
+ if (opts.encoding === 'utf8') {
2473
+ buf = UTF8ArrayToString(buf);
2474
+ }
2475
+ FS.close(stream);
2476
+ return buf;
2477
+ },
2478
+ writeFile(path, data, opts = {}) {
2479
+ opts.flags = opts.flags ?? 577;
2480
+ var stream = FS.open(path, opts.flags, opts.mode);
2481
+ data = FS_fileDataToTypedArray(data);
2482
+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
2483
+ FS.close(stream);
2484
+ },
2485
+ cwd:() => FS.currentPath,
2486
+ chdir(path) {
2487
+ var lookup = FS.lookupPath(path, { follow: true });
2488
+ if (lookup.node === null) {
2489
+ throw new FS.ErrnoError(44);
2490
+ }
2491
+ if (!FS.isDir(lookup.node.mode)) {
2492
+ throw new FS.ErrnoError(54);
2493
+ }
2494
+ var errCode = FS.nodePermissions(lookup.node, 'x');
2495
+ if (errCode) {
2496
+ throw new FS.ErrnoError(errCode);
2497
+ }
2498
+ FS.currentPath = lookup.path;
2499
+ },
2500
+ createDefaultDirectories() {
2501
+ FS.mkdir('/tmp');
2502
+ FS.mkdir('/home');
2503
+ FS.mkdir('/home/web_user');
2504
+ },
2505
+ createDefaultDevices() {
2506
+ // create /dev
2507
+ FS.mkdir('/dev');
2508
+ // setup /dev/null
2509
+ FS.registerDevice(FS.makedev(1, 3), {
2510
+ read: () => 0,
2511
+ write: (stream, buffer, offset, length, pos) => length,
2512
+ llseek: () => 0,
2513
+ });
2514
+ FS.mkdev('/dev/null', FS.makedev(1, 3));
2515
+ // setup /dev/tty and /dev/tty1
2516
+ // stderr needs to print output using err() rather than out()
2517
+ // so we register a second tty just for it.
2518
+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
2519
+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
2520
+ FS.mkdev('/dev/tty', FS.makedev(5, 0));
2521
+ FS.mkdev('/dev/tty1', FS.makedev(6, 0));
2522
+ // setup /dev/[u]random
2523
+ // use a buffer to avoid overhead of individual crypto calls per byte
2524
+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;
2525
+ var randomByte = () => {
2526
+ if (randomLeft === 0) {
2527
+ randomFill(randomBuffer);
2528
+ randomLeft = randomBuffer.byteLength;
2529
+ }
2530
+ return randomBuffer[--randomLeft];
2531
+ };
2532
+ FS.createDevice('/dev', 'random', randomByte);
2533
+ FS.createDevice('/dev', 'urandom', randomByte);
2534
+ // we're not going to emulate the actual shm device,
2535
+ // just create the tmp dirs that reside in it commonly
2536
+ FS.mkdir('/dev/shm');
2537
+ FS.mkdir('/dev/shm/tmp');
2538
+ },
2539
+ createSpecialDirectories() {
2540
+ // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the
2541
+ // name of the stream for fd 6 (see test_unistd_ttyname)
2542
+ FS.mkdir('/proc');
2543
+ var proc_self = FS.mkdir('/proc/self');
2544
+ FS.mkdir('/proc/self/fd');
2545
+ FS.mount({
2546
+ mount() {
2547
+ var node = FS.createNode(proc_self, 'fd', 16895, 73);
2548
+ node.stream_ops = {
2549
+ llseek: MEMFS.stream_ops.llseek,
2550
+ };
2551
+ node.node_ops = {
2552
+ lookup(parent, name) {
2553
+ var fd = +name;
2554
+ var stream = FS.getStreamChecked(fd);
2555
+ var ret = {
2556
+ parent: null,
2557
+ mount: { mountpoint: 'fake' },
2558
+ node_ops: { readlink: () => stream.path },
2559
+ id: fd + 1,
2560
+ };
2561
+ ret.parent = ret; // make it look like a simple root node
2562
+ return ret;
2563
+ },
2564
+ readdir() {
2565
+ return Array.from(FS.streams.entries())
2566
+ .filter(([k, v]) => v)
2567
+ .map(([k, v]) => k.toString());
2568
+ }
2569
+ };
2570
+ return node;
2571
+ }
2572
+ }, {}, '/proc/self/fd');
2573
+ },
2574
+ createStandardStreams(input, output, error) {
2575
+ // TODO deprecate the old functionality of a single
2576
+ // input / output callback and that utilizes FS.createDevice
2577
+ // and instead require a unique set of stream ops
2578
+
2579
+ // by default, we symlink the standard streams to the
2580
+ // default tty devices. however, if the standard streams
2581
+ // have been overwritten we create a unique device for
2582
+ // them instead.
2583
+ if (input) {
2584
+ FS.createDevice('/dev', 'stdin', input);
2585
+ } else {
2586
+ FS.symlink('/dev/tty', '/dev/stdin');
2587
+ }
2588
+ if (output) {
2589
+ FS.createDevice('/dev', 'stdout', null, output);
2590
+ } else {
2591
+ FS.symlink('/dev/tty', '/dev/stdout');
2592
+ }
2593
+ if (error) {
2594
+ FS.createDevice('/dev', 'stderr', null, error);
2595
+ } else {
2596
+ FS.symlink('/dev/tty1', '/dev/stderr');
2597
+ }
2598
+
2599
+ // open default streams for the stdin, stdout and stderr devices
2600
+ var stdin = FS.open('/dev/stdin', 0);
2601
+ var stdout = FS.open('/dev/stdout', 1);
2602
+ var stderr = FS.open('/dev/stderr', 1);
2603
+ },
2604
+ staticInit() {
2605
+ FS.nameTable = new Array(4096);
2606
+
2607
+ FS.mount(MEMFS, {}, '/');
2608
+
2609
+ FS.createDefaultDirectories();
2610
+ FS.createDefaultDevices();
2611
+ FS.createSpecialDirectories();
2612
+
2613
+ FS.filesystems = {
2614
+ 'MEMFS': MEMFS,
2615
+ };
2616
+ },
2617
+ init(input, output, error) {
2618
+ FS.initialized = true;
2619
+
2620
+ // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
2621
+
2622
+ FS.createStandardStreams(input, output, error);
2623
+ },
2624
+ quit() {
2625
+ FS.initialized = false;
2626
+ // force-flush all streams, so we get musl std streams printed out
2627
+ // close all of our streams
2628
+ for (var stream of FS.streams) {
2629
+ if (stream) {
2630
+ FS.close(stream);
2631
+ }
2632
+ }
2633
+ },
2634
+ findObject(path, dontResolveLastLink) {
2635
+ var ret = FS.analyzePath(path, dontResolveLastLink);
2636
+ if (!ret.exists) {
2637
+ return null;
2638
+ }
2639
+ return ret.object;
2640
+ },
2641
+ analyzePath(path, dontResolveLastLink) {
2642
+ // operate from within the context of the symlink's target
2643
+ try {
2644
+ var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
2645
+ path = lookup.path;
2646
+ } catch (e) {
2647
+ }
2648
+ var ret = {
2649
+ isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
2650
+ parentExists: false, parentPath: null, parentObject: null
2651
+ };
2652
+ try {
2653
+ var lookup = FS.lookupPath(path, { parent: true });
2654
+ ret.parentExists = true;
2655
+ ret.parentPath = lookup.path;
2656
+ ret.parentObject = lookup.node;
2657
+ ret.name = PATH.basename(path);
2658
+ lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
2659
+ ret.exists = true;
2660
+ ret.path = lookup.path;
2661
+ ret.object = lookup.node;
2662
+ ret.name = lookup.node.name;
2663
+ ret.isRoot = lookup.path === '/';
2664
+ } catch (e) {
2665
+ ret.error = e.errno;
2666
+ };
2667
+ return ret;
2668
+ },
2669
+ createPath(parent, path, canRead, canWrite) {
2670
+ parent = typeof parent == 'string' ? parent : FS.getPath(parent);
2671
+ var parts = path.split('/').reverse();
2672
+ while (parts.length) {
2673
+ var part = parts.pop();
2674
+ if (!part) continue;
2675
+ var current = PATH.join2(parent, part);
2676
+ try {
2677
+ FS.mkdir(current);
2678
+ } catch (e) {
2679
+ if (e.errno != 20) throw e;
2680
+ }
2681
+ parent = current;
2682
+ }
2683
+ return current;
2684
+ },
2685
+ createFile(parent, name, properties, canRead, canWrite) {
2686
+ var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
2687
+ var mode = FS_getMode(canRead, canWrite);
2688
+ return FS.create(path, mode);
2689
+ },
2690
+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {
2691
+ var path = name;
2692
+ if (parent) {
2693
+ parent = typeof parent == 'string' ? parent : FS.getPath(parent);
2694
+ path = name ? PATH.join2(parent, name) : parent;
2695
+ }
2696
+ var mode = FS_getMode(canRead, canWrite);
2697
+ var node = FS.create(path, mode);
2698
+ if (data) {
2699
+ data = FS_fileDataToTypedArray(data);
2700
+ // make sure we can write to the file
2701
+ FS.chmod(node, mode | 146);
2702
+ var stream = FS.open(node, 577);
2703
+ FS.write(stream, data, 0, data.length, 0, canOwn);
2704
+ FS.close(stream);
2705
+ FS.chmod(node, mode);
2706
+ }
2707
+ },
2708
+ createDevice(parent, name, input, output) {
2709
+ var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
2710
+ var mode = FS_getMode(!!input, !!output);
2711
+ FS.createDevice.major ??= 64;
2712
+ var dev = FS.makedev(FS.createDevice.major++, 0);
2713
+ // Create a fake device that a set of stream ops to emulate
2714
+ // the old behavior.
2715
+ FS.registerDevice(dev, {
2716
+ open(stream) {
2717
+ stream.seekable = false;
2718
+ },
2719
+ close(stream) {
2720
+ // flush any pending line data
2721
+ if (output?.buffer?.length) {
2722
+ output(10);
2723
+ }
2724
+ },
2725
+ read(stream, buffer, offset, length, pos /* ignored */) {
2726
+ var bytesRead = 0;
2727
+ for (var i = 0; i < length; i++) {
2728
+ var result;
2729
+ try {
2730
+ result = input();
2731
+ } catch (e) {
2732
+ throw new FS.ErrnoError(29);
2733
+ }
2734
+ if (result === undefined && bytesRead === 0) {
2735
+ throw new FS.ErrnoError(6);
2736
+ }
2737
+ if (result === null || result === undefined) break;
2738
+ bytesRead++;
2739
+ buffer[offset+i] = result;
2740
+ }
2741
+ if (bytesRead) {
2742
+ stream.node.atime = Date.now();
2743
+ }
2744
+ return bytesRead;
2745
+ },
2746
+ write(stream, buffer, offset, length, pos) {
2747
+ for (var i = 0; i < length; i++) {
2748
+ try {
2749
+ output(buffer[offset+i]);
2750
+ } catch (e) {
2751
+ throw new FS.ErrnoError(29);
2752
+ }
2753
+ }
2754
+ if (length) {
2755
+ stream.node.mtime = stream.node.ctime = Date.now();
2756
+ }
2757
+ return i;
2758
+ }
2759
+ });
2760
+ return FS.mkdev(path, mode, dev);
2761
+ },
2762
+ forceLoadFile(obj) {
2763
+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
2764
+ if (globalThis.XMLHttpRequest) {
2765
+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");
2766
+ } else { // Command-line.
2767
+ try {
2768
+ obj.contents = readBinary(obj.url);
2769
+ } catch (e) {
2770
+ throw new FS.ErrnoError(29);
2771
+ }
2772
+ }
2773
+ },
2774
+ createLazyFile(parent, name, url, canRead, canWrite) {
2775
+ // Lazy chunked Uint8Array (implements get and length from Uint8Array).
2776
+ // Actual getting is abstracted away for eventual reuse.
2777
+ class LazyUint8Array {
2778
+ lengthKnown = false;
2779
+ chunks = []; // Loaded chunks. Index is the chunk number
2780
+ get(idx) {
2781
+ if (idx > this.length-1 || idx < 0) {
2782
+ return undefined;
2783
+ }
2784
+ var chunkOffset = idx % this.chunkSize;
2785
+ var chunkNum = (idx / this.chunkSize)|0;
2786
+ return this.getter(chunkNum)[chunkOffset];
2787
+ }
2788
+ setDataGetter(getter) {
2789
+ this.getter = getter;
2790
+ }
2791
+ cacheLength() {
2792
+ // Find length
2793
+ var xhr = new XMLHttpRequest();
2794
+ xhr.open('HEAD', url, false);
2795
+ xhr.send(null);
2796
+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);
2797
+ var datalength = Number(xhr.getResponseHeader("Content-length"));
2798
+ var header;
2799
+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
2800
+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
2801
+
2802
+ var chunkSize = 1024*1024; // Chunk size in bytes
2803
+
2804
+ if (!hasByteServing) chunkSize = datalength;
2805
+
2806
+ // Function to get a range from the remote URL.
2807
+ var doXHR = (from, to) => {
2808
+ if (from > to) abort(`invalid range (${from}, ${to}) or no bytes requested!`);
2809
+ if (to > datalength-1) abort(`only ${datalength} bytes available! programmer error!`);
2810
+
2811
+ // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
2812
+ var xhr = new XMLHttpRequest();
2813
+ xhr.open('GET', url, false);
2814
+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
2815
+
2816
+ // Some hints to the browser that we want binary data.
2817
+ xhr.responseType = 'arraybuffer';
2818
+ if (xhr.overrideMimeType) {
2819
+ xhr.overrideMimeType('text/plain; charset=x-user-defined');
2820
+ }
2821
+
2822
+ xhr.send(null);
2823
+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);
2824
+ if (xhr.response !== undefined) {
2825
+ return new Uint8Array(/** @type{Array<number>} */(xhr.response || []));
2826
+ }
2827
+ return intArrayFromString(xhr.responseText ?? '', true);
2828
+ };
2829
+ var lazyArray = this;
2830
+ lazyArray.setDataGetter((chunkNum) => {
2831
+ var start = chunkNum * chunkSize;
2832
+ var end = (chunkNum+1) * chunkSize - 1; // including this byte
2833
+ end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
2834
+ if (typeof lazyArray.chunks[chunkNum] == 'undefined') {
2835
+ lazyArray.chunks[chunkNum] = doXHR(start, end);
2836
+ }
2837
+ if (typeof lazyArray.chunks[chunkNum] == 'undefined') abort('doXHR failed!');
2838
+ return lazyArray.chunks[chunkNum];
2839
+ });
2840
+
2841
+ if (usesGzip || !datalength) {
2842
+ // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
2843
+ chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
2844
+ datalength = this.getter(0).length;
2845
+ chunkSize = datalength;
2846
+ out("LazyFiles on gzip forces download of the whole file when length is accessed");
2847
+ }
2848
+
2849
+ this._length = datalength;
2850
+ this._chunkSize = chunkSize;
2851
+ this.lengthKnown = true;
2852
+ }
2853
+ get length() {
2854
+ if (!this.lengthKnown) {
2855
+ this.cacheLength();
2856
+ }
2857
+ return this._length;
2858
+ }
2859
+ get chunkSize() {
2860
+ if (!this.lengthKnown) {
2861
+ this.cacheLength();
2862
+ }
2863
+ return this._chunkSize;
2864
+ }
2865
+ }
2866
+
2867
+ if (globalThis.XMLHttpRequest) {
2868
+ if (!ENVIRONMENT_IS_WORKER) abort('Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc');
2869
+ var lazyArray = new LazyUint8Array();
2870
+ var properties = { isDevice: false, contents: lazyArray };
2871
+ } else {
2872
+ var properties = { isDevice: false, url: url };
2873
+ }
2874
+
2875
+ var node = FS.createFile(parent, name, properties, canRead, canWrite);
2876
+ // This is a total hack, but I want to get this lazy file code out of the
2877
+ // core of MEMFS. If we want to keep this lazy file concept I feel it should
2878
+ // be its own thin LAZYFS proxying calls to MEMFS.
2879
+ if (properties.contents) {
2880
+ node.contents = properties.contents;
2881
+ } else if (properties.url) {
2882
+ node.contents = null;
2883
+ node.url = properties.url;
2884
+ }
2885
+ // Add a function that defers querying the file size until it is asked the first time.
2886
+ Object.defineProperties(node, {
2887
+ usedBytes: {
2888
+ get: function() { return this.contents.length; }
2889
+ }
2890
+ });
2891
+ // override each stream op with one that tries to force load the lazy file first
2892
+ var stream_ops = {};
2893
+ for (const [key, fn] of Object.entries(node.stream_ops)) {
2894
+ stream_ops[key] = (...args) => {
2895
+ FS.forceLoadFile(node);
2896
+ return fn(...args);
2897
+ };
2898
+ }
2899
+ function writeChunks(stream, buffer, offset, length, position) {
2900
+ var contents = stream.node.contents;
2901
+ if (position >= contents.length)
2902
+ return 0;
2903
+ var size = Math.min(contents.length - position, length);
2904
+ if (contents.slice) { // normal array
2905
+ for (var i = 0; i < size; i++) {
2906
+ buffer[offset + i] = contents[position + i];
2907
+ }
2908
+ } else {
2909
+ for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
2910
+ buffer[offset + i] = contents.get(position + i);
2911
+ }
2912
+ }
2913
+ return size;
2914
+ }
2915
+ // use a custom read function
2916
+ stream_ops.read = (stream, buffer, offset, length, position) => {
2917
+ FS.forceLoadFile(node);
2918
+ return writeChunks(stream, buffer, offset, length, position)
2919
+ };
2920
+ // use a custom mmap function
2921
+ stream_ops.mmap = (stream, length, position, prot, flags) => {
2922
+ FS.forceLoadFile(node);
2923
+ var ptr = mmapAlloc(length);
2924
+ if (!ptr) {
2925
+ throw new FS.ErrnoError(48);
2926
+ }
2927
+ writeChunks(stream, HEAP8, ptr, length, position);
2928
+ return { ptr, allocated: true };
2929
+ };
2930
+ node.stream_ops = stream_ops;
2931
+ return node;
2932
+ },
2933
+ };
2934
+
2935
+ var SYSCALLS = {
2936
+ currentUmask:18,
2937
+ calculateAt(dirfd, path, allowEmpty) {
2938
+ if (PATH.isAbs(path)) {
2939
+ return path;
2940
+ }
2941
+ // relative path
2942
+ var dir;
2943
+ if (dirfd === -100) {
2944
+ dir = FS.cwd();
2945
+ } else {
2946
+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);
2947
+ dir = dirstream.path;
2948
+ }
2949
+ if (path.length == 0) {
2950
+ if (!allowEmpty) {
2951
+ throw new FS.ErrnoError(44);;
2952
+ }
2953
+ return dir;
2954
+ }
2955
+ return dir + '/' + path;
2956
+ },
2957
+ writeStat(buf, stat) {
2958
+ HEAPU32[((buf)>>2)] = stat.dev;
2959
+ HEAPU32[(((buf)+(4))>>2)] = stat.mode;
2960
+ HEAPU32[(((buf)+(8))>>2)] = stat.nlink;
2961
+ HEAPU32[(((buf)+(12))>>2)] = stat.uid;
2962
+ HEAPU32[(((buf)+(16))>>2)] = stat.gid;
2963
+ HEAPU32[(((buf)+(20))>>2)] = stat.rdev;
2964
+ HEAP64[(((buf)+(24))>>3)] = BigInt(stat.size);
2965
+ HEAP32[(((buf)+(32))>>2)] = 4096;
2966
+ HEAP32[(((buf)+(36))>>2)] = stat.blocks;
2967
+ var atime = stat.atime.getTime();
2968
+ var mtime = stat.mtime.getTime();
2969
+ var ctime = stat.ctime.getTime();
2970
+ HEAP64[(((buf)+(40))>>3)] = BigInt(Math.floor(atime / 1000));
2971
+ HEAPU32[(((buf)+(48))>>2)] = (atime % 1000) * 1000 * 1000;
2972
+ HEAP64[(((buf)+(56))>>3)] = BigInt(Math.floor(mtime / 1000));
2973
+ HEAPU32[(((buf)+(64))>>2)] = (mtime % 1000) * 1000 * 1000;
2974
+ HEAP64[(((buf)+(72))>>3)] = BigInt(Math.floor(ctime / 1000));
2975
+ HEAPU32[(((buf)+(80))>>2)] = (ctime % 1000) * 1000 * 1000;
2976
+ HEAP64[(((buf)+(88))>>3)] = BigInt(stat.ino);
2977
+ return 0;
2978
+ },
2979
+ writeStatFs(buf, stats) {
2980
+ HEAPU32[(((buf)+(4))>>2)] = stats.bsize;
2981
+ HEAPU32[(((buf)+(60))>>2)] = stats.bsize;
2982
+ HEAP64[(((buf)+(8))>>3)] = BigInt(stats.blocks);
2983
+ HEAP64[(((buf)+(16))>>3)] = BigInt(stats.bfree);
2984
+ HEAP64[(((buf)+(24))>>3)] = BigInt(stats.bavail);
2985
+ HEAP64[(((buf)+(32))>>3)] = BigInt(stats.files);
2986
+ HEAP64[(((buf)+(40))>>3)] = BigInt(stats.ffree);
2987
+ HEAPU32[(((buf)+(48))>>2)] = stats.fsid;
2988
+ HEAPU32[(((buf)+(64))>>2)] = stats.flags; // ST_NOSUID
2989
+ HEAPU32[(((buf)+(56))>>2)] = stats.namelen;
2990
+ },
2991
+ doMsync(addr, stream, len, flags, offset) {
2992
+ if (!FS.isFile(stream.node.mode)) {
2993
+ throw new FS.ErrnoError(43);
2994
+ }
2995
+ if (flags & 2) {
2996
+ // MAP_PRIVATE calls need not to be synced back to underlying fs
2997
+ return 0;
2998
+ }
2999
+ var buffer = HEAPU8.subarray(addr, addr + len);
3000
+ FS.msync(stream, buffer, offset, len, flags);
3001
+ },
3002
+ getStreamFromFD(fd) {
3003
+ var stream = FS.getStreamChecked(fd);
3004
+ return stream;
3005
+ },
3006
+ varargs:undefined,
3007
+ getStr(ptr) {
3008
+ var ret = UTF8ToString(ptr);
3009
+ return ret;
3010
+ },
3011
+ };
3012
+ function ___syscall_fcntl64(fd, cmd, varargs) {
3013
+ SYSCALLS.varargs = varargs;
3014
+ try {
3015
+
3016
+ var stream = SYSCALLS.getStreamFromFD(fd);
3017
+ switch (cmd) {
3018
+ case 0: {
3019
+ var arg = syscallGetVarargI();
3020
+ if (arg < 0) {
3021
+ return -28;
3022
+ }
3023
+ while (FS.streams[arg]) {
3024
+ arg++;
3025
+ }
3026
+ var newStream;
3027
+ newStream = FS.dupStream(stream, arg);
3028
+ return newStream.fd;
3029
+ }
3030
+ case 1:
3031
+ case 2:
3032
+ return 0; // FD_CLOEXEC makes no sense for a single process.
3033
+ case 3:
3034
+ return stream.flags;
3035
+ case 4: {
3036
+ var arg = syscallGetVarargI();
3037
+ var mask = 289792;
3038
+ stream.flags = (stream.flags & ~mask) | (arg & mask);
3039
+ return 0;
3040
+ }
3041
+ case 12: {
3042
+ var arg = syscallGetVarargP();
3043
+ var offset = 0;
3044
+ // We're always unlocked.
3045
+ HEAP16[(((arg)+(offset))>>1)] = 2;
3046
+ return 0;
3047
+ }
3048
+ case 13:
3049
+ case 14:
3050
+ // Pretend that the locking is successful. These are process-level locks,
3051
+ // and Emscripten programs are a single process. If we supported linking a
3052
+ // filesystem between programs, we'd need to do more here.
3053
+ // See https://github.com/emscripten-core/emscripten/issues/23697
3054
+ return 0;
3055
+ }
3056
+ return -28;
3057
+ } catch (e) {
3058
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3059
+ return -e.errno;
3060
+ }
3061
+ }
3062
+
3063
+
3064
+ function ___syscall_fstat64(fd, buf) {
3065
+ try {
3066
+
3067
+ return SYSCALLS.writeStat(buf, FS.fstat(fd));
3068
+ } catch (e) {
3069
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3070
+ return -e.errno;
3071
+ }
3072
+ }
3073
+
3074
+
3075
+ var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
3076
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
3077
+ };
3078
+
3079
+ function ___syscall_getdents64(fd, dirp, count) {
3080
+ try {
3081
+
3082
+ var stream = SYSCALLS.getStreamFromFD(fd)
3083
+ stream.getdents ||= FS.readdir(stream.path);
3084
+
3085
+ var struct_size = 280;
3086
+ var pos = 0;
3087
+ var off = FS.llseek(stream, 0, 1);
3088
+
3089
+ var startIdx = Math.floor(off / struct_size);
3090
+ var endIdx = Math.min(stream.getdents.length, startIdx + Math.floor(count/struct_size))
3091
+ for (var idx = startIdx; idx < endIdx; idx++) {
3092
+ var id;
3093
+ var type;
3094
+ var name = stream.getdents[idx];
3095
+ if (name === '.') {
3096
+ id = stream.node.id;
3097
+ type = 4;
3098
+ }
3099
+ else if (name === '..') {
3100
+ var lookup = FS.lookupPath(stream.path, { parent: true });
3101
+ id = lookup.node.id;
3102
+ type = 4;
3103
+ }
3104
+ else {
3105
+ var child;
3106
+ try {
3107
+ child = FS.lookupNode(stream.node, name);
3108
+ } catch (e) {
3109
+ // If the entry is not a directory, file, or symlink, nodefs
3110
+ // lookupNode will raise EINVAL. Skip these and continue.
3111
+ if (e?.errno === 28) {
3112
+ continue;
3113
+ }
3114
+ throw e;
3115
+ }
3116
+ id = child.id;
3117
+ type = FS.isChrdev(child.mode) ? 2 : // character device.
3118
+ FS.isDir(child.mode) ? 4 : // directory
3119
+ FS.isLink(child.mode) ? 10 : // symbolic link.
3120
+ 8; // regular file.
3121
+ }
3122
+ HEAP64[((dirp + pos)>>3)] = BigInt(id);
3123
+ HEAP64[(((dirp + pos)+(8))>>3)] = BigInt((idx + 1) * struct_size);
3124
+ HEAP16[(((dirp + pos)+(16))>>1)] = 280;
3125
+ HEAP8[(dirp + pos)+(18)] = type;
3126
+ stringToUTF8(name, dirp + pos + 19, 256);
3127
+ pos += struct_size;
3128
+ }
3129
+ FS.llseek(stream, idx * struct_size, 0);
3130
+ return pos;
3131
+ } catch (e) {
3132
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3133
+ return -e.errno;
3134
+ }
3135
+ }
3136
+
3137
+
3138
+
3139
+ function ___syscall_ioctl(fd, op, varargs) {
3140
+ SYSCALLS.varargs = varargs;
3141
+ try {
3142
+
3143
+ var stream = SYSCALLS.getStreamFromFD(fd);
3144
+ switch (op) {
3145
+ case 21509: {
3146
+ if (!stream.tty) return -59;
3147
+ return 0;
3148
+ }
3149
+ case 21505: {
3150
+ if (!stream.tty) return -59;
3151
+ if (stream.tty.ops.ioctl_tcgets) {
3152
+ var termios = stream.tty.ops.ioctl_tcgets(stream);
3153
+ var argp = syscallGetVarargP();
3154
+ HEAP32[((argp)>>2)] = termios.c_iflag || 0;
3155
+ HEAP32[(((argp)+(4))>>2)] = termios.c_oflag || 0;
3156
+ HEAP32[(((argp)+(8))>>2)] = termios.c_cflag || 0;
3157
+ HEAP32[(((argp)+(12))>>2)] = termios.c_lflag || 0;
3158
+ for (var i = 0; i < 32; i++) {
3159
+ HEAP8[(argp + i)+(17)] = termios.c_cc[i] || 0;
3160
+ }
3161
+ return 0;
3162
+ }
3163
+ return 0;
3164
+ }
3165
+ case 21510:
3166
+ case 21511:
3167
+ case 21512: {
3168
+ if (!stream.tty) return -59;
3169
+ return 0; // no-op, not actually adjusting terminal settings
3170
+ }
3171
+ case 21506:
3172
+ case 21507:
3173
+ case 21508: {
3174
+ if (!stream.tty) return -59;
3175
+ if (stream.tty.ops.ioctl_tcsets) {
3176
+ var argp = syscallGetVarargP();
3177
+ var c_iflag = HEAP32[((argp)>>2)];
3178
+ var c_oflag = HEAP32[(((argp)+(4))>>2)];
3179
+ var c_cflag = HEAP32[(((argp)+(8))>>2)];
3180
+ var c_lflag = HEAP32[(((argp)+(12))>>2)];
3181
+ var c_cc = []
3182
+ for (var i = 0; i < 32; i++) {
3183
+ c_cc.push(HEAP8[(argp + i)+(17)]);
3184
+ }
3185
+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, { c_iflag, c_oflag, c_cflag, c_lflag, c_cc });
3186
+ }
3187
+ return 0; // no-op, not actually adjusting terminal settings
3188
+ }
3189
+ case 21519: {
3190
+ if (!stream.tty) return -59;
3191
+ var argp = syscallGetVarargP();
3192
+ HEAP32[((argp)>>2)] = 0;
3193
+ return 0;
3194
+ }
3195
+ case 21520: {
3196
+ if (!stream.tty) return -59;
3197
+ return -28; // not supported
3198
+ }
3199
+ case 21537:
3200
+ case 21531: {
3201
+ var argp = syscallGetVarargP();
3202
+ return FS.ioctl(stream, op, argp);
3203
+ }
3204
+ case 21523: {
3205
+ // TODO: in theory we should write to the winsize struct that gets
3206
+ // passed in, but for now musl doesn't read anything on it
3207
+ if (!stream.tty) return -59;
3208
+ if (stream.tty.ops.ioctl_tiocgwinsz) {
3209
+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
3210
+ var argp = syscallGetVarargP();
3211
+ HEAP16[((argp)>>1)] = winsize[0];
3212
+ HEAP16[(((argp)+(2))>>1)] = winsize[1];
3213
+ }
3214
+ return 0;
3215
+ }
3216
+ case 21524: {
3217
+ // TODO: technically, this ioctl call should change the window size.
3218
+ // but, since emscripten doesn't have any concept of a terminal window
3219
+ // yet, we'll just silently throw it away as we do TIOCGWINSZ
3220
+ if (!stream.tty) return -59;
3221
+ return 0;
3222
+ }
3223
+ case 21515: {
3224
+ if (!stream.tty) return -59;
3225
+ return 0;
3226
+ }
3227
+ default: return -28; // not supported
3228
+ }
3229
+ } catch (e) {
3230
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3231
+ return -e.errno;
3232
+ }
3233
+ }
3234
+
3235
+
3236
+ function ___syscall_lstat64(path, buf) {
3237
+ try {
3238
+
3239
+ path = SYSCALLS.getStr(path);
3240
+ return SYSCALLS.writeStat(buf, FS.lstat(path));
3241
+ } catch (e) {
3242
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3243
+ return -e.errno;
3244
+ }
3245
+ }
3246
+
3247
+
3248
+ function ___syscall_mkdirat(dirfd, path, mode) {
3249
+ try {
3250
+
3251
+ path = SYSCALLS.getStr(path);
3252
+ path = SYSCALLS.calculateAt(dirfd, path);
3253
+ mode &= ~SYSCALLS.currentUmask;
3254
+ FS.mkdir(path, mode, 0);
3255
+ return 0;
3256
+ } catch (e) {
3257
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3258
+ return -e.errno;
3259
+ }
3260
+ }
3261
+
3262
+
3263
+ function ___syscall_newfstatat(dirfd, path, buf, flags) {
3264
+ try {
3265
+
3266
+ path = SYSCALLS.getStr(path);
3267
+ var nofollow = flags & 256;
3268
+ var allowEmpty = flags & 4096;
3269
+ flags = flags & (~6400);
3270
+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
3271
+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));
3272
+ } catch (e) {
3273
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3274
+ return -e.errno;
3275
+ }
3276
+ }
3277
+
3278
+
3279
+
3280
+ function ___syscall_openat(dirfd, path, flags, varargs) {
3281
+ SYSCALLS.varargs = varargs;
3282
+ try {
3283
+
3284
+ path = SYSCALLS.getStr(path);
3285
+ path = SYSCALLS.calculateAt(dirfd, path);
3286
+ var mode = varargs ? syscallGetVarargI() : 0;
3287
+ if (flags & 64) {
3288
+ mode &= ~SYSCALLS.currentUmask;
3289
+ }
3290
+ return FS.open(path, flags, mode).fd;
3291
+ } catch (e) {
3292
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3293
+ return -e.errno;
3294
+ }
3295
+ }
3296
+
3297
+
3298
+
3299
+
3300
+ function ___syscall_readlinkat(dirfd, path, buf, bufsize) {
3301
+ try {
3302
+
3303
+ path = SYSCALLS.getStr(path);
3304
+ path = SYSCALLS.calculateAt(dirfd, path);
3305
+ if (bufsize <= 0) return -28;
3306
+ var ret = FS.readlink(path);
3307
+
3308
+ var len = Math.min(bufsize, lengthBytesUTF8(ret));
3309
+ var endChar = HEAP8[buf+len];
3310
+ stringToUTF8(ret, buf, bufsize+1);
3311
+ // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
3312
+ // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
3313
+ HEAP8[buf+len] = endChar;
3314
+ return len;
3315
+ } catch (e) {
3316
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3317
+ return -e.errno;
3318
+ }
3319
+ }
3320
+
3321
+
3322
+ function ___syscall_stat64(path, buf) {
3323
+ try {
3324
+
3325
+ path = SYSCALLS.getStr(path);
3326
+ return SYSCALLS.writeStat(buf, FS.stat(path));
3327
+ } catch (e) {
3328
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3329
+ return -e.errno;
3330
+ }
3331
+ }
3332
+
3333
+
3334
+ var __abort_js = () =>
3335
+ abort('');
3336
+
3337
+ var isLeapYear = (year) => year%4 === 0 && (year%100 !== 0 || year%400 === 0);
3338
+
3339
+ var MONTH_DAYS_LEAP_CUMULATIVE = [0,31,60,91,121,152,182,213,244,274,305,335];
3340
+
3341
+ var MONTH_DAYS_REGULAR_CUMULATIVE = [0,31,59,90,120,151,181,212,243,273,304,334];
3342
+ var ydayFromDate = (date) => {
3343
+ var leap = isLeapYear(date.getFullYear());
3344
+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);
3345
+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1; // -1 since it's days since Jan 1
3346
+
3347
+ return yday;
3348
+ };
3349
+
3350
+ var INT53_MAX = 9007199254740992;
3351
+
3352
+ var INT53_MIN = -9007199254740992;
3353
+ var bigintToI53Checked = (num) => (num < INT53_MIN || num > INT53_MAX) ? NaN : Number(num);
3354
+ function __localtime_js(time, tmPtr) {
3355
+ time = bigintToI53Checked(time);
3356
+
3357
+
3358
+ var date = new Date(time*1000);
3359
+ if (isNaN(date.getTime())) {
3360
+ return 1;
3361
+ }
3362
+ HEAP32[((tmPtr)>>2)] = date.getSeconds();
3363
+ HEAP32[(((tmPtr)+(4))>>2)] = date.getMinutes();
3364
+ HEAP32[(((tmPtr)+(8))>>2)] = date.getHours();
3365
+ HEAP32[(((tmPtr)+(12))>>2)] = date.getDate();
3366
+ HEAP32[(((tmPtr)+(16))>>2)] = date.getMonth();
3367
+ HEAP32[(((tmPtr)+(20))>>2)] = date.getFullYear()-1900;
3368
+ HEAP32[(((tmPtr)+(24))>>2)] = date.getDay();
3369
+
3370
+ var yday = ydayFromDate(date)|0;
3371
+ HEAP32[(((tmPtr)+(28))>>2)] = yday;
3372
+ HEAP32[(((tmPtr)+(36))>>2)] = -(date.getTimezoneOffset() * 60);
3373
+
3374
+ // Attention: DST is in December in South, and some regions don't have DST at all.
3375
+ var start = new Date(date.getFullYear(), 0, 1);
3376
+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
3377
+ var winterOffset = start.getTimezoneOffset();
3378
+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0;
3379
+ HEAP32[(((tmPtr)+(32))>>2)] = dst;
3380
+ return 0;
3381
+ ;
3382
+ }
3383
+
3384
+ var __tzset_js = (timezone, daylight, std_name, dst_name) => {
3385
+ // TODO: Use (malleable) environment variables instead of system settings.
3386
+ var currentYear = new Date().getFullYear();
3387
+ var winter = new Date(currentYear, 0, 1);
3388
+ var summer = new Date(currentYear, 6, 1);
3389
+ var winterOffset = winter.getTimezoneOffset();
3390
+ var summerOffset = summer.getTimezoneOffset();
3391
+
3392
+ // Local standard timezone offset. Local standard time is not adjusted for
3393
+ // daylight savings. This code uses the fact that getTimezoneOffset returns
3394
+ // a greater value during Standard Time versus Daylight Saving Time (DST).
3395
+ // Thus it determines the expected output during Standard Time, and it
3396
+ // compares whether the output of the given date the same (Standard) or less
3397
+ // (DST).
3398
+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
3399
+
3400
+ // timezone is specified as seconds west of UTC ("The external variable
3401
+ // `timezone` shall be set to the difference, in seconds, between
3402
+ // Coordinated Universal Time (UTC) and local standard time."), the same
3403
+ // as returned by stdTimezoneOffset.
3404
+ // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html
3405
+ HEAPU32[((timezone)>>2)] = stdTimezoneOffset * 60;
3406
+
3407
+ HEAP32[((daylight)>>2)] = Number(winterOffset != summerOffset);
3408
+
3409
+ var extractZone = (timezoneOffset) => {
3410
+ // Why inverse sign?
3411
+ // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
3412
+ var sign = timezoneOffset >= 0 ? "-" : "+";
3413
+
3414
+ var absOffset = Math.abs(timezoneOffset)
3415
+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
3416
+ var minutes = String(absOffset % 60).padStart(2, "0");
3417
+
3418
+ return `UTC${sign}${hours}${minutes}`;
3419
+ }
3420
+
3421
+ var winterName = extractZone(winterOffset);
3422
+ var summerName = extractZone(summerOffset);
3423
+ if (summerOffset < winterOffset) {
3424
+ // Northern hemisphere
3425
+ stringToUTF8(winterName, std_name, 17);
3426
+ stringToUTF8(summerName, dst_name, 17);
3427
+ } else {
3428
+ stringToUTF8(winterName, dst_name, 17);
3429
+ stringToUTF8(summerName, std_name, 17);
3430
+ }
3431
+ };
3432
+
3433
+ var _emscripten_get_now = () => performance.now();
3434
+
3435
+ var _emscripten_date_now = () => Date.now();
3436
+
3437
+ var nowIsMonotonic = 1;
3438
+
3439
+ var checkWasiClock = (clock_id) => clock_id >= 0 && clock_id <= 3;
3440
+
3441
+ function _clock_time_get(clk_id, ignored_precision, ptime) {
3442
+ ignored_precision = bigintToI53Checked(ignored_precision);
3443
+
3444
+
3445
+ if (!checkWasiClock(clk_id)) {
3446
+ return 28;
3447
+ }
3448
+ var now;
3449
+ // all wasi clocks but realtime are monotonic
3450
+ if (clk_id === 0) {
3451
+ now = _emscripten_date_now();
3452
+ } else if (nowIsMonotonic) {
3453
+ now = _emscripten_get_now();
3454
+ } else {
3455
+ return 52;
3456
+ }
3457
+ // "now" is in ms, and wasi times are in ns.
3458
+ var nsec = Math.round(now * 1000 * 1000);
3459
+ HEAP64[((ptime)>>3)] = BigInt(nsec);
3460
+ return 0;
3461
+ ;
3462
+ }
3463
+
3464
+
3465
+ var _emscripten_exit_with_live_runtime = () => {
3466
+
3467
+ throw 'unwind';
3468
+ };
3469
+
3470
+ var getHeapMax = () =>
3471
+ // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
3472
+ // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
3473
+ // for any code that deals with heap sizes, which would require special
3474
+ // casing all heap size related code to treat 0 specially.
3475
+ 2147483648;
3476
+
3477
+ var alignMemory = (size, alignment) => {
3478
+ return Math.ceil(size / alignment) * alignment;
3479
+ };
3480
+
3481
+ var growMemory = (size) => {
3482
+ var oldHeapSize = wasmMemory.buffer.byteLength;
3483
+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;
3484
+ try {
3485
+ // round size grow request up to wasm page size (fixed 64KB per spec)
3486
+ wasmMemory.grow(pages); // .grow() takes a delta compared to the previous size
3487
+ updateMemoryViews();
3488
+ return 1 /*success*/;
3489
+ } catch(e) {
3490
+ }
3491
+ // implicit 0 return to save code size (caller will cast "undefined" into 0
3492
+ // anyhow)
3493
+ };
3494
+ var _emscripten_resize_heap = (requestedSize) => {
3495
+ var oldSize = HEAPU8.length;
3496
+ // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
3497
+ requestedSize >>>= 0;
3498
+ // With multithreaded builds, races can happen (another thread might increase the size
3499
+ // in between), so return a failure, and let the caller retry.
3500
+
3501
+ // Memory resize rules:
3502
+ // 1. Always increase heap size to at least the requested size, rounded up
3503
+ // to next page multiple.
3504
+ // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap
3505
+ // geometrically: increase the heap size according to
3506
+ // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most
3507
+ // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
3508
+ // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap
3509
+ // linearly: increase the heap size by at least
3510
+ // MEMORY_GROWTH_LINEAR_STEP bytes.
3511
+ // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by
3512
+ // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
3513
+ // 4. If we were unable to allocate as much memory, it may be due to
3514
+ // over-eager decision to excessively reserve due to (3) above.
3515
+ // Hence if an allocation fails, cut down on the amount of excess
3516
+ // growth, in an attempt to succeed to perform a smaller allocation.
3517
+
3518
+ // A limit is set for how much we can grow. We should not exceed that
3519
+ // (the wasm binary specifies it, so if we tried, we'd fail anyhow).
3520
+ var maxHeapSize = getHeapMax();
3521
+ if (requestedSize > maxHeapSize) {
3522
+ return false;
3523
+ }
3524
+
3525
+ // Loop through potential heap size increases. If we attempt a too eager
3526
+ // reservation that fails, cut down on the attempted size and reserve a
3527
+ // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
3528
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
3529
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); // ensure geometric growth
3530
+ // but limit overreserving (default to capping at +96MB overgrowth at most)
3531
+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 );
3532
+
3533
+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
3534
+
3535
+ var replacement = growMemory(newSize);
3536
+ if (replacement) {
3537
+
3538
+ return true;
3539
+ }
3540
+ }
3541
+ return false;
3542
+ };
3543
+
3544
+ var ENV = {
3545
+ };
3546
+
3547
+ var getExecutableName = () => thisProgram;
3548
+ var getEnvStrings = () => {
3549
+ if (!getEnvStrings.strings) {
3550
+ // Default values.
3551
+ var lang = (globalThis.navigator?.language ?? 'C').replace('-', '_') + '.UTF-8';
3552
+ var env = {
3553
+ 'USER': 'web_user',
3554
+ 'LOGNAME': 'web_user',
3555
+ 'PATH': '/',
3556
+ 'PWD': '/',
3557
+ 'HOME': '/home/web_user',
3558
+ 'LANG': lang,
3559
+ '_': getExecutableName()
3560
+ };
3561
+ // Apply the user-provided values, if any.
3562
+ for (var x in ENV) {
3563
+ // x is a key in ENV; if ENV[x] is undefined, that means it was
3564
+ // explicitly set to be so. We allow user code to do that to
3565
+ // force variables with default values to remain unset.
3566
+ if (ENV[x] === undefined) delete env[x];
3567
+ else env[x] = ENV[x];
3568
+ }
3569
+ var strings = [];
3570
+ for (var x in env) {
3571
+ strings.push(`${x}=${env[x]}`);
3572
+ }
3573
+ getEnvStrings.strings = strings;
3574
+ }
3575
+ return getEnvStrings.strings;
3576
+ };
3577
+
3578
+ var _environ_get = (__environ, environ_buf) => {
3579
+ var bufSize = 0;
3580
+ var envp = 0;
3581
+ for (var string of getEnvStrings()) {
3582
+ var ptr = environ_buf + bufSize;
3583
+ HEAPU32[(((__environ)+(envp))>>2)] = ptr;
3584
+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;
3585
+ envp += 4;
3586
+ }
3587
+ return 0;
3588
+ };
3589
+
3590
+
3591
+ var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
3592
+ var strings = getEnvStrings();
3593
+ HEAPU32[((penviron_count)>>2)] = strings.length;
3594
+ var bufSize = 0;
3595
+ for (var string of strings) {
3596
+ bufSize += lengthBytesUTF8(string) + 1;
3597
+ }
3598
+ HEAPU32[((penviron_buf_size)>>2)] = bufSize;
3599
+ return 0;
3600
+ };
3601
+
3602
+
3603
+ var keepRuntimeAlive = () => true;
3604
+ var _proc_exit = (code) => {
3605
+ EXITSTATUS = code;
3606
+ if (!keepRuntimeAlive()) {
3607
+ ABORT = true;
3608
+ }
3609
+ quit_(code, new ExitStatus(code));
3610
+ };
3611
+ /** @param {boolean|number=} implicit */
3612
+ var exitJS = (status, implicit) => {
3613
+ EXITSTATUS = status;
3614
+
3615
+ _proc_exit(status);
3616
+ };
3617
+ var _exit = exitJS;
3618
+
3619
+ function _fd_close(fd) {
3620
+ try {
3621
+
3622
+ var stream = SYSCALLS.getStreamFromFD(fd);
3623
+ FS.close(stream);
3624
+ return 0;
3625
+ } catch (e) {
3626
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3627
+ return e.errno;
3628
+ }
3629
+ }
3630
+
3631
+
3632
+ /** @param {number=} offset */
3633
+ var doReadv = (stream, iov, iovcnt, offset) => {
3634
+ var ret = 0;
3635
+ for (var i = 0; i < iovcnt; i++) {
3636
+ var ptr = HEAPU32[((iov)>>2)];
3637
+ var len = HEAPU32[(((iov)+(4))>>2)];
3638
+ iov += 8;
3639
+ var curr = FS.read(stream, HEAP8, ptr, len, offset);
3640
+ if (curr < 0) return -1;
3641
+ ret += curr;
3642
+ if (curr < len) break; // nothing more to read
3643
+ if (typeof offset != 'undefined') {
3644
+ offset += curr;
3645
+ }
3646
+ }
3647
+ return ret;
3648
+ };
3649
+
3650
+ function _fd_read(fd, iov, iovcnt, pnum) {
3651
+ try {
3652
+
3653
+ var stream = SYSCALLS.getStreamFromFD(fd);
3654
+ var num = doReadv(stream, iov, iovcnt);
3655
+ HEAPU32[((pnum)>>2)] = num;
3656
+ return 0;
3657
+ } catch (e) {
3658
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3659
+ return e.errno;
3660
+ }
3661
+ }
3662
+
3663
+
3664
+
3665
+ function _fd_seek(fd, offset, whence, newOffset) {
3666
+ offset = bigintToI53Checked(offset);
3667
+
3668
+
3669
+ try {
3670
+
3671
+ if (isNaN(offset)) return 22;
3672
+ var stream = SYSCALLS.getStreamFromFD(fd);
3673
+ FS.llseek(stream, offset, whence);
3674
+ HEAP64[((newOffset)>>3)] = BigInt(stream.position);
3675
+ if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
3676
+ return 0;
3677
+ } catch (e) {
3678
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3679
+ return e.errno;
3680
+ }
3681
+ ;
3682
+ }
3683
+
3684
+ /** @param {number=} offset */
3685
+ var doWritev = (stream, iov, iovcnt, offset) => {
3686
+ var ret = 0;
3687
+ for (var i = 0; i < iovcnt; i++) {
3688
+ var ptr = HEAPU32[((iov)>>2)];
3689
+ var len = HEAPU32[(((iov)+(4))>>2)];
3690
+ iov += 8;
3691
+ var curr = FS.write(stream, HEAP8, ptr, len, offset);
3692
+ if (curr < 0) return -1;
3693
+ ret += curr;
3694
+ if (curr < len) {
3695
+ // No more space to write.
3696
+ break;
3697
+ }
3698
+ if (typeof offset != 'undefined') {
3699
+ offset += curr;
3700
+ }
3701
+ }
3702
+ return ret;
3703
+ };
3704
+
3705
+ function _fd_write(fd, iov, iovcnt, pnum) {
3706
+ try {
3707
+
3708
+ var stream = SYSCALLS.getStreamFromFD(fd);
3709
+ var num = doWritev(stream, iov, iovcnt);
3710
+ HEAPU32[((pnum)>>2)] = num;
3711
+ return 0;
3712
+ } catch (e) {
3713
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
3714
+ return e.errno;
3715
+ }
3716
+ }
3717
+
3718
+
3719
+ function _fos_nim_http_free(ptr) {
3720
+ if (ptr) _free(ptr)
3721
+ }
3722
+
3723
+
3724
+ function _fos_nim_http_request(
3725
+ methodPtr,
3726
+ urlPtr,
3727
+ bodyPtr,
3728
+ bodyLen,
3729
+ headersPtr,
3730
+ headersLen,
3731
+ timeoutMs,
3732
+ maxBytes,
3733
+ outStatusPtr,
3734
+ outLenPtr
3735
+ ) {
3736
+ HEAP32[((outStatusPtr)>>2)] = 0
3737
+ HEAP32[((outLenPtr)>>2)] = 0
3738
+ var method = UTF8ToString(methodPtr)
3739
+ var url = UTF8ToString(urlPtr)
3740
+ // When a same-origin backend proxy is configured, it is the FALLBACK:
3741
+ // requests go straight from the browser first (client-side, no server
3742
+ // load), and only CORS/network failures are retried through the proxy,
3743
+ // which fetches server-side like the device would.
3744
+ var proxyUrl = Module['frameosProxyUrl']
3745
+ try {
3746
+ var body = null
3747
+ if (bodyLen > 0) {
3748
+ body = new Uint8Array(HEAPU8.buffer, bodyPtr, bodyLen).slice()
3749
+ }
3750
+ var headers = {}
3751
+ if (headersLen > 0) {
3752
+ var headerBlock = UTF8ToString(headersPtr, headersLen)
3753
+ var lines = headerBlock.split('\n')
3754
+ for (var i = 0; i < lines.length; i++) {
3755
+ var line = lines[i]
3756
+ var colon = line.indexOf(':')
3757
+ if (colon > 0) {
3758
+ headers[line.slice(0, colon).trim()] = line.slice(colon + 1).trim()
3759
+ }
3760
+ }
3761
+ }
3762
+
3763
+ // Synchronous XHR: the Nim/pixie pipeline is fully synchronous and this
3764
+ // module runs in a Web Worker, where sync XHR is permitted.
3765
+ var directRequest = function () {
3766
+ var xhr = new XMLHttpRequest()
3767
+ xhr.open(method, url, false)
3768
+ try {
3769
+ xhr.responseType = 'arraybuffer'
3770
+ if (timeoutMs > 0) xhr.timeout = timeoutMs
3771
+ } catch (e) {
3772
+ // Main-thread fallback: sync XHR only supports text responses there.
3773
+ }
3774
+ for (var name in headers) {
3775
+ try {
3776
+ xhr.setRequestHeader(name, headers[name])
3777
+ } catch (e) {
3778
+ // Forbidden header names (User-Agent & co) throw; skip them.
3779
+ }
3780
+ }
3781
+ xhr.send(body)
3782
+ return xhr
3783
+ }
3784
+
3785
+ var proxyRequest = function () {
3786
+ var xhr = new XMLHttpRequest()
3787
+ xhr.open('POST', proxyUrl, false)
3788
+ xhr.withCredentials = true
3789
+ try {
3790
+ xhr.responseType = 'arraybuffer'
3791
+ if (timeoutMs > 0) xhr.timeout = timeoutMs
3792
+ } catch (e) {}
3793
+ var bodyBase64 = ''
3794
+ if (body && body.length > 0) {
3795
+ var bin = ''
3796
+ for (var j = 0; j < body.length; j++) bin += String.fromCharCode(body[j])
3797
+ bodyBase64 = btoa(bin)
3798
+ }
3799
+ xhr.setRequestHeader('Content-Type', 'application/json')
3800
+ xhr.send(
3801
+ JSON.stringify({ method: method, url: url, headers: headers, bodyBase64: bodyBase64, timeoutMs: timeoutMs })
3802
+ )
3803
+ return xhr
3804
+ }
3805
+
3806
+ var xhr = null
3807
+ var directError = null
3808
+ try {
3809
+ xhr = directRequest()
3810
+ } catch (e) {
3811
+ // A cross-origin host without CORS headers throws on sync send.
3812
+ directError = e
3813
+ }
3814
+ if ((xhr === null || xhr.status === 0) && proxyUrl) {
3815
+ xhr = proxyRequest()
3816
+ } else if (xhr === null) {
3817
+ throw directError
3818
+ }
3819
+
3820
+ var bytes
3821
+ if (xhr.response instanceof ArrayBuffer) {
3822
+ bytes = new Uint8Array(xhr.response)
3823
+ } else {
3824
+ bytes = new TextEncoder().encode(xhr.responseText || '')
3825
+ }
3826
+ if (maxBytes > 0 && bytes.length > maxBytes) {
3827
+ if (Module['onFrameosLog']) {
3828
+ Module['onFrameosLog']('http: response for ' + url + ' exceeded ' + maxBytes + ' bytes')
3829
+ }
3830
+ return 0
3831
+ }
3832
+ var ptr = _malloc(bytes.length > 0 ? bytes.length : 1)
3833
+ if (!ptr) return 0
3834
+ HEAPU8.set(bytes, ptr)
3835
+ HEAP32[((outStatusPtr)>>2)] = xhr.status
3836
+ HEAP32[((outLenPtr)>>2)] = bytes.length
3837
+ return ptr
3838
+ } catch (e) {
3839
+ if (Module['onFrameosLog']) {
3840
+ Module['onFrameosLog']('http: ' + method + ' ' + url + ' failed: ' + e)
3841
+ }
3842
+ return 0
3843
+ }
3844
+ }
3845
+
3846
+ function _frameos_wasm_js_event(eventPtr, payloadPtr) {
3847
+ if (Module['onFrameosEvent']) {
3848
+ Module['onFrameosEvent'](UTF8ToString(eventPtr), UTF8ToString(payloadPtr))
3849
+ }
3850
+ }
3851
+
3852
+ function _frameos_wasm_js_log(msgPtr) {
3853
+ var msg = UTF8ToString(msgPtr)
3854
+ if (Module['onFrameosLog']) {
3855
+ Module['onFrameosLog'](msg)
3856
+ } else {
3857
+ console.log('[frameos]', msg)
3858
+ }
3859
+ }
3860
+
3861
+
3862
+ var handleException = (e) => {
3863
+ // Certain exception types we do not treat as errors since they are used for
3864
+ // internal control flow.
3865
+ // 1. ExitStatus, which is thrown by exit()
3866
+ // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others
3867
+ // that wish to return to JS event loop.
3868
+ if (e instanceof ExitStatus || e == 'unwind') {
3869
+ return EXITSTATUS;
3870
+ }
3871
+ quit_(1, e);
3872
+ };
3873
+
3874
+
3875
+
3876
+ var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
3877
+ var stringToUTF8OnStack = (str) => {
3878
+ var size = lengthBytesUTF8(str) + 1;
3879
+ var ret = stackAlloc(size);
3880
+ stringToUTF8(str, ret, size);
3881
+ return ret;
3882
+ };
3883
+
3884
+ var getCFunc = (ident) => {
3885
+ var func = Module['_' + ident]; // closure exported function
3886
+ return func;
3887
+ };
3888
+
3889
+ var writeArrayToMemory = (array, buffer) => {
3890
+ HEAP8.set(array, buffer);
3891
+ };
3892
+
3893
+
3894
+
3895
+
3896
+
3897
+
3898
+ /**
3899
+ * @param {string|null=} returnType
3900
+ * @param {Array=} argTypes
3901
+ * @param {Array=} args
3902
+ * @param {Object=} opts
3903
+ */
3904
+ var ccall = (ident, returnType, argTypes, args, opts) => {
3905
+ // For fast lookup of conversion functions
3906
+ var toC = {
3907
+ 'string': (str) => {
3908
+ var ret = 0;
3909
+ if (str !== null && str !== undefined && str !== 0) { // null string
3910
+ ret = stringToUTF8OnStack(str);
3911
+ }
3912
+ return ret;
3913
+ },
3914
+ 'array': (arr) => {
3915
+ var ret = stackAlloc(arr.length);
3916
+ writeArrayToMemory(arr, ret);
3917
+ return ret;
3918
+ }
3919
+ };
3920
+
3921
+ function convertReturnValue(ret) {
3922
+ if (returnType === 'string') {
3923
+ return UTF8ToString(ret);
3924
+ }
3925
+ if (returnType === 'boolean') return Boolean(ret);
3926
+ return ret;
3927
+ }
3928
+
3929
+ var func = getCFunc(ident);
3930
+ var cArgs = [];
3931
+ var stack = 0;
3932
+ if (args) {
3933
+ for (var i = 0; i < args.length; i++) {
3934
+ var converter = toC[argTypes[i]];
3935
+ if (converter) {
3936
+ if (stack === 0) stack = stackSave();
3937
+ cArgs[i] = converter(args[i]);
3938
+ } else {
3939
+ cArgs[i] = args[i];
3940
+ }
3941
+ }
3942
+ }
3943
+ var ret = func(...cArgs);
3944
+ function onDone(ret) {
3945
+ if (stack !== 0) stackRestore(stack);
3946
+ return convertReturnValue(ret);
3947
+ }
3948
+
3949
+ ret = onDone(ret);
3950
+ return ret;
3951
+ };
3952
+
3953
+
3954
+ /**
3955
+ * @param {string=} returnType
3956
+ * @param {Array=} argTypes
3957
+ * @param {Object=} opts
3958
+ */
3959
+ var cwrap = (ident, returnType, argTypes, opts) => {
3960
+ // When the function takes numbers and returns a number, we can just return
3961
+ // the original function
3962
+ var numericArgs = !argTypes || argTypes.every((type) => type === 'number' || type === 'boolean');
3963
+ var numericRet = returnType !== 'string';
3964
+ if (numericRet && numericArgs && !opts) {
3965
+ return getCFunc(ident);
3966
+ }
3967
+ return (...args) => ccall(ident, returnType, argTypes, args, opts);
3968
+ };
3969
+
3970
+
3971
+
3972
+
3973
+
3974
+ var stringToNewUTF8 = (str) => {
3975
+ var size = lengthBytesUTF8(str) + 1;
3976
+ var ret = _malloc(size);
3977
+ if (ret) stringToUTF8(str, ret, size);
3978
+ return ret;
3979
+ };
3980
+
3981
+
3982
+
3983
+ FS.createPreloadedFile = FS_createPreloadedFile;
3984
+ FS.preloadFile = FS_preloadFile;
3985
+ FS.staticInit();;
3986
+ // End JS library code
3987
+
3988
+ // include: postlibrary.js
3989
+ // This file is included after the automatically-generated JS library code
3990
+ // but before the wasm module is created.
3991
+
3992
+ {
3993
+
3994
+ // Begin ATMODULES hooks
3995
+
3996
+ if (Module['print']) out = Module['print'];
3997
+ if (Module['printErr']) err = Module['printErr'];
3998
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
3999
+ // End ATMODULES hooks
4000
+
4001
+
4002
+
4003
+
4004
+ }
4005
+
4006
+ // Begin runtime exports
4007
+ Module['ccall'] = ccall;
4008
+ Module['cwrap'] = cwrap;
4009
+ Module['UTF8ToString'] = UTF8ToString;
4010
+ Module['lengthBytesUTF8'] = lengthBytesUTF8;
4011
+ Module['stringToNewUTF8'] = stringToNewUTF8;
4012
+ // End runtime exports
4013
+ // Begin JS library exports
4014
+ // End JS library exports
4015
+
4016
+ // end include: postlibrary.js
4017
+
4018
+
4019
+ // Imports from the Wasm binary.
4020
+ var _malloc,
4021
+ _free,
4022
+ _frameos_wasm_init,
4023
+ _frameos_wasm_load_scenes,
4024
+ _frameos_wasm_select_scene,
4025
+ _frameos_wasm_render,
4026
+ _frameos_wasm_buffer,
4027
+ _frameos_wasm_buffer_len,
4028
+ _frameos_wasm_width,
4029
+ _frameos_wasm_height,
4030
+ _frameos_wasm_event,
4031
+ _frameos_wasm_render_requested,
4032
+ _frameos_wasm_next_sleep,
4033
+ _frameos_wasm_scene_interval,
4034
+ _frameos_wasm_scene_info,
4035
+ _frameos_wasm_scene_state,
4036
+ _frameos_wasm_last_error,
4037
+ _main,
4038
+ __emscripten_stack_restore,
4039
+ __emscripten_stack_alloc,
4040
+ _emscripten_stack_get_current,
4041
+ memory,
4042
+ __indirect_function_table,
4043
+ wasmMemory;
4044
+
4045
+
4046
+ function assignWasmExports(wasmExports) {
4047
+ _malloc = Module['_malloc'] = wasmExports['malloc'];
4048
+ _free = Module['_free'] = wasmExports['free'];
4049
+ _frameos_wasm_init = Module['_frameos_wasm_init'] = wasmExports['frameos_wasm_init'];
4050
+ _frameos_wasm_load_scenes = Module['_frameos_wasm_load_scenes'] = wasmExports['frameos_wasm_load_scenes'];
4051
+ _frameos_wasm_select_scene = Module['_frameos_wasm_select_scene'] = wasmExports['frameos_wasm_select_scene'];
4052
+ _frameos_wasm_render = Module['_frameos_wasm_render'] = wasmExports['frameos_wasm_render'];
4053
+ _frameos_wasm_buffer = Module['_frameos_wasm_buffer'] = wasmExports['frameos_wasm_buffer'];
4054
+ _frameos_wasm_buffer_len = Module['_frameos_wasm_buffer_len'] = wasmExports['frameos_wasm_buffer_len'];
4055
+ _frameos_wasm_width = Module['_frameos_wasm_width'] = wasmExports['frameos_wasm_width'];
4056
+ _frameos_wasm_height = Module['_frameos_wasm_height'] = wasmExports['frameos_wasm_height'];
4057
+ _frameos_wasm_event = Module['_frameos_wasm_event'] = wasmExports['frameos_wasm_event'];
4058
+ _frameos_wasm_render_requested = Module['_frameos_wasm_render_requested'] = wasmExports['frameos_wasm_render_requested'];
4059
+ _frameos_wasm_next_sleep = Module['_frameos_wasm_next_sleep'] = wasmExports['frameos_wasm_next_sleep'];
4060
+ _frameos_wasm_scene_interval = Module['_frameos_wasm_scene_interval'] = wasmExports['frameos_wasm_scene_interval'];
4061
+ _frameos_wasm_scene_info = Module['_frameos_wasm_scene_info'] = wasmExports['frameos_wasm_scene_info'];
4062
+ _frameos_wasm_scene_state = Module['_frameos_wasm_scene_state'] = wasmExports['frameos_wasm_scene_state'];
4063
+ _frameos_wasm_last_error = Module['_frameos_wasm_last_error'] = wasmExports['frameos_wasm_last_error'];
4064
+ _main = Module['_main'] = wasmExports['main'];
4065
+ __emscripten_stack_restore = wasmExports['_emscripten_stack_restore'];
4066
+ __emscripten_stack_alloc = wasmExports['_emscripten_stack_alloc'];
4067
+ _emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'];
4068
+ memory = wasmMemory = wasmExports['memory'];
4069
+ __indirect_function_table = wasmExports['__indirect_function_table'];
4070
+ }
4071
+
4072
+ var wasmImports = {
4073
+ /** @export */
4074
+ __assert_fail: ___assert_fail,
4075
+ /** @export */
4076
+ __syscall_fcntl64: ___syscall_fcntl64,
4077
+ /** @export */
4078
+ __syscall_fstat64: ___syscall_fstat64,
4079
+ /** @export */
4080
+ __syscall_getdents64: ___syscall_getdents64,
4081
+ /** @export */
4082
+ __syscall_ioctl: ___syscall_ioctl,
4083
+ /** @export */
4084
+ __syscall_lstat64: ___syscall_lstat64,
4085
+ /** @export */
4086
+ __syscall_mkdirat: ___syscall_mkdirat,
4087
+ /** @export */
4088
+ __syscall_newfstatat: ___syscall_newfstatat,
4089
+ /** @export */
4090
+ __syscall_openat: ___syscall_openat,
4091
+ /** @export */
4092
+ __syscall_readlinkat: ___syscall_readlinkat,
4093
+ /** @export */
4094
+ __syscall_stat64: ___syscall_stat64,
4095
+ /** @export */
4096
+ _abort_js: __abort_js,
4097
+ /** @export */
4098
+ _localtime_js: __localtime_js,
4099
+ /** @export */
4100
+ _tzset_js: __tzset_js,
4101
+ /** @export */
4102
+ clock_time_get: _clock_time_get,
4103
+ /** @export */
4104
+ emscripten_date_now: _emscripten_date_now,
4105
+ /** @export */
4106
+ emscripten_exit_with_live_runtime: _emscripten_exit_with_live_runtime,
4107
+ /** @export */
4108
+ emscripten_resize_heap: _emscripten_resize_heap,
4109
+ /** @export */
4110
+ environ_get: _environ_get,
4111
+ /** @export */
4112
+ environ_sizes_get: _environ_sizes_get,
4113
+ /** @export */
4114
+ exit: _exit,
4115
+ /** @export */
4116
+ fd_close: _fd_close,
4117
+ /** @export */
4118
+ fd_read: _fd_read,
4119
+ /** @export */
4120
+ fd_seek: _fd_seek,
4121
+ /** @export */
4122
+ fd_write: _fd_write,
4123
+ /** @export */
4124
+ fos_nim_http_free: _fos_nim_http_free,
4125
+ /** @export */
4126
+ fos_nim_http_request: _fos_nim_http_request,
4127
+ /** @export */
4128
+ frameos_wasm_js_event: _frameos_wasm_js_event,
4129
+ /** @export */
4130
+ frameos_wasm_js_log: _frameos_wasm_js_log
4131
+ };
4132
+
4133
+
4134
+ // include: postamble.js
4135
+ // === Auto-generated postamble setup entry stuff ===
4136
+
4137
+ function callMain(args = []) {
4138
+
4139
+ var entryFunction = _main;
4140
+
4141
+ args.unshift(thisProgram);
4142
+
4143
+ var argc = args.length;
4144
+ var argv = stackAlloc((argc + 1) * 4);
4145
+ var argv_ptr = argv;
4146
+ for (var arg of args) {
4147
+ HEAPU32[((argv_ptr)>>2)] = stringToUTF8OnStack(arg);
4148
+ argv_ptr += 4;
4149
+ }
4150
+ HEAPU32[((argv_ptr)>>2)] = 0;
4151
+
4152
+ try {
4153
+
4154
+ var ret = entryFunction(argc, argv);
4155
+
4156
+ // if we're not running an evented main loop, it's time to exit
4157
+ exitJS(ret, /* implicit = */ true);
4158
+ return ret;
4159
+ } catch (e) {
4160
+ return handleException(e);
4161
+ }
4162
+ }
4163
+
4164
+ async function run(args = programArgs) {
4165
+
4166
+ preRun();
4167
+
4168
+ if (runDependencies) {
4169
+ await resolveRunDependencies();
4170
+ }
4171
+
4172
+ if (ABORT) return;
4173
+
4174
+ initRuntime();
4175
+
4176
+ // No ATMAINS hooks
4177
+
4178
+ Module['onRuntimeInitialized']?.();
4179
+
4180
+ var noInitialRun = false;
4181
+ if (!noInitialRun) callMain(args);
4182
+
4183
+ postRun();
4184
+ }
4185
+
4186
+ var wasmExports;
4187
+
4188
+ // In modularize mode the generated code is within a factory function so we
4189
+ // can use await here (since it's not top-level-await).
4190
+ wasmExports = await createWasm();
4191
+ await run();
4192
+
4193
+ // end include: postamble.js
4194
+
4195
+ // include: postamble_modularize.js
4196
+ // In MODULARIZE mode we wrap the generated code in a factory function
4197
+ // and return either the Module itself, or a promise of the module.
4198
+
4199
+ // end include: postamble_modularize.js
4200
+
4201
+
4202
+
4203
+ return Module;
4204
+ }
4205
+
4206
+ // Export using a UMD style export, or ES6 exports if selected
4207
+ export default createFrameOS;
4208
+