wasm-rquickjs-cli 0.5.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
import { runJavaScript } from 'wasm-rquickjs:execution';

const npmCli = '/tool/npm/lib/cli.js';

async function executeNpm(args, timeoutMs) {
    try {
        const result = await runJavaScript({
            cwd: '/workspace',
            argv: ['node', '/tool/npm/bin/npm-cli.js', ...args],
            env: {
                HOME: '/home/npm',
                NODE: process.execPath,
                NPM: '/tool/npm/bin/npm-cli.js',
                NPM_CONFIG_AUDIT: 'false',
                NPM_CONFIG_CACHE: '/cache/npm',
                NPM_CONFIG_FUND: 'false',
                NPM_CONFIG_FETCH_RETRIES: '0',
                NPM_CONFIG_PREFIX: '/prefix',
                NPM_CONFIG_UPDATE_NOTIFIER: 'false',
                PATH: '',
            },
            maxBytes: 4 * 1024 * 1024,
            timeoutMs,
            source: `
            const cli = (await import(${JSON.stringify(npmCli)})).default;
            const originalExit = process.exit;
            process.exit = code => {
                if (code !== undefined) process.exitCode = Number(code);
                if (!process._exiting) {
                    process._exiting = true;
                    process.emit('exit', process.exitCode || 0);
                }
            };
            try {
                await cli(process);
                await new Promise(resolve => setTimeout(resolve, 0));
                return { exitCode: process.exitCode || 0 };
            } finally {
                process.exit = originalExit;
            }
            `,
        });
        return JSON.stringify(result);
    } catch (error) {
        return JSON.stringify({
            runnerError: {
                name: error && error.name,
                message: error && error.message,
                stack: error && error.stack,
            },
        });
    }
}

export async function run(args) {
    return executeNpm(args, 60_000);
}

export async function runWithTimeout(args, timeoutMs) {
    return executeNpm(args, timeoutMs);
}

export async function runNpx(args) {
    const result = await runJavaScript({
        cwd: '/workspace',
        argv: ['node', '/tool/npm/bin/npx-cli.js', ...args],
        env: {
            HOME: '/home/npm',
            NODE: process.execPath,
            NPM: '/tool/npm/bin/npm-cli.js',
            NPM_CONFIG_AUDIT: 'false',
            NPM_CONFIG_CACHE: '/cache/npm',
            NPM_CONFIG_FUND: 'false',
            NPM_CONFIG_PREFIX: '/prefix',
            NPM_CONFIG_UPDATE_NOTIFIER: 'false',
            PATH: '',
        },
        maxBytes: 4 * 1024 * 1024,
        timeoutMs: 60_000,
        source: `
            const originalExit = process.exit;
            process.exit = code => {
                if (code !== undefined) process.exitCode = Number(code);
                if (!process._exiting) {
                    process._exiting = true;
                    process.emit('exit', process.exitCode || 0);
                }
            };
            try {
                await import('/tool/npm/bin/npx-cli.js');
                for (let attempt = 0; attempt < 3_000 && !process._exiting; attempt++) {
                    await new Promise(resolve => setTimeout(resolve, 10));
                }
                return { exitCode: process.exitCode || 0 };
            } finally {
                process.exit = originalExit;
            }
        `,
    });
    return JSON.stringify(result);
}

export async function runInstalled() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const dependency = (await import('fixture-dependency')).default;
            return dependency();
        `,
    });
    return JSON.stringify(result);
}

export async function runInstalledTypescript() {
    const project = await runJavaScript({
        cwd: '/workspace',
        entry: './typescript-app.ts',
    });
    const rawTypeScriptDependency = await runJavaScript({
        cwd: '/workspace',
        source: `
            try {
                await import('fixture-dependency/raw-typescript');
                return { loaded: true };
            } catch (error) {
                return { code: error.code, name: error.name, message: error.message };
            }
        `,
    });
    return JSON.stringify({
        project,
        rawTypeScriptDependencyError: rawTypeScriptDependency.value,
    });
}

export async function runRegistryInstalled() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const dependency = (await import('fixture-registry-dependency')).default;
            return dependency();
        `,
    });
    return JSON.stringify(result);
}

