protobufjs
Version:
Protocol Buffers for JavaScript & TypeScript.
1,402 lines (1,261 loc) • 281 kB
JavaScript
/*!
* protobuf.js v8.6.6 (c) 2016, daniel wirtz
* compiled sat, 04 jul 2026 01:09:57 utc
* licensed under the bsd-3-clause license
* see: https://github.com/dcodeio/protobuf.js for details
*/
(function(undefined){"use strict";(function prelude(modules, cache, entries) {
// This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS
// sources through a conflict-free require shim and is again wrapped within an iife that
// provides a minification-friendly `undefined` var plus a global "use strict" directive
// so that minification can remove the directives of each module.
function $require(name) {
var $module = cache[name];
if (!$module)
modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);
return $module.exports;
}
var protobuf = $require(entries[0]);
// Expose globally
protobuf.util.global.protobuf = protobuf;
// Be nice to AMD
if (typeof define === "function" && define.amd)
define(["long"], function(Long) {
if (Long && Long.isLong) {
protobuf.util.Long = Long;
protobuf.configure();
}
return protobuf;
});
// Be nice to CommonJS
if (typeof module === "object" && module && module.exports)
module.exports = protobuf;
})/* end of prelude */({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
"use strict";
/**
* Runtime message from/to plain object converters.
* @namespace
*/
var converter = exports;
var Enum = require(5),
types = require(23),
util = require(24);
/**
* Generates a partial value fromObject conveter.
* @param {Codegen} gen Codegen instance
* @param {Field} field Reflected field
* @param {number} fieldIndex Field index
* @param {string} prop Property reference
* @param {string} [dstProp] Repeated destination property reference
* @returns {Codegen} Codegen instance
* @ignore
*/
function genValuePartial_fromObject(gen, field, fieldIndex, prop, dstProp) {
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
var dst = dstProp
? "m" + dstProp + "[m" + dstProp + ".length]"
: "m" + prop;
gen
("switch(d%s){", prop);
for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { gen
("case%j:", keys[i])
("case %i:", values[keys[i]])
("%s=%j", dst, values[keys[i]])
("break");
}
gen
("default:");
if (field.resolvedType._features.enum_type !== "CLOSED") {
gen
("if(typeof d%s===\"number\"&&(d%s|0)===d%s)", prop, prop, prop)
("%s=d%s", dst, prop);
}
gen
("}");
} else gen
("if(!util.isObject(d%s))", prop)
("throw TypeError(%j)", field.fullName + ": object expected")
("m%s=types[%i].fromObject(d%s,q+1)", prop, fieldIndex, prop);
} else {
var isUnsigned = false;
switch (field.type) {
case "double":
case "float": gen
("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"
break;
case "uint32":
case "fixed32": gen
("m%s=d%s>>>0", prop, prop);
break;
case "int32":
case "sint32":
case "sfixed32": gen
("m%s=d%s|0", prop, prop);
break;
case "uint64":
case "fixed64":
isUnsigned = true;
// eslint-disable-next-line no-fallthrough
case "int64":
case "sint64":
case "sfixed64": gen
("if(util.Long)")
("m%s=util.Long.fromValue(d%s,%j)", prop, prop, isUnsigned)
("else if(typeof d%s===\"string\")", prop)
("m%s=parseInt(d%s,10)", prop, prop)
("else if(typeof d%s===\"number\")", prop)
("m%s=d%s", prop, prop)
("else if(typeof d%s===\"object\")", prop)
("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
break;
case "bytes": gen
("if(typeof d%s===\"string\")", prop)
("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)
("else if(d%s.length>=0)", prop)
("m%s=d%s", prop, prop);
break;
case "string": gen
("m%s=String(d%s)", prop, prop);
break;
case "bool": gen
("m%s=Boolean(d%s)", prop, prop);
break;
/* default: gen
("m%s=d%s", prop, prop);
break; */
}
}
return gen;
/* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
}
/**
* Generates a plain object to runtime message converter specific to the specified message type.
* @param {Type} mtype Message type
* @returns {Codegen} Codegen instance
*/
converter.fromObject = function fromObject(mtype) {
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
var fields = mtype.fieldsArray;
var gen = util.codegen(["d", "q"])
("if(d instanceof C)")
("return d")
("if(!util.isObject(d))")
("throw TypeError(%j)", mtype.fullName + ": object expected")
("if(q===undefined)q=0")
("if(q>util.recursionLimit)")
("throw Error(\"max depth exceeded\")");
if (!fields.length) return gen
("return new C");
gen
("var m=new C");
for (var i = 0; i < fields.length; ++i) {
var field = fields[i].resolve(),
prop = util.safeProp(field.name),
implicitPresence = !field.hasPresence && !field.repeated && !field.map
&& (field.resolvedType instanceof Enum || types.basic[field.type] !== undefined);
// Map fields
if (field.map) { gen
("if(d%s){", prop)
("if(!util.isObject(d%s))", prop)
("throw TypeError(%j)", field.fullName + ": object expected")
("m%s={}", prop)
("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
gen
("if(ks[i]===\"__proto__\")")
("util.makeProp(m%s,ks[i])", prop);
genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")
("}")
("}");
// Repeated fields
} else if (field.repeated) { gen
("if(d%s){", prop)
("if(!Array.isArray(d%s))", prop)
("throw TypeError(%j)", field.fullName + ": array expected");
if (field.resolvedType instanceof Enum) gen
("m%s=[]", prop);
else gen
("m%s=Array(d%s.length)", prop, prop);
gen
("for(var i=0;i<d%s.length;++i){", prop);
genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]", field.resolvedType instanceof Enum ? prop : undefined)
("}")
("}");
// Non-repeated fields
} else {
if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)
("if(d%s!=null){", prop); // !== undefined && !== null
if (implicitPresence) {
if (field.resolvedType instanceof Enum) gen
("if(d%s!==%j&&(typeof d%s!==\"string\"||types[%i].values[d%s]!==%j)){", prop, field.typeDefault, prop, i, prop, field.typeDefault);
else if (field.type === "string") gen
("if(typeof d%s!==\"string\"||d%s.length){", prop, prop);
else if (field.type === "bytes") gen
("if(d%s.length){", prop);
else if (field.type === "bool") gen
("if(d%s){", prop);
else if (field.type === "double" || field.type === "float") gen
("if(!Object.is(Number(d%s),0)){", prop);
else if (types.long[field.type] !== undefined) gen
("if(typeof d%s===\"object\"?d%s.low||d%s.high:Number(d%s)!==0){", prop, prop, prop, prop);
else gen
("if(Number(d%s)!==0){", prop);
}
genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);
if (implicitPresence) gen
("}");
if (!(field.resolvedType instanceof Enum)) gen
("}");
}
} return gen
("return m");
/* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
};
/**
* Generates a partial value toObject converter.
* @param {Codegen} gen Codegen instance
* @param {Field} field Reflected field
* @param {number} fieldIndex Field index
* @param {string} dstProp Destination property reference
* @param {string} [srcProp] Source property reference
* @returns {Codegen} Codegen instance
* @ignore
*/
function genValuePartial_toObject(gen, field, fieldIndex, dstProp, srcProp) {
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
if (!srcProp)
srcProp = dstProp;
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) gen
("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", dstProp, fieldIndex, srcProp, srcProp, fieldIndex, srcProp, srcProp);
else gen
("d%s=types[%i].toObject(m%s,o,q+1)", dstProp, fieldIndex, srcProp);
} else {
var isUnsigned = false;
switch (field.type) {
case "double":
case "float": gen
("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", dstProp, srcProp, srcProp, srcProp);
break;
case "uint64":
case "fixed64":
isUnsigned = true;
// eslint-disable-next-line no-fallthrough
case "int64":
case "sint64":
case "sfixed64": gen
("if(typeof BigInt!==\"undefined\"&&o.longs===BigInt)")
("d%s=typeof m%s===\"number\"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()", dstProp, srcProp, srcProp, srcProp, srcProp, isUnsigned)
("else if(typeof m%s===\"number\")", srcProp)
("d%s=o.longs===String?String(m%s):m%s", dstProp, srcProp, srcProp)
("else") // Long-like
("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", dstProp, srcProp, srcProp, srcProp, isUnsigned ? "true": "", srcProp);
break;
case "bytes": gen
("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", dstProp, srcProp, srcProp, srcProp, srcProp);
break;
default: gen
("d%s=m%s", dstProp, srcProp);
break;
}
}
return gen;
/* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
}
/**
* Generates a runtime message to plain object converter specific to the specified message type.
* @param {Type} mtype Message type
* @returns {Codegen} Codegen instance
*/
converter.toObject = function toObject(mtype) {
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
if (!fields.length)
return util.codegen()("return {}");
var gen = util.codegen(["m", "o", "q"])
("if(!o)")
("o={}")
("if(q===undefined)q=0")
("if(q>util.recursionLimit)")
("throw Error(\"max depth exceeded\")")
("var d={}");
var repeatedFields = [],
mapFields = [],
normalFields = [],
i = 0;
for (; i < fields.length; ++i)
if (!fields[i].partOf)
( fields[i].resolve().repeated ? repeatedFields
: fields[i].map ? mapFields
: normalFields).push(fields[i]);
if (repeatedFields.length) { gen
("if(o.arrays||o.defaults){");
for (i = 0; i < repeatedFields.length; ++i) gen
("d%s=[]", util.safeProp(repeatedFields[i].name));
gen
("}");
}
if (mapFields.length) { gen
("if(o.objects||o.defaults){");
for (i = 0; i < mapFields.length; ++i) gen
("d%s={}", util.safeProp(mapFields[i].name));
gen
("}");
}
if (normalFields.length) { gen
("if(o.defaults){");
for (i = 0; i < normalFields.length; ++i) {
var field = normalFields[i],
prop = util.safeProp(field.name);
if (field.resolvedType instanceof Enum) gen
("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
else if (field.long) gen
("if(util.Long){")
("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)
("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!==\"undefined\"&&o.longs===BigInt?n.toBigInt():n", prop)
("}else")
("d%s=o.longs===String?%j:typeof BigInt!==\"undefined\"&&o.longs===BigInt?BigInt(%j):%i", prop, field.typeDefault.toString(), field.typeDefault.toString(), field.typeDefault.toNumber());
else if (field.bytes) {
var arrayDefault = Array.prototype.slice.call(field.typeDefault);
gen
("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))
("else{")
("d%s=%j", prop, arrayDefault)
("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)
("}");
} else gen
("d%s=%j", prop, field.typeDefault); // also messages (=null)
} gen
("}");
}
var hasKs2 = false;
for (i = 0; i < fields.length; ++i) {
var field = fields[i],
index = mtype._fieldsArray.indexOf(field),
prop = util.safeProp(field.name);
if (field.map) {
if (!hasKs2) { hasKs2 = true; gen
("var ks2");
} gen
("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)
("d%s={}", prop);
var longKey = types.long[field.keyType] !== undefined,
srcProp = prop + "[ks2[j]]";
gen
("for(var j=0;j<ks2.length;++j){");
if (longKey) gen
("var k2=util.longFromKey(ks2[j],%j).toString()", field.keyType === "uint64" || field.keyType === "fixed64");
gen
("if(ks2[j]===\"__proto__\")")
("util.makeProp(d%s,ks2[j])", prop);
genValuePartial_toObject(gen, field, /* sorted */ index, longKey ? prop + "[k2]" : srcProp, srcProp)
("}");
} else if (field.repeated) { gen
("if(m%s&&m%s.length){", prop, prop)
("d%s=Array(m%s.length)", prop, prop)
("for(var j=0;j<m%s.length;++j){", prop);
genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")
("}");
} else { gen
("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){", prop, field.name); // !== undefined && !== null
genValuePartial_toObject(gen, field, /* sorted */ index, prop);
if (field.partOf && !field.partOf.isProto3Optional) gen
("if(o.oneofs)")
("d%s=%j", util.safeProp(field.partOf.name), field.name);
}
gen
("}");
}
return gen
("return d");
/* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
};
},{"23":23,"24":24,"5":5}],3:[function(require,module,exports){
"use strict";
module.exports = decoder;
var Enum = require(5),
types = require(23),
util = require(24);
function missing(field) {
return "missing required '" + field.name + "'";
}
function stringMethod(field) {
return field._features.utf8_validation === "VERIFY" ? "stringVerify" : "string";
}
function genPreserveUnknown(gen, ref) {
/* eslint-disable no-unexpected-multiline */
return gen
("if(!r.discardUnknown){")
("util.makeProp(m,\"$unknowns\",false);")
("(m.$unknowns||(m.$unknowns=[])).push(%s)", ref)
("}");
/* eslint-enable no-unexpected-multiline */
}
/**
* Generates a decoder specific to the specified message type.
* @param {Type} mtype Message type
* @returns {Codegen} Codegen instance
*/
function decoder(mtype) {
/* eslint-disable no-unexpected-multiline */
var hasMapField = false,
needsValueVar = false,
i = 0;
for (; i < mtype.fieldsArray.length; ++i) {
var pfield = mtype._fieldsArray[i];
if (pfield.map)
hasMapField = true;
if (pfield.resolvedType instanceof Enum || !pfield.repeated && !pfield.map && !pfield.hasPresence)
needsValueVar = true;
}
var gen = util.codegen(["r", "l", "z", "q", "g"])
("if(!(r instanceof Reader))")
("r=Reader.create(r)")
("if(q===undefined)q=0")
("if(q>Reader.recursionLimit)")
("throw Error(\"max depth exceeded\")")
("var c=l===undefined?r.len:r.pos+l,m=g||new C" + (hasMapField ? ",k,v" : needsValueVar ? ",v" : ""))
("while(r.pos<c){")
("var s=r.pos")
("var t=r.tag()")
("if(t===z){")
("z=undefined")
("break")
("}");
if (mtype.fieldsArray.length) gen
("var u=t&7")
("switch(t>>>=3){");
for (i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
var field = mtype._fieldsArray[i].resolve(),
type = field.resolvedType instanceof Enum ? "int32" : field.type,
ref = "m" + util.safeProp(field.name),
closed = field.resolvedType instanceof Enum && field.resolvedType._features.enum_type === "CLOSED";
// Map fields
if (field.map) {
gen
("case %i:{", field.id)
("if(u!==2)")
("break");
if (!closed) gen
("if(%s===util.emptyObject)", ref)
("%s={}", ref);
gen
("var c2=r.uint32()+r.pos");
if (types.defaults[field.keyType] !== undefined) gen
("k=%j", types.defaults[field.keyType]);
else gen
("k=null");
if (types.long[type] !== undefined) gen
("v=util.Long?util.Long.fromNumber(0,%j):0", type === "uint64" || type === "fixed64");
else if (types.defaults[type] !== undefined) gen
("v=%j", types.defaults[type]);
else gen
("v=null");
gen
("while(r.pos<c2){")
("var t2=r.tag()")
("u=t2&7")
("switch(t2>>>=3){")
("case 1:")
("if(u!==%i)", types.mapKey[field.keyType])
("break")
("k=r.%s()", field.keyType === "string" ? stringMethod(field) : field.keyType)
("continue")
("case 2:")
("if(u!==%i)", types.basic[type] === undefined ? 2 : types.basic[type])
("break");
if (types.basic[type] === undefined) gen
("v=types[%i].decode(r,r.uint32(),undefined,q+1)", i); // can't be groups
else gen
("v=r.%s()", type === "string" ? stringMethod(field) : type);
gen
("continue")
("}")
("r.skipType(u,q,t2)")
("}");
if (closed) { gen
("if(types[%i].valuesById[v]===undefined){", i);
genPreserveUnknown(gen, "r.raw(s,r.pos)")
("continue")
("}")
("if(%s===util.emptyObject)", ref)
("%s={}", ref);
}
var val = types.basic[type] === undefined ? "v||new types[" + i + "].ctor" : "v";
if (types.long[field.keyType] !== undefined) gen
("%s[typeof k===\"object\"?util.longToHash(k):k]=%s", ref, val);
else {
if (field.keyType === "string") gen
("if(k===\"__proto__\")")
("util.makeProp(%s,k)", ref);
gen
("%s[k]=%s", ref, val);
}
// Repeated fields
} else if (field.repeated) { gen
("case %i:", field.id)
("{");
// Packable (always check for forward and backward compatiblity)
if (types.packed[type] !== undefined) {
gen
("if(u===2){");
if (!closed) gen
("if(!(%s&&%s.length))", ref, ref)
("%s=[]", ref);
gen
("var c2=r.uint32()+r.pos");
if (closed) {
gen
("while(r.pos<c2){")
("s=r.pos")
("v=r.%s()", type)
("if(types[%i].valuesById[v]!==undefined){", i)
("if(!(%s&&%s.length))", ref, ref)
("%s=[]", ref)
("%s.push(v)", ref)
("}else");
genPreserveUnknown(gen, "util.rawField(" + field.id + ",0,r.raw(s,r.pos))")
("}");
} else gen
("while(r.pos<c2)")
("%s.push(r.%s())", ref, type);
gen
("continue")
("}");
}
// Non-packed
gen
("if(u!==%i)", types.basic[type] === undefined ? field.delimited ? 3 : 2 : types.basic[type])
("break");
if (!closed) gen
("if(!(%s&&%s.length))", ref, ref)
("%s=[]", ref);
if (types.basic[type] === undefined) {
if (field.delimited) gen
("%s.push(types[%i].decode(r,undefined,%i,q+1))", ref, i, field.id * 8 + 4);
else gen
("%s.push(types[%i].decode(r,r.uint32(),undefined,q+1))", ref, i);
} else if (closed) { gen
("v=r.%s()", type)
("if(types[%i].valuesById[v]!==undefined){", i)
("if(!(%s&&%s.length))", ref, ref)
("%s=[]", ref)
("%s.push(v)", ref)
("}else");
genPreserveUnknown(gen, "r.raw(s,r.pos)");
} else gen
("%s.push(r.%s())", ref, type === "string" ? stringMethod(field) : type);
// Non-repeated
} else if (types.basic[type] === undefined) {
gen
("case %i:{", field.id)
("if(u!==%i)", field.delimited ? 3 : 2)
("break");
if (field.delimited) gen
("%s=types[%i].decode(r,undefined,%i,q+1,%s)", ref, i, field.id * 8 + 4, ref);
else gen
("%s=types[%i].decode(r,r.uint32(),undefined,q+1,%s)", ref, i, ref);
}
else if (field.hasPresence) {
gen
("case %i:{", field.id)
("if(u!==%i)", types.basic[type])
("break");
if (closed) { gen
("v=r.%s()", type)
("if(types[%i].valuesById[v]!==undefined){", i)
("%s=v", ref);
if (field.partOf) gen
("m%s=%j", util.safeProp(field.partOf.name), field.name);
gen
("}else");
genPreserveUnknown(gen, "r.raw(s,r.pos)");
} else gen
("%s=r.%s()", ref, type === "string" ? stringMethod(field) : type);
} else {
gen
("case %i:{", field.id)
("if(u!==%i)", types.basic[type])
("break");
if (closed) { gen
("v=r.%s()", type)
("if(types[%i].valuesById[v]!==undefined){", i)
("if(v!==%j)", field.typeDefault)
("%s=v", ref)
("else")
("delete %s", ref)
("}else{");
genPreserveUnknown(gen, "r.raw(s,r.pos)")
("}");
} else {
if (field.resolvedType instanceof Enum && field.typeDefault !== 0) gen
// TODO: Protoc rejects open enums whose first value is not zero.
// We should do the same, but for v8 this would be a regression.
("if((v=r.%s())!==%j)", type, field.typeDefault);
else if (type === "string") gen
("if((v=r.%s()).length)", stringMethod(field));
else if (type === "bytes") gen
("if((v=r.%s()).length)", type);
else if (types.long[type] !== undefined) gen
("if(typeof(v=r.%s())===\"object\"?v.low||v.high:v!==0)", type);
else if (type === "double" || type === "float") gen
("if(!Object.is(v=r.%s(),0))", type);
else gen
("if(v=r.%s())", type);
gen
("%s=v", ref)
("else")
("delete %s", ref); // rare/odd case: later default clears earlier non-default
}
}
if (field.partOf && !closed) gen
("m%s=%j", util.safeProp(field.partOf.name), field.name);
gen
("continue")
("}");
}
if (i) gen
("}");
// Unknown fields
gen
("r.skipType(%s,q,t)", i ? "u" : "t&7");
genPreserveUnknown(gen, "r.raw(s,r.pos)")
("}")
("if(z!==undefined)")
("throw Error(\"missing end group\")");
// Field presence
for (i = 0; i < mtype._fieldsArray.length; ++i) {
var rfield = mtype._fieldsArray[i];
if (rfield.required) gen
("if(!Object.hasOwnProperty.call(m,%j))", rfield.name)
("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
}
return gen
("return m");
/* eslint-enable no-unexpected-multiline */
}
},{"23":23,"24":24,"5":5}],4:[function(require,module,exports){
"use strict";
module.exports = encoder;
var Enum = require(5),
types = require(23),
util = require(24);
/**
* Generates a partial message type encoder.
* @param {Codegen} gen Codegen instance
* @param {Field} field Reflected field
* @param {number} fieldIndex Field index
* @param {string} ref Variable reference
* @returns {Codegen} Codegen instance
* @ignore
*/
function genTypePartial(gen, field, fieldIndex, ref) {
return field.delimited
? gen("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)
: gen("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
}
/**
* Generates an encoder specific to the specified message type.
* @param {Type} mtype Message type
* @returns {Codegen} Codegen instance
*/
function encoder(mtype) {
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
var gen = util.codegen(["m", "w", "q"])
("if(!w)")
("w=Writer.create()")
("if(q===undefined)q=0")
("if(q>util.recursionLimit)")
("throw Error(\"max depth exceeded\")");
var i, ref;
// "when a message is serialized its known fields should be written sequentially by field number"
var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);
for (var i = 0; i < fields.length; ++i) {
var field = fields[i].resolve(),
index = mtype._fieldsArray.indexOf(field),
type = field.resolvedType instanceof Enum ? "int32" : field.type,
wireType = types.basic[type];
ref = "m" + util.safeProp(field.name);
// Map fields
if (field.map) {
gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null
("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref);
if (field.keyType === "bool") gen
("w.uint32(%i).fork().uint32(%i).bool(util.boolFromKey(ks[i]))", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType]);
else if (types.long[field.keyType] !== undefined) gen
("w.uint32(%i).fork().uint32(%i).%s(util.longFromKey(ks[i],%j))", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType, field.keyType === "uint64" || field.keyType === "fixed64");
else gen
("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
if (wireType === undefined) gen
("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()", index, ref); // can't be groups
else gen
(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
gen
("}")
("}");
// Repeated fields
} else if (field.repeated) { gen
("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null
// Packed repeated
if (field.packed && types.packed[type] !== undefined) { gen
("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)
("for(var i=0;i<%s.length;++i)", ref)
("w.%s(%s[i])", type, ref)
("w.ldelim()");
// Non-packed
} else { gen
("for(var i=0;i<%s.length;++i)", ref);
if (wireType === undefined)
genTypePartial(gen, field, index, ref + "[i]");
else gen
("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
} gen
("}");
// Non-repeated
} else {
if (!field.required)
if (field.hasPresence || !(field.resolvedType instanceof Enum || types.basic[type] !== undefined)) gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null
else if (field.resolvedType instanceof Enum) gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&%s!==%j)", ref, field.name, ref, field.typeDefault);
else if (type === "bool") gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&%s!==false)", ref, field.name, ref);
else if (type === "string") gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&%s!==\"\")", ref, field.name, ref);
else if (type === "bytes") gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&%s.length)", ref, field.name, ref);
else if (type === "double" || type === "float") gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&!Object.is(%s,0))", ref, field.name, ref);
else if (types.long[type] !== undefined) gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&(typeof %s===\"object\"?%s.low||%s.high:%s!==0))", ref, field.name, ref, ref, ref, ref);
else gen
("if(%s!=null&&Object.hasOwnProperty.call(m,%j)&&%s!==0)", ref, field.name, ref);
if (wireType === undefined)
genTypePartial(gen, field, index, ref);
else gen
("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
}
}
return gen
("if(m.$unknowns!=null&&Object.hasOwnProperty.call(m,\"$unknowns\"))")
("for(var i=0;i<m.$unknowns.length;++i)")
("w.raw(m.$unknowns[i])")
("return w");
/* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
}
},{"23":23,"24":24,"5":5}],5:[function(require,module,exports){
"use strict";
module.exports = Enum;
// extends ReflectionObject
var ReflectionObject = require(13);
Enum.prototype = Object.create(ReflectionObject.prototype, {
constructor: {
value: Enum,
writable: true,
enumerable: false,
configurable: true
}
});
Enum.className = "Enum";
var Namespace = require(12),
util = require(24);
/**
* Constructs a new enum instance.
* @classdesc Reflected enum.
* @extends ReflectionObject
* @constructor
* @param {string} name Unique name within its namespace
* @param {Object.<string,number>} [values] Enum values as an object, by name
* @param {Object.<string,*>} [options] Declared options
* @param {string} [comment] The comment for this enum
* @param {Object.<string,string|null>} [comments] The value comments for this enum
* @param {Object.<string,Object<string,*>>|undefined} [valuesOptions] The value options for this enum
*/
function Enum(name, values, options, comment, comments, valuesOptions) {
ReflectionObject.call(this, name, options);
if (values && typeof values !== "object")
throw TypeError("values must be an object");
/**
* Enum values by id.
* @type {Object.<number,string>}
*/
this.valuesById = Object.create(null);
/**
* Enum values by name.
* @type {Object.<string,number>}
*/
this.values = Object.create(this.valuesById); // toJSON, marker
/**
* Enum comment text.
* @type {string|null}
*/
this.comment = comment;
/**
* Value comment texts, if any.
* @type {Object.<string,string|null>}
*/
this.comments = comments || {};
/**
* Values options, if any
* @type {Object<string, Object<string, *>>|undefined}
*/
this.valuesOptions = valuesOptions;
/**
* Resolved values features, if any
* @type {Object<string, Object<string, *>>|undefined}
*/
this._valuesFeatures = {};
/**
* Reserved ranges, if any.
* @type {Array.<number[]|string>}
*/
this.reserved = undefined; // toJSON
// Note that values inherit valuesById on their prototype which makes them a TypeScript-
// compatible enum. This is used by pbts to write actual enum definitions that work for
// static and reflection code alike instead of emitting generic object definitions.
if (values)
for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number") // use forward entries only
this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];
}
/**
* @override
*/
Enum.prototype._resolveFeatures = function _resolveFeatures(edition) {
edition = this._edition || edition;
ReflectionObject.prototype._resolveFeatures.call(this, edition);
Object.keys(this.values).forEach(key => {
var parentFeaturesCopy = util.merge({}, this._features);
this._valuesFeatures[key] = util.merge(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features || {});
});
return this;
};
/**
* Enum descriptor.
* @interface IEnum
* @property {string} [edition] Edition
* @property {Object.<string,number>} values Enum values
* @property {Object.<string,*>} [options] Enum options
* @property {Object.<string,Object.<string,*>>} [valuesOptions] Enum value options
* @property {Array.<number[]|string>} [reserved] Reserved ranges
* @property {string|null} [comment] Enum comment
* @property {Object.<string,string|null>} [comments] Value comments
*/
/**
* Constructs an enum from an enum descriptor.
* @param {string} name Enum name
* @param {IEnum} json Enum descriptor
* @returns {Enum} Created enum
* @throws {TypeError} If arguments are invalid
*/
Enum.fromJSON = function fromJSON(name, json) {
var enm = new Enum(name, json.values, json.options, json.comment, json.comments, json.valuesOptions);
enm.reserved = json.reserved;
if (json.edition)
enm._edition = json.edition;
enm._defaultEdition = "proto3"; // For backwards-compatibility.
return enm;
};
/**
* Converts this enum to an enum descriptor.
* @param {IToJSONOptions} [toJSONOptions] JSON conversion options
* @returns {IEnum} Enum descriptor
*/
Enum.prototype.toJSON = function toJSON(toJSONOptions) {
var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
return util.toObject([
"edition" , this._editionToJSON(),
"options" , this.options,
"valuesOptions" , this.valuesOptions,
"values" , this.values,
"reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
"comment" , keepComments ? this.comment : undefined,
"comments" , keepComments ? this.comments : undefined
]);
};
/**
* Adds a value to this enum.
* @param {string} name Value name
* @param {number} id Value id
* @param {string} [comment] Comment, if any
* @param {Object.<string, *>|undefined} [options] Options, if any
* @returns {Enum} `this`
* @throws {TypeError} If arguments are invalid
* @throws {Error} If there is already a value with this name or id
*/
Enum.prototype.add = function add(name, id, comment, options) {
// utilized by the parser but not by .fromJSON
if (!util.isString(name))
throw TypeError("name must be a string");
if (!util.isInteger(id))
throw TypeError("id must be an integer");
if (name === "__proto__")
return this;
if (this.values[name] !== undefined)
throw Error("duplicate name '" + name + "' in " + this);
if (this.isReservedId(id))
throw Error("id " + id + " is reserved in " + this);
if (this.isReservedName(name))
throw Error("name '" + name + "' is reserved in " + this);
if (this.valuesById[id] !== undefined) {
if (!(this.options && this.options.allow_alias))
throw Error("duplicate id " + id + " in " + this);
this.values[name] = id;
} else
this.valuesById[this.values[name] = id] = name;
if (options) {
if (this.valuesOptions === undefined)
this.valuesOptions = {};
this.valuesOptions[name] = options || null;
}
this.comments[name] = comment || null;
return this;
};
/**
* Removes a value from this enum
* @param {string} name Value name
* @returns {Enum} `this`
* @throws {TypeError} If arguments are invalid
* @throws {Error} If `name` is not a name of this enum
*/
Enum.prototype.remove = function remove(name) {
if (!util.isString(name))
throw TypeError("name must be a string");
var val = this.values[name];
if (val == null)
throw Error("name '" + name + "' does not exist in " + this);
delete this.valuesById[val];
delete this.values[name];
delete this.comments[name];
if (this.valuesOptions)
delete this.valuesOptions[name];
return this;
};
/**
* Tests if the specified id is reserved.
* @param {number} id Id to test
* @returns {boolean} `true` if reserved, otherwise `false`
*/
Enum.prototype.isReservedId = function isReservedId(id) {
return Namespace.isReservedId(this.reserved, id);
};
/**
* Tests if the specified name is reserved.
* @param {string} name Name to test
* @returns {boolean} `true` if reserved, otherwise `false`
*/
Enum.prototype.isReservedName = function isReservedName(name) {
return Namespace.isReservedName(this.reserved, name);
};
},{"12":12,"13":13,"24":24}],6:[function(require,module,exports){
"use strict";
module.exports = Field;
// extends ReflectionObject
var ReflectionObject = require(13);
Field.prototype = Object.create(ReflectionObject.prototype, {
constructor: {
value: Field,
writable: true,
enumerable: false,
configurable: true
}
});
Field.className = "Field";
var Enum = require(5),
types = require(23),
util = require(24);
var Type; // cyclic
var ruleRe = /^(?:required|optional|repeated)$/;
/**
* Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
* @name Field
* @classdesc Reflected message field.
* @extends FieldBase
* @constructor
* @param {string} name Unique name within its namespace
* @param {number} id Unique id within its namespace
* @param {string} type Value type
* @param {string|Object.<string,*>} [rule="optional"] Field rule
* @param {string|Object.<string,*>} [extend] Extended type if different from parent
* @param {Object.<string,*>} [options] Declared options
*/
/**
* Constructs a field from a field descriptor.
* @param {string} name Field name
* @param {IField} json Field descriptor
* @returns {Field} Created field
* @throws {TypeError} If arguments are invalid
*/
Field.fromJSON = function fromJSON(name, json) {
var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
if (json.edition)
field._edition = json.edition;
if (json.protoName)
field.protoName = json.protoName;
if (json.jsonName !== undefined)
field.jsonName = json.jsonName;
else if (json.options && json.options.json_name !== undefined)
field.jsonName = json.options.json_name;
field._defaultEdition = "proto3"; // For backwards-compatibility.
return field;
};
/**
* Not an actual constructor. Use {@link Field} instead.
* @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.
* @exports FieldBase
* @extends ReflectionObject
* @constructor
* @param {string} name Unique name within its namespace
* @param {number} id Unique id within its namespace
* @param {string} type Value type
* @param {string|Object.<string,*>} [rule="optional"] Field rule
* @param {string|Object.<string,*>} [extend] Extended type if different from parent
* @param {Object.<string,*>} [options] Declared options
* @param {string} [comment] Comment associated with this field
*/
function Field(name, id, type, rule, extend, options, comment) {
if (util.isObject(rule)) {
comment = extend;
options = rule;
rule = extend = undefined;
} else if (util.isObject(extend)) {
comment = options;
options = extend;
extend = undefined;
}
ReflectionObject.call(this, name, options);
if (!util.isInteger(id) || id < 0)
throw TypeError("id must be a non-negative integer");
if (!util.isString(type))
throw TypeError("type must be a string");
if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))
throw TypeError("rule must be a string rule");
if (extend !== undefined && !util.isString(extend))
throw TypeError("extend must be a string");
/**
* Field rule, if any.
* @type {string|undefined}
*/
this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON
/**
* Field type.
* @type {string}
*/
this.type = type; // toJSON
/**
* Unique field id.
* @type {number}
*/
this.id = id; // toJSON, marker
/**
* Extended type if different from parent.
* @type {string|undefined}
*/
this.extend = extend || undefined; // toJSON
/**
* Whether this field is repeated.
* @type {boolean}
*/
this.repeated = rule === "repeated";
/**
* Whether this field is a map or not.
* @type {boolean}
*/
this.map = false;
/**
* Message this field belongs to.
* @type {Type|null}
*/
this.message = null;
/**
* OneOf this field belongs to, if any,
* @type {OneOf|null}
*/
this.partOf = null;
/**
* The field type's default value.
* @type {*}
*/
this.typeDefault = null;
/**
* The field's default value on prototypes.
* @type {*}
*/
this.defaultValue = null;
/**
* Whether this field's value should be treated as a long.
* @type {boolean}
*/
this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;
/**
* Whether this field's value is a buffer.
* @type {boolean}
*/
this.bytes = type === "bytes";
/**
* Resolved type if not a basic type.
* @type {Type|Enum|null}
*/
this.resolvedType = null;
/**
* Sister-field within the extended type if a declaring extension field.
* @type {Field|null}
*/
this.extensionField = null;
/**
* Sister-field within the declaring namespace if an extended field.
* @type {Field|null}
*/
this.declaringField = null;
/**
* Comment for this field.
* @type {string|null}
*/
this.comment = comment;
/**
* Field name as declared in the .proto source, if different from `name`.
* @type {string|undefined}
*/
this.protoName = undefined;
/**
* JSON name, if different from the derived default.
* @type {string|undefined}
*/
this.jsonName = undefined;
}
/**
* Determines whether this field is required.
* @name Field#required
* @type {boolean}
* @readonly
*/
Object.defineProperty(Field.prototype, "required", {
get: function() {
return this._features.field_presence === "LEGACY_REQUIRED";
}
});
/**
* Determines whether this field is not required.
* @name Field#optional
* @type {boolean}
* @readonly
*/
Object.defineProperty(Field.prototype, "optional", {
get: function() {
return !this.required;
}
});
/**
* Determines whether this field uses tag-delimited encoding. In proto2 this
* corresponded to group syntax.
* @name Field#delimited
* @type {boolean}
* @readonly
*/
Object.defineProperty(Field.prototype, "delimited", {
get: function() {
return this.resolvedType instanceof Type &&
this._features.message_encoding === "DELIMITED";
}
});
/**
* Determines whether this field is packed. Only relevant when repeated.
* @name Field#packed
* @type {boolean}
* @readonly
*/
Object.defineProperty(Field.prototype, "packed", {
get: function() {
return this._features.repeated_field_encoding === "PACKED";
}
});
/**
* Determines whether this field tracks presence.
* @name Field#hasPresence
* @type {boolean}
* @readonly
*/
Object.defineProperty(Field.prototype, "hasPresence", {
get: function() {
if (this.repeated || this.map) {
return false;
}
return this.partOf || // oneofs
this.declaringField || this.extensionField || // extensions
this._features.field_presence !== "IMPLICIT";
}
});
/**
* The field name as declared in the .proto source (snake_case). Populated on resolve,
* falling back to `name`. Mirrors `FieldDescriptorProto.name`.
* @name Field#protoName
* @type {string}
* @readonly
*/
/**
* The JSON name of this field (lowerCamelCase per protoc's `ToJsonName`, or an
* explicit `[json_name]`). Populated on resolve. This is the key used on ProtoJSON output.
* @name Field#jsonName
* @type {string}
* @readonly
*/
/**
* @override
*/
Field.prototype.setOption = function setOption(name, value, ifNotSet) {
return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
};
/**
* Field descriptor.
* @interface IField
* @property {string} [edition] Edition
* @property {string} [rule="optional"] Field rule
* @property {string} type Field type
* @property {number} id Field id
* @property {Object.<string,*>} [options] Field options
* @property {string|null} [comment] Field comment
*/
/**
* Extension field descriptor.
* @interface IExtensionField
* @extends IField
* @property {string} extend Extended type
*/
/**
* Converts this field to a field descriptor.
* @param {IToJSONOptions} [toJSONOptions] JSON conversion options
* @returns {IField} Field descriptor
*/
Field.prototype.toJSON = function toJSON(toJSONOptions) {
var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
return util.toObject([
"edition" , this._editionToJSON(),
"rule" , this.rule !== "optional" && this.rule || undefined,
"type" , this.type,
"id" , this.id,
"extend" , this.extend,
"protoName" , this.protoName !== this.name ? this.protoName : undefined,
"jsonName" , this.jsonName !== util.jsonName(this.protoName || this.name) ? this.jsonName : undefined,
"options" , this.options,
"comment" , keepComments ? this.comment : undefined
]);
};
/**
* Resolves this field's type references.
* @returns {Field} `this`
* @throws {Error} If any reference cannot be resolved
*/
Field.prototype.resolve = function resolve() {
if (this.resolved)
return this;
if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it
this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
if (this.resolvedType instanceof Type)
this.typeDefault = null;
else // instanceof Enum
this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined
} else if (this.options && this.options.proto3_optional) {
// proto3 scalar value marked optional;