protobuf.js/cli/targets/json-module.js
Taylor McIntyre da34f43ccd
feat!: move command line tool to a new package named protobufjs-cli (#1234)
* Get protobufjs-cli to a publishable state

* Fix eslint issues

* Fix pbts path

* Install cli package deps on CI 'build' job

* fix: get rid of require-protobufjs.js

* fix: lint

* fix: versions

* chore(deps): update package-lock.json

Co-authored-by: Stacey Sern <stacey@dropbox.com>
Co-authored-by: Gabriel Cangussu <gabrielcangussu@gmail.com>
Co-authored-by: Alexander Fenster <fenster@google.com>
2021-01-15 16:02:00 -08:00

39 lines
1.3 KiB
JavaScript

"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;
}