wasm-rquickjs 0.4.4

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
import {
    get_args,
    get_env,
    get_cwd,
    chdir as native_chdir,
    write_stdout,
    write_stderr,
    hrtime_ns,
    memory_usage as _native_memory_usage,
    has_typescript_runtime,
    typescript_runtime_mode
} from '__wasm_rquickjs_builtin/process_native';

import EventEmitter from 'node:events';

function _invalidArgTypeHelper(value) {
    if (value == null) return ' Received ' + String(value);
    if (typeof value === 'function') return ' Received function ' + value.name;
    if (typeof value === 'object') {
        if (value.constructor && value.constructor.name) return ' Received an instance of ' + value.constructor.name;
        return ' Received an instance of Object';
    }
    let inspected = String(value);
    if (typeof value === 'string') inspected = "'" + value + "'";
    if (typeof value === 'bigint') inspected = String(value) + 'n';
    if (inspected.length > 28) inspected = inspected.slice(0, 25) + '...';
    return ' Received type ' + typeof value + ' (' + inspected + ')';
}

function _makeTypeError(code, message) {
    const err = new TypeError(message);
    err.code = code;
    Object.defineProperty(err, 'toString', {
        value: function() { return 'TypeError [' + code + ']: ' + message; },
        writable: true, configurable: true, enumerable: false
    });
    return err;
}

function _makeRangeError(code, message) {
    const err = new RangeError(message);
    err.code = code;
    Object.defineProperty(err, 'toString', {
        value: function() { return 'RangeError [' + code + ']: ' + message; },
        writable: true, configurable: true, enumerable: false
    });
    return err;
}

function _makeError(code, message) {
    const err = new Error(message);
    err.code = code;
    Object.defineProperty(err, 'toString', {
        value: function() { return 'Error [' + code + ']: ' + message; },
        writable: true, configurable: true, enumerable: false
    });
    return err;
}

var process = new EventEmitter();

const _argv = get_args();
const _env = get_env();
let _exitCode = 0;
var _exiting = false;

export var argv = _argv;
Object.defineProperty(process, 'argv', {
    get: function() { return argv; },
    set: function(value) { argv = value; },
    enumerable: true,
    configurable: true,
});
export var argv0 = _argv[0] || '';
Object.defineProperty(process, 'argv0', {
    get: function() { return argv0; },
    set: function(value) { argv0 = value; },
    enumerable: true,
    configurable: true,
});

function _createEnv(values) {
    return new Proxy(values, {
        get: function(target, key) {
            if (typeof key === 'symbol') return undefined;
            if (key === '') return undefined;
            return target[key];
        },
        set: function(target, key, value) {
            if (typeof key === 'symbol') {
                throw new TypeError('Cannot convert a Symbol value to a string');
            }
            if (typeof value === 'symbol') {
                throw new TypeError('Cannot convert a Symbol value to a string');
            }
            if (key === '') return true;
            target[key] = String(value);
            return true;
        },
        deleteProperty: function(target, key) {
            if (typeof key === 'symbol') return true;
            delete target[key];
            return true;
        },
        has: function(target, key) {
            if (typeof key === 'symbol') return false;
            return Object.prototype.hasOwnProperty.call(target, key);
        },
        ownKeys: function(target) {
            return Object.keys(target);
        },
        getOwnPropertyDescriptor: function(target, key) {
            if (typeof key === 'symbol') return undefined;
            if (Object.prototype.hasOwnProperty.call(target, key)) {
                return { value: target[key], writable: true, enumerable: true, configurable: true };
            }
            return undefined;
        },
        defineProperty: function(target, key, descriptor) {
            if ('get' in descriptor || 'set' in descriptor) {
                const err = new TypeError("'process.env' does not accept an accessor(getter/setter) descriptor");
                err.code = 'ERR_INVALID_OBJECT_DEFINE_PROPERTY';
                throw err;
            }
            if (descriptor.configurable !== true || descriptor.writable !== true || descriptor.enumerable !== true) {
                const err = new TypeError("'process.env' only accepts a configurable, writable, and enumerable data descriptor");
                err.code = 'ERR_INVALID_OBJECT_DEFINE_PROPERTY';
                throw err;
            }
            if (descriptor.value !== undefined) {
                target[key] = String(descriptor.value);
            }
            return true;
        }
    });
}

export var env = _createEnv(_env);
Object.defineProperty(process, 'env', {
    get: function() { return env; },
    set: function(value) { env = value; },
    enumerable: true,
    configurable: true,
});

