1
0
mirror of https://github.com/musix-org/musix-oss synced 2025-06-17 04:26:00 +00:00
This commit is contained in:
MatteZ02
2020-03-03 22:30:50 +02:00
parent edfcc6f474
commit 30022c7634
11800 changed files with 1984416 additions and 1 deletions

33
node_modules/protobufjs/cli/LICENSE generated vendored Normal file
View File

@ -0,0 +1,33 @@
Copyright (c) 2016, Daniel Wirtz All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of its author, nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---
Code generated by the command line utilities is owned by the owner
of the input file used when generating it. This code is not
standalone and requires a support library to be linked with it. This
support library is itself covered by the above license.

11
node_modules/protobufjs/cli/README.md generated vendored Normal file
View File

@ -0,0 +1,11 @@
protobufjs-cli
==============
[![npm](https://img.shields.io/npm/v/protobufjscli.svg)](https://www.npmjs.com/package/protobufjs-cli)
Command line interface (CLI) for [protobuf.js](https://github.com/dcodeIO/protobuf.js). Translates between file formats and generates static code as well as TypeScript definitions.
* [CLI Documentation](https://github.com/dcodeIO/protobuf.js#command-line)
**Note** that moving the CLI to its own package is a work in progress. At the moment, it's still part of the main package.
**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause)

6
node_modules/protobufjs/cli/bin/pbjs generated vendored Normal file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "pbjs.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

6
node_modules/protobufjs/cli/bin/pbts generated vendored Normal file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "pbts.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

3
node_modules/protobufjs/cli/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,3 @@
import * as pbjs from "./pbjs.js";
import * as pbts from "./pbts.js";
export { pbjs, pbts };

3
node_modules/protobufjs/cli/index.js generated vendored Normal file
View File

@ -0,0 +1,3 @@
"use strict";
exports.pbjs = require("./pbjs");
exports.pbts = require("./pbts");

18
node_modules/protobufjs/cli/lib/tsd-jsdoc.json generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"tags": {
"allowUnknownTags": false
},
"plugins": [
"./tsd-jsdoc/plugin"
],
"opts": {
"encoding" : "utf8",
"recurse" : true,
"lenient" : true,
"template" : "./tsd-jsdoc",
"private" : false,
"comments" : true,
"destination" : false
}
}

21
node_modules/protobufjs/cli/lib/tsd-jsdoc/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2016 Chad Engler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

23
node_modules/protobufjs/cli/lib/tsd-jsdoc/README.md generated vendored Normal file
View File

@ -0,0 +1,23 @@
protobuf.js fork of tsd-jsdoc
=============================
This is a modified version of [tsd-jsdoc](https://github.com/englercj/tsd-jsdoc) v1.0.1 for use with protobuf.js, parked here so we can process issues and pull requests. The ultimate goal is to switch back to the a recent version of tsd-jsdoc once it meets our needs.
Options
-------
* **module: `string`**<br />
Wraps everything in a module of the specified name.
* **private: `boolean`**<br />
Includes private members when set to `true`.
* **comments: `boolean`**<br />
Skips comments when explicitly set to `false`.
* **destination: `string|boolean`**<br />
Saves to the specified destination file or to console when set to `false`.
Setting options on the command line
-----------------------------------
Providing `-q, --query <queryString>` on the command line will set respectively override existing options. Example: `-q module=protobufjs`

21
node_modules/protobufjs/cli/lib/tsd-jsdoc/plugin.js generated vendored Normal file
View File

@ -0,0 +1,21 @@
"use strict";
exports.defineTags = function(dictionary) {
dictionary.defineTag("template", {
mustHaveValue: true,
canHaveType: false,
canHaveName: false,
onTagged: function(doclet, tag) {
(doclet.templates || (doclet.templates = [])).push(tag.text);
}
});
dictionary.defineTag("tstype", {
mustHaveValue: true,
canHaveType: false,
canHaveName: false,
onTagged: function(doclet, tag) {
doclet.tsType = tag.text;
}
});
};

693
node_modules/protobufjs/cli/lib/tsd-jsdoc/publish.js generated vendored Normal file
View File

@ -0,0 +1,693 @@
"use strict";
var fs = require("fs");
// output stream
var out = null;
// documentation data
var data = null;
// already handled objects, by name
var seen = {};
// indentation level
var indent = 0;
// whether indent has been written for the current line yet
var indentWritten = false;
// provided options
var options = {};
// queued interfaces
var queuedInterfaces = [];
// whether writing the first line
var firstLine = true;
// JSDoc hook
exports.publish = function publish(taffy, opts) {
options = opts || {};
// query overrides options
if (options.query)
Object.keys(options.query).forEach(function(key) {
if (key !== "query")
switch (options[key] = options.query[key]) {
case "true":
options[key] = true;
break;
case "false":
options[key] = false;
break;
case "null":
options[key] = null;
break;
}
});
// remove undocumented
taffy({ undocumented: true }).remove();
taffy({ ignore: true }).remove();
taffy({ inherited: true }).remove();
// remove private
if (!options.private)
taffy({ access: "private" }).remove();
// setup output
out = options.destination
? fs.createWriteStream(options.destination)
: process.stdout;
try {
// setup environment
data = taffy().get();
indent = 0;
indentWritten = false;
firstLine = true;
// wrap everything in a module if configured
if (options.module) {
writeln("export = ", options.module, ";");
writeln();
writeln("declare namespace ", options.module, " {");
writeln();
++indent;
}
// handle all
getChildrenOf(undefined).forEach(function(child) {
handleElement(child, null);
});
// process queued
while (queuedInterfaces.length) {
var element = queuedInterfaces.shift();
begin(element);
writeInterface(element);
writeln(";");
}
// end wrap
if (options.module) {
--indent;
writeln("}");
}
// close file output
if (out !== process.stdout)
out.end();
} finally {
// gc environment objects
out = data = null;
seen = options = {};
queuedInterfaces = [];
}
};
//
// Utility
//
// writes one or multiple strings
function write() {
var s = Array.prototype.slice.call(arguments).join("");
if (!indentWritten) {
for (var i = 0; i < indent; ++i)
s = " " + s;
indentWritten = true;
}
out.write(s);
firstLine = false;
}
// writes zero or multiple strings, followed by a new line
function writeln() {
var s = Array.prototype.slice.call(arguments).join("");
if (s.length)
write(s, "\n");
else if (!firstLine)
out.write("\n");
indentWritten = false;
}
var keepTags = [
"param",
"returns",
"throws",
"see"
];
// parses a comment into text and tags
function parseComment(comment) {
var lines = comment.replace(/^ *\/\*\* *|^ *\*\/| *\*\/ *$|^ *\* */mg, "").trim().split(/\r?\n|\r/g); // property.description has just "\r" ?!
var desc;
var text = [];
var tags = null;
for (var i = 0; i < lines.length; ++i) {
var match = /^@(\w+)\b/.exec(lines[i]);
if (match) {
if (!tags) {
tags = [];
desc = text;
}
text = [];
tags.push({ name: match[1], text: text });
lines[i] = lines[i].substring(match[1].length + 1).trim();
}
if (lines[i].length || text.length)
text.push(lines[i]);
}
return {
text: desc || text,
tags: tags || []
};
}
// writes a comment
function writeComment(comment, otherwiseNewline) {
if (!comment || options.comments === false) {
if (otherwiseNewline)
writeln();
return;
}
if (typeof comment !== "object")
comment = parseComment(comment);
comment.tags = comment.tags.filter(function(tag) {
return keepTags.indexOf(tag.name) > -1 && (tag.name !== "returns" || tag.text[0] !== "{undefined}");
});
writeln();
if (!comment.tags.length && comment.text.length < 2) {
writeln("/** " + comment.text[0] + " */");
return;
}
writeln("/**");
comment.text.forEach(function(line) {
if (line.length)
writeln(" * ", line);
else
writeln(" *");
});
comment.tags.forEach(function(tag) {
var started = false;
if (tag.text.length) {
tag.text.forEach(function(line, i) {
if (i > 0)
write(" * ");
else if (tag.name !== "throws")
line = line.replace(/^\{[^\s]*} ?/, "");
if (!line.length)
return;
if (!started) {
write(" * @", tag.name, " ");
started = true;
}
writeln(line);
});
}
});
writeln(" */");
}
// recursively replaces all occurencies of re's match
function replaceRecursive(name, re, fn) {
var found;
function replacer() {
found = true;
return fn.apply(null, arguments);
}
do {
found = false;
name = name.replace(re, replacer);
} while (found);
return name;
}
// tests if an element is considered to be a class or class-like
function isClassLike(element) {
return isClass(element) || isInterface(element);
}
// tests if an element is considered to be a class
function isClass(element) {
return element && element.kind === "class";
}
// tests if an element is considered to be an interface
function isInterface(element) {
return element && (element.kind === "interface" || element.kind === "mixin");
}
// tests if an element is considered to be a namespace
function isNamespace(element) {
return element && (element.kind === "namespace" || element.kind === "module");
}
// gets all children of the specified parent
function getChildrenOf(parent) {
var memberof = parent ? parent.longname : undefined;
return data.filter(function(element) {
return element.memberof === memberof;
});
}
// gets the literal type of an element
function getTypeOf(element) {
if (element.tsType)
return element.tsType.replace(/\r?\n|\r/g, "\n");
var name = "any";
var type = element.type;
if (type && type.names && type.names.length) {
if (type.names.length === 1)
name = element.type.names[0].trim();
else
name = "(" + element.type.names.join("|") + ")";
} else
return name;
// Replace catchalls with any
name = name.replace(/\*|\bmixed\b/g, "any");
// Ensure upper case Object for map expressions below
name = name.replace(/\bobject\b/g, "Object");
// Correct Something.<Something> to Something<Something>
name = replaceRecursive(name, /\b(?!Object|Array)([\w$]+)\.<([^>]*)>/gi, function($0, $1, $2) {
return $1 + "<" + $2 + ">";
});
// Replace Array.<string> with string[]
name = replaceRecursive(name, /\bArray\.?<([^>]*)>/gi, function($0, $1) {
return $1 + "[]";
});
// Replace Object.<string,number> with { [k: string]: number }
name = replaceRecursive(name, /\bObject\.?<([^,]*), *([^>]*)>/gi, function($0, $1, $2) {
return "{ [k: " + $1 + "]: " + $2 + " }";
});
// Replace functions (there are no signatures) with Function
name = name.replace(/\bfunction(?:\(\))?\b/g, "Function");
// Convert plain Object back to just object
name = name.replace(/\b(Object\b(?!\.))/g, function($0, $1) {
return $1.toLowerCase();
});
return name;
}
// begins writing the definition of the specified element
function begin(element, is_interface) {
if (!seen[element.longname]) {
if (isClass(element)) {
var comment = parseComment(element.comment);
var classdesc = comment.tags.find(function(tag) { return tag.name === "classdesc"; });
if (classdesc) {
comment.text = classdesc.text;
comment.tags = [];
}
writeComment(comment, true);
} else
writeComment(element.comment, is_interface || isClassLike(element) || isNamespace(element) || element.isEnum || element.scope === "global");
seen[element.longname] = element;
} else
writeln();
if (element.scope !== "global" || options.module)
return;
write("export ");
}
// writes the function signature describing element
function writeFunctionSignature(element, isConstructor, isTypeDef) {
write("(");
var params = {};
// this type
if (element.this)
params["this"] = {
type: element.this.replace(/^{|}$/g, ""),
optional: false
};
// parameter types
if (element.params)
element.params.forEach(function(param) {
var path = param.name.split(/\./g);
if (path.length === 1)
params[param.name] = {
type: getTypeOf(param),
variable: param.variable === true,
optional: param.optional === true,
defaultValue: param.defaultvalue // Not used yet (TODO)
};
else // Property syntax (TODO)
params[path[0]].type = "{ [k: string]: any }";
});
var paramNames = Object.keys(params);
paramNames.forEach(function(name, i) {
var param = params[name];
var type = param.type;
if (param.variable) {
name = "..." + name;
type = param.type.charAt(0) === "(" ? "any[]" : param.type + "[]";
}
write(name, !param.variable && param.optional ? "?: " : ": ", type);
if (i < paramNames.length - 1)
write(", ");
});
write(")");
// return type
if (!isConstructor) {
write(isTypeDef ? " => " : ": ");
var typeName;
if (element.returns && element.returns.length && (typeName = getTypeOf(element.returns[0])) !== "undefined")
write(typeName);
else
write("void");
}
}
// writes (a typedef as) an interface
function writeInterface(element) {
write("interface ", element.name);
writeInterfaceBody(element);
writeln();
}
function writeInterfaceBody(element) {
writeln("{");
++indent;
if (element.tsType)
writeln(element.tsType.replace(/\r?\n|\r/g, "\n"));
else if (element.properties && element.properties.length)
element.properties.forEach(writeProperty);
--indent;
write("}");
}
function writeProperty(property, declare) {
writeComment(property.description);
if (declare)
write("let ");
write(property.name);
if (property.optional)
write("?");
writeln(": ", getTypeOf(property), ";");
}
//
// Handlers
//
// handles a single element of any understood type
function handleElement(element, parent) {
if (element.scope === "inner")
return false;
if (element.optional !== true && element.type && element.type.names && element.type.names.length) {
for (var i = 0; i < element.type.names.length; i++) {
if (element.type.names[i].toLowerCase() === "undefined") {
// This element is actually optional. Set optional to true and
// remove the 'undefined' type
element.optional = true;
element.type.names.splice(i, 1);
i--;
}
}
}
if (seen[element.longname])
return true;
if (isClassLike(element))
handleClass(element, parent);
else switch (element.kind) {
case "module":
case "namespace":
handleNamespace(element, parent);
break;
case "constant":
case "member":
handleMember(element, parent);
break;
case "function":
handleFunction(element, parent);
break;
case "typedef":
handleTypeDef(element, parent);
break;
case "package":
break;
}
seen[element.longname] = element;
return true;
}
// handles (just) a namespace
function handleNamespace(element/*, parent*/) {
var children = getChildrenOf(element);
if (!children.length)
return;
var first = true;
if (element.properties)
element.properties.forEach(function(property) {
if (!/^[$\w]+$/.test(property.name)) // incompatible in namespace
return;
if (first) {
begin(element);
writeln("namespace ", element.name, " {");
++indent;
first = false;
}
writeProperty(property, true);
});
children.forEach(function(child) {
if (child.scope === "inner" || seen[child.longname])
return;
if (first) {
begin(element);
writeln("namespace ", element.name, " {");
++indent;
first = false;
}
handleElement(child, element);
});
if (!first) {
--indent;
writeln("}");
}
}
// a filter function to remove any module references
function notAModuleReference(ref) {
return ref.indexOf("module:") === -1;
}
// handles a class or class-like
function handleClass(element, parent) {
var is_interface = isInterface(element);
begin(element, is_interface);
if (is_interface)
write("interface ");
else {
if (element.virtual)
write("abstract ");
write("class ");
}
write(element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
write(" ");
// extended classes
if (element.augments) {
var augments = element.augments.filter(notAModuleReference);
if (augments.length)
write("extends ", augments[0], " ");
}
// implemented interfaces
var impls = [];
if (element.implements)
Array.prototype.push.apply(impls, element.implements);
if (element.mixes)
Array.prototype.push.apply(impls, element.mixes);
impls = impls.filter(notAModuleReference);
if (impls.length)
write("implements ", impls.join(", "), " ");
writeln("{");
++indent;
if (element.tsType)
writeln(element.tsType.replace(/\r?\n|\r/g, "\n"));
// constructor
if (!is_interface && !element.virtual)
handleFunction(element, parent, true);
// properties
if (is_interface && element.properties)
element.properties.forEach(function(property) {
writeProperty(property);
});
// class-compatible members
var incompatible = [];
getChildrenOf(element).forEach(function(child) {
if (isClassLike(child) || child.kind === "module" || child.kind === "typedef" || child.isEnum) {
incompatible.push(child);
return;
}
handleElement(child, element);
});
--indent;
writeln("}");
// class-incompatible members
if (incompatible.length) {
writeln();
if (element.scope === "global" && !options.module)
write("export ");
writeln("namespace ", element.name, " {");
++indent;
incompatible.forEach(function(child) {
handleElement(child, element);
});
--indent;
writeln("}");
}
}
// handles a namespace or class member
function handleMember(element, parent) {
begin(element);
if (element.isEnum) {
var stringEnum = false;
element.properties.forEach(function(property) {
if (isNaN(property.defaultvalue)) {
stringEnum = true;
}
});
if (stringEnum) {
writeln("type ", element.name, " =");
++indent;
element.properties.forEach(function(property, i) {
write(i === 0 ? "" : "| ", JSON.stringify(property.defaultvalue));
});
--indent;
writeln(";");
} else {
writeln("enum ", element.name, " {");
++indent;
element.properties.forEach(function(property, i) {
write(property.name);
if (property.defaultvalue !== undefined)
write(" = ", JSON.stringify(property.defaultvalue));
if (i < element.properties.length - 1)
writeln(",");
else
writeln();
});
--indent;
writeln("}");
}
} else {
var inClass = isClassLike(parent);
if (inClass) {
write(element.access || "public", " ");
if (element.scope === "static")
write("static ");
if (element.readonly)
write("readonly ");
} else
write(element.kind === "constant" ? "const " : "let ");
write(element.name);
if (element.optional)
write("?");
write(": ");
if (element.type && element.type.names && /^Object\b/i.test(element.type.names[0]) && element.properties) {
writeln("{");
++indent;
element.properties.forEach(function(property, i) {
writeln(JSON.stringify(property.name), ": ", getTypeOf(property), i < element.properties.length - 1 ? "," : "");
});
--indent;
writeln("};");
} else
writeln(getTypeOf(element), ";");
}
}
// handles a function or method
function handleFunction(element, parent, isConstructor) {
var insideClass = true;
if (isConstructor) {
writeComment(element.comment);
write("constructor");
} else {
begin(element);
insideClass = isClassLike(parent);
if (insideClass) {
write(element.access || "public", " ");
if (element.scope === "static")
write("static ");
} else
write("function ");
write(element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
}
writeFunctionSignature(element, isConstructor, false);
writeln(";");
if (!insideClass)
handleNamespace(element);
}
// handles a type definition (not a real type)
function handleTypeDef(element, parent) {
if (isInterface(element)) {
if (isClassLike(parent))
queuedInterfaces.push(element);
else {
begin(element);
writeInterface(element);
}
} else {
writeComment(element.comment, true);
write("type ", element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
write(" = ");
if (element.tsType)
write(element.tsType.replace(/\r?\n|\r/g, "\n"));
else {
var type = getTypeOf(element);
if (element.type && element.type.names.length === 1 && element.type.names[0] === "function")
writeFunctionSignature(element, false, true);
else if (type === "object") {
if (element.properties && element.properties.length)
writeInterfaceBody(element);
else
write("{}");
} else
write(type);
}
writeln(";");
}
}

View File

@ -0,0 +1,25 @@
'use strict';
var isWindows = process.platform === 'win32';
var trailingSlashRe = isWindows ? /[^:]\\$/ : /.\/$/;
// https://github.com/nodejs/node/blob/3e7a14381497a3b73dda68d05b5130563cdab420/lib/os.js#L25-L43
module.exports = function () {
var path;
if (isWindows) {
path = process.env.TEMP ||
process.env.TMP ||
(process.env.SystemRoot || process.env.windir) + '\\temp';
} else {
path = process.env.TMPDIR ||
process.env.TMP ||
process.env.TEMP ||
'/tmp';
}
if (trailingSlashRe.test(path)) {
path = path.slice(0, -1);
}
return path;
};

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,32 @@
# os-tmpdir [![Build Status](https://travis-ci.org/sindresorhus/os-tmpdir.svg?branch=master)](https://travis-ci.org/sindresorhus/os-tmpdir)
> Node.js [`os.tmpdir()`](https://nodejs.org/api/os.html#os_os_tmpdir) [ponyfill](https://ponyfill.com)
Use this instead of `require('os').tmpdir()` to get a consistent behavior on different Node.js versions (even 0.8).
## Install
```
$ npm install --save os-tmpdir
```
## Usage
```js
const osTmpdir = require('os-tmpdir');
osTmpdir();
//=> '/var/folders/m3/5574nnhn0yj488ccryqr7tc80000gn/T'
```
## API
See the [`os.tmpdir()` docs](https://nodejs.org/api/os.html#os_os_tmpdir).
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

21
node_modules/protobufjs/cli/node_modules/tmp/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 KARASZI István
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

314
node_modules/protobufjs/cli/node_modules/tmp/README.md generated vendored Normal file
View File

@ -0,0 +1,314 @@
# Tmp
A simple temporary file and directory creator for [node.js.][1]
[![Build Status](https://travis-ci.org/raszi/node-tmp.svg?branch=master)](https://travis-ci.org/raszi/node-tmp)
[![Dependencies](https://david-dm.org/raszi/node-tmp.svg)](https://david-dm.org/raszi/node-tmp)
[![npm version](https://badge.fury.io/js/tmp.svg)](https://badge.fury.io/js/tmp)
[![API documented](https://img.shields.io/badge/API-documented-brightgreen.svg)](https://raszi.github.io/node-tmp/)
[![Known Vulnerabilities](https://snyk.io/test/npm/tmp/badge.svg)](https://snyk.io/test/npm/tmp)
## About
This is a [widely used library][2] to create temporary files and directories
in a [node.js][1] environment.
Tmp offers both an asynchronous and a synchronous API. For all API calls, all
the parameters are optional. There also exists a promisified version of the
API, see (5) under references below.
Tmp uses crypto for determining random file names, or, when using templates,
a six letter random identifier. And just in case that you do not have that much
entropy left on your system, Tmp will fall back to pseudo random numbers.
You can set whether you want to remove the temporary file on process exit or
not, and the destination directory can also be set.
## How to install
```bash
npm install tmp
```
## Usage
Please also check [API docs][4].
### Asynchronous file creation
Simple temporary file creation, the file will be closed and unlinked on process exit.
```javascript
var tmp = require('tmp');
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
console.log('File: ', path);
console.log('Filedescriptor: ', fd);
// If we don't need the file anymore we could manually call the cleanupCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
cleanupCallback();
});
```
### Synchronous file creation
A synchronous version of the above.
```javascript
var tmp = require('tmp');
var tmpobj = tmp.fileSync();
console.log('File: ', tmpobj.name);
console.log('Filedescriptor: ', tmpobj.fd);
// If we don't need the file anymore we could manually call the removeCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
tmpobj.removeCallback();
```
Note that this might throw an exception if either the maximum limit of retries
for creating a temporary name fails, or, in case that you do not have the permission
to write to the directory where the temporary file should be created in.
### Asynchronous directory creation
Simple temporary directory creation, it will be removed on process exit.
If the directory still contains items on process exit, then it won't be removed.
```javascript
var tmp = require('tmp');
tmp.dir(function _tempDirCreated(err, path, cleanupCallback) {
if (err) throw err;
console.log('Dir: ', path);
// Manual cleanup
cleanupCallback();
});
```
If you want to cleanup the directory even when there are entries in it, then
you can pass the `unsafeCleanup` option when creating it.
### Synchronous directory creation
A synchronous version of the above.
```javascript
var tmp = require('tmp');
var tmpobj = tmp.dirSync();
console.log('Dir: ', tmpobj.name);
// Manual cleanup
tmpobj.removeCallback();
```
Note that this might throw an exception if either the maximum limit of retries
for creating a temporary name fails, or, in case that you do not have the permission
to write to the directory where the temporary directory should be created in.
### Asynchronous filename generation
It is possible with this library to generate a unique filename in the specified
directory.
```javascript
var tmp = require('tmp');
tmp.tmpName(function _tempNameGenerated(err, path) {
if (err) throw err;
console.log('Created temporary filename: ', path);
});
```
### Synchronous filename generation
A synchronous version of the above.
```javascript
var tmp = require('tmp');
var name = tmp.tmpNameSync();
console.log('Created temporary filename: ', name);
```
## Advanced usage
### Asynchronous file creation
Creates a file with mode `0644`, prefix will be `prefix-` and postfix will be `.txt`.
```javascript
var tmp = require('tmp');
tmp.file({ mode: 0644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileCreated(err, path, fd) {
if (err) throw err;
console.log('File: ', path);
console.log('Filedescriptor: ', fd);
});
```
### Synchronous file creation
A synchronous version of the above.
```javascript
var tmp = require('tmp');
var tmpobj = tmp.fileSync({ mode: 0644, prefix: 'prefix-', postfix: '.txt' });
console.log('File: ', tmpobj.name);
console.log('Filedescriptor: ', tmpobj.fd);
```
### Controlling the Descriptor
As a side effect of creating a unique file `tmp` gets a file descriptor that is
returned to the user as the `fd` parameter. The descriptor may be used by the
application and is closed when the `removeCallback` is invoked.
In some use cases the application does not need the descriptor, needs to close it
without removing the file, or needs to remove the file without closing the
descriptor. Two options control how the descriptor is managed:
* `discardDescriptor` - if `true` causes `tmp` to close the descriptor after the file
is created. In this case the `fd` parameter is undefined.
* `detachDescriptor` - if `true` causes `tmp` to return the descriptor in the `fd`
parameter, but it is the application's responsibility to close it when it is no
longer needed.
```javascript
var tmp = require('tmp');
tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
// fd will be undefined, allowing application to use fs.createReadStream(path)
// without holding an unused descriptor open.
});
```
```javascript
var tmp = require('tmp');
tmp.file({ detachDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
cleanupCallback();
// Application can store data through fd here; the space used will automatically
// be reclaimed by the operating system when the descriptor is closed or program
// terminates.
});
```
### Asynchronous directory creation
Creates a directory with mode `0755`, prefix will be `myTmpDir_`.
```javascript
var tmp = require('tmp');
tmp.dir({ mode: 0750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path) {
if (err) throw err;
console.log('Dir: ', path);
});
```
### Synchronous directory creation
Again, a synchronous version of the above.
```javascript
var tmp = require('tmp');
var tmpobj = tmp.dirSync({ mode: 0750, prefix: 'myTmpDir_' });
console.log('Dir: ', tmpobj.name);
```
### mkstemp like, asynchronously
Creates a new temporary directory with mode `0700` and filename like `/tmp/tmp-nk2J1u`.
```javascript
var tmp = require('tmp');
tmp.dir({ template: '/tmp/tmp-XXXXXX' }, function _tempDirCreated(err, path) {
if (err) throw err;
console.log('Dir: ', path);
});
```
### mkstemp like, synchronously
This will behave similarly to the asynchronous version.
```javascript
var tmp = require('tmp');
var tmpobj = tmp.dirSync({ template: '/tmp/tmp-XXXXXX' });
console.log('Dir: ', tmpobj.name);
```
### Asynchronous filename generation
The `tmpName()` function accepts the `prefix`, `postfix`, `dir`, etc. parameters also:
```javascript
var tmp = require('tmp');
tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, function _tempNameGenerated(err, path) {
if (err) throw err;
console.log('Created temporary filename: ', path);
});
```
### Synchronous filename generation
The `tmpNameSync()` function works similarly to `tmpName()`.
```javascript
var tmp = require('tmp');
var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' });
console.log('Created temporary filename: ', tmpname);
```
## Graceful cleanup
One may want to cleanup the temporary files even when an uncaught exception
occurs. To enforce this, you can call the `setGracefulCleanup()` method:
```javascript
var tmp = require('tmp');
tmp.setGracefulCleanup();
```
## Options
All options are optional :)
* `mode`: the file mode to create with, it fallbacks to `0600` on file creation and `0700` on directory creation
* `prefix`: the optional prefix, fallbacks to `tmp-` if not provided
* `postfix`: the optional postfix, fallbacks to `.tmp` on file creation
* `template`: [`mkstemp`][3] like filename template, no default
* `dir`: the optional temporary directory, fallbacks to system default (guesses from environment)
* `tries`: how many times should the function try to get a unique filename before giving up, default `3`
* `keep`: signals that the temporary file or directory should not be deleted on exit, default is `false`, means delete
* Please keep in mind that it is recommended in this case to call the provided `cleanupCallback` function manually.
* `unsafeCleanup`: recursively removes the created temporary directory, even when it's not empty. default is `false`
[1]: http://nodejs.org/
[2]: https://www.npmjs.com/browse/depended/tmp
[3]: http://www.kernel.org/doc/man-pages/online/pages/man3/mkstemp.3.html
[4]: https://raszi.github.io/node-tmp/
[5]: https://github.com/benjamingr/tmp-promise

611
node_modules/protobufjs/cli/node_modules/tmp/lib/tmp.js generated vendored Normal file
View File

@ -0,0 +1,611 @@
/*!
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/
/*
* Module dependencies.
*/
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const osTmpDir = require('os-tmpdir');
const _c = process.binding('constants');
/*
* The working inner variables.
*/
const
/**
* The temporary directory.
* @type {string}
*/
tmpDir = osTmpDir(),
// the random characters to choose from
RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
TEMPLATE_PATTERN = /XXXXXX/,
DEFAULT_TRIES = 3,
CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),
EBADF = _c.EBADF || _c.os.errno.EBADF,
ENOENT = _c.ENOENT || _c.os.errno.ENOENT,
DIR_MODE = 448 /* 0o700 */,
FILE_MODE = 384 /* 0o600 */,
// this will hold the objects need to be removed on exit
_removeObjects = [];
var
_gracefulCleanup = false,
_uncaughtException = false;
/**
* Random name generator based on crypto.
* Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
*
* @param {number} howMany
* @returns {string} the generated random name
* @private
*/
function _randomChars(howMany) {
var
value = [],
rnd = null;
// make sure that we do not fail because we ran out of entropy
try {
rnd = crypto.randomBytes(howMany);
} catch (e) {
rnd = crypto.pseudoRandomBytes(howMany);
}
for (var i = 0; i < howMany; i++) {
value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
}
return value.join('');
}
/**
* Checks whether the `obj` parameter is defined or not.
*
* @param {Object} obj
* @returns {boolean} true if the object is undefined
* @private
*/
function _isUndefined(obj) {
return typeof obj === 'undefined';
}
/**
* Parses the function arguments.
*
* This function helps to have optional arguments.
*
* @param {(Options|Function)} options
* @param {Function} callback
* @returns {Array} parsed arguments
* @private
*/
function _parseArguments(options, callback) {
if (typeof options == 'function') {
return [callback || {}, options];
}
if (_isUndefined(options)) {
return [{}, callback];
}
return [options, callback];
}
/**
* Generates a new temporary name.
*
* @param {Object} opts
* @returns {string} the new random name according to opts
* @private
*/
function _generateTmpName(opts) {
if (opts.name) {
return path.join(opts.dir || tmpDir, opts.name);
}
// mkstemps like template
if (opts.template) {
return opts.template.replace(TEMPLATE_PATTERN, _randomChars(6));
}
// prefix and postfix
const name = [
opts.prefix || 'tmp-',
process.pid,
_randomChars(12),
opts.postfix || ''
].join('');
return path.join(opts.dir || tmpDir, name);
}
/**
* Gets a temporary file name.
*
* @param {(Options|tmpNameCallback)} options options or callback
* @param {?tmpNameCallback} callback the callback function
*/
function tmpName(options, callback) {
var
args = _parseArguments(options, callback),
opts = args[0],
cb = args[1],
tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES;
if (isNaN(tries) || tries < 0)
return cb(new Error('Invalid tries'));
if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
return cb(new Error('Invalid template provided'));
(function _getUniqueName() {
const name = _generateTmpName(opts);
// check whether the path exists then retry if needed
fs.stat(name, function (err) {
if (!err) {
if (tries-- > 0) return _getUniqueName();
return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
}
cb(null, name);
});
}());
}
/**
* Synchronous version of tmpName.
*
* @param {Object} options
* @returns {string} the generated random name
* @throws {Error} if the options are invalid or could not generate a filename
*/
function tmpNameSync(options) {
var
args = _parseArguments(options),
opts = args[0],
tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES;
if (isNaN(tries) || tries < 0)
throw new Error('Invalid tries');
if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
throw new Error('Invalid template provided');
do {
const name = _generateTmpName(opts);
try {
fs.statSync(name);
} catch (e) {
return name;
}
} while (tries-- > 0);
throw new Error('Could not get a unique tmp filename, max tries reached');
}
/**
* Creates and opens a temporary file.
*
* @param {(Options|fileCallback)} options the config options or the callback function
* @param {?fileCallback} callback
*/
function file(options, callback) {
var
args = _parseArguments(options, callback),
opts = args[0],
cb = args[1];
opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix;
// gets a temporary filename
tmpName(opts, function _tmpNameCreated(err, name) {
if (err) return cb(err);
// create and open the file
fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {
if (err) return cb(err);
if (opts.discardDescriptor) {
return fs.close(fd, function _discardCallback(err) {
if (err) {
// Low probability, and the file exists, so this could be
// ignored. If it isn't we certainly need to unlink the
// file, and if that fails too its error is more
// important.
try {
fs.unlinkSync(name);
} catch (e) {
if (!isENOENT(e)) {
err = e;
}
}
return cb(err);
}
cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts));
});
}
if (opts.detachDescriptor) {
return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts));
}
cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts));
});
});
}
/**
* Synchronous version of file.
*
* @param {Options} options
* @returns {FileSyncObject} object consists of name, fd and removeCallback
* @throws {Error} if cannot create a file
*/
function fileSync(options) {
var
args = _parseArguments(options),
opts = args[0];
opts.postfix = opts.postfix || '.tmp';
const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
const name = tmpNameSync(opts);
var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
if (opts.discardDescriptor) {
fs.closeSync(fd);
fd = undefined;
}
return {
name: name,
fd: fd,
removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts)
};
}
/**
* Removes files and folders in a directory recursively.
*
* @param {string} root
* @private
*/
function _rmdirRecursiveSync(root) {
const dirs = [root];
do {
var
dir = dirs.pop(),
deferred = false,
files = fs.readdirSync(dir);
for (var i = 0, length = files.length; i < length; i++) {
var
file = path.join(dir, files[i]),
stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories
if (stat.isDirectory()) {
if (!deferred) {
deferred = true;
dirs.push(dir);
}
dirs.push(file);
} else {
fs.unlinkSync(file);
}
}
if (!deferred) {
fs.rmdirSync(dir);
}
} while (dirs.length !== 0);
}
/**
* Creates a temporary directory.
*
* @param {(Options|dirCallback)} options the options or the callback function
* @param {?dirCallback} callback
*/
function dir(options, callback) {
var
args = _parseArguments(options, callback),
opts = args[0],
cb = args[1];
// gets a temporary filename
tmpName(opts, function _tmpNameCreated(err, name) {
if (err) return cb(err);
// create the directory
fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
if (err) return cb(err);
cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
});
});
}
/**
* Synchronous version of dir.
*
* @param {Options} options
* @returns {DirSyncObject} object consists of name and removeCallback
* @throws {Error} if it cannot create a directory
*/
function dirSync(options) {
var
args = _parseArguments(options),
opts = args[0];
const name = tmpNameSync(opts);
fs.mkdirSync(name, opts.mode || DIR_MODE);
return {
name: name,
removeCallback: _prepareTmpDirRemoveCallback(name, opts)
};
}
/**
* Prepares the callback for removal of the temporary file.
*
* @param {string} name the path of the file
* @param {number} fd file descriptor
* @param {Object} opts
* @returns {fileCallback}
* @private
*/
function _prepareTmpFileRemoveCallback(name, fd, opts) {
const removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
try {
if (0 <= fdPath[0]) {
fs.closeSync(fdPath[0]);
}
}
catch (e) {
// under some node/windows related circumstances, a temporary file
// may have not be created as expected or the file was already closed
// by the user, in which case we will simply ignore the error
if (!isEBADF(e) && !isENOENT(e)) {
// reraise any unanticipated error
throw e;
}
}
try {
fs.unlinkSync(fdPath[1]);
}
catch (e) {
if (!isENOENT(e)) {
// reraise any unanticipated error
throw e;
}
}
}, [fd, name]);
if (!opts.keep) {
_removeObjects.unshift(removeCallback);
}
return removeCallback;
}
/**
* Prepares the callback for removal of the temporary directory.
*
* @param {string} name
* @param {Object} opts
* @returns {Function} the callback
* @private
*/
function _prepareTmpDirRemoveCallback(name, opts) {
const removeFunction = opts.unsafeCleanup ? _rmdirRecursiveSync : fs.rmdirSync.bind(fs);
const removeCallback = _prepareRemoveCallback(removeFunction, name);
if (!opts.keep) {
_removeObjects.unshift(removeCallback);
}
return removeCallback;
}
/**
* Creates a guarded function wrapping the removeFunction call.
*
* @param {Function} removeFunction
* @param {Object} arg
* @returns {Function}
* @private
*/
function _prepareRemoveCallback(removeFunction, arg) {
var called = false;
return function _cleanupCallback(next) {
if (!called) {
const index = _removeObjects.indexOf(_cleanupCallback);
if (index >= 0) {
_removeObjects.splice(index, 1);
}
called = true;
removeFunction(arg);
}
if (next) next(null);
};
}
/**
* The garbage collector.
*
* @private
*/
function _garbageCollector() {
if (_uncaughtException && !_gracefulCleanup) {
return;
}
// the function being called removes itself from _removeObjects,
// loop until _removeObjects is empty
while (_removeObjects.length) {
try {
_removeObjects[0].call(null);
} catch (e) {
// already removed?
}
}
}
/**
* Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.
*/
function isEBADF(error) {
return isExpectedError(error, -EBADF, 'EBADF');
}
/**
* Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.
*/
function isENOENT(error) {
return isExpectedError(error, -ENOENT, 'ENOENT');
}
/**
* Helper to determine whether the expected error code matches the actual code and errno,
* which will differ between the supported node versions.
*
* - Node >= 7.0:
* error.code {String}
* error.errno {String|Number} any numerical value will be negated
*
* - Node >= 6.0 < 7.0:
* error.code {String}
* error.errno {Number} negated
*
* - Node >= 4.0 < 6.0: introduces SystemError
* error.code {String}
* error.errno {Number} negated
*
* - Node >= 0.10 < 4.0:
* error.code {Number} negated
* error.errno n/a
*/
function isExpectedError(error, code, errno) {
return error.code == code || error.code == errno;
}
/**
* Sets the graceful cleanup.
*
* Also removes the created files and directories when an uncaught exception occurs.
*/
function setGracefulCleanup() {
_gracefulCleanup = true;
}
const version = process.versions.node.split('.').map(function (value) {
return parseInt(value, 10);
});
if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
_uncaughtException = true;
_garbageCollector();
throw err;
});
}
process.addListener('exit', function _exit(code) {
if (code) _uncaughtException = true;
_garbageCollector();
});
/**
* Configuration options.
*
* @typedef {Object} Options
* @property {?number} tries the number of tries before give up the name generation
* @property {?string} template the "mkstemp" like filename template
* @property {?string} name fix name
* @property {?string} dir the tmp directory to use
* @property {?string} prefix prefix for the generated name
* @property {?string} postfix postfix for the generated name
*/
/**
* @typedef {Object} FileSyncObject
* @property {string} name the name of the file
* @property {string} fd the file descriptor
* @property {fileCallback} removeCallback the callback function to remove the file
*/
/**
* @typedef {Object} DirSyncObject
* @property {string} name the name of the directory
* @property {fileCallback} removeCallback the callback function to remove the directory
*/
/**
* @callback tmpNameCallback
* @param {?Error} err the error object if anything goes wrong
* @param {string} name the temporary file name
*/
/**
* @callback fileCallback
* @param {?Error} err the error object if anything goes wrong
* @param {string} name the temporary file name
* @param {number} fd the file descriptor
* @param {cleanupCallback} fn the cleanup callback function
*/
/**
* @callback dirCallback
* @param {?Error} err the error object if anything goes wrong
* @param {string} name the temporary file name
* @param {cleanupCallback} fn the cleanup callback function
*/
/**
* Removes the temporary created file or directory.
*
* @callback cleanupCallback
* @param {simpleCallback} [next] function to call after entry was removed
*/
/**
* Callback function for function composition.
* @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57}
*
* @callback simpleCallback
*/
// exporting all the needed methods
module.exports.tmpdir = tmpDir;
module.exports.dir = dir;
module.exports.dirSync = dirSync;
module.exports.file = file;
module.exports.fileSync = fileSync;
module.exports.tmpName = tmpName;
module.exports.tmpNameSync = tmpNameSync;
module.exports.setGracefulCleanup = setGracefulCleanup;

1
node_modules/protobufjs/cli/package.json generated vendored Normal file
View File

@ -0,0 +1 @@
{"version": "6.7.0"}

32
node_modules/protobufjs/cli/package.standalone.json generated vendored Normal file
View File

@ -0,0 +1,32 @@
{
"name": "protobufjs-cli",
"description": "Translates between file formats and generates static code as well as TypeScript definitions.",
"version": "6.7.0",
"author": "Daniel Wirtz <dcode+protobufjs@dcode.io>",
"repository": {
"type": "git",
"url": "https://github.com/dcodeIO/protobuf.js.git"
},
"license": "BSD-3-Clause",
"main": "index.js",
"types": "index.d.ts",
"bin": {
"pbjs": "bin/pbjs",
"pbts": "bin/pbts"
},
"peerDependencies": {
"protobufjs": "~6.7.0"
},
"dependencies": {
"chalk": "^1.1.3",
"escodegen": "^1.8.1",
"espree": "^3.1.3",
"estraverse": "^4.2.0",
"glob": "^7.1.1",
"jsdoc": "^3.4.2",
"minimist": "^1.2.0",
"semver": "^5.3.0",
"tmp": "0.0.31",
"uglify-js": "^2.8.15"
}
}

9
node_modules/protobufjs/cli/pbjs.d.ts generated vendored Normal file
View File

@ -0,0 +1,9 @@
type pbjsCallback = (err: Error|null, output?: string) => void;
/**
* Runs pbjs programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
export function main(args: string[], callback?: pbjsCallback): number|undefined;

329
node_modules/protobufjs/cli/pbjs.js generated vendored Normal file
View File

@ -0,0 +1,329 @@
"use strict";
var path = require("path"),
fs = require("fs"),
pkg = require("./package.json"),
util = require("./util");
util.setup();
var protobuf = require(util.pathToProtobufJs),
minimist = require("minimist"),
chalk = require("chalk"),
glob = require("glob");
var targets = util.requireAll("./targets");
/**
* Runs pbjs 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 main(args, callback) {
var lintDefault = "eslint-disable " + [
"block-scoped-var",
"id-length",
"no-control-regex",
"no-magic-numbers",
"no-prototype-builtins",
"no-redeclare",
"no-shadow",
"no-var",
"sort-vars"
].join(", ");
var argv = minimist(args, {
alias: {
target: "t",
out: "o",
path: "p",
wrap: "w",
root: "r",
lint: "l",
// backward compatibility:
"force-long": "strict-long",
"force-message": "strict-message"
},
string: [ "target", "out", "path", "wrap", "dependency", "root", "lint" ],
boolean: [ "create", "encode", "decode", "verify", "convert", "delimited", "beautify", "comments", "es6", "sparse", "keep-case", "force-long", "force-number", "force-enum-string", "force-message" ],
default: {
target: "json",
create: true,
encode: true,
decode: true,
verify: true,
convert: true,
delimited: true,
beautify: true,
comments: true,
es6: null,
lint: lintDefault,
"keep-case": false,
"force-long": false,
"force-number": false,
"force-enum-string": false,
"force-message": false
}
});
var target = targets[argv.target],
files = argv._,
paths = typeof argv.path === "string" ? [ argv.path ] : argv.path || [];
// alias hyphen args in camel case
Object.keys(argv).forEach(function(key) {
var camelKey = key.replace(/-([a-z])/g, function($0, $1) { return $1.toUpperCase(); });
if (camelKey !== key)
argv[camelKey] = argv[key];
});
// protobuf.js package directory contains additional, otherwise non-bundled google types
paths.push(path.relative(process.cwd(), path.join(__dirname, "..")) || ".");
if (!files.length) {
var descs = Object.keys(targets).filter(function(key) { return !targets[key].private; }).map(function(key) {
return " " + util.pad(key, 14, true) + targets[key].description;
});
if (callback)
callback(Error("usage")); // eslint-disable-line callback-return
else
process.stderr.write([
"protobuf.js v" + pkg.version + " CLI for JavaScript",
"",
chalk.bold.white("Translates between file formats and generates static code."),
"",
" -t, --target Specifies the target format. Also accepts a path to require a custom target.",
"",
descs.join("\n"),
"",
" -p, --path Adds a directory to the include path.",
"",
" -o, --out Saves to a file instead of writing to stdout.",
"",
" --sparse Exports only those types referenced from a main file (experimental).",
"",
chalk.bold.gray(" Module targets only:"),
"",
" -w, --wrap Specifies the wrapper to use. Also accepts a path to require a custom wrapper.",
"",
" default Default wrapper supporting both CommonJS and AMD",
" commonjs CommonJS wrapper",
" amd AMD wrapper",
" es6 ES6 wrapper (implies --es6)",
" closure A closure adding to protobuf.roots where protobuf is a global",
"",
" --dependency Specifies which version of protobuf to require. Accepts any valid module id",
"",
" -r, --root Specifies an alternative protobuf.roots name.",
"",
" -l, --lint Linter configuration. Defaults to protobuf.js-compatible rules:",
"",
" " + lintDefault,
"",
" --es6 Enables ES6 syntax (const/let instead of var)",
"",
chalk.bold.gray(" Proto sources only:"),
"",
" --keep-case Keeps field casing instead of converting to camel case.",
"",
chalk.bold.gray(" Static targets only:"),
"",
" --no-create Does not generate create functions used for reflection compatibility.",
" --no-encode Does not generate encode functions.",
" --no-decode Does not generate decode functions.",
" --no-verify Does not generate verify functions.",
" --no-convert Does not generate convert functions like from/toObject",
" --no-delimited Does not generate delimited encode/decode functions.",
" --no-beautify Does not beautify generated code.",
" --no-comments Does not output any JSDoc comments.",
"",
" --force-long Enfores the use of 'Long' for s-/u-/int64 and s-/fixed64 fields.",
" --force-number Enfores the use of 'number' for s-/u-/int64 and s-/fixed64 fields.",
" --force-message Enfores the use of message instances instead of plain objects.",
"",
"usage: " + chalk.bold.green("pbjs") + " [options] file1.proto file2.json ..." + chalk.gray(" (or pipe) ") + "other | " + chalk.bold.green("pbjs") + " [options] -",
""
].join("\n"));
return 1;
}
if (typeof argv["strict-long"] === "boolean")
argv["force-long"] = argv["strict-long"];
// 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;
}
// Require custom target
if (!target)
target = require(path.resolve(process.cwd(), argv.target));
var root = new protobuf.Root();
var mainFiles = [];
// Search include paths when resolving imports
root.resolvePath = function pbjsResolvePath(origin, target) {
var normOrigin = protobuf.util.path.normalize(origin),
normTarget = protobuf.util.path.normalize(target);
if (!normOrigin)
mainFiles.push(normTarget);
var resolved = protobuf.util.path.resolve(normOrigin, normTarget, true);
var idx = resolved.lastIndexOf("google/protobuf/");
if (idx > -1) {
var altname = resolved.substring(idx);
if (altname in protobuf.common)
resolved = altname;
}
if (fs.existsSync(resolved))
return resolved;
for (var i = 0; i < paths.length; ++i) {
var iresolved = protobuf.util.path.resolve(paths[i] + "/", target);
if (fs.existsSync(iresolved))
return iresolved;
}
return resolved;
};
// Use es6 syntax if not explicitly specified on the command line and the es6 wrapper is used
if (argv.wrap === "es6" || argv.es6) {
argv.wrap = "es6";
argv.es6 = true;
}
var parseOptions = {
"keepCase": argv["keep-case"] || false
};
// Read from stdin
if (files.length === 1 && files[0] === "-") {
var data = [];
process.stdin.on("data", function(chunk) {
data.push(chunk);
});
process.stdin.on("end", function() {
var source = Buffer.concat(data).toString("utf8");
try {
if (source.charAt(0) !== "{") {
protobuf.parse.filename = "-";
protobuf.parse(source, root, parseOptions);
} else {
var json = JSON.parse(source);
root.setOptions(json.options).addJSON(json);
}
callTarget();
} catch (err) {
if (callback) {
callback(err);
return;
}
throw err;
}
});
// Load from disk
} else {
try {
root.loadSync(files, parseOptions).resolveAll(); // sync is deterministic while async is not
if (argv.sparse)
sparsify(root);
callTarget();
} catch (err) {
if (callback) {
callback(err);
return undefined;
}
throw err;
}
}
function markReferenced(tobj) {
tobj.referenced = true;
// also mark a type's fields and oneofs
if (tobj.fieldsArray)
tobj.fieldsArray.forEach(function(fobj) {
fobj.referenced = true;
});
if (tobj.oneofsArray)
tobj.oneofsArray.forEach(function(oobj) {
oobj.referenced = true;
});
// also mark an extension field's extended type, but not its (other) fields
if (tobj.extensionField)
tobj.extensionField.parent.referenced = true;
}
function sparsify(root) {
// 1. mark directly or indirectly referenced objects
util.traverse(root, function(obj) {
if (!obj.filename)
return;
if (mainFiles.indexOf(obj.filename) > -1)
util.traverseResolved(obj, markReferenced);
});
// 2. empty unreferenced objects
util.traverse(root, function(obj) {
var parent = obj.parent;
if (!parent || obj.referenced) // root or referenced
return;
// remove unreferenced namespaces
if (obj instanceof protobuf.Namespace) {
var hasReferenced = false;
util.traverse(obj, function(iobj) {
if (iobj.referenced)
hasReferenced = true;
});
if (hasReferenced) { // replace with plain namespace if a namespace subclass
if (obj instanceof protobuf.Type || obj instanceof protobuf.Service) {
var robj = new protobuf.Namespace(obj.name, obj.options);
robj.nested = obj.nested;
parent.add(robj);
}
} else // remove completely if nothing inside is referenced
parent.remove(obj);
// remove everything else unreferenced
} else if (!(obj instanceof protobuf.Namespace))
parent.remove(obj);
});
// 3. validate that everything is fine
root.resolveAll();
}
function callTarget() {
target(root, argv, function targetCallback(err, output) {
if (err) {
if (callback)
return callback(err);
throw err;
}
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;
};

9
node_modules/protobufjs/cli/pbts.d.ts generated vendored Normal file
View File

@ -0,0 +1,9 @@
type pbtsCallback = (err: Error|null, output?: string) => void;
/**
* Runs pbts programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
export function main(args: string[], callback?: pbtsCallback): number|undefined;

197
node_modules/protobufjs/cli/pbts.js generated vendored Normal file
View File

@ -0,0 +1,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;
};

38
node_modules/protobufjs/cli/targets/json-module.js generated vendored Normal file
View File

@ -0,0 +1,38 @@
"use strict";
module.exports = json_module;
var util = require("../util");
var protobuf = require("../..");
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;
}

8
node_modules/protobufjs/cli/targets/json.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
"use strict";
module.exports = json_target;
json_target.description = "JSON representation";
function json_target(root, options, callback) {
callback(null, JSON.stringify(root, null, 2));
}

326
node_modules/protobufjs/cli/targets/proto.js generated vendored Normal file
View File

@ -0,0 +1,326 @@
"use strict";
module.exports = proto_target;
proto_target.private = true;
var protobuf = require("../..");
var Namespace = protobuf.Namespace,
Enum = protobuf.Enum,
Type = protobuf.Type,
Field = protobuf.Field,
OneOf = protobuf.OneOf,
Service = protobuf.Service,
Method = protobuf.Method,
types = protobuf.types,
util = protobuf.util;
function underScore(str) {
return str.substring(0,1)
+ str.substring(1)
.replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
}
var out = [];
var indent = 0;
var first = false;
var syntax = 3;
function proto_target(root, options, callback) {
if (options) {
switch (options.syntax) {
case undefined:
case "proto3":
case "3":
syntax = 3;
break;
case "proto2":
case "2":
syntax = 2;
break;
default:
return callback(Error("invalid syntax: " + options.syntax));
}
}
indent = 0;
first = false;
try {
buildRoot(root);
return callback(null, out.join("\n"));
} catch (err) {
return callback(err);
} finally {
out = [];
syntax = 3;
}
}
function push(line) {
if (line === "")
out.push("");
else {
var ind = "";
for (var i = 0; i < indent; ++i)
ind += " ";
out.push(ind + line);
}
}
function escape(str) {
return str.replace(/[\\"']/g, "\\$&")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\u0000/g, "\\0"); // eslint-disable-line no-control-regex
}
function value(v) {
switch (typeof v) {
case "boolean":
return v ? "true" : "false";
case "number":
return v.toString();
default:
return "\"" + escape(String(v)) + "\"";
}
}
function buildRoot(root) {
root.resolveAll();
var pkg = [];
var ptr = root;
var repeat = true;
do {
var nested = ptr.nestedArray;
if (nested.length === 1 && nested[0] instanceof Namespace && !(nested[0] instanceof Type || nested[0] instanceof Service)) {
ptr = nested[0];
if (ptr !== root)
pkg.push(ptr.name);
} else
repeat = false;
} while (repeat);
out.push("syntax = \"proto" + syntax + "\";");
if (pkg.length)
out.push("", "package " + pkg.join(".") + ";");
buildOptions(ptr);
ptr.nestedArray.forEach(build);
}
function build(object) {
if (object instanceof Enum)
buildEnum(object);
else if (object instanceof Type)
buildType(object);
else if (object instanceof Field)
buildField(object);
else if (object instanceof OneOf)
buildOneOf(object);
else if (object instanceof Service)
buildService(object);
else if (object instanceof Method)
buildMethod(object);
else
buildNamespace(object);
}
function buildNamespace(namespace) { // just a namespace, not a type etc.
push("");
push("message " + namespace.name + " {");
++indent;
buildOptions(namespace);
consolidateExtends(namespace.nestedArray).remaining.forEach(build);
--indent;
push("}");
}
function buildEnum(enm) {
push("");
push("enum " + enm.name + " {");
buildOptions(enm);
++indent; first = true;
Object.keys(enm.values).forEach(function(name) {
var val = enm.values[name];
if (first) {
push("");
first = false;
}
push(name + " = " + val + ";");
});
--indent; first = false;
push("}");
}
function buildRanges(keyword, ranges) {
if (ranges && ranges.length) {
var parts = [];
ranges.forEach(function(range) {
if (typeof range === "string")
parts.push("\"" + escape(range) + "\"");
else if (range[0] === range[1])
parts.push(range[0]);
else
parts.push(range[0] + " to " + (range[1] === 0x1FFFFFFF ? "max" : range[1]));
});
push("");
push(keyword + " " + parts.join(", ") + ";");
}
}
function buildType(type) {
if (type.group)
return; // built with the sister-field
push("");
push("message " + type.name + " {");
++indent;
buildOptions(type);
type.oneofsArray.forEach(build);
first = true;
type.fieldsArray.forEach(build);
consolidateExtends(type.nestedArray).remaining.forEach(build);
buildRanges("extensions", type.extensions);
buildRanges("reserved", type.reserved);
--indent;
push("}");
}
function buildField(field, passExtend) {
if (field.partOf || field.declaringField || field.extend !== undefined && !passExtend)
return;
if (first) {
first = false;
push("");
}
if (field.resolvedType && field.resolvedType.group) {
buildGroup(field);
return;
}
var sb = [];
if (field.map)
sb.push("map<" + field.keyType + ", " + field.type + ">");
else if (field.repeated)
sb.push("repeated", field.type);
else if (syntax === 2 || field.parent.group)
sb.push(field.required ? "required" : "optional", field.type);
else
sb.push(field.type);
sb.push(underScore(field.name), "=", field.id);
var opts = buildFieldOptions(field);
if (opts)
sb.push(opts);
push(sb.join(" ") + ";");
}
function buildGroup(field) {
push(field.rule + " group " + field.resolvedType.name + " = " + field.id + " {");
++indent;
buildOptions(field.resolvedType);
first = true;
field.resolvedType.fieldsArray.forEach(function(field) {
buildField(field);
});
--indent;
push("}");
}
function buildFieldOptions(field) {
var keys;
if (!field.options || !(keys = Object.keys(field.options)).length)
return null;
var sb = [];
keys.forEach(function(key) {
var val = field.options[key];
var wireType = types.packed[field.resolvedType instanceof Enum ? "int32" : field.type];
switch (key) {
case "packed":
val = Boolean(val);
// skip when not packable or syntax default
if (wireType === undefined || syntax === 3 === val)
return;
break;
case "default":
if (syntax === 3)
return;
// skip default (resolved) default values
if (field.long && !util.longNeq(field.defaultValue, types.defaults[field.type]) || !field.long && field.defaultValue === types.defaults[field.type])
return;
// enum defaults specified as strings are type references and not enclosed in quotes
if (field.resolvedType instanceof Enum)
break;
// otherwise fallthrough
default:
val = value(val);
break;
}
sb.push(key + "=" + val);
});
return sb.length
? "[" + sb.join(", ") + "]"
: null;
}
function consolidateExtends(nested) {
var ext = {};
nested = nested.filter(function(obj) {
if (!(obj instanceof Field) || obj.extend === undefined)
return true;
(ext[obj.extend] || (ext[obj.extend] = [])).push(obj);
return false;
});
Object.keys(ext).forEach(function(extend) {
push("");
push("extend " + extend + " {");
++indent; first = true;
ext[extend].forEach(function(field) {
buildField(field, true);
});
--indent;
push("}");
});
return {
remaining: nested
};
}
function buildOneOf(oneof) {
push("");
push("oneof " + underScore(oneof.name) + " {");
++indent; first = true;
oneof.oneof.forEach(function(fieldName) {
var field = oneof.parent.get(fieldName);
if (first) {
first = false;
push("");
}
var opts = buildFieldOptions(field);
push(field.type + " " + underScore(field.name) + " = " + field.id + (opts ? " " + opts : "") + ";");
});
--indent;
push("}");
}
function buildService(service) {
push("service " + service.name + " {");
++indent;
service.methodsArray.forEach(build);
consolidateExtends(service.nestedArray).remaining.forEach(build);
--indent;
push("}");
}
function buildMethod(method) {
push(method.type + " " + method.name + " (" + (method.requestStream ? "stream " : "") + method.requestType + ") returns (" + (method.responseStream ? "stream " : "") + method.responseType + ");");
}
function buildOptions(object) {
if (!object.options)
return;
first = true;
Object.keys(object.options).forEach(function(key) {
if (first) {
first = false;
push("");
}
var val = object.options[key];
push("option " + key + " = " + JSON.stringify(val) + ";");
});
}

10
node_modules/protobufjs/cli/targets/proto2.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
"use strict";
module.exports = proto2_target;
var protobuf = require("../..");
proto2_target.description = "Protocol Buffers, Version 2";
function proto2_target(root, options, callback) {
require("./proto")(root, protobuf.util.merge(options, { syntax: "proto2" }), callback);
}

10
node_modules/protobufjs/cli/targets/proto3.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
"use strict";
module.exports = proto3_target;
var protobuf = require("../..");
proto3_target.description = "Protocol Buffers, Version 3";
function proto3_target(root, options, callback) {
require("./proto")(root, protobuf.util.merge(options, { syntax: "proto3" }), callback);
}

29
node_modules/protobufjs/cli/targets/static-module.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
"use strict";
module.exports = static_module_target;
// - The default wrapper supports AMD, CommonJS and the global scope (as window.root), in this order.
// - You can specify a custom wrapper with the --wrap argument.
// - CommonJS modules depend on the minimal build for reduced package size with browserify.
// - AMD and global scope depend on the full library for now.
var util = require("../util");
var protobuf = require("../..");
static_module_target.description = "Static code without reflection as a module";
function static_module_target(root, options, callback) {
require("./static")(root, options, function(err, output) {
if (err) {
callback(err);
return;
}
try {
output = util.wrap(output, protobuf.util.merge({ dependency: "protobufjs/minimal" }, options));
} catch (e) {
callback(e);
return;
}
callback(null, output);
});
}

702
node_modules/protobufjs/cli/targets/static.js generated vendored Normal file
View File

@ -0,0 +1,702 @@
"use strict";
module.exports = static_target;
var protobuf = require("../.."),
UglifyJS = require("uglify-js"),
espree = require("espree"),
escodegen = require("escodegen"),
estraverse = require("estraverse");
var Type = protobuf.Type,
Service = protobuf.Service,
Enum = protobuf.Enum,
Namespace = protobuf.Namespace,
util = protobuf.util;
var out = [];
var indent = 0;
var config = {};
static_target.description = "Static code without reflection (non-functional on its own)";
function static_target(root, options, callback) {
config = options;
try {
var aliases = [];
if (config.decode)
aliases.push("Reader");
if (config.encode)
aliases.push("Writer");
aliases.push("util");
if (aliases.length) {
if (config.comments)
push("// Common aliases");
push((config.es6 ? "const " : "var ") + aliases.map(function(name) { return "$" + name + " = $protobuf." + name; }).join(", ") + ";");
push("");
}
if (config.comments) {
if (root.comment) {
pushComment("@fileoverview " + root.comment);
push("");
}
push("// Exported root namespace");
}
var rootProp = util.safeProp(config.root || "default");
push((config.es6 ? "const" : "var") + " $root = $protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = {});");
buildNamespace(null, root);
return callback(null, out.join("\n"));
} catch (err) {
return callback(err);
} finally {
out = [];
indent = 0;
config = {};
}
}
function push(line) {
if (line === "")
return out.push("");
var ind = "";
for (var i = 0; i < indent; ++i)
ind += " ";
return out.push(ind + line);
}
function pushComment(lines) {
if (!config.comments)
return;
var split = [];
for (var i = 0; i < lines.length; ++i)
if (lines[i] != null && lines[i].substring(0, 8) !== "@exclude")
Array.prototype.push.apply(split, lines[i].split(/\r?\n/g));
push("/**");
split.forEach(function(line) {
if (line === null)
return;
push(" * " + line.replace(/\*\//g, "* /"));
});
push(" */");
}
function exportName(object, asInterface) {
if (asInterface) {
if (object.__interfaceName)
return object.__interfaceName;
} else if (object.__exportName)
return object.__exportName;
var parts = object.fullName.substring(1).split("."),
i = 0;
while (i < parts.length)
parts[i] = escapeName(parts[i++]);
if (asInterface)
parts[i - 1] = "I" + parts[i - 1];
return object[asInterface ? "__interfaceName" : "__exportName"] = parts.join(".");
}
function escapeName(name) {
if (!name)
return "$root";
return util.isReserved(name) ? name + "_" : name;
}
function aOrAn(name) {
return ((/^[hH](?:ou|on|ei)/.test(name) || /^[aeiouAEIOU][a-z]/.test(name)) && !/^us/i.test(name)
? "an "
: "a ") + name;
}
function buildNamespace(ref, ns) {
if (!ns)
return;
if (ns.name !== "") {
push("");
if (!ref && config.es6)
push("export const " + escapeName(ns.name) + " = " + escapeName(ref) + "." + escapeName(ns.name) + " = (() => {");
else
push(escapeName(ref) + "." + escapeName(ns.name) + " = (function() {");
++indent;
}
if (ns instanceof Type) {
buildType(undefined, ns);
} else if (ns instanceof Service)
buildService(undefined, ns);
else if (ns.name !== "") {
push("");
pushComment([
ns.comment || "Namespace " + ns.name + ".",
ns.parent instanceof protobuf.Root ? "@exports " + escapeName(ns.name) : "@memberof " + exportName(ns.parent),
"@namespace"
]);
push((config.es6 ? "const" : "var") + " " + escapeName(ns.name) + " = {};");
}
ns.nestedArray.forEach(function(nested) {
if (nested instanceof Enum)
buildEnum(ns.name, nested);
else if (nested instanceof Namespace)
buildNamespace(ns.name, nested);
});
if (ns.name !== "") {
push("");
push("return " + escapeName(ns.name) + ";");
--indent;
push("})();");
}
}
var reduceableBlockStatements = {
IfStatement: true,
ForStatement: true,
WhileStatement: true
};
var shortVars = {
"r": "reader",
"w": "writer",
"m": "message",
"t": "tag",
"l": "length",
"c": "end", "c2": "end2",
"k": "key",
"ks": "keys", "ks2": "keys2",
"e": "error",
"f": "impl",
"o": "options",
"d": "object",
"n": "long",
"p": "properties"
};
function beautifyCode(code) {
// Add semicolons
code = UglifyJS.minify(code, {
compress: false,
mangle: false,
output: { beautify: true }
}).code;
// Properly beautify
var ast = espree.parse(code);
estraverse.replace(ast, {
enter: function(node, parent) {
// rename short vars
if (node.type === "Identifier" && (parent.property !== node || parent.computed) && shortVars[node.name])
return {
"type": "Identifier",
"name": shortVars[node.name]
};
// replace var with let if es6
if (config.es6 && node.type === "VariableDeclaration" && node.kind === "var") {
node.kind = "let";
return undefined;
}
// remove braces around block statements with a single child
if (node.type === "BlockStatement" && reduceableBlockStatements[parent.type] && node.body.length === 1)
return node.body[0];
return undefined;
}
});
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
// Add id, wireType comments
if (config.comments)
code = code.replace(/\.uint32\((\d+)\)/g, function($0, $1) {
var id = $1 >>> 3,
wireType = $1 & 7;
return ".uint32(/* id " + id + ", wireType " + wireType + " =*/" + $1 + ")";
});
return code;
}
var renameVars = {
"Writer": "$Writer",
"Reader": "$Reader",
"util": "$util"
};
function buildFunction(type, functionName, gen, scope) {
var code = gen.toString(functionName)
.replace(/((?!\.)types\[\d+])(\.values)/g, "$1"); // enums: use types[N] instead of reflected types[N].values
var ast = espree.parse(code);
/* eslint-disable no-extra-parens */
estraverse.replace(ast, {
enter: function(node, parent) {
// rename vars
if (
node.type === "Identifier" && renameVars[node.name]
&& (
(parent.type === "MemberExpression" && parent.object === node)
|| (parent.type === "BinaryExpression" && parent.right === node)
)
)
return {
"type": "Identifier",
"name": renameVars[node.name]
};
// replace this.ctor with the actual ctor
if (
node.type === "MemberExpression"
&& node.object.type === "ThisExpression"
&& node.property.type === "Identifier" && node.property.name === "ctor"
)
return {
"type": "Identifier",
"name": "$root" + type.fullName
};
// replace types[N] with the field's actual type
if (
node.type === "MemberExpression"
&& node.object.type === "Identifier" && node.object.name === "types"
&& node.property.type === "Literal"
)
return {
"type": "Identifier",
"name": "$root" + type.fieldsArray[node.property.value].resolvedType.fullName
};
return undefined;
}
});
/* eslint-enable no-extra-parens */
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
if (config.beautify)
code = beautifyCode(code);
code = code.replace(/ {4}/g, "\t");
var hasScope = scope && Object.keys(scope).length,
isCtor = functionName === type.name;
if (hasScope) // remove unused scope vars
Object.keys(scope).forEach(function(key) {
if (!new RegExp("\\b(" + key + ")\\b", "g").test(code))
delete scope[key];
});
var lines = code.split(/\n/g);
if (isCtor) // constructor
push(lines[0]);
else if (hasScope) // enclose in an iife
push(escapeName(type.name) + "." + escapeName(functionName) + " = (function(" + Object.keys(scope).map(escapeName).join(", ") + ") { return " + lines[0]);
else
push(escapeName(type.name) + "." + escapeName(functionName) + " = " + lines[0]);
lines.slice(1, lines.length - 1).forEach(function(line) {
var prev = indent;
var i = 0;
while (line.charAt(i++) === "\t")
++indent;
push(line.trim());
indent = prev;
});
if (isCtor)
push("}");
else if (hasScope)
push("};})(" + Object.keys(scope).map(function(key) { return scope[key]; }).join(", ") + ");");
else
push("};");
}
function toJsType(field) {
var type;
switch (field.type) {
case "double":
case "float":
case "int32":
case "uint32":
case "sint32":
case "fixed32":
case "sfixed32":
type = "number";
break;
case "int64":
case "uint64":
case "sint64":
case "fixed64":
case "sfixed64":
type = config.forceLong ? "Long" : config.forceNumber ? "number" : "number|Long";
break;
case "bool":
type = "boolean";
break;
case "string":
type = "string";
break;
case "bytes":
type = "Uint8Array";
break;
default:
if (field.resolve().resolvedType)
type = exportName(field.resolvedType, !(field.resolvedType instanceof protobuf.Enum || config.forceMessage));
else
type = "*"; // should not happen
break;
}
if (field.map)
return "Object.<string," + type + ">";
if (field.repeated)
return "Array.<" + type + ">";
return type;
}
function buildType(ref, type) {
if (config.comments) {
var typeDef = [
"Properties of " + aOrAn(type.name) + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName("I" + type.name) : "@memberof " + exportName(type.parent),
"@interface " + escapeName("I" + type.name)
];
type.fieldsArray.forEach(function(field) {
var prop = util.safeProp(field.name); // either .name or ["name"]
prop = prop.substring(1, prop.charAt(0) === "[" ? prop.length - 1 : prop.length);
var jsType = toJsType(field);
if (field.optional)
jsType = jsType + "|null";
typeDef.push("@property {" + jsType + "} " + (field.optional ? "[" + prop + "]" : prop) + " " + (field.comment || type.name + " " + field.name));
});
push("");
pushComment(typeDef);
}
// constructor
push("");
pushComment([
"Constructs a new " + type.name + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName(type.name) : "@memberof " + exportName(type.parent),
"@classdesc " + (type.comment || "Represents " + aOrAn(type.name) + "."),
config.comments ? "@implements " + escapeName("I" + type.name) : null,
"@constructor",
"@param {" + exportName(type, true) + "=} [" + (config.beautify ? "properties" : "p") + "] Properties to set"
]);
buildFunction(type, type.name, Type.generateConstructor(type));
// default values
var firstField = true;
type.fieldsArray.forEach(function(field) {
field.resolve();
var prop = util.safeProp(field.name);
if (config.comments) {
push("");
var jsType = toJsType(field);
if (field.optional && !field.map && !field.repeated && field.resolvedType instanceof Type)
jsType = jsType + "|null|undefined";
pushComment([
field.comment || type.name + " " + field.name + ".",
"@member {" + jsType + "} " + field.name,
"@memberof " + exportName(type),
"@instance"
]);
} else if (firstField) {
push("");
firstField = false;
}
if (field.repeated)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyArray;"); // overwritten in constructor
else if (field.map)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyObject;"); // overwritten in constructor
else if (field.long)
push(escapeName(type.name) + ".prototype" + prop + " = $util.Long ? $util.Long.fromBits("
+ JSON.stringify(field.typeDefault.low) + ","
+ JSON.stringify(field.typeDefault.high) + ","
+ JSON.stringify(field.typeDefault.unsigned)
+ ") : " + field.typeDefault.toNumber(field.type.charAt(0) === "u") + ";");
else if (field.bytes) {
push(escapeName(type.name) + ".prototype" + prop + " = $util.newBuffer(" + JSON.stringify(Array.prototype.slice.call(field.typeDefault)) + ");");
} else
push(escapeName(type.name) + ".prototype" + prop + " = " + JSON.stringify(field.typeDefault) + ";");
});
// virtual oneof fields
var firstOneOf = true;
type.oneofsArray.forEach(function(oneof) {
if (firstOneOf) {
firstOneOf = false;
push("");
if (config.comments)
push("// OneOf field names bound to virtual getters and setters");
push((config.es6 ? "let" : "var") + " $oneOfFields;");
}
oneof.resolve();
push("");
pushComment([
oneof.comment || type.name + " " + oneof.name + ".",
"@member {" + oneof.oneof.map(JSON.stringify).join("|") + "|undefined} " + escapeName(oneof.name),
"@memberof " + exportName(type),
"@instance"
]);
push("Object.defineProperty(" + escapeName(type.name) + ".prototype, " + JSON.stringify(oneof.name) +", {");
++indent;
push("get: $util.oneOfGetter($oneOfFields = [" + oneof.oneof.map(JSON.stringify).join(", ") + "]),");
push("set: $util.oneOfSetter($oneOfFields)");
--indent;
push("});");
});
if (config.create) {
push("");
pushComment([
"Creates a new " + type.name + " instance using the specified properties.",
"@function create",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, true) + "=} [properties] Properties to set",
"@returns {" + exportName(type) + "} " + type.name + " instance"
]);
push(escapeName(type.name) + ".create = function create(properties) {");
++indent;
push("return new " + escapeName(type.name) + "(properties);");
--indent;
push("};");
}
if (config.encode) {
push("");
pushComment([
"Encodes the specified " + type.name + " message. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encode",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} " + (config.beautify ? "message" : "m") + " " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [" + (config.beautify ? "writer" : "w") + "] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
buildFunction(type, "encode", protobuf.encoder(type));
if (config.delimited) {
push("");
pushComment([
"Encodes the specified " + type.name + " message, length delimited. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} message " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [writer] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
push(escapeName(type.name) + ".encodeDelimited = function encodeDelimited(message, writer) {");
++indent;
push("return this.encode(message, writer).ldelim();");
--indent;
push("};");
}
}
if (config.decode) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer.",
"@function decode",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} " + (config.beautify ? "reader" : "r") + " Reader or buffer to decode from",
"@param {number} [" + (config.beautify ? "length" : "l") + "] Message length if known beforehand",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
buildFunction(type, "decode", protobuf.decoder(type));
if (config.delimited) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer, length delimited.",
"@function decodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
push(escapeName(type.name) + ".decodeDelimited = function decodeDelimited(reader) {");
++indent;
push("if (!(reader instanceof $Reader))");
++indent;
push("reader = new $Reader(reader);");
--indent;
push("return this.decode(reader, reader.uint32());");
--indent;
push("};");
}
}
if (config.verify) {
push("");
pushComment([
"Verifies " + aOrAn(type.name) + " message.",
"@function verify",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "message" : "m") + " Plain object to verify",
"@returns {string|null} `null` if valid, otherwise the reason why it is not"
]);
buildFunction(type, "verify", protobuf.verifier(type));
}
if (config.convert) {
push("");
pushComment([
"Creates " + aOrAn(type.name) + " message from a plain object. Also converts values to their respective internal types.",
"@function fromObject",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "object" : "d") + " Plain object",
"@returns {" + exportName(type) + "} " + type.name
]);
buildFunction(type, "fromObject", protobuf.converter.fromObject(type));
push("");
pushComment([
"Creates a plain object from " + aOrAn(type.name) + " message. Also converts values to other types if specified.",
"@function toObject",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type) + "} " + (config.beautify ? "message" : "m") + " " + type.name,
"@param {$protobuf.IConversionOptions} [" + (config.beautify ? "options" : "o") + "] Conversion options",
"@returns {Object.<string,*>} Plain object"
]);
buildFunction(type, "toObject", protobuf.converter.toObject(type));
push("");
pushComment([
"Converts this " + type.name + " to JSON.",
"@function toJSON",
"@memberof " + exportName(type),
"@instance",
"@returns {Object.<string,*>} JSON object"
]);
push(escapeName(type.name) + ".prototype.toJSON = function toJSON() {");
++indent;
push("return this.constructor.toObject(this, $protobuf.util.toJSONOptions);");
--indent;
push("};");
}
}
function buildService(ref, service) {
push("");
pushComment([
"Constructs a new " + service.name + " service.",
service.parent instanceof protobuf.Root ? "@exports " + escapeName(service.name) : "@memberof " + exportName(service.parent),
"@classdesc " + (service.comment || "Represents " + aOrAn(service.name)),
"@extends $protobuf.rpc.Service",
"@constructor",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited"
]);
push("function " + escapeName(service.name) + "(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("$protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("}");
push("");
push("(" + escapeName(service.name) + ".prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = " + escapeName(service.name) + ";");
if (config.create) {
push("");
pushComment([
"Creates new " + service.name + " service using the specified rpc implementation.",
"@function create",
"@memberof " + exportName(service),
"@static",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited",
"@returns {" + escapeName(service.name) + "} RPC service. Useful where requests and/or responses are streamed."
]);
push(escapeName(service.name) + ".create = function create(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("return new this(rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("};");
}
service.methodsArray.forEach(function(method) {
method.resolve();
var lcName = protobuf.util.lcFirst(method.name),
cbName = escapeName(method.name + "Callback");
push("");
pushComment([
"Callback as used by {@link " + exportName(service) + "#" + escapeName(lcName) + "}.",
// This is a more specialized version of protobuf.rpc.ServiceCallback
"@memberof " + exportName(service),
"@typedef " + cbName,
"@type {function}",
"@param {Error|null} error Error, if any",
"@param {" + exportName(method.resolvedResponseType) + "} [response] " + method.resolvedResponseType.name
]);
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@param {" + exportName(service) + "." + cbName + "} callback Node-style callback called with the error, if any, and " + method.resolvedResponseType.name,
"@returns {undefined}",
"@variation 1"
]);
push("Object.defineProperty(" + escapeName(service.name) + ".prototype" + util.safeProp(lcName) + " = function " + escapeName(lcName) + "(request, callback) {");
++indent;
push("return this.rpcCall(" + escapeName(lcName) + ", $root." + exportName(method.resolvedRequestType) + ", $root." + exportName(method.resolvedResponseType) + ", request, callback);");
--indent;
push("}, \"name\", { value: " + JSON.stringify(method.name) + " });");
if (config.comments)
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@returns {Promise<" + exportName(method.resolvedResponseType) + ">} Promise",
"@variation 2"
]);
});
}
function buildEnum(ref, enm) {
push("");
var comment = [
enm.comment || enm.name + " enum.",
enm.parent instanceof protobuf.Root ? "@exports " + escapeName(enm.name) : "@name " + exportName(enm),
config.forceEnumString ? "@enum {number}" : "@enum {string}",
];
Object.keys(enm.values).forEach(function(key) {
var val = config.forceEnumString ? key : enm.values[key];
comment.push((config.forceEnumString ? "@property {string} " : "@property {number} ") + key + "=" + val + " " + (enm.comments[key] || key + " value"));
});
pushComment(comment);
push(escapeName(ref) + "." + escapeName(enm.name) + " = (function() {");
++indent;
push((config.es6 ? "const" : "var") + " valuesById = {}, values = Object.create(valuesById);");
var aliased = [];
Object.keys(enm.values).forEach(function(key) {
var valueId = enm.values[key];
var val = config.forceEnumString ? JSON.stringify(key) : valueId;
if (aliased.indexOf(valueId) > -1)
push("values[" + JSON.stringify(key) + "] = " + val + ";");
else {
push("values[valuesById[" + valueId + "] = " + JSON.stringify(key) + "] = " + val + ";");
aliased.push(valueId);
}
});
push("return values;");
--indent;
push("})();");
}