export async function runPackageFormats() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const { createRequire } = await import('node:module');
            const require = createRequire('/workspace/format-probe.cjs');
            const commonjs = require('fixture-commonjs-dependency');
            const dualEsm = (await import('fixture-dual-dependency')).default;
            const dualCommonjs = require('fixture-dual-dependency');
            return { commonjs, dualEsm, dualCommonjs };
        `,
    });
    return JSON.stringify(result);
}

export async function runBinDirect() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const { spawn } = await import('node:child_process');
            const fs = await import('node:fs');
            const binPath = '/workspace/node_modules/.bin/fixture-bin';
            const probe = {};
            for (const [name, operation] of Object.entries({
                source: () => fs.readFileSync(binPath, 'utf8').split('\\n', 1)[0],
                link: () => fs.readlinkSync(binPath),
                realpath: () => fs.realpathSync(binPath),
                mode: () => fs.statSync(binPath).mode & 0o777,
            })) {
                try {
                    probe[name] = operation();
                } catch (error) {
                    probe[name] = error.code + ':' + error.message;
                }
            }
            const child = spawn('sh', ['-c', 'fixture-bin direct'], {
                cwd: '/workspace',
                env: { PATH: '/workspace/node_modules/.bin' },
            });
            let stdout = '';
            let stderr = '';
            let error = null;
            const events = [];
            child.stdout.on('data', chunk => { stdout += chunk.toString(); });
            child.stderr.on('data', chunk => { stderr += chunk.toString(); });
            child.on('error', value => {
                events.push('error');
                error = value.code + ':' + value.message;
            });
            child.on('exit', () => { events.push('exit'); });
            const state = await new Promise(resolve => {
                child.on('close', (code, signal) => {
                    events.push('close');
                    resolve({ code, signal });
                });
            });
            return { ...state, stdout, stderr, error, events, probe };
        `,
    });
    return JSON.stringify(result);
}

