pbts.js
6.69 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
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
"use strict";
var child_process = require("child_process"),
path = require("path"),
fs = require("fs"),
pkg = require("./package.json"),
util = require("./util");
util.setup();
var minimist = require("minimist"),
chalk = require("chalk"),
glob = require("glob"),
tmp = require("tmp");
/**
* Runs pbts programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
exports.main = function(args, callback) {
var argv = minimist(args, {
alias: {
name: "n",
out : "o",
main: "m",
global: "g",
import: "i"
},
string: [ "name", "out", "global", "import" ],
boolean: [ "comments", "main" ],
default: {
comments: true,
main: false
}
});
var files = argv._;
if (!files.length) {
if (callback)
callback(Error("usage")); // eslint-disable-line callback-return
else
process.stderr.write([
"protobuf.js v" + pkg.version + " CLI for TypeScript",
"",
chalk.bold.white("Generates TypeScript definitions from annotated JavaScript files."),
"",
" -o, --out Saves to a file instead of writing to stdout.",
"",
" -g, --global Name of the global object in browser environments, if any.",
"",
" -i, --import Comma delimited list of imports. Local names will equal camelCase of the basename.",
"",
" --no-comments Does not output any JSDoc comments.",
"",
chalk.bold.gray(" Internal flags:"),
"",
" -n, --name Wraps everything in a module of the specified name.",
"",
" -m, --main Whether building the main library without any imports.",
"",
"usage: " + chalk.bold.green("pbts") + " [options] file1.js file2.js ..." + chalk.bold.gray(" (or) ") + "other | " + chalk.bold.green("pbts") + " [options] -",
""
].join("\n"));
return 1;
}
// Resolve glob expressions
for (var i = 0; i < files.length;) {
if (glob.hasMagic(files[i])) {
var matches = glob.sync(files[i]);
Array.prototype.splice.apply(files, [i, 1].concat(matches));
i += matches.length;
} else
++i;
}
var cleanup = [];
// Read from stdin (to a temporary file)
if (files.length === 1 && files[0] === "-") {
var data = [];
process.stdin.on("data", function(chunk) {
data.push(chunk);
});
process.stdin.on("end", function() {
files[0] = tmp.tmpNameSync() + ".js";
fs.writeFileSync(files[0], Buffer.concat(data));
cleanup.push(files[0]);
callJsdoc();
});
// Load from disk
} else {
callJsdoc();
}
function callJsdoc() {
// There is no proper API for jsdoc, so this executes the CLI and pipes the output
var basedir = path.join(__dirname, ".");
var moduleName = argv.name || "null";
var nodePath = process.execPath;
var cmd = "\"" + nodePath + "\" \"" + require.resolve("jsdoc/jsdoc.js") + "\" -c \"" + path.join(basedir, "lib", "tsd-jsdoc.json") + "\" -q \"module=" + encodeURIComponent(moduleName) + "&comments=" + Boolean(argv.comments) + "\" " + files.map(function(file) { return "\"" + file + "\""; }).join(" ");
var child = child_process.exec(cmd, {
cwd: process.cwd(),
argv0: "node",
stdio: "pipe",
maxBuffer: 1 << 24 // 16mb
});
var out = [];
var ended = false;
var closed = false;
child.stdout.on("data", function(data) {
out.push(data);
});
child.stdout.on("end", function() {
if (closed) finish();
else ended = true;
});
child.stderr.pipe(process.stderr);
child.on("close", function(code) {
// clean up temporary files, no matter what
try { cleanup.forEach(fs.unlinkSync); } catch(e) {/**/} cleanup = [];
if (code) {
out = out.join("").replace(/\s*JSDoc \d+\.\d+\.\d+ [^$]+/, "");
process.stderr.write(out);
var err = Error("code " + code);
if (callback)
return callback(err);
throw err;
}
if (ended) return finish();
closed = true;
return undefined;
});
function getImportName(importItem) {
return path.basename(importItem, ".js").replace(/([-_~.+]\w)/g, function(match) {
return match[1].toUpperCase();
});
}
function finish() {
var output = [];
if (argv.main)
output.push(
"// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run types'.",
""
);
if (argv.global)
output.push(
"export as namespace " + argv.global + ";",
""
);
if (!argv.main) {
// Ensure we have a usable array of imports
var importArray = typeof argv.import === "string" ? argv.import.split(",") : argv.import || [];
// Build an object of imports and paths
var imports = {
$protobuf: "protobufjs"
};
importArray.forEach(function(importItem) {
imports[getImportName(importItem)] = importItem;
});
// Write out the imports
Object.keys(imports).forEach(function(key) {
output.push("import * as " + key + " from \"" + imports[key] + "\";");
});
}
output = output.join("\n") + "\n" + out.join("");
try {
if (argv.out)
fs.writeFileSync(argv.out, output, { encoding: "utf8" });
else if (!callback)
process.stdout.write(output, "utf8");
return callback
? callback(null, output)
: undefined;
} catch (err) {
if (callback)
return callback(err);
throw err;
}
}
}
return undefined;
};