Object.defineProperty(process, Symbol.for('__wasm_rquickjs_refresh_process_state'), {
    value: function(nextArgv, nextEnv) {
        let argvRefreshed = false;
        const currentArgv = argv;
        if (Array.isArray(currentArgv)) {
            try {
                currentArgv.length = 0;
                for (const value of nextArgv) currentArgv.push(value);
                argvRefreshed = currentArgv.length === nextArgv.length
                    && currentArgv.every((value, index) => value === nextArgv[index]);
            } catch (_) {
                argvRefreshed = false;
            }
        }
        if (!argvRefreshed) argv = nextArgv;
        argv0 = nextArgv[0] || '';

        const currentEnv = env;
        const wasExtensible = Object.isExtensible(currentEnv);
        let envRefreshed = true;
        try {
            for (const key of Object.keys(currentEnv)) delete currentEnv[key];
            for (const [key, value] of Object.entries(nextEnv)) currentEnv[key] = value;
            const keys = Object.keys(nextEnv);
            envRefreshed = Object.keys(currentEnv).length === keys.length
                && keys.every((key) => currentEnv[key] === nextEnv[key]);
        } catch (_) {
            envRefreshed = false;
        }
        if (!envRefreshed) {
            env = _createEnv(nextEnv);
            if (!wasExtensible) Object.preventExtensions(env);
        }

        return process.argv === argv
            && process.argv0 === argv0
            && process.env === env;
    },
    writable: false,
    enumerable: false,
    configurable: false,
});
process.exitCode = _exitCode;
process.domain = null;
process.pid = 1;
process.ppid = 0;
process.platform = 'wasi';
process.arch = 'wasm32';
process.version = 'v22.0.0';
process.versions = {
    node: '22.0.0',
    modules: '127',
    openssl: '3.0.0',
};
process.config = {
    target_defaults: { default_configuration: 'Release' },
    variables: {
        v8_enable_i18n_support: 0,
        asan: 0,
        openssl_quic: 0,
        node_module_version: 127,
        node_use_amaro: has_typescript_runtime(),
    },
};
Object.freeze(process.config.target_defaults);
Object.freeze(process.config.variables);
Object.freeze(process.config);
process.execArgv = [];
const typescriptRuntimeMode = typescript_runtime_mode();
process.features = {
    inspector: false,
    debug: false,
    uv: true,
    ipv6: true,
    tls_alpn: false,
    tls_sni: false,
    tls_ocsp: false,
    tls: false,
    cached_builtins: true,
    require_module: true,
    typescript: typescriptRuntimeMode ?? false,
};
process.execPath = '/usr/local/bin/node';
let _title = 'wasm-rquickjs';
Object.defineProperty(process, 'title', {
    get: function() { return _title; },
    set: function(v) { _title = String(v); },
    enumerable: true,
    configurable: true,
});
process.release = { name: 'node' };
process.allowedNodeEnvironmentFlags = new Set();

const _reportOptions = {
    directory: '',
    filename: '',
    compact: false,
    excludeNetwork: false,
    signal: 'SIGUSR2',
    reportOnFatalError: false,
    reportOnSignal: false,
    reportOnUncaughtException: false,
    excludeEnv: false,
};

function _reportStringOption(name, value) {
    if (typeof value !== 'string') {
        throw _makeTypeError(
            'ERR_INVALID_ARG_TYPE',
            'The "' + name + '" property must be of type string.' + _invalidArgTypeHelper(value),
        );
    }
    _reportOptions[name] = value;
}

function _reportBooleanOption(name, value) {
    if (typeof value !== 'boolean') {
        throw _makeTypeError(
            'ERR_INVALID_ARG_TYPE',
            'The "' + name + '" property must be of type boolean.' + _invalidArgTypeHelper(value),
        );
    }
    _reportOptions[name] = value;
}

function _diagnosticReport(error) {
    if (error === undefined) {
        error = new Error('JavaScript Callstack');
        error.name = 'Error [ERR_SYNTHETIC]';
        const frames = String(error.stack).split('\n').slice(1);
        error.stack = 'Error [ERR_SYNTHETIC]: JavaScript Callstack\n' + frames.join('\n');
    }
    const now = new Date();
    const memory = process.memoryUsage();
    const usage = process.cpuUsage();
    const hasStack = error !== null && typeof error.stack === 'string';
    const stackLines = hasStack ? error.stack.split('\n') : [];
    return {
        header: {
            reportVersion: 5,
            event: 'JavaScript API',
            trigger: 'GetReport',
            filename: null,
            dumpEventTime: now.toISOString(),
            dumpEventTimeStamp: String(now.getTime()),
            processId: process.pid,
            threadId: 0,
            cwd: process.cwd(),
            commandLine: process.argv.slice(),
            nodejsVersion: process.version,
            wordSize: 32,
            arch: process.arch,
            platform: process.platform,
            componentVersions: Object.assign({}, process.versions),
            release: Object.assign({}, process.release),
            cpus: [],
            networkInterfaces: [],
            host: '',
        },
        javascriptStack: {
            message: hasStack ? stackLines[0] : 'No stack.',
            stack: hasStack ? stackLines.slice(1) : [],
            errorProperties: {},
        },
        javascriptHeap: {
            totalMemory: memory.heapTotal,
            executableMemory: 0,
            totalCommittedMemory: memory.heapTotal,
            availableMemory: 0,
            totalGlobalHandlesMemory: 0,
            usedGlobalHandlesMemory: 0,
            usedMemory: memory.heapUsed,
            memoryLimit: memory.heapTotal,
            mallocedMemory: memory.external,
            externalMemory: memory.external,
            peakMallocedMemory: memory.rss,
            nativeContextCount: 1,
            detachedContextCount: 0,
            doesZapGarbage: 0,
            heapSpaces: {},
        },
        nativeStack: [],
        resourceUsage: {
            userCpuSeconds: usage.user / 1e6,
            kernelCpuSeconds: usage.system / 1e6,
            cpuConsumptionPercent: 0,
            userCpuConsumptionPercent: 0,
            kernelCpuConsumptionPercent: 0,
            maxRss: memory.rss,
            pageFaults: { IORequired: 0, IONotRequired: 0 },
            fsActivity: { reads: 0, writes: 0 },
        },
        libuv: [],
        workers: [],
        environmentVariables: _reportOptions.excludeEnv ? {} : Object.assign({}, process.env),
        userLimits: {},
        sharedObjects: [],
    };
}

