leannode-core
Version:
Simple Node.js wrapper for Lean 4 theorem prover
60 lines (51 loc) • 1.74 kB
JavaScript
// ./lib/index.js
const { spawn } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const os = require('os');
class LeanRunner {
/**
* Run Lean code and return result
* @param {string} leanCode - The Lean code to execute
* @param {Object} options - Optional configuration
* @returns {Promise<Object>} Result with stdout, stderr, exitCode
*/
static async run(leanCode, options = {}) {
const runner = new LeanRunner();
return await runner.execute(leanCode, options);
}
async execute(leanCode, options) {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'leannode-core-'));
const leanFile = path.join(tempDir, 'temp.lean');
try {
await fs.writeFile(leanFile, leanCode);
return await this.runLeanProcess(leanFile, options);
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
}
runLeanProcess(filePath, options) {
return new Promise((resolve, reject) => {
const args = options.args || [];
const lean = spawn('lean', [filePath, ...args], {
cwd: options.cwd || process.cwd(),
env: { ...process.env, ...options.env }
});
let stdout = '';
let stderr = '';
lean.stdout.on('data', (data) => stdout += data.toString());
lean.stderr.on('data', (data) => stderr += data.toString());
lean.on('close', (code) => {
resolve({
stdout: stdout.trim(),
stderr: stderr.trim(),
exitCode: code
});
});
lean.on('error', (error) => {
reject(new Error(`Failed to start Lean process: ${error.message}`));
});
});
}
}
module.exports = LeanRunner;