export async function probeLinkedLayouts() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const fs = await import('node:fs');
            const { createRequire } = await import('node:module');
            const require = createRequire('/workspace/probe.cjs');
            const workspaceLinked = require('workspace-package');
            const workspaceReal = require('/workspace/packages/workspace-package');
            const npmLinked = require('linked-package');
            const npmReal = require('/workspace/linked-package');

            const pnpmStore = '/workspace/node_modules/.pnpm/pnpm-package@1.0.0/node_modules/pnpm-package';
            fs.mkdirSync(pnpmStore, { recursive: true });
            fs.writeFileSync(pnpmStore + '/package.json', JSON.stringify({
                name: 'pnpm-package', version: '1.0.0', main: 'index.cjs',
            }));
            fs.writeFileSync(pnpmStore + '/index.cjs', 'module.exports = { identity: {} };');
            fs.symlinkSync('.pnpm/pnpm-package@1.0.0/node_modules/pnpm-package',
                '/workspace/node_modules/pnpm-package', 'dir');
            const pnpmLinked = require('pnpm-package');
            const pnpmReal = require(pnpmStore);

            return {
                workspaceIdentity: workspaceLinked === workspaceReal,
                workspaceTarget: fs.readlinkSync('/workspace/node_modules/workspace-package'),
                workspaceRealpath: fs.realpathSync('/workspace/node_modules/workspace-package'),
                npmLinkIdentity: npmLinked === npmReal,
                npmLinkTarget: fs.readlinkSync('/workspace/node_modules/linked-package'),
                npmLinkRealpath: fs.realpathSync('/workspace/node_modules/linked-package'),
                pnpmIdentity: pnpmLinked === pnpmReal,
                pnpmTarget: fs.readlinkSync('/workspace/node_modules/pnpm-package'),
                pnpmRealpath: fs.realpathSync('/workspace/node_modules/pnpm-package'),
            };
        `,
    });
    return JSON.stringify(result);
}

export function probeRuntime() {
    return JSON.stringify({
        cwd: process.cwd(),
        fileUrl: new URL('file:packages/fixture-dependency', 'file:///workspace/').pathname,
    });
}

export async function probePrimitives() {
    const result = await runJavaScript({
        cwd: '/workspace',
        source: `
            const { createRequire } = await import('node:module');
            const require = createRequire('/workspace/probe.cjs');
            const constants = require('node:constants');
            const fs = require('node:fs');
            const v8 = require('node:v8');
            const zlib = require('node:zlib');
            const { exec, execFile, spawn, spawnSync } = require('node:child_process');
            const original = Buffer.from([1, 2, 3]);
            const species = Buffer[Symbol.species];
            const hostile = Buffer.from([4, 5, 6]);
            Object.defineProperty(hostile, 'constructor', {
                value: { [Symbol.species]: class HostileSpecies extends Uint8Array {} },
            });
            let dep0005Emitted = false;
            const originalEmitWarning = process.emitWarning;
            process.emitWarning = (warning, typeOrOptions, code) => {
                const warningCode = typeOrOptions && typeof typeOrOptions === 'object'
                    ? typeOrOptions.code
                    : code;
                if (warningCode === 'DEP0005') dep0005Emitted = true;
            };
            let view;
            let mapped;
            let filtered;
            let hostileView;
            let rejectsBigIntOffset = false;
            try {
                view = original.subarray(1, 3);
                view[0] = 9;
                mapped = original.map(value => value + 1);
                filtered = original.filter(value => value > 1);
                hostileView = hostile.subarray(1);
                try {
                    original.subarray(1n);
                } catch (error) {
                    rejectsBigIntOffset = error instanceof TypeError;
                }
            } finally {
                process.emitWarning = originalEmitWarning;
            }

            const shebangDir = '/workspace/shebang-bin';
            const missDir = '/workspace/shebang-missing';
            // WASI filesystem metadata does not expose host permission bits.
            // npm establishes executable .bin modes with chmod, which our fs
            // compatibility layer records and reports through stat/fstat.
            fs.chmodSync(shebangDir + '/env-node.cjs', 0o755);
            fs.chmodSync(shebangDir + '/not-node.cjs', 0o755);
            const runShebang = (command, pathValue = shebangDir) => spawnSync(
                'sh',
                ['-c', command],
                { cwd: '/workspace', env: { PATH: pathValue } },
            );
            const envNode = runShebang('env-node.cjs', missDir + ':' + shebangDir);
            const notNode = runShebang('not-node.cjs');
            const shellSync = spawnSync(process.execPath, ['-e', 'process.stdout.write("bad")'], {
                shell: true,
            });
            const assignedExitCode = spawnSync(
                process.execPath,
                ['-e', 'process.exitCode = 7'],
            );
            const beforeExitCode = spawnSync(
                process.execPath,
                ['-e', 'process.on("beforeExit", () => { process.exitCode = 9; })'],
            );
            const omittedExplicitExitCode = spawnSync(
                process.execPath,
                ['-e', 'process.exitCode = 7; process.exit()'],
            );
            const exitListenerCode = spawnSync(
                process.execPath,
                ['-e', 'process.on("exit", () => { process.exitCode = 9; }); process.exit(7)'],
            );
            const caughtExitCode = spawnSync(
                process.execPath,
                ['-e', 'try { process.exit(2); } catch { process.exit(1); }'],
            );
            const caughtExitListenerCode = spawnSync(
                process.execPath,
                ['-e', 'process.on("exit", () => { process.exitCode = 9; }); try { process.exit(7); } catch {}'],
            );
            const caughtExitThenThrow = spawnSync(
                process.execPath,
                ['-e', 'try { process.exit(2); } catch {} throw new Error("later");'],
            );
            const exitListenerThrows = spawnSync(
                process.execPath,
                ['-e', 'process.on("exit", () => { throw new Error("exit-listener"); }); process.exit(7)'],
            );
            const swallowedExitListenerThrows = spawnSync(
                process.execPath,
                ['-e', 'process.on("exit", () => { throw new Error("exit-listener-swallowed"); }); try { process.exit(7); } catch {}'],
            );
            const swallowedNullExitListenerThrows = spawnSync(
                process.execPath,
                ['-e', 'process.on("exit", () => { throw null; }); try { process.exit(7); } catch {}'],
            );
            process._runExit.call = () => {};
            let hardenedRunExit;
            try {
                hardenedRunExit = spawnSync(
                    process.execPath,
                    ['-e', 'process.exit(6); process.exitCode = 0'],
                );
            } finally {
                delete process._runExit.call;
            }
            const freshExitCode = spawnSync(
                process.execPath,
                ['-e', 'process.stdout.write("fresh")'],
            );
            const shellAsync = await new Promise(resolve => {
                const child = spawn(process.execPath, ['-e', 'process.stdout.write("bad")'], {
                    shell: true,
                });
                let error = null;
                const events = [];
                child.on('error', value => {
                    error = value;
                    events.push('error');
                });
                child.on('exit', () => events.push('exit'));
                child.on('close', code => {
                    events.push('close');
                    resolve({ code, error, events });
                });
            });
            const probeExecFailure = launch => new Promise(resolve => {
                const events = [];
                let callbackError = null;
                let emittedError = null;
                let stdout = null;
                let stderr = null;
                const child = launch((error, output, errorOutput) => {
                    callbackError = error;
                    stdout = output;
                    stderr = errorOutput;
                    events.push('callback');
                });
                child.on('error', error => {
                    emittedError = error;
                    events.push('error');
                });
                child.on('exit', () => events.push('exit'));
                child.on('close', code => {
                    events.push('close');
                    resolve({ callbackError, emittedError, code, exitCode: child.exitCode, stdout, stderr, events });
                });
            });
            const execFailure = await probeExecFailure(callback =>
                exec('wasm-rquickjs-missing-command', callback));
            const execFileFailure = await probeExecFailure(callback =>
                execFile('wasm-rquickjs-missing-command', callback));
            const genericEnvCommand = process.execPath + ' -p "process.argv[1]" "' + '$' + '{EXEC_VALUE}"';
            const backtick = String.fromCharCode(96);
            const genericEnvValues = [
                'generic-env', 'a|b', 'a<b', 'a"b', 'a&&b', 'a$(b)', 'a' + backtick + 'b',
            ];
            const genericEnvExpansions = await Promise.all(genericEnvValues.map(value =>
                probeExecFailure(callback =>
                    exec(genericEnvCommand, { env: { EXEC_VALUE: value } }, callback))));
            const splitEnvArgumentValues = ['-p -e', '-p\\t-e', '-p\\n-e'];
            const splitEnvArguments = await Promise.all(splitEnvArgumentValues.map(value =>
                probeExecFailure(callback =>
                    exec(process.execPath + ' \${EXEC_ARGS} 42', {
                        env: { EXEC_ARGS: value },
                    }, callback))));
            const unquotedEnvFields = [
                'a;b', 'c|d', 'a"b', '$(x)', '<', '>',
                'a' + backtick + 'b', 'a' + String.fromCharCode(92) + 'b', '~',
                'a' + String.fromCharCode(13) + 'b',
            ];
            const unquotedEnvData = await Promise.all(unquotedEnvFields.map(value =>
                probeExecFailure(callback =>
                    exec(process.execPath + ' -p "JSON.stringify(process.argv.slice(1))" \${EXEC_VALUE}', {
                        env: { EXEC_VALUE: value },
                    }, callback))));
            const rejectedEnvExpansions = await Promise.all([
                // NUL currently fails closed with ENOSYS. Node-style
                // synchronous validation across every spawn path is separate.
                '*', '?', '[x]', 'a' + String.fromCharCode(0) + 'b',
            ].map(value => probeExecFailure(callback =>
                exec(process.execPath + ' -p 42 \${EXEC_VALUE}', {
                    env: { EXEC_VALUE: value },
                }, callback))));
            const envRedirectInput = '/workspace/env-redirect-input';
            fs.writeFileSync(envRedirectInput, 'must-not-be-consumed');
            const derivedRedirectToken = await probeExecFailure(callback =>
                exec(process.execPath + ' -p "JSON.stringify(process.argv.slice(1))" \${EXEC_VALUE} ' +
                    envRedirectInput, { env: { EXEC_VALUE: '<' } }, callback));
            const rejectedRedirectCommands = await Promise.all([
                process.execPath + ' -e "$(x)" < ' + envRedirectInput,
                process.execPath + ' -e "' + backtick + 'x' + backtick + '" < ' + envRedirectInput,
                process.execPath + ' -e "\${MISSING}" < ' + envRedirectInput,
                process.execPath + ' -e "0" ' + '\\\\' + '\\ncontinued < ' + envRedirectInput,
                process.execPath + ' -e "0' + '\\\\' + '\\ncontinued" < ' + envRedirectInput,
            ].map(command => probeExecFailure(callback => exec(command, callback))));
            const injectedEnvStructure = await probeExecFailure(callback =>
                exec('$' + '{EXEC_COMMAND}', {
                    env: { EXEC_COMMAND: 'echo ok | ' + process.execPath + ' -e "0"' },
                }, callback));
            const quotedPipePipeline = await probeExecFailure(callback =>
                exec('echo ok | ' + process.execPath + ' -e "process.stdout.write(String(1|2))"', callback));
            const redirectionProbe = '/workspace/redirection-probe.cjs';
            const redirectionSideEffect = '/workspace/redirection-side-effect';
            fs.writeFileSync(redirectionProbe,
                'require("node:fs").writeFileSync("' + redirectionSideEffect + '", "partial")');
            const rejectedShellCommands = await Promise.all([
                process.execPath + ' -e "process.stdout.write(\\"partial\\")" && ' + process.execPath + ' -e "0"',
                process.execPath + ' -e "0" $UNSUPPORTED',
                process.execPath + ' -e "0" \${UNSUPPORTED}',
                process.execPath + ' -e "0" $(echo unsupported)',
                process.execPath + ' -e "0" > /workspace/partial-output',
                process.execPath + ' -e "0" ' + '\\\\' + '\\n' + 'continued',
                'echo ok | ' + process.execPath + ' -e "process.stdout.write(\\"partial\\")" && unsupported',
                'echo ok | ' + process.execPath + ' -e "0" $UNSUPPORTED',
                'echo ok | ' + process.execPath + ' -e "0" $(echo unsupported)',
                process.execPath + ' ' + redirectionProbe + ' < /workspace/missing-input',
            ].map(command => probeExecFailure(callback => exec(command, callback))));
            const compressed = zlib.gzipSync('npm');
            return {
                constantsCjs: typeof constants.COPYFILE_EXCL === 'number',
                processExitName: process.exit.name,
                heapSizeLimit: v8.getHeapStatistics().heap_size_limit,
                bufferView: Buffer.isBuffer(view) && original[1] === 9,
                bufferSpecies: species !== Buffer && species.prototype === Buffer.prototype &&
                    Object.getPrototypeOf(species) === Uint8Array && Buffer.prototype.constructor === Buffer,
                bufferTypedArrayMethods: Buffer.isBuffer(mapped) && Buffer.isBuffer(filtered),
                bufferOperationsAvoidDep0005: !dep0005Emitted,
                bufferSubarrayEdges: original.subarray(-Infinity).length === original.length &&
                    original.subarray(Infinity).length === 0 &&
                    original.subarray(NaN, 2).length === 2 && rejectsBigIntOffset,
                bufferSubarrayIgnoresSpecies: Buffer.isBuffer(hostileView) && hostileView[0] === 5,
                shellNodeShebangs: envNode.status === 0 &&
                    envNode.stdout.toString().trim() === 'env-node:ok',
                shellSkipsPathMisses: envNode.status === 0,
                shellRejectsMisleadingShebang: notNode.status === null && notNode.error &&
                    notNode.error.code === 'ENOSYS',
                shellOptionFailsExplicitly: shellSync.status === null &&
                    shellSync.error && shellSync.error.code === 'ENOSYS' &&
                    shellAsync.code === -38 && shellAsync.error &&
                    shellAsync.error.code === 'ENOSYS' &&
                    shellAsync.events.join(',') === 'error,close',
                childExitStatus: {
                    assigned: assignedExitCode.status,
                    beforeExit: beforeExitCode.status,
                    omittedExplicit: omittedExplicitExitCode.status,
                    exitListener: exitListenerCode.status,
                    caughtExit: caughtExitCode.status,
                    caughtExitListener: caughtExitListenerCode.status,
                    caughtExitThenThrow: caughtExitThenThrow.status,
                    exitListenerThrows: exitListenerThrows.status,
                    swallowedExitListenerThrows: swallowedExitListenerThrows.status,
                    swallowedNullExitListenerThrows: swallowedNullExitListenerThrows.status,
                    hardenedRunExit: hardenedRunExit.status,
                    fresh: freshExitCode.status,
                },
                childExitDiagnostics: {
                    suppressesPostExitError: caughtExitThenThrow.stderr.toString() === '',
                    reportsExitListenerError: exitListenerThrows.stderr.toString().includes('Error: exit-listener'),
                    reportsSwallowedExitListenerError:
                        swallowedExitListenerThrows.stderr.toString().includes('Error: exit-listener-swallowed'),
                    reportsSwallowedNullExitListenerError:
                        swallowedNullExitListenerThrows.stderr.toString().includes('null'),
                },
                execFailuresOmitExit: [execFailure, execFileFailure].every(failure =>
                    failure.callbackError && failure.callbackError.code === 'ENOSYS' &&
                    failure.emittedError && failure.emittedError.code === 'ENOSYS' &&
                    failure.code === -38 && failure.exitCode === -38 &&
                    failure.events.join(',') === 'callback,error,close'),
                execExpandsPresentBracedEnv: genericEnvExpansions.every((expansion, index) =>
                    !expansion.callbackError &&
                    expansion.stdout === genericEnvValues[index] + '\\n' &&
                    expansion.stderr === '' &&
                    expansion.events.join(',') === 'callback,exit,close') &&
                    splitEnvArguments.every(expansion =>
                        !expansion.callbackError &&
                        expansion.stdout === '42\\n' &&
                        expansion.stderr === '' &&
                        expansion.events.join(',') === 'callback,exit,close') &&
                    unquotedEnvData.every((expansion, index) =>
                        !expansion.callbackError &&
                        expansion.stdout === JSON.stringify([unquotedEnvFields[index]]) + '\\n' &&
                        expansion.stderr === '' &&
                        expansion.events.join(',') === 'callback,exit,close') &&
                    rejectedEnvExpansions.every(expansion =>
                        expansion.callbackError && expansion.callbackError.code === 'ENOSYS' &&
                        expansion.stdout === '' && expansion.stderr === '') &&
                    !derivedRedirectToken.callbackError &&
                    derivedRedirectToken.stdout === JSON.stringify(['<', envRedirectInput]) + '\\n' &&
                    derivedRedirectToken.stderr === '' &&
                    rejectedRedirectCommands.every(expansion =>
                        expansion.callbackError && expansion.callbackError.code === 'ENOSYS' &&
                        expansion.emittedError && expansion.emittedError.code === 'ENOSYS' &&
                        expansion.code === -38 && expansion.exitCode === -38 &&
                        expansion.stdout === '' && expansion.stderr === '' &&
                        expansion.events.join(',') === 'callback,error,close') &&
                    injectedEnvStructure.callbackError &&
                    injectedEnvStructure.callbackError.code === 'ENOSYS' &&
                    injectedEnvStructure.stdout === '',
                execEnvProbe: Object.fromEntries(Object.entries({
                    derivedRedirectToken,
                    injectedEnvStructure,
                    ...Object.fromEntries(splitEnvArguments.map(
                        (expansion, index) => ['split' + index, expansion])),
                    ...Object.fromEntries(rejectedRedirectCommands.map(
                        (expansion, index) => ['redirectRejected' + index, expansion])),
                    ...Object.fromEntries(unquotedEnvData.map(
                        (expansion, index) => ['unquoted' + index, expansion])),
                    ...Object.fromEntries(rejectedEnvExpansions.map(
                        (expansion, index) => ['rejected' + index, expansion])),
                }).map(([name, result]) => [name, {
                    error: result.callbackError && result.callbackError.code,
                    stdout: result.stdout,
                    stderr: result.stderr,
                    events: result.events,
                }])),
                execPreservesQuotedPipelineSyntax: !quotedPipePipeline.callbackError &&
                    quotedPipePipeline.stdout === '3' &&
                    quotedPipePipeline.stderr === '' &&
                    quotedPipePipeline.events.join(',') === 'callback,exit,close',
                execRejectsShellSyntax: rejectedShellCommands.every(failure =>
                    failure.callbackError && failure.callbackError.code === 'ENOSYS' &&
                    failure.emittedError && failure.emittedError.code === 'ENOSYS' &&
                    failure.code === -38 && failure.exitCode === -38 &&
                    failure.stdout === '' && failure.stderr === '' &&
                    failure.events.join(',') === 'callback,error,close') &&
                    !fs.existsSync(redirectionSideEffect),
                shellProbe: Object.fromEntries(Object.entries({ envNode, notNode }).map(
                    ([name, result]) => [name, {
                        status: result.status,
                        error: result.error && result.error.code,
                        stdout: result.stdout.toString(),
                        stderr: result.stderr.toString(),
                    }],
                )),
                zlibRoundTrip: zlib.gunzipSync(compressed).toString() === 'npm',
            };
        `,
    });
    const runDirectShebang = async (command, expectedOutput, executable) => runJavaScript({
        cwd: '/workspace',
        source: `
            const { createRequire } = await import('node:module');
            const require = createRequire('/workspace/direct-shebang-probe.cjs');
            const { spawnSync } = require('node:child_process');
            if (${JSON.stringify(executable)}) {
                require('node:fs').chmodSync(${JSON.stringify(command)}, 0o755);
            }
            const child = spawnSync('sh', ['-c', ${JSON.stringify(command)}], {
                cwd: '/workspace',
                env: { PATH: '/workspace/shebang-bin' },
            });
            return {
                ok: child.status === 0 && child.stdout.toString().trim() === ${JSON.stringify(expectedOutput)},
                status: child.status,
                error: child.error && child.error.code,
                stdout: child.stdout.toString(),
                stderr: child.stderr.toString(),
            };
        `,
    });
    const relativeEnvShebang = await runDirectShebang(
        './shebang-bin/env-node.cjs',
        'env-node:ok',
        true,
    );
    const absoluteNodeShebang = await runDirectShebang(
        '/workspace/shebang-bin/direct-node.cjs',
        'direct-node:ok',
        true,
    );
    const directMisleadingShebang = await runDirectShebang(
        './shebang-bin/not-node.cjs',
        'not-node:bad',
        true,
    );
    const nonExecutableShebang = await runDirectShebang(
        './shebang-bin/not-executable.cjs',
        'not-executable:bad',
        false,
    );
    const nonRegularCandidate = await runDirectShebang(
        './shebang-bin',
        'directory:bad',
        false,
    );
    result.value.shellDirectNodeShebang = relativeEnvShebang.value.ok &&
        absoluteNodeShebang.value.ok;
    result.value.shellRejectsDirectMisleadingShebang =
        directMisleadingShebang.value.status === null &&
        directMisleadingShebang.value.error === 'ENOSYS';
    result.value.shellRejectsNonExecutableShebang =
        nonExecutableShebang.value.status === null &&
        nonExecutableShebang.value.error === 'ENOSYS';
    result.value.shellRejectsNonRegularCandidate =
        nonRegularCandidate.value.status === null &&
        nonRegularCandidate.value.error === 'ENOSYS';
    result.value.directShellProbe = {
        relativeEnvShebang: relativeEnvShebang.value,
        absoluteNodeShebang: absoluteNodeShebang.value,
        directMisleadingShebang: directMisleadingShebang.value,
        nonExecutableShebang: nonExecutableShebang.value,
        nonRegularCandidate: nonRegularCandidate.value,
    };
    return JSON.stringify(result);
}

export async function probeInlineChildModuleIsolation() {
    try {
        const result = await runJavaScript({
            cwd: '/workspace',
            source: `
            const { createRequire } = await import('node:module');
            const require = createRequire('/workspace/inline-module-parent.cjs');
            const { spawnSync } = require('node:child_process');
            const Module = require('node:module');
            const protectedModuleKey = Symbol.for(
                'wasm-rquickjs:inline-parent-protected',
            );
            Object.defineProperty(Module, protectedModuleKey, {
                value: 'parent',
            });
            Object.defineProperty(
                Module.prototype,
                '__wasmRquickjsInlineParentProtected',
                { value: 'parent' },
            );
            const parent = spawnSync(
                process.execPath,
                ['/workspace/inline-module-parent.cjs'],
                { encoding: 'utf8' },
            );
            Object.freeze(Module.globalPaths);
            const frozenPathsChild = spawnSync(
                process.execPath,
                ['/workspace/inline-module-observer.cjs'],
                { encoding: 'utf8' },
            );
            const irreversibleChild = spawnSync(
                process.execPath,
                ['/workspace/inline-module-child.cjs', 'nonconfig'],
                { encoding: 'utf8' },
            );
            const afterIrreversibleChild = spawnSync(
                process.execPath,
                ['/workspace/inline-module-observer.cjs'],
                { encoding: 'utf8' },
            );
            return {
                parentStatus: parent.status,
                parent: parent.status === 0 ? JSON.parse(parent.stdout) : null,
                parentStderr: parent.stderr,
                parentProtectedStatePreserved:
                    Module[protectedModuleKey] === 'parent' &&
                    Module.prototype.__wasmRquickjsInlineParentProtected === 'parent',
                frozenPathsChildStatus: frozenPathsChild.status,
                frozenPathsChild: frozenPathsChild.status === 0
                    ? JSON.parse(frozenPathsChild.stdout)
                    : null,
                frozenPathsChildStderr: frozenPathsChild.stderr,
                irreversibleChildStatus: irreversibleChild.status,
                irreversibleChildStderr: irreversibleChild.stderr,
                afterIrreversibleChildStatus: afterIrreversibleChild.status,
                afterIrreversibleChild: afterIrreversibleChild.status === 0
                    ? JSON.parse(afterIrreversibleChild.stdout)
                    : null,
                afterIrreversibleChildStderr: afterIrreversibleChild.stderr,
            };
            `,
        });
        return JSON.stringify(result);
    } catch (error) {
        return JSON.stringify({
            runnerError: {
                name: error && error.name,
                message: error && error.message,
                stack: error && error.stack,
            },
        });
    }
}