function _defaultReportFilename() {
    const stamp = new Date().toISOString().replace(/[-:TZ.]/g, '');
    return 'report.' + stamp + '.' + process.pid + '.0.001.json';
}

process.report = {
    getReport(error) {
        if (error !== undefined &&
            (error === null || typeof error !== 'object' || Array.isArray(error))) {
            throw _makeTypeError(
                'ERR_INVALID_ARG_TYPE',
                'The "err" argument must be of type object.' + _invalidArgTypeHelper(error),
            );
        }
        return _diagnosticReport(error);
    },
    writeReport(filename, error) {
        if (filename !== undefined && filename !== null && typeof filename === 'object') {
            error = filename;
            filename = undefined;
        } else if (filename !== undefined && typeof filename !== 'string') {
            throw _makeTypeError(
                'ERR_INVALID_ARG_TYPE',
                'The "file" argument must be of type string.' + _invalidArgTypeHelper(filename),
            );
        }
        if (error !== undefined &&
            (error === null || typeof error !== 'object' || Array.isArray(error))) {
            throw _makeTypeError(
                'ERR_INVALID_ARG_TYPE',
                'The "err" argument must be of type object.' + _invalidArgTypeHelper(error),
            );
        }
        const selected = filename || _reportOptions.filename || _defaultReportFilename();
        const output = _reportOptions.directory && selected.charCodeAt(0) !== 47
            ? _reportOptions.directory.replace(/\/+$/, '') + '/' + selected
            : selected;
        const createRequire = globalThis.__wasm_rquickjs_create_require;
        if (typeof createRequire !== 'function') {
            throw _makeError('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM', 'process.report.writeReport is unavailable');
        }
        const fs = createRequire(process.cwd(), null)('node:fs');
        const report = _diagnosticReport(error);
        report.header.filename = output;
        fs.writeFileSync(output, JSON.stringify(report, null, _reportOptions.compact ? 0 : 2));
        return output;
    },
};

for (const name of ['directory', 'filename', 'signal']) {
    Object.defineProperty(process.report, name, {
        get() { return _reportOptions[name]; },
        set(value) { _reportStringOption(name, value); },
        enumerable: true,
        configurable: true,
    });
}
for (const name of [
    'compact',
    'excludeNetwork',
    'reportOnFatalError',
    'reportOnSignal',
    'reportOnUncaughtException',
    'excludeEnv',
]) {
    Object.defineProperty(process.report, name, {
        get() { return _reportOptions[name]; },
        set(value) { _reportBooleanOption(name, value); },
        enumerable: true,
        configurable: true,
    });
}
Object.defineProperty(process, Symbol.toStringTag, {
    value: 'process',
    writable: true,
    enumerable: false,
    configurable: true,
});

let _startTime = null;

process.cpuUsage = function cpuUsage(previousValue) {
    if (previousValue !== undefined) {
        if (typeof previousValue !== 'object' || previousValue === null) {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "prevValue" argument must be of type object.' + _invalidArgTypeHelper(previousValue));
        }
        if (typeof previousValue.user !== 'number') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "prevValue.user" property must be of type number.' + _invalidArgTypeHelper(previousValue.user));
        }
        if (typeof previousValue.system !== 'number') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "prevValue.system" property must be of type number.' + _invalidArgTypeHelper(previousValue.system));
        }
        if (previousValue.user < 0 || !Number.isFinite(previousValue.user)) {
            throw _makeRangeError('ERR_INVALID_ARG_VALUE',
                "The property 'prevValue.user' is invalid. Received " + previousValue.user);
        }
        if (previousValue.system < 0 || !Number.isFinite(previousValue.system)) {
            throw _makeRangeError('ERR_INVALID_ARG_VALUE',
                "The property 'prevValue.system' is invalid. Received " + previousValue.system);
        }
        return { user: -previousValue.user, system: -previousValue.system };
    }
    return { user: 0, system: 0 };
};

process.memoryUsage = function memoryUsage() {
    const stats = _native_memory_usage();
    return {
        rss: stats[0],
        heapTotal: stats[1],
        heapUsed: stats[1],
        external: stats[2],
        arrayBuffers: stats[3],
    };
};

process.memoryUsage.rss = function rss() {
    return _native_memory_usage()[0];
};

process.constrainedMemory = function constrainedMemory() {
    return 0;
};

process.availableMemory = function availableMemory() {
    return 0;
};

process.uptime = function uptime() {
    if (_startTime === null) {
        _startTime = Date.now();
    }
    return (Date.now() - _startTime) / 1000;
};

process.binding = function binding() {
    throw new Error('process.binding is not supported in WASM environment');
};

