utils.js (2614B)
1 import path from "path"; 2 import { promises as fs } from "fs"; 3 import isFinite from "lodash/isFinite.js"; 4 import { SqProject } from "../public/SqProject/index.js"; 5 import { bold, red } from "./colors.js"; 6 export async function measure(callback) { 7 const t1 = new Date(); 8 await callback(); 9 const t2 = new Date(); 10 return (t2.getTime() - t1.getTime()) / 1000; 11 } 12 const linker = { 13 resolve: (name, fromId) => { 14 if (!name.startsWith("./") && !name.startsWith("../")) { 15 throw new Error("Only relative paths in imports are allowed"); 16 } 17 return path.resolve(path.dirname(fromId), name); 18 }, 19 loadSource: async (importId) => { 20 return await fs.readFile(importId, "utf-8"); 21 }, 22 }; 23 async function _run(args) { 24 const project = SqProject.create({ linker }); 25 if (args.environment) { 26 project.setEnvironment(args.environment); 27 } 28 const filename = path.resolve(args.filename || "./__anonymous__"); 29 project.setSource(filename, args.src); 30 const time = await measure(async () => await project.run(filename)); 31 const output = project.getOutput(filename); 32 return { output, time }; 33 } 34 export async function run(args) { 35 let environment; 36 if (args.sampleCount && isFinite(Number(args.sampleCount))) { 37 environment = { 38 sampleCount: Number(args.sampleCount), 39 xyPointLength: Number(args.sampleCount), 40 }; 41 } 42 const { output, time } = await _run({ 43 src: args.src, 44 filename: args.filename, 45 environment, 46 }); 47 let isFirstSection = true; 48 const printLines = (...lines) => { 49 if (!isFirstSection) { 50 console.log(); 51 } 52 isFirstSection = false; 53 lines.forEach((line) => console.log(line)); 54 }; 55 if (!output.ok) { 56 printLines(red("Error:"), output.value.toStringWithDetails()); 57 } 58 else { 59 switch (args.output) { 60 case "RESULT_OR_BINDINGS": 61 if (output.value.result.tag === "Void") { 62 printLines(output.value.bindings.toString()); 63 } 64 else { 65 printLines(output.value.result.toString()); 66 } 67 break; 68 case "RESULT_AND_BINDINGS": 69 printLines(bold("Result:"), output.value.result.toString()); 70 printLines(bold("Bindings:"), output.value.bindings.toString()); 71 break; 72 case "NONE": 73 } 74 } 75 if (args.measure) { 76 printLines(`${bold("Time:")} ${time}s`); 77 } 78 } 79 //# sourceMappingURL=utils.js.map