-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
json-module.js
38 lines (33 loc) · 1.26 KB
/
json-module.js
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
"use strict";
module.exports = json_module;
var util = require("../util");
var protobuf = require("protobufjs");
json_module.description = "JSON representation as a module";
function jsonSafeProp(json) {
return json.replace(/^( +)"(\w+)":/mg, function($0, $1, $2) {
return protobuf.util.safeProp($2).charAt(0) === "."
? $1 + $2 + ":"
: $0;
});
}
function json_module(root, options, callback) {
try {
var rootProp = protobuf.util.safeProp(options.root || "default");
var output = [
(options.es6 ? "const" : "var") + " $root = ($protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = new $protobuf.Root()))\n"
];
if (root.options) {
var optionsJson = jsonSafeProp(JSON.stringify(root.options, null, 2));
output.push(".setOptions(" + optionsJson + ")\n");
}
var json = jsonSafeProp(JSON.stringify(root.nested, null, 2).trim());
output.push(".addJSON(" + json + ");");
output = util.wrap(output.join(""), protobuf.util.merge({ dependency: "protobufjs/light" }, options));
process.nextTick(function() {
callback(null, output);
});
} catch (e) {
return callback(e);
}
return undefined;
}