process._linkedBinding = function _linkedBinding() {
    throw new Error('process._linkedBinding is not supported in WASM environment');
};

let _uncaughtExceptionCallback = null;

process.setUncaughtExceptionCaptureCallback = function setUncaughtExceptionCaptureCallback(fn) {
    if (fn !== null && typeof fn !== 'function') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "fn" argument must be of type function or null.' + _invalidArgTypeHelper(fn));
    }
    if (fn !== null && _uncaughtExceptionCallback !== null) {
        const err = new Error('`process.setupUncaughtExceptionCapture()` was called while a capture callback was already active');
        err.code = 'ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET';
        throw err;
    }
    _uncaughtExceptionCallback = fn;
};

process.hasUncaughtExceptionCaptureCallback = function hasUncaughtExceptionCaptureCallback() {
    return _uncaughtExceptionCallback !== null;
};

process.dlopen = function dlopen(module, filename) {
    const err = new Error('Cannot load native addon in WASM environment: ' + (filename || ''));
    err.code = 'ERR_DLOPEN_FAILED';
    throw err;
};

process.stdin = { isTTY: false, fd: 0, read() { return null; }, on() { return this; }, resume() { return this; }, pause() { return this; } };

function createWritableStdio(fd, writer) {
    const stream = new EventEmitter();
    Object.assign(stream, {
        isTTY: false,
        fd,
        writable: true,
        writableNeedDrain: false,
        write(chunk, encoding, callback) {
            let cb = callback;
            if (typeof encoding === 'function') {
                cb = encoding;
            }
            writer(String(chunk));
            if (typeof cb === 'function') {
                cb();
            }
            return true;
        },
        end(chunk, encoding, callback) {
            if (chunk !== undefined && typeof chunk !== 'function') {
                this.write(chunk, encoding);
            }
            const cb = typeof chunk === 'function' ? chunk :
                (typeof encoding === 'function' ? encoding : callback);
            if (typeof cb === 'function') {
                cb();
            }
            this.emit('finish');
            return this;
        }
    });
    return stream;
}

process.stdout = createWritableStdio(1, write_stdout);
process.stderr = createWritableStdio(2, write_stderr);

let _cwd = get_cwd();

process.cwd = function cwd() {
    return _cwd;
};

// nextTick queue: callbacks are drained at Node.js-style checkpoints exposed
// by the timer/event-loop shims and process exit handling.  A zero-delay timer
// is used only as a wakeup when no other host callback would reach a checkpoint;
// this keeps nextTick separate from ECMAScript Promise jobs, unlike the previous
// Promise-based drain which could run during dynamic import evaluation.
const __nextTickQueue = [];
let __nextTickWakeupScheduled = false;

function __wasm_rquickjs_handleUncaughtError(err, domain) {
    if (domain && typeof domain.emit === 'function') {
        if (err != null && (typeof err === 'object' || typeof err === 'function')) {
            err.domain = domain;
            err.domainThrown = true;
        }
        domain.emit('error', err);
        return;
    }

    if (_uncaughtExceptionCallback !== null) {
        _uncaughtExceptionCallback(err);
        return;
    }

    if (process.listenerCount('uncaughtException') > 0) {
        process.emit('uncaughtException', err, 'uncaughtException');
        return;
    }

    if (typeof console !== 'undefined') {
        console.error(err);
    }
}

globalThis.__wasm_rquickjs_handleUncaughtError = __wasm_rquickjs_handleUncaughtError;

function __drainNextTickQueue() {
    __nextTickWakeupScheduled = false;
    let drained = 0;
    while (__nextTickQueue.length > 0) {
        const entry = __nextTickQueue.shift();
        drained += 1;
        try {
            if (entry.domain) {
                entry.domain.enter();
            }
            entry.callback.apply(undefined, entry.args);
            if (entry.domain) {
                entry.domain.exit();
            }
        } catch (e) {
            if (entry.domain) {
                entry.domain.exit();
            }
            __wasm_rquickjs_handleUncaughtError(e, entry.domain);
        }
    }
    return drained;
}

function __requestNextTickWakeup() {
    if (__nextTickWakeupScheduled || __nextTickQueue.length === 0) {
        return;
    }
    __nextTickWakeupScheduled = true;
    if (typeof globalThis.setTimeout === 'function') {
        globalThis.setTimeout(function __nextTickWakeup() {
            __drainNextTickQueue();
        }, 0);
    } else {
        Promise.resolve().then(__drainNextTickQueue);
    }
}

// Expose the drain function for the Rust turn-checkpoint bridge, which owns
// draining nextTick before QuickJS jobs and host callbacks.
globalThis.__wasm_rquickjs_drainNextTick = __drainNextTickQueue;
globalThis.__wasm_rquickjs_requestNextTickWakeup = __requestNextTickWakeup;

process.nextTick = function processNextTick(callback, ...args) {
    if (typeof callback !== 'function') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "callback" argument must be of type function.' + _invalidArgTypeHelper(callback));
    }
    const domain = process.domain || null;
    __nextTickQueue.push({ callback, args, domain });
    __requestNextTickWakeup();
};

