UNPKG

3.07 kBJavaScriptView Raw
1#!/usr/bin/env node
2"use strict";
3Object.defineProperty(exports, "__esModule", { value: true });
4const child_process_1 = require("child_process");
5const path = require("path");
6const readline = require("readline");
7const BIN_PATH = path.join(__dirname, "../bin/fable-cli/Fable.Cli.dll");
8function log(args, msg) {
9 if (!(args && args.silent)) {
10 console.log(msg);
11 }
12}
13// From https://gist.github.com/LeverOne/1308368
14/* tslint:disable:no-bitwise */
15function uuid() {
16 let b = "";
17 for (let a = 0; a++ < 36;) {
18 b += a * 51 & 52
19 ? (a ^ 15 ? 8 ^ Math.random() * (a ^ 20 ? 16 : 4) : 4).toString(16)
20 : "-";
21 }
22 return b;
23}
24/* tslint:enable:no-bitwise */
25function getVersion() {
26 try {
27 return require("../package.json").version;
28 }
29 catch (_a) {
30 return "";
31 }
32}
33function processArgs(args) {
34 let cliArgs = [BIN_PATH, "start-stdin"];
35 if (args != null) {
36 if (args.path) {
37 const filePath = path.resolve(args.path);
38 log(args, `dotnet binary: ${filePath}`);
39 cliArgs = filePath.endsWith(".dll")
40 ? [filePath, "start-stdin", "--force-pkgs"]
41 : ["run", "-c", "Release", "-p", filePath, "start-stdin", "--force-pkgs"];
42 delete args.path;
43 }
44 for (const k of Object.keys(args)) {
45 if (args[k] !== false) {
46 cliArgs.push("--" + k.replace(/[A-Z]/g, (x) => "-" + x.toLowerCase()));
47 if (args[k] !== true) {
48 cliArgs.push(args[k]);
49 }
50 }
51 }
52 }
53 return cliArgs;
54}
55function start(cliArgs) {
56 log(cliArgs, `fable-compiler ${getVersion()}`);
57 const child = child_process_1.spawn("dotnet", processArgs(cliArgs));
58 // Error handling
59 child.on("error", (err) => {
60 console.error("Cannot spawn dotnet", err.message);
61 });
62 child.stderr.on("data", (data) => {
63 console.error(`child proccess errored: ${data}`);
64 });
65 // child.on("close", (code) => {
66 // log(cliArgs, `child process exited with code ${code}`);
67 // });
68 // Pending promises
69 const pending = new Map();
70 const linereader = readline.createInterface({
71 input: child.stdout,
72 });
73 linereader.on("line", (data) => {
74 const pattern = /^JSON:([\w-]+):/.exec(data);
75 if (pattern != null) {
76 const id = pattern[1];
77 const resolve = pending.get(id);
78 if (resolve != null) {
79 pending.delete(id);
80 resolve(JSON.parse(data.substr(pattern[0].length)));
81 }
82 }
83 else { // LOG
84 log(cliArgs, data);
85 }
86 });
87 return {
88 send(data) {
89 return new Promise((resolve) => {
90 const id = uuid();
91 pending.set(id, resolve);
92 child.stdin.write(`${id}:${JSON.stringify(data)}\n`);
93 });
94 },
95 close() {
96 child.stdin.write("exit\n");
97 },
98 };
99}
100exports.default = start;
101
\No newline at end of file