183
node_modules/protobufjs/cli/util.js generated vendored Normal file
View File

@ -0,0 +1,183 @@
"use strict";
var fs = require("fs"),
path = require("path"),
child_process = require("child_process");
var semver;
try {
// installed as a peer dependency
require.resolve("protobufjs");
exports.pathToProtobufJs = "protobufjs";
} catch (e) {
// local development, i.e. forked from github
exports.pathToProtobufJs = "..";
}
var protobuf = require(exports.pathToProtobufJs);
function basenameCompare(a, b) {
var aa = String(a).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g),
bb = String(b).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g);
for (var i = 0, k = Math.min(aa.length, bb.length); i < k; i++) {
var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
y = parseFloat(bb[i]) || bb[i].toLowerCase();
if (x < y)
return -1;
if (x > y)
return 1;
}
return a.length < b.length ? -1 : 0;
}
exports.requireAll = function requireAll(dirname) {
dirname = path.join(__dirname, dirname);
var files = fs.readdirSync(dirname).sort(basenameCompare),
all = {};
files.forEach(function(file) {
var basename = path.basename(file, ".js"),
extname = path.extname(file);
if (extname === ".js")
all[basename] = require(path.join(dirname, file));
});
return all;
};
exports.traverse = function traverse(current, fn) {
fn(current);
if (current.fieldsArray)
current.fieldsArray.forEach(function(field) {
traverse(field, fn);
});
if (current.oneofsArray)
current.oneofsArray.forEach(function(oneof) {
traverse(oneof, fn);
});
if (current.methodsArray)
current.methodsArray.forEach(function(method) {
traverse(method, fn);
});
if (current.nestedArray)
current.nestedArray.forEach(function(nested) {
traverse(nested, fn);
});
};
exports.traverseResolved = function traverseResolved(current, fn) {
fn(current);
if (current.resolvedType)
traverseResolved(current.resolvedType, fn);
if (current.resolvedKeyType)
traverseResolved(current.resolvedKeyType, fn);
if (current.resolvedRequestType)
traverseResolved(current.resolvedRequestType, fn);
if (current.resolvedResponseType)
traverseResolved(current.resolvedResponseType, fn);
};
exports.inspect = function inspect(object, indent) {
if (!object)
return "";
var chalk = require("chalk");
var sb = [];
if (!indent)
indent = "";
var ind = indent ? indent.substring(0, indent.length - 2) + "└ " : "";
sb.push(
ind + chalk.bold(object.toString()) + (object.visible ? " (visible)" : ""),
indent + chalk.gray("parent: ") + object.parent
);
if (object instanceof protobuf.Field) {
if (object.extend !== undefined)
sb.push(indent + chalk.gray("extend: ") + object.extend);
if (object.partOf)
sb.push(indent + chalk.gray("oneof : ") + object.oneof);
}
sb.push("");
if (object.fieldsArray)
object.fieldsArray.forEach(function(field) {
sb.push(inspect(field, indent + " "));
});
if (object.oneofsArray)
object.oneofsArray.forEach(function(oneof) {
sb.push(inspect(oneof, indent + " "));
});
if (object.methodsArray)
object.methodsArray.forEach(function(service) {
sb.push(inspect(service, indent + " "));
});
if (object.nestedArray)
object.nestedArray.forEach(function(nested) {
sb.push(inspect(nested, indent + " "));
});
return sb.join("\n");
};
function modExists(name, version) {
for (var i = 0; i < module.paths.length; ++i) {
try {
var pkg = JSON.parse(fs.readFileSync(path.join(module.paths[i], name, "package.json")));
return semver
? semver.satisfies(pkg.version, version)
: parseInt(pkg.version, 10) === parseInt(version.replace(/^[\^~]/, ""), 10); // used for semver only
} catch (e) {/**/}
}
return false;
}
function modInstall(install) {
child_process.execSync("npm --silent install " + (typeof install === "string" ? install : install.join(" ")), {
cwd: __dirname,
stdio: "ignore"
});
}
exports.setup = function() {
var pkg = require(path.join(__dirname, "..", "package.json"));
var version = pkg.dependencies["semver"] || pkg.devDependencies["semver"];
if (!modExists("semver", version)) {
process.stderr.write("installing semver@" + version + "\n");
modInstall("semver@" + version);
}
semver = require("semver"); // used from now on for version comparison
var install = [];
pkg.cliDependencies.forEach(function(name) {
if (name === "semver")
return;
version = pkg.dependencies[name] || pkg.devDependencies[name];
if (!modExists(name, version)) {
process.stderr.write("installing " + name + "@" + version + "\n");
install.push(name + "@" + version);
}
});
require("../scripts/postinstall"); // emit postinstall warning, if any
if (!install.length)
return;
modInstall(install);
};
exports.wrap = function(OUTPUT, options) {
var name = options.wrap || "default";
var wrap;
try {
// try built-in wrappers first
wrap = fs.readFileSync(path.join(__dirname, "wrappers", name + ".js")).toString("utf8");
} catch (e) {
// otherwise fetch the custom one
wrap = fs.readFileSync(path.resolve(process.cwd(), name)).toString("utf8");
}
wrap = wrap.replace(/\$DEPENDENCY/g, JSON.stringify(options.dependency || "protobufjs"));
wrap = wrap.replace(/( *)\$OUTPUT;/, function($0, $1) {
return $1.length ? OUTPUT.replace(/^/mg, $1) : OUTPUT;
});
if (options.lint !== "")
wrap = "/*" + options.lint + "*/\n" + wrap;
return wrap.replace(/\r?\n/g, "\n");
};
exports.pad = function(str, len, l) {
while (str.length < len)
str = l ? str + " " : " " + str;
return str;
};

7
node_modules/protobufjs/cli/wrappers/amd.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
define([$DEPENDENCY], function($protobuf) {
"use strict";
$OUTPUT;
return $root;
});

7
node_modules/protobufjs/cli/wrappers/closure.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
(function($protobuf) {
"use strict";
$OUTPUT;
return $root;
})(protobuf);

7
node_modules/protobufjs/cli/wrappers/commonjs.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
"use strict";
var $protobuf = require($DEPENDENCY);
$OUTPUT;
module.exports = $root;

15
node_modules/protobufjs/cli/wrappers/default.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
(function(global, factory) { /* global define, require, module */
/* AMD */ if (typeof define === 'function' && define.amd)
define([$DEPENDENCY], factory);
/* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports)
module.exports = factory(require($DEPENDENCY));
})(this, function($protobuf) {
"use strict";
$OUTPUT;
return $root;
});

5
node_modules/protobufjs/cli/wrappers/es6.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
import * as $protobuf from $DEPENDENCY;
$OUTPUT;
export { $root as default };