let _umask = 0o022;
process.umask = function umask(mask) {
    if (mask === undefined) return _umask;
    const old = _umask;
    if (typeof mask === 'string') {
        if (!/^[0-7]+$/.test(mask)) {
            const err = new TypeError('The "mask" argument must be a valid octal string. Received \'' + mask + '\'');
            err.code = 'ERR_INVALID_ARG_VALUE';
            throw err;
        }
        _umask = parseInt(mask, 8) & 0o777;
    } else if (typeof mask === 'number') {
        _umask = mask & 0o777;
    } else {
        const err = new TypeError('The "mask" argument must be one of type number or string. Received an instance of ' + (typeof mask === 'object' ? mask.constructor.name : typeof mask));
        err.code = 'ERR_INVALID_ARG_TYPE';
        throw err;
    }
    return old;
};

process.getuid = function getuid() { return 0; };
process.getgid = function getgid() { return 0; };
process.geteuid = function geteuid() { return 0; };
process.getegid = function getegid() { return 0; };
process.getgroups = function getgroups() { return [0]; };

process.chdir = function chdir(directory) {
    if (typeof directory !== 'string') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "directory" argument must be of type string.' + _invalidArgTypeHelper(directory));
    }
    // Resolve relative paths against current cwd
    let resolved = directory;
    if (resolved.charAt(0) !== '/') {
        const currentCwd = process.cwd();
        resolved = currentCwd + (currentCwd === '/' ? '' : '/') + resolved;
    }
    // Normalize . and ..
    const parts = resolved.split('/');
    const normalized = [];
    for (let i = 0; i < parts.length; i++) {
        if (parts[i] === '' || parts[i] === '.') continue;
        if (parts[i] === '..') { normalized.pop(); continue; }
        normalized.push(parts[i]);
    }
    resolved = '/' + normalized.join('/');
    const code = native_chdir(resolved);
    if (code !== undefined && code !== null) {
        const err = new Error(`${code}: no such file or directory, chdir '${process.cwd()}' -> '${directory}'`);
        err.errno = code === 'ENOENT' ? -2 : -22;
        err.code = code;
        err.syscall = 'chdir';
        err.path = process.cwd();
        err.dest = directory;
        throw err;
    }
    // WASI's current_dir display can be lossy after changing into a nested
    // preopened path. Node's process.cwd() reflects the successful chdir
    // target, so keep the normalized absolute path as the JavaScript-visible
    // cwd once the native chdir succeeds.
    _cwd = resolved;
};

function _makeCredentialSetter(name, argName, credentialType) {
    return function(id) {
        if (typeof id !== 'number' && typeof id !== 'string') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "' + argName + '" argument must be one of type number or string.' + _invalidArgTypeHelper(id));
        }
        if (typeof id === 'string') {
            throw _makeError('ERR_UNKNOWN_CREDENTIAL', credentialType + ' identifier does not exist: ' + id);
        }
    };
}
// Named functions preserve .name for compatibility
process.setuid = _makeCredentialSetter('setuid', 'id', 'User');
Object.defineProperty(process.setuid, 'name', { value: 'setuid' });
process.setgid = _makeCredentialSetter('setgid', 'id', 'Group');
Object.defineProperty(process.setgid, 'name', { value: 'setgid' });
process.seteuid = _makeCredentialSetter('seteuid', 'id', 'User');
Object.defineProperty(process.seteuid, 'name', { value: 'seteuid' });
process.setegid = _makeCredentialSetter('setegid', 'id', 'Group');
Object.defineProperty(process.setegid, 'name', { value: 'setegid' });

process.setgroups = function setgroups(groups) {
    if (!Array.isArray(groups)) {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "groups" argument must be an instance of Array.' + _invalidArgTypeHelper(groups));
    }
    for (let i = 0; i < groups.length; i++) {
        const g = groups[i];
        if (typeof g !== 'number' && typeof g !== 'string') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "groups[' + i + ']" argument must be one of type number or string.' + _invalidArgTypeHelper(g));
        }
        if (typeof g === 'number' && g < 0) {
            throw _makeRangeError('ERR_OUT_OF_RANGE',
                'The value of "groups[' + i + ']" is out of range. It must be >= 0. Received ' + g);
        }
        if (typeof g === 'string') {
            throw _makeError('ERR_UNKNOWN_CREDENTIAL', 'Group identifier does not exist: ' + g);
        }
    }
};

process.initgroups = function initgroups(user, extraGroup) {
    if (typeof user !== 'number' && typeof user !== 'string') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "user" argument must be one of type number or string.' + _invalidArgTypeHelper(user));
    }
    if (typeof extraGroup !== 'number' && typeof extraGroup !== 'string') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "extraGroup" argument must be one of type number or string.' + _invalidArgTypeHelper(extraGroup));
    }
    if (typeof extraGroup === 'string') {
        throw _makeError('ERR_UNKNOWN_CREDENTIAL', 'Group identifier does not exist: ' + extraGroup);
    }
    if (typeof user === 'string') {
        throw _makeError('ERR_UNKNOWN_CREDENTIAL', 'User identifier does not exist: ' + user);
    }
};

