Skip to content

Commit 090d8ea

Browse files
committed
Refactored cli targets; added 'defaults' option to Prototype#asJSON, see #521
1 parent 046fc9f commit 090d8ea

File tree

7 files changed

+367
-339
lines changed

7 files changed

+367
-339
lines changed

cli/targets/json-module.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ function json_modulee(root, options, callback) {
1414
else
1515
options.wrap = path.join(__dirname, "json-module.tpl");
1616
var wrap = fs.readFileSync(options.wrap).toString("utf8");
17-
callback(null, wrap.replace(/%OUTPUT%/, JSON.stringify(root, null, 2)));
17+
callback(null, wrap.replace(/%OUTPUT%/, JSON.stringify(root, null, 2).replace(/^(?!$)/mg, " ").trim()));
1818
}

cli/targets/json-module.tpl

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@
99
/* Global */ else
1010
global.root = factory(global.protobuf);
1111

12-
})(this, function(protobuf) { return protobuf.Root.fromJSON(
13-
14-
%OUTPUT%
15-
16-
);});
12+
})(this, function(protobuf) {
13+
return protobuf.Root.fromJSON(%OUTPUT%);
14+
});

cli/targets/proto.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ var first = false;
2121
var syntax = 3;
2222

2323
function proto_target(root, options, callback) {
24-
2524
if (options) {
2625
switch (options.syntax) {
2726
case undefined:
@@ -46,8 +45,8 @@ function proto_target(root, options, callback) {
4645
callback(err);
4746
} finally {
4847
out = [];
48+
syntax = 3;
4949
}
50-
5150
}
5251

5352
function push(line) {

cli/targets/static-module.js

Lines changed: 8 additions & 311 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"use strict";
2-
module.exports = static_target;
2+
module.exports = static_module_target;
33

4-
// - Static code does not have any reflection or JSON features.
54
// - The default wrapper supports AMD, CommonJS and the global scope (as window.root), in this order.
65
// - You can specify a custom wrapper with the --wrap argument.
76
// - CommonJS modules depend on the minimal static runtime for reduced package size with browserify.
@@ -12,323 +11,21 @@ var path = require("path"),
1211

1312
var protobuf = require("../..");
1413

15-
var Type = protobuf.Type,
16-
Service = protobuf.Service,
17-
Enum = protobuf.Enum,
18-
Namespace = protobuf.Namespace,
19-
encoder = protobuf.encoder,
20-
decoder = protobuf.decoder,
21-
verifier = protobuf.verifier,
22-
util = protobuf.util;
14+
static_module_target.description = "Static code without reflection as a module (AMD, CommonJS, global)";
2315

24-
var out = [];
25-
var indent = 0;
26-
27-
static_target.description = "Static code without reflection as a module (AMD, CommonJS, global)";
28-
29-
function static_target(root, options, callback) {
16+
function static_module_target(root, options, callback) {
3017
if (options.wrap)
3118
options.wrap = path.resolve(process.cwd(), options.wrap);
3219
else
3320
options.wrap = path.join(__dirname, "static-module.tpl");
3421
try {
3522
var wrap = fs.readFileSync(options.wrap).toString("utf8");
36-
++indent;
37-
buildNamespace(null, root);
38-
--indent;
39-
callback(null, wrap.replace(/\r?\n%OUTPUT%/, out.join('\n')));
23+
require("./static")(root, options, function(err, output) {
24+
if (err)
25+
return callback(err);
26+
callback(null, wrap.replace(/%OUTPUT%/, output.replace(/^(?!$)/mg, " ")));
27+
});
4028
} catch (err) {
4129
callback(err);
42-
} finally {
43-
out = [];
44-
indent = 0;
45-
}
46-
}
47-
48-
function push(line) {
49-
if (line === "")
50-
return out.push("");
51-
var ind = "";
52-
for (var i = 0; i < indent; ++i)
53-
ind += " ";
54-
out.push(ind + line);
55-
}
56-
57-
function pushComment(lines) {
58-
push("/**");
59-
lines.forEach(function(line, i) {
60-
push(" * " + line);
61-
});
62-
push(" */");
63-
}
64-
65-
function name(name) {
66-
if (!name)
67-
return "$root";
68-
return name;
69-
}
70-
71-
function buildNamespace(ref, ns) {
72-
if (!ns)
73-
return;
74-
if (ns.name !== "") {
75-
push("");
76-
push("/** @alias " + ns.fullName.substring(1) + " */");
77-
push(name(ref) + "." + name(ns.name) + " = (function() {");
78-
++indent;
79-
}
80-
81-
if (ns instanceof Type) {
82-
buildType(undefined, ns);
83-
} else if (ns instanceof Service)
84-
buildService(undefined, ns);
85-
else if (ns.name !== "") {
86-
push("");
87-
push("/** @alias " + (ns.name && ns.fullName.substring(1) || "exports") + " */");
88-
push("var " + name(ns.name) + " = {};");
89-
}
90-
91-
ns.nestedArray.forEach(function(nested) {
92-
if (nested instanceof Enum)
93-
buildEnum(ns.name, nested);
94-
else if (nested instanceof Namespace)
95-
buildNamespace(ns.name, nested);
96-
});
97-
if (ns.name !== "") {
98-
push("");
99-
push("return " + name(ns.name) + ";");
100-
--indent;
101-
push("})();");
102-
}
103-
}
104-
105-
function buildFunction(type, functionName, gen, scope) {
106-
var lines = gen.str(functionName)
107-
.replace("(this.getCtor())", " $root" + type.fullName)
108-
.split(/\n/g);
109-
push(name(type.name) + "." + functionName + " = (function() {");
110-
++indent;
111-
push("/* eslint-disable */");
112-
Object.keys(scope).forEach(function(key) {
113-
push("var " + key + " = " + scope[key] + ";");
114-
});
115-
push("var types; $lazyTypes.push(types = [" + type.fieldsArray.map(function(field) {
116-
return field.resolve().resolvedType
117-
? JSON.stringify(field.resolvedType.fullName.substring(1))
118-
: "null";
119-
}).join(',') + "]);");
120-
push("return " + lines[0]);
121-
lines.slice(1).forEach(function(line) {
122-
if (line === '\t"use strict"')
123-
return;
124-
var prev = indent;
125-
var i = 0;
126-
while (line.charAt(i++) === "\t")
127-
++indent;
128-
push(line.trim());
129-
indent = prev;
130-
});
131-
push("/* eslint-enable */");
132-
--indent;
133-
push("})();");
134-
}
135-
136-
function buildType(ref, type) {
137-
var fullName = type.fullName.substring(1);
138-
139-
push("");
140-
pushComment([
141-
"Constructs a new " + type.name + ".",
142-
"@exports " + fullName,
143-
"@constructor",
144-
"@param {Object} [properties] Properties to set"
145-
]);
146-
push("function " + name(type.name) + "(properties) {");
147-
++indent;
148-
push("if (properties) {");
149-
++indent;
150-
push("var keys = Object.keys(properties);");
151-
push("for (var i = 0; i < keys.length; ++i)");
152-
++indent;
153-
push("this[keys[i]] = properties[keys[i]];");
154-
--indent;
155-
--indent;
156-
push("}");
157-
--indent;
158-
push("}");
159-
push("");
160-
type.fieldsArray.forEach(function(field) {
161-
field.resolve();
162-
if (typeof field.defaultValue === 'object' && field.defaultValue)
163-
return;
164-
push(name(type.name) + ".prototype." + name(field.name) + " = " +JSON.stringify(field.defaultValue) + ";");
165-
});
166-
167-
// #encode
168-
push("");
169-
pushComment([
170-
"Encodes the specified " + type.name + ".",
171-
"@function",
172-
"@param {" + fullName + "|Object} message " + type.name + " or plain object to encode",
173-
"@param {Writer} [writer] Writer to encode to",
174-
"@returns {Writer} Writer"
175-
]);
176-
buildFunction(type, "encode", encoder.generate(type), {
177-
Writer : "$runtime.Writer",
178-
util : "$runtime.util"
179-
});
180-
181-
// #encodeDelimited
182-
push("");
183-
pushComment([
184-
"Encodes the specified " + type.name + ", length delimited.",
185-
"@param {" + fullName + "|Object} message " + type.name + " or plain object to encode",
186-
"@param {Writer} [writer] Writer to encode to",
187-
"@returns {Writer} Writer"
188-
]);
189-
push(name(type.name) + ".encodeDelimited = function encodeDelimited(message, writer) {");
190-
++indent;
191-
push("return this.encode(message, writer).ldelim();");
192-
--indent;
193-
push("};");
194-
195-
// #decode
196-
push("");
197-
pushComment([
198-
"Decodes a " + type.name + " from the specified reader or buffer.",
199-
"@function",
200-
"@param {Reader|Uint8Array} readerOrBuffer Reader or buffer to decode from",
201-
"@param {number} [length] Message length if known beforehand",
202-
"@returns {" + fullName + "} " + type.name
203-
]);
204-
buildFunction(type, "decode", decoder.generate(type), {
205-
Reader : "$runtime.Reader",
206-
util : "$runtime.util"
207-
});
208-
209-
// #decodeDelimited
210-
push("");
211-
pushComment([
212-
"Decodes a " + type.name + " from the specified reader or buffer, length delimited.",
213-
"@param {Reader|Uint8Array} readerOrBuffer Reader or buffer to decode from",
214-
"@returns {" + fullName + "} " + type.name
215-
]);
216-
push(name(type.name) + ".decodeDelimited = function decodeDelimited(readerOrBuffer) {");
217-
++indent;
218-
push("readerOrBuffer = readerOrBuffer instanceof Reader ? readerOrBuffer : Reader(readerOrBuffer);");
219-
push("return this.decode(readerOrBuffer, readerOrBuffer.uint32());");
220-
--indent;
221-
push("};");
222-
223-
// #verify
224-
push("");
225-
pushComment([
226-
"Verifies a " + type.name + ".",
227-
"@param {" + fullName + "|Object} message " + type.name + " or plain object to verify",
228-
"@returns {?string} `null` if valid, otherwise the reason why it is not"
229-
]);
230-
buildFunction(type, "verify", verifier.generate(type), {});
231-
}
232-
233-
function buildService(ref, service) {
234-
var fullName = service.fullName.substring(1);
235-
236-
push("");
237-
pushComment([
238-
"Constructs a new " + service.name + ".",
239-
"@exports " + fullName,
240-
"@constructor",
241-
"@param {function(function, Uint8Array, function)} rpc RPC implementation",
242-
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
243-
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited"
244-
]);
245-
push("function " + name(service.name) + "(rpc, requestDelimited, responseDelimited) {");
246-
++indent;
247-
push("");
248-
pushComment([
249-
"RPC implementation.",
250-
"@type {function(function, Uint8Array, function)}"
251-
]);
252-
push("this.rpc = rpc;");
253-
push("");
254-
pushComment([
255-
"Whether requests are length-delimited.",
256-
"@type {boolean}"
257-
]);
258-
push("this.requestDelimited = Boolean(requestDelimited);");
259-
push("");
260-
pushComment([
261-
"Whether responses are length-delimited.",
262-
"@type {boolean}"
263-
]);
264-
push("this.responseDelimited = Boolean(responseDelimited);");
265-
--indent;
266-
push("};");
267-
service.getMethodsArray().forEach(function(method) {
268-
method.resolve();
269-
var lcName = method.name.substring(0, 1).toLowerCase() + method.name.substring(1);
270-
push("");
271-
pushComment([
272-
"Calls " + method.name + ".",
273-
"@param {" + method.resolvedRequestType.fullName.substring(1) + "|Object} request " + method.resolvedRequestType.name + " or plain object",
274-
"@param {function(?Error, " + method.resolvedResponseType.fullName.substring(1) + "=)} callback Node-style callback called with the error, if any, and " + method.resolvedResponseType.name,
275-
"@returns {undefined}"
276-
]);
277-
push(name(service.name) + ".prototype." + name(lcName) + " = function " + name(lcName) + "(request, callback) {");
278-
++indent;
279-
push("var requestData;");
280-
push("try {");
281-
++indent;
282-
push("requestData = (this.requestDelimited && $root" + name(method.resolvedRequestType.fullName) + ".encodeDelimited(request) || $root" + name(method.resolvedRequestType.fullName) + ".encode(request)).finish();");
283-
--indent;
284-
push("} catch (err) {");
285-
++indent;
286-
push("(typeof setImmediate === 'function' && setImmediate || setTimeout)(function() { callback(err); });");
287-
push("return;");
288-
--indent;
289-
push("}");
290-
push("var self = this;");
291-
push("this.rpc(" + name(lcName) + ", requestData, function(err, responseData) {");
292-
++indent;
293-
push("if (err) {");
294-
++indent;
295-
push("callback(err);");
296-
push("return;");
297-
--indent;
298-
push("}");
299-
push("var response;");
300-
push("try {");
301-
++indent;
302-
push("response = self.responseDelimited && $root" + name(method.resolvedResponseType.fullName) + ".decodeDelimited(responseData) || $root" + name(method.resolvedResponseType.fullName) + ".decode(responseData);");
303-
--indent;
304-
push("} catch (err2) {");
305-
++indent;
306-
push("callback(err2);");
307-
push("return;");
308-
--indent;
309-
push("}");
310-
push("callback(null, response);");
311-
--indent;
312-
push("});");
313-
--indent;
314-
push("};");
315-
});
316-
}
317-
318-
function buildEnum(ref, enm) {
319-
push("");
320-
pushComment([
321-
enm.name + " values.",
322-
"@exports " + enm.fullName.substring(1),
323-
"@type {Object.<string,number>}"
324-
]);
325-
push(name(ref) + "." + name(enm.name) + " = {");
326-
++indent;
327-
push("");
328-
var keys = Object.keys(enm.values);
329-
for (var i = 0; i < keys.length; ++i) {
330-
push(name(keys[i]) + ": " + enm.values[keys[i]].toString(10) + (i < keys.length - 1 ? "," : ""));
33130
}
332-
--indent;
333-
push("};");
33431
}

0 commit comments

Comments
 (0)