forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute.mjs
More file actions
99 lines (86 loc) · 2.22 KB
/
execute.mjs
File metadata and controls
99 lines (86 loc) · 2.22 KB
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
// @ts-check
import { spawn } from 'node:child_process';
/**
* @typedef {import('../types.mjs').FailurePhase} FailurePhase
*/
/**
* @typedef {{
* timeout?: number,
* verbose?: boolean
* }} ExecuteOptions
*/
/**
* @typedef {{
* success: boolean,
* phase?: FailurePhase,
* error?: string
* }} ExecuteResult
*/
/**
* Classify stderr output into a FailurePhase.
* @param {string} stderr
* @returns {FailurePhase}
*/
function classifyError(stderr) {
if (/RuntimeError|unreachable/i.test(stderr)) {
return 'runtime-trap';
}
if (/LinkError|import/i.test(stderr)) {
return 'link-error';
}
if (/AssertionError/i.test(stderr)) {
return 'wrong-result';
}
return 'runtime-error';
}
/**
* Execute a Node.js harness script and classify the result.
*
* @param {string} harnessPath — Absolute path to the harness .mjs file
* @param {ExecuteOptions} [options]
* @returns {Promise<ExecuteResult>}
*/
export async function executeHarness(harnessPath, options = {}) {
const { timeout = 30_000, verbose = false } = options;
return new Promise((resolve, reject) => {
const child = spawn('node', [harnessPath], {
stdio: ['ignore', 'pipe', 'pipe'],
timeout,
});
/** @type {string[]} */
const stdoutChunks = [];
/** @type {string[]} */
const stderrChunks = [];
child.stdout.on('data', (/** @type {Buffer} */ chunk) => {
const text = chunk.toString();
stdoutChunks.push(text);
if (verbose) process.stdout.write(text);
});
child.stderr.on('data', (/** @type {Buffer} */ chunk) => {
const text = chunk.toString();
stderrChunks.push(text);
if (verbose) process.stderr.write(text);
});
child.on('error', (err) => {
resolve({
success: false,
phase: 'runtime-error',
error: err.message,
});
});
child.on('close', (code) => {
const stderr = stderrChunks.join('');
const stdout = stdoutChunks.join('');
if (code === 0) {
resolve({ success: true });
} else {
const combined = (stderr + '\n' + stdout).trim();
resolve({
success: false,
phase: classifyError(combined),
error: combined,
});
}
});
});
}