process.hrtime = function hrtime(time) {
    const ns = hrtime_ns();
    if (time !== undefined) {
        if (!Array.isArray(time)) {
            const err = new TypeError('The "time" argument must be an instance of Array. Received type ' + typeof time + ' (' + String(time) + ')');
            err.code = 'ERR_INVALID_ARG_TYPE';
            throw err;
        }
        if (time.length !== 2) {
            const err = new RangeError('The value of "time" is out of range. It must be 2. Received ' + time.length);
            err.code = 'ERR_OUT_OF_RANGE';
            throw err;
        }
        let sec = Math.floor(ns / 1e9) - time[0];
        let nsec = (ns % 1e9) - time[1];
        if (nsec < 0) {
            sec -= 1;
            nsec += 1e9;
        }
        return [sec, nsec];
    }
    return [Math.floor(ns / 1e9), ns % 1e9];
};

process.hrtime.bigint = function bigint() {
    return BigInt(hrtime_ns());
};

process.abort = () => {
    throw new Error('process.abort is not supported in WASM environment');
};

const _signals = {
    SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6,
    SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11, SIGUSR2: 12,
    SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15, SIGCHLD: 17, SIGCONT: 18,
    SIGSTOP: 19, SIGTSTP: 20, SIGTTIN: 21, SIGTTOU: 22, SIGURG: 23,
    SIGXCPU: 24, SIGXFSZ: 25, SIGVTALRM: 26, SIGPROF: 27, SIGWINCH: 28,
    SIGIO: 29, SIGPWR: 30, SIGSYS: 31, 0: 0
};

process.kill = function kill(pid, signal) {
    const origPid = pid;
    if (typeof pid === 'string') pid = Number(pid);
    if (typeof pid !== 'number' || Number.isNaN(pid) || !Number.isFinite(pid)) {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "pid" argument must be of type number.' + _invalidArgTypeHelper(origPid));
    }
    pid = Math.trunc(pid);
    if (signal === undefined) signal = 'SIGTERM';
    let sigNum;
    if (typeof signal === 'number') {
        if (signal < 0 || signal > 31) {
            throw _makeError('EINVAL', 'kill EINVAL');
        }
        sigNum = signal;
    } else if (typeof signal === 'string') {
        sigNum = _signals[signal];
        if (sigNum === undefined) {
            throw _makeTypeError('ERR_UNKNOWN_SIGNAL', 'Unknown signal: ' + signal);
        }
    } else {
        throw _makeTypeError('ERR_UNKNOWN_SIGNAL', 'Unknown signal: ' + String(signal));
    }
    if (typeof process._kill === 'function') {
        process._kill(pid, sigNum);
    } else {
        throw _makeError('ERR_OPERATION_FAILED', 'process.kill is not supported in WASI environment');
    }
};

process.emitWarning = function emitWarning(warning, typeOrOptions, code, ctor) {
    if (typeof code === 'function') {
        ctor = code;
        code = undefined;
    }
    if (warning === undefined || (typeof warning !== 'string' && !(warning instanceof Error))) {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "warning" argument must be of type string or an instance of Error.' + _invalidArgTypeHelper(warning));
    }
    if (typeof warning === 'string') {
        if (typeOrOptions !== undefined && typeOrOptions !== null && typeof typeOrOptions !== 'string' && typeof typeOrOptions !== 'object' && typeof typeOrOptions !== 'function') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "type" argument must be of type string.' + _invalidArgTypeHelper(typeOrOptions));
        }
        if (typeof typeOrOptions === 'object' && typeOrOptions !== null && !(typeOrOptions instanceof Error)) {
            if (Array.isArray(typeOrOptions)) {
                throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                    'The "type" argument must be of type string.' + _invalidArgTypeHelper(typeOrOptions));
            }
        }
        if (code !== undefined && typeof code !== 'string') {
            throw _makeTypeError('ERR_INVALID_ARG_TYPE',
                'The "code" argument must be of type string.' + _invalidArgTypeHelper(code));
        }
    }
    let obj;
    let createdWarning = false;
    if (typeof warning === 'string') {
        createdWarning = true;
        obj = new Error(warning);
        obj.name = (typeof typeOrOptions === 'string') ? typeOrOptions : 'Warning';
        if (typeof typeOrOptions === 'object' && typeOrOptions !== null) {
            if (typeOrOptions.type) obj.name = typeOrOptions.type;
            if (typeOrOptions.code) obj.code = typeOrOptions.code;
            if (typeOrOptions.detail) obj.detail = typeOrOptions.detail;
        } else if (typeof code === 'string') {
            obj.code = code;
        }
    } else {
        obj = warning;
        if (!obj.name) obj.name = 'Warning';
    }
    const warningName = String(obj.name || 'Warning');
    const isDeprecationWarning = warningName === 'DeprecationWarning';
    if (isDeprecationWarning && process.noDeprecation) {
        return;
    }
    const warningCode = obj.code ? ' [' + String(obj.code) + ']' : '';
    const warningHeader = warningName + ': ' + String(obj.message || obj);
    const stderrHeader = warningName + warningCode + ': ' + String(obj.message || obj);
    let formattedStack;
    if (typeof obj.stack === 'string') {
        const newline = obj.stack.indexOf('\n');
        const rest = newline === -1 ? '' : obj.stack.slice(newline);
        formattedStack = obj.stack.startsWith(warningHeader)
            ? obj.stack
            : warningHeader + rest;
    } else {
        formattedStack = warningHeader;
    }
    if (createdWarning) {
        obj.stack = formattedStack;
    }

    const suppressDefaultWarning = !!globalThis.__wasm_rquickjs_suppress_warning_stderr;
    const shouldThrowDeprecation = isDeprecationWarning && !!process.throwDeprecation;
    process.nextTick(function() {
        if (shouldThrowDeprecation) {
            throw obj;
        }
        if (!suppressDefaultWarning && process.stderr && typeof process.stderr.write === 'function') {
            let text = stderrHeader;
            if (typeof formattedStack === 'string') {
                text = formattedStack.indexOf(String(obj.message || obj)) >= 0
                    ? formattedStack
                    : stderrHeader + '\n' + formattedStack;
                if (warningCode && text.startsWith(warningHeader)) {
                    text = stderrHeader + text.slice(warningHeader.length);
                }
            }
            process.stderr.write(text.endsWith('\n') ? text : text + '\n');
        }
        process.emit('warning', obj);
    });
};

process.exit = function exit(code) {
    if (code !== undefined) {
        process.exitCode = code;
    }
    if (!_exiting) {
        _exiting = true;
        process.emit('exit', process.exitCode || 0);
    }
    throw new ProcessExitError(process.exitCode || 0);
};

process._exiting = false;

// Active handle tracking for process._getActiveHandles() / process._getActiveRequests()
if (!globalThis.__wasm_rquickjs_active_handles) {
    globalThis.__wasm_rquickjs_active_handles = new Set();
}

process._getActiveHandles = function _getActiveHandles() {
    return Array.from(globalThis.__wasm_rquickjs_active_handles);
};

process._getActiveRequests = function _getActiveRequests() {
    return [];
};

process.channel = undefined;
process.connected = false;
process.debugPort = 9229;
process.setSourceMapsEnabled = function setSourceMapsEnabled(val) {
    if (typeof val !== 'boolean') {
        throw _makeTypeError('ERR_INVALID_ARG_TYPE',
            'The "val" argument must be of type boolean.' + _invalidArgTypeHelper(val));
    }
};

Object.defineProperty(process, '_exiting', {
    get: function() { return _exiting; },
    set: function(v) { _exiting = v; },
    enumerable: false,
    configurable: true,
});

// Sentinel error for process.exit()
class ProcessExitError extends Error {
    constructor(code) {
        super('process.exit(' + code + ')');
        this.code = code;
        this.name = 'ProcessExitError';
        this.__isProcessExit = true;
    }
}

// Internal: run exit handlers without throwing the sentinel
process._runExitHandlers = function _runExitHandlers(code) {
    if (!_exiting) {
        _exiting = true;
        if (code !== undefined) {
            process.exitCode = code;
        }
        __drainNextTickQueue();
        process.emit('beforeExit', process.exitCode || 0);
        __drainNextTickQueue();
        process.emit('exit', process.exitCode || 0);
    }
};

// Unhandled promise rejection tracking.
// The native rejection tracker (set_host_promise_rejection_tracker) calls
// __wasm_rquickjs_rejection_tracker(promise, reason, is_handled) for every
// rejection event. We track unhandled rejections and only emit the event
// after a microtask turn, so that assert.rejects() and similar patterns
// that handle the rejection synchronously don't cause false positives.
const _pendingRejections = new Map();
const _ignoredUnhandledRejections = new WeakSet();
const _emittedUnhandledRejections = new WeakSet();
const _pendingRejectionHandled = new Set();
const _requireEsmRejectionScopes = [];
const _sameValue = Object.is;
let _nextRequireEsmRejectionScope = 0;

function _isIgnoredUnhandledRejection(promise) {
    return _ignoredUnhandledRejections.has(promise);
}

globalThis.__wasm_rquickjs_rejection_tracker = function(promise, reason, isHandled) {
    if (_isIgnoredUnhandledRejection(promise)) {
        _pendingRejections.delete(promise);
        _pendingRejectionHandled.delete(promise);
        return;
    }
    if (!isHandled) {
        _pendingRejections.set(promise, { reason });
        const scope = _requireEsmRejectionScopes[_requireEsmRejectionScopes.length - 1];
        if (scope !== undefined) {
            scope.promises.push(promise);
        }
    } else {
        if (!_pendingRejections.delete(promise) && _emittedUnhandledRejections.has(promise)) {
            _emittedUnhandledRejections.delete(promise);
            _pendingRejectionHandled.add(promise);
        }
    }
};

// Called only by the host event-loop checkpoint after process.nextTick and
// QuickJS jobs have stabilized. Keeping this private avoids introducing a
// public timer whose lifetime or ordering would differ from Node's turn-end
// promise rejection processing.
globalThis.__wasm_rquickjs_unhandled_rejection_checkpoint = function() {
    if (_pendingRejectionHandled.size === 0 && _pendingRejections.size === 0) {
        return 0;
    }

    let emitted = 0;
    const handled = Array.from(_pendingRejectionHandled);
    for (const promise of handled) {
        if (!_pendingRejectionHandled.delete(promise)) {
            continue;
        }
        if (!_isIgnoredUnhandledRejection(promise)) {
            emitted += 1;
            try {
                process.emit('rejectionHandled', promise);
            } catch (error) {
                __wasm_rquickjs_handleUncaughtError(error);
            }
        }
    }

    const pending = Array.from(_pendingRejections);
    for (const [promise, entry] of pending) {
        if (!_pendingRejections.has(promise)) {
            continue;
        }
        _pendingRejections.delete(promise);
        if (!_isIgnoredUnhandledRejection(promise)) {
            _emittedUnhandledRejections.add(promise);
            emitted += 1;
            try {
                process.emit('unhandledRejection', entry.reason, promise);
            } catch (error) {
                __wasm_rquickjs_handleUncaughtError(error);
            }
        }
    }
    return emitted;
};

globalThis.__wasm_rquickjs_ignore_unhandled_rejection = function(promise) {
    _ignoredUnhandledRejections.add(promise);
    _pendingRejections.delete(promise);
    _emittedUnhandledRejections.delete(promise);
    _pendingRejectionHandled.delete(promise);
};

globalThis.__wasm_rquickjs_begin_require_esm_rejection_scope = function() {
    const id = ++_nextRequireEsmRejectionScope;
    _requireEsmRejectionScopes.push({ id, promises: [] });
    return id;
};

function _takeRequireEsmRejectionScope(id) {
    for (let i = _requireEsmRejectionScopes.length - 1; i >= 0; i--) {
        if (_requireEsmRejectionScopes[i].id === id) {
            return _requireEsmRejectionScopes.splice(i, 1)[0];
        }
    }
    return undefined;
}

globalThis.__wasm_rquickjs_end_require_esm_rejection_scope = function(id) {
    _takeRequireEsmRejectionScope(id);
};

globalThis.__wasm_rquickjs_ignore_require_esm_rejection = function(evaluationPromise, rejectedReason, id) {
    const scope = _takeRequireEsmRejectionScope(id);
    _ignoredUnhandledRejections.add(evaluationPromise);
    _pendingRejections.delete(evaluationPromise);
    _emittedUnhandledRejections.delete(evaluationPromise);
    _pendingRejectionHandled.delete(evaluationPromise);

    if (scope !== undefined) {
        // QuickJS reports the internal module-evaluation promise immediately
        // before the outward promise returned by JS_EvalFunction. Suppress only
        // that pair. Searching backward for any still-pending promise can select
        // an unrelated rejection created by user module code.
        const evaluationIndex = scope.promises.length - 1;
        if (evaluationIndex > 0 && scope.promises[evaluationIndex] === evaluationPromise) {
            const modulePromise = scope.promises[evaluationIndex - 1];
            const moduleEntry = _pendingRejections.get(modulePromise);
            if (moduleEntry !== undefined && _sameValue(moduleEntry.reason, rejectedReason)) {
                _ignoredUnhandledRejections.add(modulePromise);
                _pendingRejections.delete(modulePromise);
                _emittedUnhandledRejections.delete(modulePromise);
                _pendingRejectionHandled.delete(modulePromise);
            }
        }
    }
};

// Named exports for import { argv } from 'node:process' style
export var stdout = process.stdout;
export var stderr = process.stderr;
export function cwd() { return process.cwd(); }
export function nextTick(callback, ...args) { process.nextTick(callback, ...args); }
export function exit(code) { process.exit(code); }
export var pid = process.pid;
export var platform = process.platform;
export var arch = process.arch;
export var version = process.version;
export var versions = process.versions;
export var config = process.config;
export var execArgv = process.execArgv;
export var execPath = process.execPath;
export var hrtime = process.hrtime;
export var cpuUsage = process.cpuUsage;
export var memoryUsage = process.memoryUsage;
export var uptime = process.uptime;
export var release = process.release;
export var report = process.report;
export var stdin = process.stdin;
export var kill = process.kill;
export var emitWarning = process.emitWarning;
export var allowedNodeEnvironmentFlags = process.allowedNodeEnvironmentFlags;
export var features = process.features;
export var title = process.title;
export var ppid = process.ppid;
export var umask = process.umask;
export var getuid = process.getuid;
export var getgid = process.getgid;
export var geteuid = process.geteuid;
export var getegid = process.getegid;
export var getgroups = process.getgroups;
export var abort = process.abort;
export var chdir = process.chdir;
export var setuid = process.setuid;
export var setgid = process.setgid;
export var seteuid = process.seteuid;
export var setegid = process.setegid;
export var setgroups = process.setgroups;
export var initgroups = process.initgroups;
export var dlopen = process.dlopen;
export var binding = process.binding;
export var _linkedBinding = process._linkedBinding;
export var _getActiveHandles = process._getActiveHandles;
export var _getActiveRequests = process._getActiveRequests;
export var constrainedMemory = process.constrainedMemory;
export var availableMemory = process.availableMemory;
export var setUncaughtExceptionCaptureCallback = process.setUncaughtExceptionCaptureCallback;
export var hasUncaughtExceptionCaptureCallback = process.hasUncaughtExceptionCaptureCallback;
export var exitCode = process.exitCode;
export var _exiting = process._exiting;
export var channel = process.channel;
export var connected = process.connected;
export var debugPort = process.debugPort;
export var setSourceMapsEnabled = process.setSourceMapsEnabled;

export default process;