GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7322 lines
222 KiB

2 months ago
  1. /*!
  2. * protobuf.js v6.11.0 (c) 2016, daniel wirtz
  3. * compiled thu, 29 apr 2021 02:20:44 utc
  4. * licensed under the bsd-3-clause license
  5. * see: https://github.com/dcodeio/protobuf.js for details
  6. */
  7. (function(undefined){"use strict";(function prelude(modules, cache, entries) {
  8. // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS
  9. // sources through a conflict-free require shim and is again wrapped within an iife that
  10. // provides a minification-friendly `undefined` var plus a global "use strict" directive
  11. // so that minification can remove the directives of each module.
  12. function $require(name) {
  13. var $module = cache[name];
  14. if (!$module)
  15. modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);
  16. return $module.exports;
  17. }
  18. var protobuf = $require(entries[0]);
  19. // Expose globally
  20. protobuf.util.global.protobuf = protobuf;
  21. // Be nice to AMD
  22. if (typeof define === "function" && define.amd)
  23. define(["long"], function(Long) {
  24. if (Long && Long.isLong) {
  25. protobuf.util.Long = Long;
  26. protobuf.configure();
  27. }
  28. return protobuf;
  29. });
  30. // Be nice to CommonJS
  31. if (typeof module === "object" && module && module.exports)
  32. module.exports = protobuf;
  33. })/* end of prelude */({1:[function(require,module,exports){
  34. "use strict";
  35. module.exports = asPromise;
  36. /**
  37. * Callback as used by {@link util.asPromise}.
  38. * @typedef asPromiseCallback
  39. * @type {function}
  40. * @param {Error|null} error Error, if any
  41. * @param {...*} params Additional arguments
  42. * @returns {undefined}
  43. */
  44. /**
  45. * Returns a promise from a node-style callback function.
  46. * @memberof util
  47. * @param {asPromiseCallback} fn Function to call
  48. * @param {*} ctx Function context
  49. * @param {...*} params Function arguments
  50. * @returns {Promise<*>} Promisified function
  51. */
  52. function asPromise(fn, ctx/*, varargs */) {
  53. var params = new Array(arguments.length - 1),
  54. offset = 0,
  55. index = 2,
  56. pending = true;
  57. while (index < arguments.length)
  58. params[offset++] = arguments[index++];
  59. return new Promise(function executor(resolve, reject) {
  60. params[offset] = function callback(err/*, varargs */) {
  61. if (pending) {
  62. pending = false;
  63. if (err)
  64. reject(err);
  65. else {
  66. var params = new Array(arguments.length - 1),
  67. offset = 0;
  68. while (offset < params.length)
  69. params[offset++] = arguments[offset];
  70. resolve.apply(null, params);
  71. }
  72. }
  73. };
  74. try {
  75. fn.apply(ctx || null, params);
  76. } catch (err) {
  77. if (pending) {
  78. pending = false;
  79. reject(err);
  80. }
  81. }
  82. });
  83. }
  84. },{}],2:[function(require,module,exports){
  85. "use strict";
  86. /**
  87. * A minimal base64 implementation for number arrays.
  88. * @memberof util
  89. * @namespace
  90. */
  91. var base64 = exports;
  92. /**
  93. * Calculates the byte length of a base64 encoded string.
  94. * @param {string} string Base64 encoded string
  95. * @returns {number} Byte length
  96. */
  97. base64.length = function length(string) {
  98. var p = string.length;
  99. if (!p)
  100. return 0;
  101. var n = 0;
  102. while (--p % 4 > 1 && string.charAt(p) === "=")
  103. ++n;
  104. return Math.ceil(string.length * 3) / 4 - n;
  105. };
  106. // Base64 encoding table
  107. var b64 = new Array(64);
  108. // Base64 decoding table
  109. var s64 = new Array(123);
  110. // 65..90, 97..122, 48..57, 43, 47
  111. for (var i = 0; i < 64;)
  112. s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
  113. /**
  114. * Encodes a buffer to a base64 encoded string.
  115. * @param {Uint8Array} buffer Source buffer
  116. * @param {number} start Source start
  117. * @param {number} end Source end
  118. * @returns {string} Base64 encoded string
  119. */
  120. base64.encode = function encode(buffer, start, end) {
  121. var parts = null,
  122. chunk = [];
  123. var i = 0, // output index
  124. j = 0, // goto index
  125. t; // temporary
  126. while (start < end) {
  127. var b = buffer[start++];
  128. switch (j) {
  129. case 0:
  130. chunk[i++] = b64[b >> 2];
  131. t = (b & 3) << 4;
  132. j = 1;
  133. break;
  134. case 1:
  135. chunk[i++] = b64[t | b >> 4];
  136. t = (b & 15) << 2;
  137. j = 2;
  138. break;
  139. case 2:
  140. chunk[i++] = b64[t | b >> 6];
  141. chunk[i++] = b64[b & 63];
  142. j = 0;
  143. break;
  144. }
  145. if (i > 8191) {
  146. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  147. i = 0;
  148. }
  149. }
  150. if (j) {
  151. chunk[i++] = b64[t];
  152. chunk[i++] = 61;
  153. if (j === 1)
  154. chunk[i++] = 61;
  155. }
  156. if (parts) {
  157. if (i)
  158. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  159. return parts.join("");
  160. }
  161. return String.fromCharCode.apply(String, chunk.slice(0, i));
  162. };
  163. var invalidEncoding = "invalid encoding";
  164. /**
  165. * Decodes a base64 encoded string to a buffer.
  166. * @param {string} string Source string
  167. * @param {Uint8Array} buffer Destination buffer
  168. * @param {number} offset Destination offset
  169. * @returns {number} Number of bytes written
  170. * @throws {Error} If encoding is invalid
  171. */
  172. base64.decode = function decode(string, buffer, offset) {
  173. var start = offset;
  174. var j = 0, // goto index
  175. t; // temporary
  176. for (var i = 0; i < string.length;) {
  177. var c = string.charCodeAt(i++);
  178. if (c === 61 && j > 1)
  179. break;
  180. if ((c = s64[c]) === undefined)
  181. throw Error(invalidEncoding);
  182. switch (j) {
  183. case 0:
  184. t = c;
  185. j = 1;
  186. break;
  187. case 1:
  188. buffer[offset++] = t << 2 | (c & 48) >> 4;
  189. t = c;
  190. j = 2;
  191. break;
  192. case 2:
  193. buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
  194. t = c;
  195. j = 3;
  196. break;
  197. case 3:
  198. buffer[offset++] = (t & 3) << 6 | c;
  199. j = 0;
  200. break;
  201. }
  202. }
  203. if (j === 1)
  204. throw Error(invalidEncoding);
  205. return offset - start;
  206. };
  207. /**
  208. * Tests if the specified string appears to be base64 encoded.
  209. * @param {string} string String to test
  210. * @returns {boolean} `true` if probably base64 encoded, otherwise false
  211. */
  212. base64.test = function test(string) {
  213. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
  214. };
  215. },{}],3:[function(require,module,exports){
  216. "use strict";
  217. module.exports = codegen;
  218. /**
  219. * Begins generating a function.
  220. * @memberof util
  221. * @param {string[]} functionParams Function parameter names
  222. * @param {string} [functionName] Function name if not anonymous
  223. * @returns {Codegen} Appender that appends code to the function's body
  224. */
  225. function codegen(functionParams, functionName) {
  226. /* istanbul ignore if */
  227. if (typeof functionParams === "string") {
  228. functionName = functionParams;
  229. functionParams = undefined;
  230. }
  231. var body = [];
  232. /**
  233. * Appends code to the function's body or finishes generation.
  234. * @typedef Codegen
  235. * @type {function}
  236. * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
  237. * @param {...*} [formatParams] Format parameters
  238. * @returns {Codegen|Function} Itself or the generated function if finished
  239. * @throws {Error} If format parameter counts do not match
  240. */
  241. function Codegen(formatStringOrScope) {
  242. // note that explicit array handling below makes this ~50% faster
  243. // finish the function
  244. if (typeof formatStringOrScope !== "string") {
  245. var source = toString();
  246. if (codegen.verbose)
  247. console.log("codegen: " + source); // eslint-disable-line no-console
  248. source = "return " + source;
  249. if (formatStringOrScope) {
  250. var scopeKeys = Object.keys(formatStringOrScope),
  251. scopeParams = new Array(scopeKeys.length + 1),
  252. scopeValues = new Array(scopeKeys.length),
  253. scopeOffset = 0;
  254. while (scopeOffset < scopeKeys.length) {
  255. scopeParams[scopeOffset] = scopeKeys[scopeOffset];
  256. scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
  257. }
  258. scopeParams[scopeOffset] = source;
  259. return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func
  260. }
  261. return Function(source)(); // eslint-disable-line no-new-func
  262. }
  263. // otherwise append to body
  264. var formatParams = new Array(arguments.length - 1),
  265. formatOffset = 0;
  266. while (formatOffset < formatParams.length)
  267. formatParams[formatOffset] = arguments[++formatOffset];
  268. formatOffset = 0;
  269. formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {
  270. var value = formatParams[formatOffset++];
  271. switch ($1) {
  272. case "d": case "f": return String(Number(value));
  273. case "i": return String(Math.floor(value));
  274. case "j": return JSON.stringify(value);
  275. case "s": return String(value);
  276. }
  277. return "%";
  278. });
  279. if (formatOffset !== formatParams.length)
  280. throw Error("parameter count mismatch");
  281. body.push(formatStringOrScope);
  282. return Codegen;
  283. }
  284. function toString(functionNameOverride) {
  285. return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";
  286. }
  287. Codegen.toString = toString;
  288. return Codegen;
  289. }
  290. /**
  291. * Begins generating a function.
  292. * @memberof util
  293. * @function codegen
  294. * @param {string} [functionName] Function name if not anonymous
  295. * @returns {Codegen} Appender that appends code to the function's body
  296. * @variation 2
  297. */
  298. /**
  299. * When set to `true`, codegen will log generated code to console. Useful for debugging.
  300. * @name util.codegen.verbose
  301. * @type {boolean}
  302. */
  303. codegen.verbose = false;
  304. },{}],4:[function(require,module,exports){
  305. "use strict";
  306. module.exports = EventEmitter;
  307. /**
  308. * Constructs a new event emitter instance.
  309. * @classdesc A minimal event emitter.
  310. * @memberof util
  311. * @constructor
  312. */
  313. function EventEmitter() {
  314. /**
  315. * Registered listeners.
  316. * @type {Object.<string,*>}
  317. * @private
  318. */
  319. this._listeners = {};
  320. }
  321. /**
  322. * Registers an event listener.
  323. * @param {string} evt Event name
  324. * @param {function} fn Listener
  325. * @param {*} [ctx] Listener context
  326. * @returns {util.EventEmitter} `this`
  327. */
  328. EventEmitter.prototype.on = function on(evt, fn, ctx) {
  329. (this._listeners[evt] || (this._listeners[evt] = [])).push({
  330. fn : fn,
  331. ctx : ctx || this
  332. });
  333. return this;
  334. };
  335. /**
  336. * Removes an event listener or any matching listeners if arguments are omitted.
  337. * @param {string} [evt] Event name. Removes all listeners if omitted.
  338. * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
  339. * @returns {util.EventEmitter} `this`
  340. */
  341. EventEmitter.prototype.off = function off(evt, fn) {
  342. if (evt === undefined)
  343. this._listeners = {};
  344. else {
  345. if (fn === undefined)
  346. this._listeners[evt] = [];
  347. else {
  348. var listeners = this._listeners[evt];
  349. for (var i = 0; i < listeners.length;)
  350. if (listeners[i].fn === fn)
  351. listeners.splice(i, 1);
  352. else
  353. ++i;
  354. }
  355. }
  356. return this;
  357. };
  358. /**
  359. * Emits an event by calling its listeners with the specified arguments.
  360. * @param {string} evt Event name
  361. * @param {...*} args Arguments
  362. * @returns {util.EventEmitter} `this`
  363. */
  364. EventEmitter.prototype.emit = function emit(evt) {
  365. var listeners = this._listeners[evt];
  366. if (listeners) {
  367. var args = [],
  368. i = 1;
  369. for (; i < arguments.length;)
  370. args.push(arguments[i++]);
  371. for (i = 0; i < listeners.length;)
  372. listeners[i].fn.apply(listeners[i++].ctx, args);
  373. }
  374. return this;
  375. };
  376. },{}],5:[function(require,module,exports){
  377. "use strict";
  378. module.exports = fetch;
  379. var asPromise = require(1),
  380. inquire = require(7);
  381. var fs = inquire("fs");
  382. /**
  383. * Node-style callback as used by {@link util.fetch}.
  384. * @typedef FetchCallback
  385. * @type {function}
  386. * @param {?Error} error Error, if any, otherwise `null`
  387. * @param {string} [contents] File contents, if there hasn't been an error
  388. * @returns {undefined}
  389. */
  390. /**
  391. * Options as used by {@link util.fetch}.
  392. * @typedef FetchOptions
  393. * @type {Object}
  394. * @property {boolean} [binary=false] Whether expecting a binary response
  395. * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest
  396. */
  397. /**
  398. * Fetches the contents of a file.
  399. * @memberof util
  400. * @param {string} filename File path or url
  401. * @param {FetchOptions} options Fetch options
  402. * @param {FetchCallback} callback Callback function
  403. * @returns {undefined}
  404. */
  405. function fetch(filename, options, callback) {
  406. if (typeof options === "function") {
  407. callback = options;
  408. options = {};
  409. } else if (!options)
  410. options = {};
  411. if (!callback)
  412. return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this
  413. // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.
  414. if (!options.xhr && fs && fs.readFile)
  415. return fs.readFile(filename, function fetchReadFileCallback(err, contents) {
  416. return err && typeof XMLHttpRequest !== "undefined"
  417. ? fetch.xhr(filename, options, callback)
  418. : err
  419. ? callback(err)
  420. : callback(null, options.binary ? contents : contents.toString("utf8"));
  421. });
  422. // use the XHR version otherwise.
  423. return fetch.xhr(filename, options, callback);
  424. }
  425. /**
  426. * Fetches the contents of a file.
  427. * @name util.fetch
  428. * @function
  429. * @param {string} path File path or url
  430. * @param {FetchCallback} callback Callback function
  431. * @returns {undefined}
  432. * @variation 2
  433. */
  434. /**
  435. * Fetches the contents of a file.
  436. * @name util.fetch
  437. * @function
  438. * @param {string} path File path or url
  439. * @param {FetchOptions} [options] Fetch options
  440. * @returns {Promise<string|Uint8Array>} Promise
  441. * @variation 3
  442. */
  443. /**/
  444. fetch.xhr = function fetch_xhr(filename, options, callback) {
  445. var xhr = new XMLHttpRequest();
  446. xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {
  447. if (xhr.readyState !== 4)
  448. return undefined;
  449. // local cors security errors return status 0 / empty string, too. afaik this cannot be
  450. // reliably distinguished from an actually empty file for security reasons. feel free
  451. // to send a pull request if you are aware of a solution.
  452. if (xhr.status !== 0 && xhr.status !== 200)
  453. return callback(Error("status " + xhr.status));
  454. // if binary data is expected, make sure that some sort of array is returned, even if
  455. // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.
  456. if (options.binary) {
  457. var buffer = xhr.response;
  458. if (!buffer) {
  459. buffer = [];
  460. for (var i = 0; i < xhr.responseText.length; ++i)
  461. buffer.push(xhr.responseText.charCodeAt(i) & 255);
  462. }
  463. return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
  464. }
  465. return callback(null, xhr.responseText);
  466. };
  467. if (options.binary) {
  468. // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers
  469. if ("overrideMimeType" in xhr)
  470. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  471. xhr.responseType = "arraybuffer";
  472. }
  473. xhr.open("GET", filename);
  474. xhr.send();
  475. };
  476. },{"1":1,"7":7}],6:[function(require,module,exports){
  477. "use strict";
  478. module.exports = factory(factory);
  479. /**
  480. * Reads / writes floats / doubles from / to buffers.
  481. * @name util.float
  482. * @namespace
  483. */
  484. /**
  485. * Writes a 32 bit float to a buffer using little endian byte order.
  486. * @name util.float.writeFloatLE
  487. * @function
  488. * @param {number} val Value to write
  489. * @param {Uint8Array} buf Target buffer
  490. * @param {number} pos Target buffer offset
  491. * @returns {undefined}
  492. */
  493. /**
  494. * Writes a 32 bit float to a buffer using big endian byte order.
  495. * @name util.float.writeFloatBE
  496. * @function
  497. * @param {number} val Value to write
  498. * @param {Uint8Array} buf Target buffer
  499. * @param {number} pos Target buffer offset
  500. * @returns {undefined}
  501. */
  502. /**
  503. * Reads a 32 bit float from a buffer using little endian byte order.
  504. * @name util.float.readFloatLE
  505. * @function
  506. * @param {Uint8Array} buf Source buffer
  507. * @param {number} pos Source buffer offset
  508. * @returns {number} Value read
  509. */
  510. /**
  511. * Reads a 32 bit float from a buffer using big endian byte order.
  512. * @name util.float.readFloatBE
  513. * @function
  514. * @param {Uint8Array} buf Source buffer
  515. * @param {number} pos Source buffer offset
  516. * @returns {number} Value read
  517. */
  518. /**
  519. * Writes a 64 bit double to a buffer using little endian byte order.
  520. * @name util.float.writeDoubleLE
  521. * @function
  522. * @param {number} val Value to write
  523. * @param {Uint8Array} buf Target buffer
  524. * @param {number} pos Target buffer offset
  525. * @returns {undefined}
  526. */
  527. /**
  528. * Writes a 64 bit double to a buffer using big endian byte order.
  529. * @name util.float.writeDoubleBE
  530. * @function
  531. * @param {number} val Value to write
  532. * @param {Uint8Array} buf Target buffer
  533. * @param {number} pos Target buffer offset
  534. * @returns {undefined}
  535. */
  536. /**
  537. * Reads a 64 bit double from a buffer using little endian byte order.
  538. * @name util.float.readDoubleLE
  539. * @function
  540. * @param {Uint8Array} buf Source buffer
  541. * @param {number} pos Source buffer offset
  542. * @returns {number} Value read
  543. */
  544. /**
  545. * Reads a 64 bit double from a buffer using big endian byte order.
  546. * @name util.float.readDoubleBE
  547. * @function
  548. * @param {Uint8Array} buf Source buffer
  549. * @param {number} pos Source buffer offset
  550. * @returns {number} Value read
  551. */
  552. // Factory function for the purpose of node-based testing in modified global environments
  553. function factory(exports) {
  554. // float: typed array
  555. if (typeof Float32Array !== "undefined") (function() {
  556. var f32 = new Float32Array([ -0 ]),
  557. f8b = new Uint8Array(f32.buffer),
  558. le = f8b[3] === 128;
  559. function writeFloat_f32_cpy(val, buf, pos) {
  560. f32[0] = val;
  561. buf[pos ] = f8b[0];
  562. buf[pos + 1] = f8b[1];
  563. buf[pos + 2] = f8b[2];
  564. buf[pos + 3] = f8b[3];
  565. }
  566. function writeFloat_f32_rev(val, buf, pos) {
  567. f32[0] = val;
  568. buf[pos ] = f8b[3];
  569. buf[pos + 1] = f8b[2];
  570. buf[pos + 2] = f8b[1];
  571. buf[pos + 3] = f8b[0];
  572. }
  573. /* istanbul ignore next */
  574. exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
  575. /* istanbul ignore next */
  576. exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
  577. function readFloat_f32_cpy(buf, pos) {
  578. f8b[0] = buf[pos ];
  579. f8b[1] = buf[pos + 1];
  580. f8b[2] = buf[pos + 2];
  581. f8b[3] = buf[pos + 3];
  582. return f32[0];
  583. }
  584. function readFloat_f32_rev(buf, pos) {
  585. f8b[3] = buf[pos ];
  586. f8b[2] = buf[pos + 1];
  587. f8b[1] = buf[pos + 2];
  588. f8b[0] = buf[pos + 3];
  589. return f32[0];
  590. }
  591. /* istanbul ignore next */
  592. exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
  593. /* istanbul ignore next */
  594. exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
  595. // float: ieee754
  596. })(); else (function() {
  597. function writeFloat_ieee754(writeUint, val, buf, pos) {
  598. var sign = val < 0 ? 1 : 0;
  599. if (sign)
  600. val = -val;
  601. if (val === 0)
  602. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
  603. else if (isNaN(val))
  604. writeUint(2143289344, buf, pos);
  605. else if (val > 3.4028234663852886e+38) // +-Infinity
  606. writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
  607. else if (val < 1.1754943508222875e-38) // denormal
  608. writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
  609. else {
  610. var exponent = Math.floor(Math.log(val) / Math.LN2),
  611. mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
  612. writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
  613. }
  614. }
  615. exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
  616. exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
  617. function readFloat_ieee754(readUint, buf, pos) {
  618. var uint = readUint(buf, pos),
  619. sign = (uint >> 31) * 2 + 1,
  620. exponent = uint >>> 23 & 255,
  621. mantissa = uint & 8388607;
  622. return exponent === 255
  623. ? mantissa
  624. ? NaN
  625. : sign * Infinity
  626. : exponent === 0 // denormal
  627. ? sign * 1.401298464324817e-45 * mantissa
  628. : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
  629. }
  630. exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
  631. exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
  632. })();
  633. // double: typed array
  634. if (typeof Float64Array !== "undefined") (function() {
  635. var f64 = new Float64Array([-0]),
  636. f8b = new Uint8Array(f64.buffer),
  637. le = f8b[7] === 128;
  638. function writeDouble_f64_cpy(val, buf, pos) {
  639. f64[0] = val;
  640. buf[pos ] = f8b[0];
  641. buf[pos + 1] = f8b[1];
  642. buf[pos + 2] = f8b[2];
  643. buf[pos + 3] = f8b[3];
  644. buf[pos + 4] = f8b[4];
  645. buf[pos + 5] = f8b[5];
  646. buf[pos + 6] = f8b[6];
  647. buf[pos + 7] = f8b[7];
  648. }
  649. function writeDouble_f64_rev(val, buf, pos) {
  650. f64[0] = val;
  651. buf[pos ] = f8b[7];
  652. buf[pos + 1] = f8b[6];
  653. buf[pos + 2] = f8b[5];
  654. buf[pos + 3] = f8b[4];
  655. buf[pos + 4] = f8b[3];
  656. buf[pos + 5] = f8b[2];
  657. buf[pos + 6] = f8b[1];
  658. buf[pos + 7] = f8b[0];
  659. }
  660. /* istanbul ignore next */
  661. exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
  662. /* istanbul ignore next */
  663. exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
  664. function readDouble_f64_cpy(buf, pos) {
  665. f8b[0] = buf[pos ];
  666. f8b[1] = buf[pos + 1];
  667. f8b[2] = buf[pos + 2];
  668. f8b[3] = buf[pos + 3];
  669. f8b[4] = buf[pos + 4];
  670. f8b[5] = buf[pos + 5];
  671. f8b[6] = buf[pos + 6];
  672. f8b[7] = buf[pos + 7];
  673. return f64[0];
  674. }
  675. function readDouble_f64_rev(buf, pos) {
  676. f8b[7] = buf[pos ];
  677. f8b[6] = buf[pos + 1];
  678. f8b[5] = buf[pos + 2];
  679. f8b[4] = buf[pos + 3];
  680. f8b[3] = buf[pos + 4];
  681. f8b[2] = buf[pos + 5];
  682. f8b[1] = buf[pos + 6];
  683. f8b[0] = buf[pos + 7];
  684. return f64[0];
  685. }
  686. /* istanbul ignore next */
  687. exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
  688. /* istanbul ignore next */
  689. exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
  690. // double: ieee754
  691. })(); else (function() {
  692. function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
  693. var sign = val < 0 ? 1 : 0;
  694. if (sign)
  695. val = -val;
  696. if (val === 0) {
  697. writeUint(0, buf, pos + off0);
  698. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
  699. } else if (isNaN(val)) {
  700. writeUint(0, buf, pos + off0);
  701. writeUint(2146959360, buf, pos + off1);
  702. } else if (val > 1.7976931348623157e+308) { // +-Infinity
  703. writeUint(0, buf, pos + off0);
  704. writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
  705. } else {
  706. var mantissa;
  707. if (val < 2.2250738585072014e-308) { // denormal
  708. mantissa = val / 5e-324;
  709. writeUint(mantissa >>> 0, buf, pos + off0);
  710. writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
  711. } else {
  712. var exponent = Math.floor(Math.log(val) / Math.LN2);
  713. if (exponent === 1024)
  714. exponent = 1023;
  715. mantissa = val * Math.pow(2, -exponent);
  716. writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
  717. writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
  718. }
  719. }
  720. }
  721. exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
  722. exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
  723. function readDouble_ieee754(readUint, off0, off1, buf, pos) {
  724. var lo = readUint(buf, pos + off0),
  725. hi = readUint(buf, pos + off1);
  726. var sign = (hi >> 31) * 2 + 1,
  727. exponent = hi >>> 20 & 2047,
  728. mantissa = 4294967296 * (hi & 1048575) + lo;
  729. return exponent === 2047
  730. ? mantissa
  731. ? NaN
  732. : sign * Infinity
  733. : exponent === 0 // denormal
  734. ? sign * 5e-324 * mantissa
  735. : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
  736. }
  737. exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
  738. exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
  739. })();
  740. return exports;
  741. }
  742. // uint helpers
  743. function writeUintLE(val, buf, pos) {
  744. buf[pos ] = val & 255;
  745. buf[pos + 1] = val >>> 8 & 255;
  746. buf[pos + 2] = val >>> 16 & 255;
  747. buf[pos + 3] = val >>> 24;
  748. }
  749. function writeUintBE(val, buf, pos) {
  750. buf[pos ] = val >>> 24;
  751. buf[pos + 1] = val >>> 16 & 255;
  752. buf[pos + 2] = val >>> 8 & 255;
  753. buf[pos + 3] = val & 255;
  754. }
  755. function readUintLE(buf, pos) {
  756. return (buf[pos ]
  757. | buf[pos + 1] << 8
  758. | buf[pos + 2] << 16
  759. | buf[pos + 3] << 24) >>> 0;
  760. }
  761. function readUintBE(buf, pos) {
  762. return (buf[pos ] << 24
  763. | buf[pos + 1] << 16
  764. | buf[pos + 2] << 8
  765. | buf[pos + 3]) >>> 0;
  766. }
  767. },{}],7:[function(require,module,exports){
  768. "use strict";
  769. module.exports = inquire;
  770. /**
  771. * Requires a module only if available.
  772. * @memberof util
  773. * @param {string} moduleName Module to require
  774. * @returns {?Object} Required module if available and not empty, otherwise `null`
  775. */
  776. function inquire(moduleName) {
  777. try {
  778. var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
  779. if (mod && (mod.length || Object.keys(mod).length))
  780. return mod;
  781. } catch (e) {} // eslint-disable-line no-empty
  782. return null;
  783. }
  784. },{}],8:[function(require,module,exports){
  785. "use strict";
  786. /**
  787. * A minimal path module to resolve Unix, Windows and URL paths alike.
  788. * @memberof util
  789. * @namespace
  790. */
  791. var path = exports;
  792. var isAbsolute =
  793. /**
  794. * Tests if the specified path is absolute.
  795. * @param {string} path Path to test
  796. * @returns {boolean} `true` if path is absolute
  797. */
  798. path.isAbsolute = function isAbsolute(path) {
  799. return /^(?:\/|\w+:)/.test(path);
  800. };
  801. var normalize =
  802. /**
  803. * Normalizes the specified path.
  804. * @param {string} path Path to normalize
  805. * @returns {string} Normalized path
  806. */
  807. path.normalize = function normalize(path) {
  808. path = path.replace(/\\/g, "/")
  809. .replace(/\/{2,}/g, "/");
  810. var parts = path.split("/"),
  811. absolute = isAbsolute(path),
  812. prefix = "";
  813. if (absolute)
  814. prefix = parts.shift() + "/";
  815. for (var i = 0; i < parts.length;) {
  816. if (parts[i] === "..") {
  817. if (i > 0 && parts[i - 1] !== "..")
  818. parts.splice(--i, 2);
  819. else if (absolute)
  820. parts.splice(i, 1);
  821. else
  822. ++i;
  823. } else if (parts[i] === ".")
  824. parts.splice(i, 1);
  825. else
  826. ++i;
  827. }
  828. return prefix + parts.join("/");
  829. };
  830. /**
  831. * Resolves the specified include path against the specified origin path.
  832. * @param {string} originPath Path to the origin file
  833. * @param {string} includePath Include path relative to origin path
  834. * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized
  835. * @returns {string} Path to the include file
  836. */
  837. path.resolve = function resolve(originPath, includePath, alreadyNormalized) {
  838. if (!alreadyNormalized)
  839. includePath = normalize(includePath);
  840. if (isAbsolute(includePath))
  841. return includePath;
  842. if (!alreadyNormalized)
  843. originPath = normalize(originPath);
  844. return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;
  845. };
  846. },{}],9:[function(require,module,exports){
  847. "use strict";
  848. module.exports = pool;
  849. /**
  850. * An allocator as used by {@link util.pool}.
  851. * @typedef PoolAllocator
  852. * @type {function}
  853. * @param {number} size Buffer size
  854. * @returns {Uint8Array} Buffer
  855. */
  856. /**
  857. * A slicer as used by {@link util.pool}.
  858. * @typedef PoolSlicer
  859. * @type {function}
  860. * @param {number} start Start offset
  861. * @param {number} end End offset
  862. * @returns {Uint8Array} Buffer slice
  863. * @this {Uint8Array}
  864. */
  865. /**
  866. * A general purpose buffer pool.
  867. * @memberof util
  868. * @function
  869. * @param {PoolAllocator} alloc Allocator
  870. * @param {PoolSlicer} slice Slicer
  871. * @param {number} [size=8192] Slab size
  872. * @returns {PoolAllocator} Pooled allocator
  873. */
  874. function pool(alloc, slice, size) {
  875. var SIZE = size || 8192;
  876. var MAX = SIZE >>> 1;
  877. var slab = null;
  878. var offset = SIZE;
  879. return function pool_alloc(size) {
  880. if (size < 1 || size > MAX)
  881. return alloc(size);
  882. if (offset + size > SIZE) {
  883. slab = alloc(SIZE);
  884. offset = 0;
  885. }
  886. var buf = slice.call(slab, offset, offset += size);
  887. if (offset & 7) // align to 32 bit
  888. offset = (offset | 7) + 1;
  889. return buf;
  890. };
  891. }
  892. },{}],10:[function(require,module,exports){
  893. "use strict";
  894. /**
  895. * A minimal UTF8 implementation for number arrays.
  896. * @memberof util
  897. * @namespace
  898. */
  899. var utf8 = exports;
  900. /**
  901. * Calculates the UTF8 byte length of a string.
  902. * @param {string} string String
  903. * @returns {number} Byte length
  904. */
  905. utf8.length = function utf8_length(string) {
  906. var len = 0,
  907. c = 0;
  908. for (var i = 0; i < string.length; ++i) {
  909. c = string.charCodeAt(i);
  910. if (c < 128)
  911. len += 1;
  912. else if (c < 2048)
  913. len += 2;
  914. else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
  915. ++i;
  916. len += 4;
  917. } else
  918. len += 3;
  919. }
  920. return len;
  921. };
  922. /**
  923. * Reads UTF8 bytes as a string.
  924. * @param {Uint8Array} buffer Source buffer
  925. * @param {number} start Source start
  926. * @param {number} end Source end
  927. * @returns {string} String read
  928. */
  929. utf8.read = function utf8_read(buffer, start, end) {
  930. var len = end - start;
  931. if (len < 1)
  932. return "";
  933. var parts = null,
  934. chunk = [],
  935. i = 0, // char offset
  936. t; // temporary
  937. while (start < end) {
  938. t = buffer[start++];
  939. if (t < 128)
  940. chunk[i++] = t;
  941. else if (t > 191 && t < 224)
  942. chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
  943. else if (t > 239 && t < 365) {
  944. t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
  945. chunk[i++] = 0xD800 + (t >> 10);
  946. chunk[i++] = 0xDC00 + (t & 1023);
  947. } else
  948. chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
  949. if (i > 8191) {
  950. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  951. i = 0;
  952. }
  953. }
  954. if (parts) {
  955. if (i)
  956. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  957. return parts.join("");
  958. }
  959. return String.fromCharCode.apply(String, chunk.slice(0, i));
  960. };
  961. /**
  962. * Writes a string as UTF8 bytes.
  963. * @param {string} string Source string
  964. * @param {Uint8Array} buffer Destination buffer
  965. * @param {number} offset Destination offset
  966. * @returns {number} Bytes written
  967. */
  968. utf8.write = function utf8_write(string, buffer, offset) {
  969. var start = offset,
  970. c1, // character 1
  971. c2; // character 2
  972. for (var i = 0; i < string.length; ++i) {
  973. c1 = string.charCodeAt(i);
  974. if (c1 < 128) {
  975. buffer[offset++] = c1;
  976. } else if (c1 < 2048) {
  977. buffer[offset++] = c1 >> 6 | 192;
  978. buffer[offset++] = c1 & 63 | 128;
  979. } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
  980. c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
  981. ++i;
  982. buffer[offset++] = c1 >> 18 | 240;
  983. buffer[offset++] = c1 >> 12 & 63 | 128;
  984. buffer[offset++] = c1 >> 6 & 63 | 128;
  985. buffer[offset++] = c1 & 63 | 128;
  986. } else {
  987. buffer[offset++] = c1 >> 12 | 224;
  988. buffer[offset++] = c1 >> 6 & 63 | 128;
  989. buffer[offset++] = c1 & 63 | 128;
  990. }
  991. }
  992. return offset - start;
  993. };
  994. },{}],11:[function(require,module,exports){
  995. "use strict";
  996. /**
  997. * Runtime message from/to plain object converters.
  998. * @namespace
  999. */
  1000. var converter = exports;
  1001. var Enum = require(14),
  1002. util = require(33);
  1003. /**
  1004. * Generates a partial value fromObject conveter.
  1005. * @param {Codegen} gen Codegen instance
  1006. * @param {Field} field Reflected field
  1007. * @param {number} fieldIndex Field index
  1008. * @param {string} prop Property reference
  1009. * @returns {Codegen} Codegen instance
  1010. * @ignore
  1011. */
  1012. function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
  1013. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1014. if (field.resolvedType) {
  1015. if (field.resolvedType instanceof Enum) { gen
  1016. ("switch(d%s){", prop);
  1017. for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
  1018. if (field.repeated && values[keys[i]] === field.typeDefault) gen
  1019. ("default:");
  1020. gen
  1021. ("case%j:", keys[i])
  1022. ("case %i:", values[keys[i]])
  1023. ("m%s=%j", prop, values[keys[i]])
  1024. ("break");
  1025. } gen
  1026. ("}");
  1027. } else gen
  1028. ("if(typeof d%s!==\"object\")", prop)
  1029. ("throw TypeError(%j)", field.fullName + ": object expected")
  1030. ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);
  1031. } else {
  1032. var isUnsigned = false;
  1033. switch (field.type) {
  1034. case "double":
  1035. case "float": gen
  1036. ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"
  1037. break;
  1038. case "uint32":
  1039. case "fixed32": gen
  1040. ("m%s=d%s>>>0", prop, prop);
  1041. break;
  1042. case "int32":
  1043. case "sint32":
  1044. case "sfixed32": gen
  1045. ("m%s=d%s|0", prop, prop);
  1046. break;
  1047. case "uint64":
  1048. isUnsigned = true;
  1049. // eslint-disable-line no-fallthrough
  1050. case "int64":
  1051. case "sint64":
  1052. case "fixed64":
  1053. case "sfixed64": gen
  1054. ("if(util.Long)")
  1055. ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)
  1056. ("else if(typeof d%s===\"string\")", prop)
  1057. ("m%s=parseInt(d%s,10)", prop, prop)
  1058. ("else if(typeof d%s===\"number\")", prop)
  1059. ("m%s=d%s", prop, prop)
  1060. ("else if(typeof d%s===\"object\")", prop)
  1061. ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
  1062. break;
  1063. case "bytes": gen
  1064. ("if(typeof d%s===\"string\")", prop)
  1065. ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)
  1066. ("else if(d%s.length)", prop)
  1067. ("m%s=d%s", prop, prop);
  1068. break;
  1069. case "string": gen
  1070. ("m%s=String(d%s)", prop, prop);
  1071. break;
  1072. case "bool": gen
  1073. ("m%s=Boolean(d%s)", prop, prop);
  1074. break;
  1075. /* default: gen
  1076. ("m%s=d%s", prop, prop);
  1077. break; */
  1078. }
  1079. }
  1080. return gen;
  1081. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1082. }
  1083. /**
  1084. * Generates a plain object to runtime message converter specific to the specified message type.
  1085. * @param {Type} mtype Message type
  1086. * @returns {Codegen} Codegen instance
  1087. */
  1088. converter.fromObject = function fromObject(mtype) {
  1089. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1090. var fields = mtype.fieldsArray;
  1091. var gen = util.codegen(["d"], mtype.name + "$fromObject")
  1092. ("if(d instanceof this.ctor)")
  1093. ("return d");
  1094. if (!fields.length) return gen
  1095. ("return new this.ctor");
  1096. gen
  1097. ("var m=new this.ctor");
  1098. for (var i = 0; i < fields.length; ++i) {
  1099. var field = fields[i].resolve(),
  1100. prop = util.safeProp(field.name);
  1101. // Map fields
  1102. if (field.map) { gen
  1103. ("if(d%s){", prop)
  1104. ("if(typeof d%s!==\"object\")", prop)
  1105. ("throw TypeError(%j)", field.fullName + ": object expected")
  1106. ("m%s={}", prop)
  1107. ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
  1108. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")
  1109. ("}")
  1110. ("}");
  1111. // Repeated fields
  1112. } else if (field.repeated) { gen
  1113. ("if(d%s){", prop)
  1114. ("if(!Array.isArray(d%s))", prop)
  1115. ("throw TypeError(%j)", field.fullName + ": array expected")
  1116. ("m%s=[]", prop)
  1117. ("for(var i=0;i<d%s.length;++i){", prop);
  1118. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")
  1119. ("}")
  1120. ("}");
  1121. // Non-repeated fields
  1122. } else {
  1123. if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)
  1124. ("if(d%s!=null){", prop); // !== undefined && !== null
  1125. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);
  1126. if (!(field.resolvedType instanceof Enum)) gen
  1127. ("}");
  1128. }
  1129. } return gen
  1130. ("return m");
  1131. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1132. };
  1133. /**
  1134. * Generates a partial value toObject converter.
  1135. * @param {Codegen} gen Codegen instance
  1136. * @param {Field} field Reflected field
  1137. * @param {number} fieldIndex Field index
  1138. * @param {string} prop Property reference
  1139. * @returns {Codegen} Codegen instance
  1140. * @ignore
  1141. */
  1142. function genValuePartial_toObject(gen, field, fieldIndex, prop) {
  1143. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1144. if (field.resolvedType) {
  1145. if (field.resolvedType instanceof Enum) gen
  1146. ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);
  1147. else gen
  1148. ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);
  1149. } else {
  1150. var isUnsigned = false;
  1151. switch (field.type) {
  1152. case "double":
  1153. case "float": gen
  1154. ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);
  1155. break;
  1156. case "uint64":
  1157. isUnsigned = true;
  1158. // eslint-disable-line no-fallthrough
  1159. case "int64":
  1160. case "sint64":
  1161. case "fixed64":
  1162. case "sfixed64": gen
  1163. ("if(typeof m%s===\"number\")", prop)
  1164. ("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)
  1165. ("else") // Long-like
  1166. ("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", prop, prop, prop, prop, isUnsigned ? "true": "", prop);
  1167. break;
  1168. case "bytes": gen
  1169. ("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", prop, prop, prop, prop, prop);
  1170. break;
  1171. default: gen
  1172. ("d%s=m%s", prop, prop);
  1173. break;
  1174. }
  1175. }
  1176. return gen;
  1177. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1178. }
  1179. /**
  1180. * Generates a runtime message to plain object converter specific to the specified message type.
  1181. * @param {Type} mtype Message type
  1182. * @returns {Codegen} Codegen instance
  1183. */
  1184. converter.toObject = function toObject(mtype) {
  1185. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1186. var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
  1187. if (!fields.length)
  1188. return util.codegen()("return {}");
  1189. var gen = util.codegen(["m", "o"], mtype.name + "$toObject")
  1190. ("if(!o)")
  1191. ("o={}")
  1192. ("var d={}");
  1193. var repeatedFields = [],
  1194. mapFields = [],
  1195. normalFields = [],
  1196. i = 0;
  1197. for (; i < fields.length; ++i)
  1198. if (!fields[i].partOf)
  1199. ( fields[i].resolve().repeated ? repeatedFields
  1200. : fields[i].map ? mapFields
  1201. : normalFields).push(fields[i]);
  1202. if (repeatedFields.length) { gen
  1203. ("if(o.arrays||o.defaults){");
  1204. for (i = 0; i < repeatedFields.length; ++i) gen
  1205. ("d%s=[]", util.safeProp(repeatedFields[i].name));
  1206. gen
  1207. ("}");
  1208. }
  1209. if (mapFields.length) { gen
  1210. ("if(o.objects||o.defaults){");
  1211. for (i = 0; i < mapFields.length; ++i) gen
  1212. ("d%s={}", util.safeProp(mapFields[i].name));
  1213. gen
  1214. ("}");
  1215. }
  1216. if (normalFields.length) { gen
  1217. ("if(o.defaults){");
  1218. for (i = 0; i < normalFields.length; ++i) {
  1219. var field = normalFields[i],
  1220. prop = util.safeProp(field.name);
  1221. if (field.resolvedType instanceof Enum) gen
  1222. ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
  1223. else if (field.long) gen
  1224. ("if(util.Long){")
  1225. ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)
  1226. ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)
  1227. ("}else")
  1228. ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());
  1229. else if (field.bytes) {
  1230. var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]";
  1231. gen
  1232. ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))
  1233. ("else{")
  1234. ("d%s=%s", prop, arrayDefault)
  1235. ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)
  1236. ("}");
  1237. } else gen
  1238. ("d%s=%j", prop, field.typeDefault); // also messages (=null)
  1239. } gen
  1240. ("}");
  1241. }
  1242. var hasKs2 = false;
  1243. for (i = 0; i < fields.length; ++i) {
  1244. var field = fields[i],
  1245. index = mtype._fieldsArray.indexOf(field),
  1246. prop = util.safeProp(field.name);
  1247. if (field.map) {
  1248. if (!hasKs2) { hasKs2 = true; gen
  1249. ("var ks2");
  1250. } gen
  1251. ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)
  1252. ("d%s={}", prop)
  1253. ("for(var j=0;j<ks2.length;++j){");
  1254. genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]")
  1255. ("}");
  1256. } else if (field.repeated) { gen
  1257. ("if(m%s&&m%s.length){", prop, prop)
  1258. ("d%s=[]", prop)
  1259. ("for(var j=0;j<m%s.length;++j){", prop);
  1260. genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")
  1261. ("}");
  1262. } else { gen
  1263. ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name); // !== undefined && !== null
  1264. genValuePartial_toObject(gen, field, /* sorted */ index, prop);
  1265. if (field.partOf) gen
  1266. ("if(o.oneofs)")
  1267. ("d%s=%j", util.safeProp(field.partOf.name), field.name);
  1268. }
  1269. gen
  1270. ("}");
  1271. }
  1272. return gen
  1273. ("return d");
  1274. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1275. };
  1276. },{"14":14,"33":33}],12:[function(require,module,exports){
  1277. "use strict";
  1278. module.exports = decoder;
  1279. var Enum = require(14),
  1280. types = require(32),
  1281. util = require(33);
  1282. function missing(field) {
  1283. return "missing required '" + field.name + "'";
  1284. }
  1285. /**
  1286. * Generates a decoder specific to the specified message type.
  1287. * @param {Type} mtype Message type
  1288. * @returns {Codegen} Codegen instance
  1289. */
  1290. function decoder(mtype) {
  1291. /* eslint-disable no-unexpected-multiline */
  1292. var gen = util.codegen(["r", "l"], mtype.name + "$decode")
  1293. ("if(!(r instanceof Reader))")
  1294. ("r=Reader.create(r)")
  1295. ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k,value" : ""))
  1296. ("while(r.pos<c){")
  1297. ("var t=r.uint32()");
  1298. if (mtype.group) gen
  1299. ("if((t&7)===4)")
  1300. ("break");
  1301. gen
  1302. ("switch(t>>>3){");
  1303. var i = 0;
  1304. for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  1305. var field = mtype._fieldsArray[i].resolve(),
  1306. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  1307. ref = "m" + util.safeProp(field.name); gen
  1308. ("case %i:", field.id);
  1309. // Map fields
  1310. if (field.map) { gen
  1311. ("if(%s===util.emptyObject)", ref)
  1312. ("%s={}", ref)
  1313. ("var c2 = r.uint32()+r.pos");
  1314. if (types.defaults[field.keyType] !== undefined) gen
  1315. ("k=%j", types.defaults[field.keyType]);
  1316. else gen
  1317. ("k=null");
  1318. if (types.defaults[type] !== undefined) gen
  1319. ("value=%j", types.defaults[type]);
  1320. else gen
  1321. ("value=null");
  1322. gen
  1323. ("while(r.pos<c2){")
  1324. ("var tag2=r.uint32()")
  1325. ("switch(tag2>>>3){")
  1326. ("case 1: k=r.%s(); break", field.keyType)
  1327. ("case 2:");
  1328. if (types.basic[type] === undefined) gen
  1329. ("value=types[%i].decode(r,r.uint32())", i); // can't be groups
  1330. else gen
  1331. ("value=r.%s()", type);
  1332. gen
  1333. ("break")
  1334. ("default:")
  1335. ("r.skipType(tag2&7)")
  1336. ("break")
  1337. ("}")
  1338. ("}");
  1339. if (types.long[field.keyType] !== undefined) gen
  1340. ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref);
  1341. else gen
  1342. ("%s[k]=value", ref);
  1343. // Repeated fields
  1344. } else if (field.repeated) { gen
  1345. ("if(!(%s&&%s.length))", ref, ref)
  1346. ("%s=[]", ref);
  1347. // Packable (always check for forward and backward compatiblity)
  1348. if (types.packed[type] !== undefined) gen
  1349. ("if((t&7)===2){")
  1350. ("var c2=r.uint32()+r.pos")
  1351. ("while(r.pos<c2)")
  1352. ("%s.push(r.%s())", ref, type)
  1353. ("}else");
  1354. // Non-packed
  1355. if (types.basic[type] === undefined) gen(field.resolvedType.group
  1356. ? "%s.push(types[%i].decode(r))"
  1357. : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);
  1358. else gen
  1359. ("%s.push(r.%s())", ref, type);
  1360. // Non-repeated
  1361. } else if (types.basic[type] === undefined) gen(field.resolvedType.group
  1362. ? "%s=types[%i].decode(r)"
  1363. : "%s=types[%i].decode(r,r.uint32())", ref, i);
  1364. else gen
  1365. ("%s=r.%s()", ref, type);
  1366. gen
  1367. ("break");
  1368. // Unknown fields
  1369. } gen
  1370. ("default:")
  1371. ("r.skipType(t&7)")
  1372. ("break")
  1373. ("}")
  1374. ("}");
  1375. // Field presence
  1376. for (i = 0; i < mtype._fieldsArray.length; ++i) {
  1377. var rfield = mtype._fieldsArray[i];
  1378. if (rfield.required) gen
  1379. ("if(!m.hasOwnProperty(%j))", rfield.name)
  1380. ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
  1381. }
  1382. return gen
  1383. ("return m");
  1384. /* eslint-enable no-unexpected-multiline */
  1385. }
  1386. },{"14":14,"32":32,"33":33}],13:[function(require,module,exports){
  1387. "use strict";
  1388. module.exports = encoder;
  1389. var Enum = require(14),
  1390. types = require(32),
  1391. util = require(33);
  1392. /**
  1393. * Generates a partial message type encoder.
  1394. * @param {Codegen} gen Codegen instance
  1395. * @param {Field} field Reflected field
  1396. * @param {number} fieldIndex Field index
  1397. * @param {string} ref Variable reference
  1398. * @returns {Codegen} Codegen instance
  1399. * @ignore
  1400. */
  1401. function genTypePartial(gen, field, fieldIndex, ref) {
  1402. return field.resolvedType.group
  1403. ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)
  1404. : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
  1405. }
  1406. /**
  1407. * Generates an encoder specific to the specified message type.
  1408. * @param {Type} mtype Message type
  1409. * @returns {Codegen} Codegen instance
  1410. */
  1411. function encoder(mtype) {
  1412. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1413. var gen = util.codegen(["m", "w"], mtype.name + "$encode")
  1414. ("if(!w)")
  1415. ("w=Writer.create()");
  1416. var i, ref;
  1417. // "when a message is serialized its known fields should be written sequentially by field number"
  1418. var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);
  1419. for (var i = 0; i < fields.length; ++i) {
  1420. var field = fields[i].resolve(),
  1421. index = mtype._fieldsArray.indexOf(field),
  1422. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  1423. wireType = types.basic[type];
  1424. ref = "m" + util.safeProp(field.name);
  1425. // Map fields
  1426. if (field.map) {
  1427. gen
  1428. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null
  1429. ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)
  1430. ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
  1431. if (wireType === undefined) gen
  1432. ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups
  1433. else gen
  1434. (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
  1435. gen
  1436. ("}")
  1437. ("}");
  1438. // Repeated fields
  1439. } else if (field.repeated) { gen
  1440. ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null
  1441. // Packed repeated
  1442. if (field.packed && types.packed[type] !== undefined) { gen
  1443. ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)
  1444. ("for(var i=0;i<%s.length;++i)", ref)
  1445. ("w.%s(%s[i])", type, ref)
  1446. ("w.ldelim()");
  1447. // Non-packed
  1448. } else { gen
  1449. ("for(var i=0;i<%s.length;++i)", ref);
  1450. if (wireType === undefined)
  1451. genTypePartial(gen, field, index, ref + "[i]");
  1452. else gen
  1453. ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
  1454. } gen
  1455. ("}");
  1456. // Non-repeated
  1457. } else {
  1458. if (field.optional) gen
  1459. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null
  1460. if (wireType === undefined)
  1461. genTypePartial(gen, field, index, ref);
  1462. else gen
  1463. ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
  1464. }
  1465. }
  1466. return gen
  1467. ("return w");
  1468. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1469. }
  1470. },{"14":14,"32":32,"33":33}],14:[function(require,module,exports){
  1471. "use strict";
  1472. module.exports = Enum;
  1473. // extends ReflectionObject
  1474. var ReflectionObject = require(22);
  1475. ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
  1476. var Namespace = require(21),
  1477. util = require(33);
  1478. /**
  1479. * Constructs a new enum instance.
  1480. * @classdesc Reflected enum.
  1481. * @extends ReflectionObject
  1482. * @constructor
  1483. * @param {string} name Unique name within its namespace
  1484. * @param {Object.<string,number>} [values] Enum values as an object, by name
  1485. * @param {Object.<string,*>} [options] Declared options
  1486. * @param {string} [comment] The comment for this enum
  1487. * @param {Object.<string,string>} [comments] The value comments for this enum
  1488. */
  1489. function Enum(name, values, options, comment, comments) {
  1490. ReflectionObject.call(this, name, options);
  1491. if (values && typeof values !== "object")
  1492. throw TypeError("values must be an object");
  1493. /**
  1494. * Enum values by id.
  1495. * @type {Object.<number,string>}
  1496. */
  1497. this.valuesById = {};
  1498. /**
  1499. * Enum values by name.
  1500. * @type {Object.<string,number>}
  1501. */
  1502. this.values = Object.create(this.valuesById); // toJSON, marker
  1503. /**
  1504. * Enum comment text.
  1505. * @type {string|null}
  1506. */
  1507. this.comment = comment;
  1508. /**
  1509. * Value comment texts, if any.
  1510. * @type {Object.<string,string>}
  1511. */
  1512. this.comments = comments || {};
  1513. /**
  1514. * Reserved ranges, if any.
  1515. * @type {Array.<number[]|string>}
  1516. */
  1517. this.reserved = undefined; // toJSON
  1518. // Note that values inherit valuesById on their prototype which makes them a TypeScript-
  1519. // compatible enum. This is used by pbts to write actual enum definitions that work for
  1520. // static and reflection code alike instead of emitting generic object definitions.
  1521. if (values)
  1522. for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
  1523. if (typeof values[keys[i]] === "number") // use forward entries only
  1524. this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];
  1525. }
  1526. /**
  1527. * Enum descriptor.
  1528. * @interface IEnum
  1529. * @property {Object.<string,number>} values Enum values
  1530. * @property {Object.<string,*>} [options] Enum options
  1531. */
  1532. /**
  1533. * Constructs an enum from an enum descriptor.
  1534. * @param {string} name Enum name
  1535. * @param {IEnum} json Enum descriptor
  1536. * @returns {Enum} Created enum
  1537. * @throws {TypeError} If arguments are invalid
  1538. */
  1539. Enum.fromJSON = function fromJSON(name, json) {
  1540. var enm = new Enum(name, json.values, json.options, json.comment, json.comments);
  1541. enm.reserved = json.reserved;
  1542. return enm;
  1543. };
  1544. /**
  1545. * Converts this enum to an enum descriptor.
  1546. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1547. * @returns {IEnum} Enum descriptor
  1548. */
  1549. Enum.prototype.toJSON = function toJSON(toJSONOptions) {
  1550. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1551. return util.toObject([
  1552. "options" , this.options,
  1553. "values" , this.values,
  1554. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  1555. "comment" , keepComments ? this.comment : undefined,
  1556. "comments" , keepComments ? this.comments : undefined
  1557. ]);
  1558. };
  1559. /**
  1560. * Adds a value to this enum.
  1561. * @param {string} name Value name
  1562. * @param {number} id Value id
  1563. * @param {string} [comment] Comment, if any
  1564. * @returns {Enum} `this`
  1565. * @throws {TypeError} If arguments are invalid
  1566. * @throws {Error} If there is already a value with this name or id
  1567. */
  1568. Enum.prototype.add = function add(name, id, comment) {
  1569. // utilized by the parser but not by .fromJSON
  1570. if (!util.isString(name))
  1571. throw TypeError("name must be a string");
  1572. if (!util.isInteger(id))
  1573. throw TypeError("id must be an integer");
  1574. if (this.values[name] !== undefined)
  1575. throw Error("duplicate name '" + name + "' in " + this);
  1576. if (this.isReservedId(id))
  1577. throw Error("id " + id + " is reserved in " + this);
  1578. if (this.isReservedName(name))
  1579. throw Error("name '" + name + "' is reserved in " + this);
  1580. if (this.valuesById[id] !== undefined) {
  1581. if (!(this.options && this.options.allow_alias))
  1582. throw Error("duplicate id " + id + " in " + this);
  1583. this.values[name] = id;
  1584. } else
  1585. this.valuesById[this.values[name] = id] = name;
  1586. this.comments[name] = comment || null;
  1587. return this;
  1588. };
  1589. /**
  1590. * Removes a value from this enum
  1591. * @param {string} name Value name
  1592. * @returns {Enum} `this`
  1593. * @throws {TypeError} If arguments are invalid
  1594. * @throws {Error} If `name` is not a name of this enum
  1595. */
  1596. Enum.prototype.remove = function remove(name) {
  1597. if (!util.isString(name))
  1598. throw TypeError("name must be a string");
  1599. var val = this.values[name];
  1600. if (val == null)
  1601. throw Error("name '" + name + "' does not exist in " + this);
  1602. delete this.valuesById[val];
  1603. delete this.values[name];
  1604. delete this.comments[name];
  1605. return this;
  1606. };
  1607. /**
  1608. * Tests if the specified id is reserved.
  1609. * @param {number} id Id to test
  1610. * @returns {boolean} `true` if reserved, otherwise `false`
  1611. */
  1612. Enum.prototype.isReservedId = function isReservedId(id) {
  1613. return Namespace.isReservedId(this.reserved, id);
  1614. };
  1615. /**
  1616. * Tests if the specified name is reserved.
  1617. * @param {string} name Name to test
  1618. * @returns {boolean} `true` if reserved, otherwise `false`
  1619. */
  1620. Enum.prototype.isReservedName = function isReservedName(name) {
  1621. return Namespace.isReservedName(this.reserved, name);
  1622. };
  1623. },{"21":21,"22":22,"33":33}],15:[function(require,module,exports){
  1624. "use strict";
  1625. module.exports = Field;
  1626. // extends ReflectionObject
  1627. var ReflectionObject = require(22);
  1628. ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
  1629. var Enum = require(14),
  1630. types = require(32),
  1631. util = require(33);
  1632. var Type; // cyclic
  1633. var ruleRe = /^required|optional|repeated$/;
  1634. /**
  1635. * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
  1636. * @name Field
  1637. * @classdesc Reflected message field.
  1638. * @extends FieldBase
  1639. * @constructor
  1640. * @param {string} name Unique name within its namespace
  1641. * @param {number} id Unique id within its namespace
  1642. * @param {string} type Value type
  1643. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  1644. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  1645. * @param {Object.<string,*>} [options] Declared options
  1646. */
  1647. /**
  1648. * Constructs a field from a field descriptor.
  1649. * @param {string} name Field name
  1650. * @param {IField} json Field descriptor
  1651. * @returns {Field} Created field
  1652. * @throws {TypeError} If arguments are invalid
  1653. */
  1654. Field.fromJSON = function fromJSON(name, json) {
  1655. return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
  1656. };
  1657. /**
  1658. * Not an actual constructor. Use {@link Field} instead.
  1659. * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.
  1660. * @exports FieldBase
  1661. * @extends ReflectionObject
  1662. * @constructor
  1663. * @param {string} name Unique name within its namespace
  1664. * @param {number} id Unique id within its namespace
  1665. * @param {string} type Value type
  1666. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  1667. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  1668. * @param {Object.<string,*>} [options] Declared options
  1669. * @param {string} [comment] Comment associated with this field
  1670. */
  1671. function Field(name, id, type, rule, extend, options, comment) {
  1672. if (util.isObject(rule)) {
  1673. comment = extend;
  1674. options = rule;
  1675. rule = extend = undefined;
  1676. } else if (util.isObject(extend)) {
  1677. comment = options;
  1678. options = extend;
  1679. extend = undefined;
  1680. }
  1681. ReflectionObject.call(this, name, options);
  1682. if (!util.isInteger(id) || id < 0)
  1683. throw TypeError("id must be a non-negative integer");
  1684. if (!util.isString(type))
  1685. throw TypeError("type must be a string");
  1686. if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))
  1687. throw TypeError("rule must be a string rule");
  1688. if (extend !== undefined && !util.isString(extend))
  1689. throw TypeError("extend must be a string");
  1690. /**
  1691. * Field rule, if any.
  1692. * @type {string|undefined}
  1693. */
  1694. if (rule === "proto3_optional") {
  1695. rule = "optional";
  1696. }
  1697. this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON
  1698. /**
  1699. * Field type.
  1700. * @type {string}
  1701. */
  1702. this.type = type; // toJSON
  1703. /**
  1704. * Unique field id.
  1705. * @type {number}
  1706. */
  1707. this.id = id; // toJSON, marker
  1708. /**
  1709. * Extended type if different from parent.
  1710. * @type {string|undefined}
  1711. */
  1712. this.extend = extend || undefined; // toJSON
  1713. /**
  1714. * Whether this field is required.
  1715. * @type {boolean}
  1716. */
  1717. this.required = rule === "required";
  1718. /**
  1719. * Whether this field is optional.
  1720. * @type {boolean}
  1721. */
  1722. this.optional = !this.required;
  1723. /**
  1724. * Whether this field is repeated.
  1725. * @type {boolean}
  1726. */
  1727. this.repeated = rule === "repeated";
  1728. /**
  1729. * Whether this field is a map or not.
  1730. * @type {boolean}
  1731. */
  1732. this.map = false;
  1733. /**
  1734. * Message this field belongs to.
  1735. * @type {Type|null}
  1736. */
  1737. this.message = null;
  1738. /**
  1739. * OneOf this field belongs to, if any,
  1740. * @type {OneOf|null}
  1741. */
  1742. this.partOf = null;
  1743. /**
  1744. * The field type's default value.
  1745. * @type {*}
  1746. */
  1747. this.typeDefault = null;
  1748. /**
  1749. * The field's default value on prototypes.
  1750. * @type {*}
  1751. */
  1752. this.defaultValue = null;
  1753. /**
  1754. * Whether this field's value should be treated as a long.
  1755. * @type {boolean}
  1756. */
  1757. this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;
  1758. /**
  1759. * Whether this field's value is a buffer.
  1760. * @type {boolean}
  1761. */
  1762. this.bytes = type === "bytes";
  1763. /**
  1764. * Resolved type if not a basic type.
  1765. * @type {Type|Enum|null}
  1766. */
  1767. this.resolvedType = null;
  1768. /**
  1769. * Sister-field within the extended type if a declaring extension field.
  1770. * @type {Field|null}
  1771. */
  1772. this.extensionField = null;
  1773. /**
  1774. * Sister-field within the declaring namespace if an extended field.
  1775. * @type {Field|null}
  1776. */
  1777. this.declaringField = null;
  1778. /**
  1779. * Internally remembers whether this field is packed.
  1780. * @type {boolean|null}
  1781. * @private
  1782. */
  1783. this._packed = null;
  1784. /**
  1785. * Comment for this field.
  1786. * @type {string|null}
  1787. */
  1788. this.comment = comment;
  1789. }
  1790. /**
  1791. * Determines whether this field is packed. Only relevant when repeated and working with proto2.
  1792. * @name Field#packed
  1793. * @type {boolean}
  1794. * @readonly
  1795. */
  1796. Object.defineProperty(Field.prototype, "packed", {
  1797. get: function() {
  1798. // defaults to packed=true if not explicity set to false
  1799. if (this._packed === null)
  1800. this._packed = this.getOption("packed") !== false;
  1801. return this._packed;
  1802. }
  1803. });
  1804. /**
  1805. * @override
  1806. */
  1807. Field.prototype.setOption = function setOption(name, value, ifNotSet) {
  1808. if (name === "packed") // clear cached before setting
  1809. this._packed = null;
  1810. return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
  1811. };
  1812. /**
  1813. * Field descriptor.
  1814. * @interface IField
  1815. * @property {string} [rule="optional"] Field rule
  1816. * @property {string} type Field type
  1817. * @property {number} id Field id
  1818. * @property {Object.<string,*>} [options] Field options
  1819. */
  1820. /**
  1821. * Extension field descriptor.
  1822. * @interface IExtensionField
  1823. * @extends IField
  1824. * @property {string} extend Extended type
  1825. */
  1826. /**
  1827. * Converts this field to a field descriptor.
  1828. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1829. * @returns {IField} Field descriptor
  1830. */
  1831. Field.prototype.toJSON = function toJSON(toJSONOptions) {
  1832. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1833. return util.toObject([
  1834. "rule" , this.rule !== "optional" && this.rule || undefined,
  1835. "type" , this.type,
  1836. "id" , this.id,
  1837. "extend" , this.extend,
  1838. "options" , this.options,
  1839. "comment" , keepComments ? this.comment : undefined
  1840. ]);
  1841. };
  1842. /**
  1843. * Resolves this field's type references.
  1844. * @returns {Field} `this`
  1845. * @throws {Error} If any reference cannot be resolved
  1846. */
  1847. Field.prototype.resolve = function resolve() {
  1848. if (this.resolved)
  1849. return this;
  1850. if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it
  1851. this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
  1852. if (this.resolvedType instanceof Type)
  1853. this.typeDefault = null;
  1854. else // instanceof Enum
  1855. this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined
  1856. }
  1857. // use explicitly set default value if present
  1858. if (this.options && this.options["default"] != null) {
  1859. this.typeDefault = this.options["default"];
  1860. if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
  1861. this.typeDefault = this.resolvedType.values[this.typeDefault];
  1862. }
  1863. // remove unnecessary options
  1864. if (this.options) {
  1865. if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))
  1866. delete this.options.packed;
  1867. if (!Object.keys(this.options).length)
  1868. this.options = undefined;
  1869. }
  1870. // convert to internal data type if necesssary
  1871. if (this.long) {
  1872. this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");
  1873. /* istanbul ignore else */
  1874. if (Object.freeze)
  1875. Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)
  1876. } else if (this.bytes && typeof this.typeDefault === "string") {
  1877. var buf;
  1878. if (util.base64.test(this.typeDefault))
  1879. util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);
  1880. else
  1881. util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);
  1882. this.typeDefault = buf;
  1883. }
  1884. // take special care of maps and repeated fields
  1885. if (this.map)
  1886. this.defaultValue = util.emptyObject;
  1887. else if (this.repeated)
  1888. this.defaultValue = util.emptyArray;
  1889. else
  1890. this.defaultValue = this.typeDefault;
  1891. // ensure proper value on prototype
  1892. if (this.parent instanceof Type)
  1893. this.parent.ctor.prototype[this.name] = this.defaultValue;
  1894. return ReflectionObject.prototype.resolve.call(this);
  1895. };
  1896. /**
  1897. * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
  1898. * @typedef FieldDecorator
  1899. * @type {function}
  1900. * @param {Object} prototype Target prototype
  1901. * @param {string} fieldName Field name
  1902. * @returns {undefined}
  1903. */
  1904. /**
  1905. * Field decorator (TypeScript).
  1906. * @name Field.d
  1907. * @function
  1908. * @param {number} fieldId Field id
  1909. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type
  1910. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  1911. * @param {T} [defaultValue] Default value
  1912. * @returns {FieldDecorator} Decorator function
  1913. * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]
  1914. */
  1915. Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
  1916. // submessage: decorate the submessage and use its name as the type
  1917. if (typeof fieldType === "function")
  1918. fieldType = util.decorateType(fieldType).name;
  1919. // enum reference: create a reflected copy of the enum and keep reuseing it
  1920. else if (fieldType && typeof fieldType === "object")
  1921. fieldType = util.decorateEnum(fieldType).name;
  1922. return function fieldDecorator(prototype, fieldName) {
  1923. util.decorateType(prototype.constructor)
  1924. .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
  1925. };
  1926. };
  1927. /**
  1928. * Field decorator (TypeScript).
  1929. * @name Field.d
  1930. * @function
  1931. * @param {number} fieldId Field id
  1932. * @param {Constructor<T>|string} fieldType Field type
  1933. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  1934. * @returns {FieldDecorator} Decorator function
  1935. * @template T extends Message<T>
  1936. * @variation 2
  1937. */
  1938. // like Field.d but without a default value
  1939. // Sets up cyclic dependencies (called in index-light)
  1940. Field._configure = function configure(Type_) {
  1941. Type = Type_;
  1942. };
  1943. },{"14":14,"22":22,"32":32,"33":33}],16:[function(require,module,exports){
  1944. "use strict";
  1945. var protobuf = module.exports = require(17);
  1946. protobuf.build = "light";
  1947. /**
  1948. * A node-style callback as used by {@link load} and {@link Root#load}.
  1949. * @typedef LoadCallback
  1950. * @type {function}
  1951. * @param {Error|null} error Error, if any, otherwise `null`
  1952. * @param {Root} [root] Root, if there hasn't been an error
  1953. * @returns {undefined}
  1954. */
  1955. /**
  1956. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  1957. * @param {string|string[]} filename One or multiple files to load
  1958. * @param {Root} root Root namespace, defaults to create a new one if omitted.
  1959. * @param {LoadCallback} callback Callback function
  1960. * @returns {undefined}
  1961. * @see {@link Root#load}
  1962. */
  1963. function load(filename, root, callback) {
  1964. if (typeof root === "function") {
  1965. callback = root;
  1966. root = new protobuf.Root();
  1967. } else if (!root)
  1968. root = new protobuf.Root();
  1969. return root.load(filename, callback);
  1970. }
  1971. /**
  1972. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  1973. * @name load
  1974. * @function
  1975. * @param {string|string[]} filename One or multiple files to load
  1976. * @param {LoadCallback} callback Callback function
  1977. * @returns {undefined}
  1978. * @see {@link Root#load}
  1979. * @variation 2
  1980. */
  1981. // function load(filename:string, callback:LoadCallback):undefined
  1982. /**
  1983. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
  1984. * @name load
  1985. * @function
  1986. * @param {string|string[]} filename One or multiple files to load
  1987. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  1988. * @returns {Promise<Root>} Promise
  1989. * @see {@link Root#load}
  1990. * @variation 3
  1991. */
  1992. // function load(filename:string, [root:Root]):Promise<Root>
  1993. protobuf.load = load;
  1994. /**
  1995. * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
  1996. * @param {string|string[]} filename One or multiple files to load
  1997. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  1998. * @returns {Root} Root namespace
  1999. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  2000. * @see {@link Root#loadSync}
  2001. */
  2002. function loadSync(filename, root) {
  2003. if (!root)
  2004. root = new protobuf.Root();
  2005. return root.loadSync(filename);
  2006. }
  2007. protobuf.loadSync = loadSync;
  2008. // Serialization
  2009. protobuf.encoder = require(13);
  2010. protobuf.decoder = require(12);
  2011. protobuf.verifier = require(36);
  2012. protobuf.converter = require(11);
  2013. // Reflection
  2014. protobuf.ReflectionObject = require(22);
  2015. protobuf.Namespace = require(21);
  2016. protobuf.Root = require(26);
  2017. protobuf.Enum = require(14);
  2018. protobuf.Type = require(31);
  2019. protobuf.Field = require(15);
  2020. protobuf.OneOf = require(23);
  2021. protobuf.MapField = require(18);
  2022. protobuf.Service = require(30);
  2023. protobuf.Method = require(20);
  2024. // Runtime
  2025. protobuf.Message = require(19);
  2026. protobuf.wrappers = require(37);
  2027. // Utility
  2028. protobuf.types = require(32);
  2029. protobuf.util = require(33);
  2030. // Set up possibly cyclic reflection dependencies
  2031. protobuf.ReflectionObject._configure(protobuf.Root);
  2032. protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);
  2033. protobuf.Root._configure(protobuf.Type);
  2034. protobuf.Field._configure(protobuf.Type);
  2035. },{"11":11,"12":12,"13":13,"14":14,"15":15,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"26":26,"30":30,"31":31,"32":32,"33":33,"36":36,"37":37}],17:[function(require,module,exports){
  2036. "use strict";
  2037. var protobuf = exports;
  2038. /**
  2039. * Build type, one of `"full"`, `"light"` or `"minimal"`.
  2040. * @name build
  2041. * @type {string}
  2042. * @const
  2043. */
  2044. protobuf.build = "minimal";
  2045. // Serialization
  2046. protobuf.Writer = require(38);
  2047. protobuf.BufferWriter = require(39);
  2048. protobuf.Reader = require(24);
  2049. protobuf.BufferReader = require(25);
  2050. // Utility
  2051. protobuf.util = require(35);
  2052. protobuf.rpc = require(28);
  2053. protobuf.roots = require(27);
  2054. protobuf.configure = configure;
  2055. /* istanbul ignore next */
  2056. /**
  2057. * Reconfigures the library according to the environment.
  2058. * @returns {undefined}
  2059. */
  2060. function configure() {
  2061. protobuf.util._configure();
  2062. protobuf.Writer._configure(protobuf.BufferWriter);
  2063. protobuf.Reader._configure(protobuf.BufferReader);
  2064. }
  2065. // Set up buffer utility according to the environment
  2066. configure();
  2067. },{"24":24,"25":25,"27":27,"28":28,"35":35,"38":38,"39":39}],18:[function(require,module,exports){
  2068. "use strict";
  2069. module.exports = MapField;
  2070. // extends Field
  2071. var Field = require(15);
  2072. ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
  2073. var types = require(32),
  2074. util = require(33);
  2075. /**
  2076. * Constructs a new map field instance.
  2077. * @classdesc Reflected map field.
  2078. * @extends FieldBase
  2079. * @constructor
  2080. * @param {string} name Unique name within its namespace
  2081. * @param {number} id Unique id within its namespace
  2082. * @param {string} keyType Key type
  2083. * @param {string} type Value type
  2084. * @param {Object.<string,*>} [options] Declared options
  2085. * @param {string} [comment] Comment associated with this field
  2086. */
  2087. function MapField(name, id, keyType, type, options, comment) {
  2088. Field.call(this, name, id, type, undefined, undefined, options, comment);
  2089. /* istanbul ignore if */
  2090. if (!util.isString(keyType))
  2091. throw TypeError("keyType must be a string");
  2092. /**
  2093. * Key type.
  2094. * @type {string}
  2095. */
  2096. this.keyType = keyType; // toJSON, marker
  2097. /**
  2098. * Resolved key type if not a basic type.
  2099. * @type {ReflectionObject|null}
  2100. */
  2101. this.resolvedKeyType = null;
  2102. // Overrides Field#map
  2103. this.map = true;
  2104. }
  2105. /**
  2106. * Map field descriptor.
  2107. * @interface IMapField
  2108. * @extends {IField}
  2109. * @property {string} keyType Key type
  2110. */
  2111. /**
  2112. * Extension map field descriptor.
  2113. * @interface IExtensionMapField
  2114. * @extends IMapField
  2115. * @property {string} extend Extended type
  2116. */
  2117. /**
  2118. * Constructs a map field from a map field descriptor.
  2119. * @param {string} name Field name
  2120. * @param {IMapField} json Map field descriptor
  2121. * @returns {MapField} Created map field
  2122. * @throws {TypeError} If arguments are invalid
  2123. */
  2124. MapField.fromJSON = function fromJSON(name, json) {
  2125. return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);
  2126. };
  2127. /**
  2128. * Converts this map field to a map field descriptor.
  2129. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2130. * @returns {IMapField} Map field descriptor
  2131. */
  2132. MapField.prototype.toJSON = function toJSON(toJSONOptions) {
  2133. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2134. return util.toObject([
  2135. "keyType" , this.keyType,
  2136. "type" , this.type,
  2137. "id" , this.id,
  2138. "extend" , this.extend,
  2139. "options" , this.options,
  2140. "comment" , keepComments ? this.comment : undefined
  2141. ]);
  2142. };
  2143. /**
  2144. * @override
  2145. */
  2146. MapField.prototype.resolve = function resolve() {
  2147. if (this.resolved)
  2148. return this;
  2149. // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
  2150. if (types.mapKey[this.keyType] === undefined)
  2151. throw Error("invalid key type: " + this.keyType);
  2152. return Field.prototype.resolve.call(this);
  2153. };
  2154. /**
  2155. * Map field decorator (TypeScript).
  2156. * @name MapField.d
  2157. * @function
  2158. * @param {number} fieldId Field id
  2159. * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
  2160. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
  2161. * @returns {FieldDecorator} Decorator function
  2162. * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
  2163. */
  2164. MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
  2165. // submessage value: decorate the submessage and use its name as the type
  2166. if (typeof fieldValueType === "function")
  2167. fieldValueType = util.decorateType(fieldValueType).name;
  2168. // enum reference value: create a reflected copy of the enum and keep reuseing it
  2169. else if (fieldValueType && typeof fieldValueType === "object")
  2170. fieldValueType = util.decorateEnum(fieldValueType).name;
  2171. return function mapFieldDecorator(prototype, fieldName) {
  2172. util.decorateType(prototype.constructor)
  2173. .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
  2174. };
  2175. };
  2176. },{"15":15,"32":32,"33":33}],19:[function(require,module,exports){
  2177. "use strict";
  2178. module.exports = Message;
  2179. var util = require(35);
  2180. /**
  2181. * Constructs a new message instance.
  2182. * @classdesc Abstract runtime message.
  2183. * @constructor
  2184. * @param {Properties<T>} [properties] Properties to set
  2185. * @template T extends object = object
  2186. */
  2187. function Message(properties) {
  2188. // not used internally
  2189. if (properties)
  2190. for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
  2191. this[keys[i]] = properties[keys[i]];
  2192. }
  2193. /**
  2194. * Reference to the reflected type.
  2195. * @name Message.$type
  2196. * @type {Type}
  2197. * @readonly
  2198. */
  2199. /**
  2200. * Reference to the reflected type.
  2201. * @name Message#$type
  2202. * @type {Type}
  2203. * @readonly
  2204. */
  2205. /*eslint-disable valid-jsdoc*/
  2206. /**
  2207. * Creates a new message of this type using the specified properties.
  2208. * @param {Object.<string,*>} [properties] Properties to set
  2209. * @returns {Message<T>} Message instance
  2210. * @template T extends Message<T>
  2211. * @this Constructor<T>
  2212. */
  2213. Message.create = function create(properties) {
  2214. return this.$type.create(properties);
  2215. };
  2216. /**
  2217. * Encodes a message of this type.
  2218. * @param {T|Object.<string,*>} message Message to encode
  2219. * @param {Writer} [writer] Writer to use
  2220. * @returns {Writer} Writer
  2221. * @template T extends Message<T>
  2222. * @this Constructor<T>
  2223. */
  2224. Message.encode = function encode(message, writer) {
  2225. return this.$type.encode(message, writer);
  2226. };
  2227. /**
  2228. * Encodes a message of this type preceeded by its length as a varint.
  2229. * @param {T|Object.<string,*>} message Message to encode
  2230. * @param {Writer} [writer] Writer to use
  2231. * @returns {Writer} Writer
  2232. * @template T extends Message<T>
  2233. * @this Constructor<T>
  2234. */
  2235. Message.encodeDelimited = function encodeDelimited(message, writer) {
  2236. return this.$type.encodeDelimited(message, writer);
  2237. };
  2238. /**
  2239. * Decodes a message of this type.
  2240. * @name Message.decode
  2241. * @function
  2242. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  2243. * @returns {T} Decoded message
  2244. * @template T extends Message<T>
  2245. * @this Constructor<T>
  2246. */
  2247. Message.decode = function decode(reader) {
  2248. return this.$type.decode(reader);
  2249. };
  2250. /**
  2251. * Decodes a message of this type preceeded by its length as a varint.
  2252. * @name Message.decodeDelimited
  2253. * @function
  2254. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  2255. * @returns {T} Decoded message
  2256. * @template T extends Message<T>
  2257. * @this Constructor<T>
  2258. */
  2259. Message.decodeDelimited = function decodeDelimited(reader) {
  2260. return this.$type.decodeDelimited(reader);
  2261. };
  2262. /**
  2263. * Verifies a message of this type.
  2264. * @name Message.verify
  2265. * @function
  2266. * @param {Object.<string,*>} message Plain object to verify
  2267. * @returns {string|null} `null` if valid, otherwise the reason why it is not
  2268. */
  2269. Message.verify = function verify(message) {
  2270. return this.$type.verify(message);
  2271. };
  2272. /**
  2273. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  2274. * @param {Object.<string,*>} object Plain object
  2275. * @returns {T} Message instance
  2276. * @template T extends Message<T>
  2277. * @this Constructor<T>
  2278. */
  2279. Message.fromObject = function fromObject(object) {
  2280. return this.$type.fromObject(object);
  2281. };
  2282. /**
  2283. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  2284. * @param {T} message Message instance
  2285. * @param {IConversionOptions} [options] Conversion options
  2286. * @returns {Object.<string,*>} Plain object
  2287. * @template T extends Message<T>
  2288. * @this Constructor<T>
  2289. */
  2290. Message.toObject = function toObject(message, options) {
  2291. return this.$type.toObject(message, options);
  2292. };
  2293. /**
  2294. * Converts this message to JSON.
  2295. * @returns {Object.<string,*>} JSON object
  2296. */
  2297. Message.prototype.toJSON = function toJSON() {
  2298. return this.$type.toObject(this, util.toJSONOptions);
  2299. };
  2300. /*eslint-enable valid-jsdoc*/
  2301. },{"35":35}],20:[function(require,module,exports){
  2302. "use strict";
  2303. module.exports = Method;
  2304. // extends ReflectionObject
  2305. var ReflectionObject = require(22);
  2306. ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
  2307. var util = require(33);
  2308. /**
  2309. * Constructs a new service method instance.
  2310. * @classdesc Reflected service method.
  2311. * @extends ReflectionObject
  2312. * @constructor
  2313. * @param {string} name Method name
  2314. * @param {string|undefined} type Method type, usually `"rpc"`
  2315. * @param {string} requestType Request message type
  2316. * @param {string} responseType Response message type
  2317. * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed
  2318. * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed
  2319. * @param {Object.<string,*>} [options] Declared options
  2320. * @param {string} [comment] The comment for this method
  2321. * @param {Object.<string,*>} [parsedOptions] Declared options, properly parsed into an object
  2322. */
  2323. function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {
  2324. /* istanbul ignore next */
  2325. if (util.isObject(requestStream)) {
  2326. options = requestStream;
  2327. requestStream = responseStream = undefined;
  2328. } else if (util.isObject(responseStream)) {
  2329. options = responseStream;
  2330. responseStream = undefined;
  2331. }
  2332. /* istanbul ignore if */
  2333. if (!(type === undefined || util.isString(type)))
  2334. throw TypeError("type must be a string");
  2335. /* istanbul ignore if */
  2336. if (!util.isString(requestType))
  2337. throw TypeError("requestType must be a string");
  2338. /* istanbul ignore if */
  2339. if (!util.isString(responseType))
  2340. throw TypeError("responseType must be a string");
  2341. ReflectionObject.call(this, name, options);
  2342. /**
  2343. * Method type.
  2344. * @type {string}
  2345. */
  2346. this.type = type || "rpc"; // toJSON
  2347. /**
  2348. * Request type.
  2349. * @type {string}
  2350. */
  2351. this.requestType = requestType; // toJSON, marker
  2352. /**
  2353. * Whether requests are streamed or not.
  2354. * @type {boolean|undefined}
  2355. */
  2356. this.requestStream = requestStream ? true : undefined; // toJSON
  2357. /**
  2358. * Response type.
  2359. * @type {string}
  2360. */
  2361. this.responseType = responseType; // toJSON
  2362. /**
  2363. * Whether responses are streamed or not.
  2364. * @type {boolean|undefined}
  2365. */
  2366. this.responseStream = responseStream ? true : undefined; // toJSON
  2367. /**
  2368. * Resolved request type.
  2369. * @type {Type|null}
  2370. */
  2371. this.resolvedRequestType = null;
  2372. /**
  2373. * Resolved response type.
  2374. * @type {Type|null}
  2375. */
  2376. this.resolvedResponseType = null;
  2377. /**
  2378. * Comment for this method
  2379. * @type {string|null}
  2380. */
  2381. this.comment = comment;
  2382. /**
  2383. * Options properly parsed into an object
  2384. */
  2385. this.parsedOptions = parsedOptions;
  2386. }
  2387. /**
  2388. * Method descriptor.
  2389. * @interface IMethod
  2390. * @property {string} [type="rpc"] Method type
  2391. * @property {string} requestType Request type
  2392. * @property {string} responseType Response type
  2393. * @property {boolean} [requestStream=false] Whether requests are streamed
  2394. * @property {boolean} [responseStream=false] Whether responses are streamed
  2395. * @property {Object.<string,*>} [options] Method options
  2396. * @property {string} comment Method comments
  2397. * @property {Object.<string,*>} [parsedOptions] Method options properly parsed into an object
  2398. */
  2399. /**
  2400. * Constructs a method from a method descriptor.
  2401. * @param {string} name Method name
  2402. * @param {IMethod} json Method descriptor
  2403. * @returns {Method} Created method
  2404. * @throws {TypeError} If arguments are invalid
  2405. */
  2406. Method.fromJSON = function fromJSON(name, json) {
  2407. return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);
  2408. };
  2409. /**
  2410. * Converts this method to a method descriptor.
  2411. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2412. * @returns {IMethod} Method descriptor
  2413. */
  2414. Method.prototype.toJSON = function toJSON(toJSONOptions) {
  2415. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2416. return util.toObject([
  2417. "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,
  2418. "requestType" , this.requestType,
  2419. "requestStream" , this.requestStream,
  2420. "responseType" , this.responseType,
  2421. "responseStream" , this.responseStream,
  2422. "options" , this.options,
  2423. "comment" , keepComments ? this.comment : undefined,
  2424. "parsedOptions" , this.parsedOptions,
  2425. ]);
  2426. };
  2427. /**
  2428. * @override
  2429. */
  2430. Method.prototype.resolve = function resolve() {
  2431. /* istanbul ignore if */
  2432. if (this.resolved)
  2433. return this;
  2434. this.resolvedRequestType = this.parent.lookupType(this.requestType);
  2435. this.resolvedResponseType = this.parent.lookupType(this.responseType);
  2436. return ReflectionObject.prototype.resolve.call(this);
  2437. };
  2438. },{"22":22,"33":33}],21:[function(require,module,exports){
  2439. "use strict";
  2440. module.exports = Namespace;
  2441. // extends ReflectionObject
  2442. var ReflectionObject = require(22);
  2443. ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
  2444. var Field = require(15),
  2445. util = require(33);
  2446. var Type, // cyclic
  2447. Service,
  2448. Enum;
  2449. /**
  2450. * Constructs a new namespace instance.
  2451. * @name Namespace
  2452. * @classdesc Reflected namespace.
  2453. * @extends NamespaceBase
  2454. * @constructor
  2455. * @param {string} name Namespace name
  2456. * @param {Object.<string,*>} [options] Declared options
  2457. */
  2458. /**
  2459. * Constructs a namespace from JSON.
  2460. * @memberof Namespace
  2461. * @function
  2462. * @param {string} name Namespace name
  2463. * @param {Object.<string,*>} json JSON object
  2464. * @returns {Namespace} Created namespace
  2465. * @throws {TypeError} If arguments are invalid
  2466. */
  2467. Namespace.fromJSON = function fromJSON(name, json) {
  2468. return new Namespace(name, json.options).addJSON(json.nested);
  2469. };
  2470. /**
  2471. * Converts an array of reflection objects to JSON.
  2472. * @memberof Namespace
  2473. * @param {ReflectionObject[]} array Object array
  2474. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2475. * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty
  2476. */
  2477. function arrayToJSON(array, toJSONOptions) {
  2478. if (!(array && array.length))
  2479. return undefined;
  2480. var obj = {};
  2481. for (var i = 0; i < array.length; ++i)
  2482. obj[array[i].name] = array[i].toJSON(toJSONOptions);
  2483. return obj;
  2484. }
  2485. Namespace.arrayToJSON = arrayToJSON;
  2486. /**
  2487. * Tests if the specified id is reserved.
  2488. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2489. * @param {number} id Id to test
  2490. * @returns {boolean} `true` if reserved, otherwise `false`
  2491. */
  2492. Namespace.isReservedId = function isReservedId(reserved, id) {
  2493. if (reserved)
  2494. for (var i = 0; i < reserved.length; ++i)
  2495. if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id)
  2496. return true;
  2497. return false;
  2498. };
  2499. /**
  2500. * Tests if the specified name is reserved.
  2501. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2502. * @param {string} name Name to test
  2503. * @returns {boolean} `true` if reserved, otherwise `false`
  2504. */
  2505. Namespace.isReservedName = function isReservedName(reserved, name) {
  2506. if (reserved)
  2507. for (var i = 0; i < reserved.length; ++i)
  2508. if (reserved[i] === name)
  2509. return true;
  2510. return false;
  2511. };
  2512. /**
  2513. * Not an actual constructor. Use {@link Namespace} instead.
  2514. * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.
  2515. * @exports NamespaceBase
  2516. * @extends ReflectionObject
  2517. * @abstract
  2518. * @constructor
  2519. * @param {string} name Namespace name
  2520. * @param {Object.<string,*>} [options] Declared options
  2521. * @see {@link Namespace}
  2522. */
  2523. function Namespace(name, options) {
  2524. ReflectionObject.call(this, name, options);
  2525. /**
  2526. * Nested objects by name.
  2527. * @type {Object.<string,ReflectionObject>|undefined}
  2528. */
  2529. this.nested = undefined; // toJSON
  2530. /**
  2531. * Cached nested objects as an array.
  2532. * @type {ReflectionObject[]|null}
  2533. * @private
  2534. */
  2535. this._nestedArray = null;
  2536. }
  2537. function clearCache(namespace) {
  2538. namespace._nestedArray = null;
  2539. return namespace;
  2540. }
  2541. /**
  2542. * Nested objects of this namespace as an array for iteration.
  2543. * @name NamespaceBase#nestedArray
  2544. * @type {ReflectionObject[]}
  2545. * @readonly
  2546. */
  2547. Object.defineProperty(Namespace.prototype, "nestedArray", {
  2548. get: function() {
  2549. return this._nestedArray || (this._nestedArray = util.toArray(this.nested));
  2550. }
  2551. });
  2552. /**
  2553. * Namespace descriptor.
  2554. * @interface INamespace
  2555. * @property {Object.<string,*>} [options] Namespace options
  2556. * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors
  2557. */
  2558. /**
  2559. * Any extension field descriptor.
  2560. * @typedef AnyExtensionField
  2561. * @type {IExtensionField|IExtensionMapField}
  2562. */
  2563. /**
  2564. * Any nested object descriptor.
  2565. * @typedef AnyNestedObject
  2566. * @type {IEnum|IType|IService|AnyExtensionField|INamespace}
  2567. */
  2568. // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)
  2569. /**
  2570. * Converts this namespace to a namespace descriptor.
  2571. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2572. * @returns {INamespace} Namespace descriptor
  2573. */
  2574. Namespace.prototype.toJSON = function toJSON(toJSONOptions) {
  2575. return util.toObject([
  2576. "options" , this.options,
  2577. "nested" , arrayToJSON(this.nestedArray, toJSONOptions)
  2578. ]);
  2579. };
  2580. /**
  2581. * Adds nested objects to this namespace from nested object descriptors.
  2582. * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors
  2583. * @returns {Namespace} `this`
  2584. */
  2585. Namespace.prototype.addJSON = function addJSON(nestedJson) {
  2586. var ns = this;
  2587. /* istanbul ignore else */
  2588. if (nestedJson) {
  2589. for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
  2590. nested = nestedJson[names[i]];
  2591. ns.add( // most to least likely
  2592. ( nested.fields !== undefined
  2593. ? Type.fromJSON
  2594. : nested.values !== undefined
  2595. ? Enum.fromJSON
  2596. : nested.methods !== undefined
  2597. ? Service.fromJSON
  2598. : nested.id !== undefined
  2599. ? Field.fromJSON
  2600. : Namespace.fromJSON )(names[i], nested)
  2601. );
  2602. }
  2603. }
  2604. return this;
  2605. };
  2606. /**
  2607. * Gets the nested object of the specified name.
  2608. * @param {string} name Nested object name
  2609. * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist
  2610. */
  2611. Namespace.prototype.get = function get(name) {
  2612. return this.nested && this.nested[name]
  2613. || null;
  2614. };
  2615. /**
  2616. * Gets the values of the nested {@link Enum|enum} of the specified name.
  2617. * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
  2618. * @param {string} name Nested enum name
  2619. * @returns {Object.<string,number>} Enum values
  2620. * @throws {Error} If there is no such enum
  2621. */
  2622. Namespace.prototype.getEnum = function getEnum(name) {
  2623. if (this.nested && this.nested[name] instanceof Enum)
  2624. return this.nested[name].values;
  2625. throw Error("no such enum: " + name);
  2626. };
  2627. /**
  2628. * Adds a nested object to this namespace.
  2629. * @param {ReflectionObject} object Nested object to add
  2630. * @returns {Namespace} `this`
  2631. * @throws {TypeError} If arguments are invalid
  2632. * @throws {Error} If there is already a nested object with this name
  2633. */
  2634. Namespace.prototype.add = function add(object) {
  2635. if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))
  2636. throw TypeError("object must be a valid nested object");
  2637. if (!this.nested)
  2638. this.nested = {};
  2639. else {
  2640. var prev = this.get(object.name);
  2641. if (prev) {
  2642. if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
  2643. // replace plain namespace but keep existing nested elements and options
  2644. var nested = prev.nestedArray;
  2645. for (var i = 0; i < nested.length; ++i)
  2646. object.add(nested[i]);
  2647. this.remove(prev);
  2648. if (!this.nested)
  2649. this.nested = {};
  2650. object.setOptions(prev.options, true);
  2651. } else
  2652. throw Error("duplicate name '" + object.name + "' in " + this);
  2653. }
  2654. }
  2655. this.nested[object.name] = object;
  2656. object.onAdd(this);
  2657. return clearCache(this);
  2658. };
  2659. /**
  2660. * Removes a nested object from this namespace.
  2661. * @param {ReflectionObject} object Nested object to remove
  2662. * @returns {Namespace} `this`
  2663. * @throws {TypeError} If arguments are invalid
  2664. * @throws {Error} If `object` is not a member of this namespace
  2665. */
  2666. Namespace.prototype.remove = function remove(object) {
  2667. if (!(object instanceof ReflectionObject))
  2668. throw TypeError("object must be a ReflectionObject");
  2669. if (object.parent !== this)
  2670. throw Error(object + " is not a member of " + this);
  2671. delete this.nested[object.name];
  2672. if (!Object.keys(this.nested).length)
  2673. this.nested = undefined;
  2674. object.onRemove(this);
  2675. return clearCache(this);
  2676. };
  2677. /**
  2678. * Defines additial namespaces within this one if not yet existing.
  2679. * @param {string|string[]} path Path to create
  2680. * @param {*} [json] Nested types to create from JSON
  2681. * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty
  2682. */
  2683. Namespace.prototype.define = function define(path, json) {
  2684. if (util.isString(path))
  2685. path = path.split(".");
  2686. else if (!Array.isArray(path))
  2687. throw TypeError("illegal path");
  2688. if (path && path.length && path[0] === "")
  2689. throw Error("path must be relative");
  2690. var ptr = this;
  2691. while (path.length > 0) {
  2692. var part = path.shift();
  2693. if (ptr.nested && ptr.nested[part]) {
  2694. ptr = ptr.nested[part];
  2695. if (!(ptr instanceof Namespace))
  2696. throw Error("path conflicts with non-namespace objects");
  2697. } else
  2698. ptr.add(ptr = new Namespace(part));
  2699. }
  2700. if (json)
  2701. ptr.addJSON(json);
  2702. return ptr;
  2703. };
  2704. /**
  2705. * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
  2706. * @returns {Namespace} `this`
  2707. */
  2708. Namespace.prototype.resolveAll = function resolveAll() {
  2709. var nested = this.nestedArray, i = 0;
  2710. while (i < nested.length)
  2711. if (nested[i] instanceof Namespace)
  2712. nested[i++].resolveAll();
  2713. else
  2714. nested[i++].resolve();
  2715. return this.resolve();
  2716. };
  2717. /**
  2718. * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
  2719. * @param {string|string[]} path Path to look up
  2720. * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
  2721. * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked
  2722. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  2723. */
  2724. Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {
  2725. /* istanbul ignore next */
  2726. if (typeof filterTypes === "boolean") {
  2727. parentAlreadyChecked = filterTypes;
  2728. filterTypes = undefined;
  2729. } else if (filterTypes && !Array.isArray(filterTypes))
  2730. filterTypes = [ filterTypes ];
  2731. if (util.isString(path) && path.length) {
  2732. if (path === ".")
  2733. return this.root;
  2734. path = path.split(".");
  2735. } else if (!path.length)
  2736. return this;
  2737. // Start at root if path is absolute
  2738. if (path[0] === "")
  2739. return this.root.lookup(path.slice(1), filterTypes);
  2740. // Test if the first part matches any nested object, and if so, traverse if path contains more
  2741. var found = this.get(path[0]);
  2742. if (found) {
  2743. if (path.length === 1) {
  2744. if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)
  2745. return found;
  2746. } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))
  2747. return found;
  2748. // Otherwise try each nested namespace
  2749. } else
  2750. for (var i = 0; i < this.nestedArray.length; ++i)
  2751. if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))
  2752. return found;
  2753. // If there hasn't been a match, try again at the parent
  2754. if (this.parent === null || parentAlreadyChecked)
  2755. return null;
  2756. return this.parent.lookup(path, filterTypes);
  2757. };
  2758. /**
  2759. * Looks up the reflection object at the specified path, relative to this namespace.
  2760. * @name NamespaceBase#lookup
  2761. * @function
  2762. * @param {string|string[]} path Path to look up
  2763. * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked
  2764. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  2765. * @variation 2
  2766. */
  2767. // lookup(path: string, [parentAlreadyChecked: boolean])
  2768. /**
  2769. * Looks up the {@link Type|type} at the specified path, relative to this namespace.
  2770. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2771. * @param {string|string[]} path Path to look up
  2772. * @returns {Type} Looked up type
  2773. * @throws {Error} If `path` does not point to a type
  2774. */
  2775. Namespace.prototype.lookupType = function lookupType(path) {
  2776. var found = this.lookup(path, [ Type ]);
  2777. if (!found)
  2778. throw Error("no such type: " + path);
  2779. return found;
  2780. };
  2781. /**
  2782. * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
  2783. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2784. * @param {string|string[]} path Path to look up
  2785. * @returns {Enum} Looked up enum
  2786. * @throws {Error} If `path` does not point to an enum
  2787. */
  2788. Namespace.prototype.lookupEnum = function lookupEnum(path) {
  2789. var found = this.lookup(path, [ Enum ]);
  2790. if (!found)
  2791. throw Error("no such Enum '" + path + "' in " + this);
  2792. return found;
  2793. };
  2794. /**
  2795. * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
  2796. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2797. * @param {string|string[]} path Path to look up
  2798. * @returns {Type} Looked up type or enum
  2799. * @throws {Error} If `path` does not point to a type or enum
  2800. */
  2801. Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {
  2802. var found = this.lookup(path, [ Type, Enum ]);
  2803. if (!found)
  2804. throw Error("no such Type or Enum '" + path + "' in " + this);
  2805. return found;
  2806. };
  2807. /**
  2808. * Looks up the {@link Service|service} at the specified path, relative to this namespace.
  2809. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2810. * @param {string|string[]} path Path to look up
  2811. * @returns {Service} Looked up service
  2812. * @throws {Error} If `path` does not point to a service
  2813. */
  2814. Namespace.prototype.lookupService = function lookupService(path) {
  2815. var found = this.lookup(path, [ Service ]);
  2816. if (!found)
  2817. throw Error("no such Service '" + path + "' in " + this);
  2818. return found;
  2819. };
  2820. // Sets up cyclic dependencies (called in index-light)
  2821. Namespace._configure = function(Type_, Service_, Enum_) {
  2822. Type = Type_;
  2823. Service = Service_;
  2824. Enum = Enum_;
  2825. };
  2826. },{"15":15,"22":22,"33":33}],22:[function(require,module,exports){
  2827. "use strict";
  2828. module.exports = ReflectionObject;
  2829. ReflectionObject.className = "ReflectionObject";
  2830. var util = require(33);
  2831. var Root; // cyclic
  2832. /**
  2833. * Constructs a new reflection object instance.
  2834. * @classdesc Base class of all reflection objects.
  2835. * @constructor
  2836. * @param {string} name Object name
  2837. * @param {Object.<string,*>} [options] Declared options
  2838. * @abstract
  2839. */
  2840. function ReflectionObject(name, options) {
  2841. if (!util.isString(name))
  2842. throw TypeError("name must be a string");
  2843. if (options && !util.isObject(options))
  2844. throw TypeError("options must be an object");
  2845. /**
  2846. * Options.
  2847. * @type {Object.<string,*>|undefined}
  2848. */
  2849. this.options = options; // toJSON
  2850. /**
  2851. * Parsed Options.
  2852. * @type {Array.<Object.<string,*>>|undefined}
  2853. */
  2854. this.parsedOptions = null;
  2855. /**
  2856. * Unique name within its namespace.
  2857. * @type {string}
  2858. */
  2859. this.name = name;
  2860. /**
  2861. * Parent namespace.
  2862. * @type {Namespace|null}
  2863. */
  2864. this.parent = null;
  2865. /**
  2866. * Whether already resolved or not.
  2867. * @type {boolean}
  2868. */
  2869. this.resolved = false;
  2870. /**
  2871. * Comment text, if any.
  2872. * @type {string|null}
  2873. */
  2874. this.comment = null;
  2875. /**
  2876. * Defining file name.
  2877. * @type {string|null}
  2878. */
  2879. this.filename = null;
  2880. }
  2881. Object.defineProperties(ReflectionObject.prototype, {
  2882. /**
  2883. * Reference to the root namespace.
  2884. * @name ReflectionObject#root
  2885. * @type {Root}
  2886. * @readonly
  2887. */
  2888. root: {
  2889. get: function() {
  2890. var ptr = this;
  2891. while (ptr.parent !== null)
  2892. ptr = ptr.parent;
  2893. return ptr;
  2894. }
  2895. },
  2896. /**
  2897. * Full name including leading dot.
  2898. * @name ReflectionObject#fullName
  2899. * @type {string}
  2900. * @readonly
  2901. */
  2902. fullName: {
  2903. get: function() {
  2904. var path = [ this.name ],
  2905. ptr = this.parent;
  2906. while (ptr) {
  2907. path.unshift(ptr.name);
  2908. ptr = ptr.parent;
  2909. }
  2910. return path.join(".");
  2911. }
  2912. }
  2913. });
  2914. /**
  2915. * Converts this reflection object to its descriptor representation.
  2916. * @returns {Object.<string,*>} Descriptor
  2917. * @abstract
  2918. */
  2919. ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {
  2920. throw Error(); // not implemented, shouldn't happen
  2921. };
  2922. /**
  2923. * Called when this object is added to a parent.
  2924. * @param {ReflectionObject} parent Parent added to
  2925. * @returns {undefined}
  2926. */
  2927. ReflectionObject.prototype.onAdd = function onAdd(parent) {
  2928. if (this.parent && this.parent !== parent)
  2929. this.parent.remove(this);
  2930. this.parent = parent;
  2931. this.resolved = false;
  2932. var root = parent.root;
  2933. if (root instanceof Root)
  2934. root._handleAdd(this);
  2935. };
  2936. /**
  2937. * Called when this object is removed from a parent.
  2938. * @param {ReflectionObject} parent Parent removed from
  2939. * @returns {undefined}
  2940. */
  2941. ReflectionObject.prototype.onRemove = function onRemove(parent) {
  2942. var root = parent.root;
  2943. if (root instanceof Root)
  2944. root._handleRemove(this);
  2945. this.parent = null;
  2946. this.resolved = false;
  2947. };
  2948. /**
  2949. * Resolves this objects type references.
  2950. * @returns {ReflectionObject} `this`
  2951. */
  2952. ReflectionObject.prototype.resolve = function resolve() {
  2953. if (this.resolved)
  2954. return this;
  2955. if (this.root instanceof Root)
  2956. this.resolved = true; // only if part of a root
  2957. return this;
  2958. };
  2959. /**
  2960. * Gets an option value.
  2961. * @param {string} name Option name
  2962. * @returns {*} Option value or `undefined` if not set
  2963. */
  2964. ReflectionObject.prototype.getOption = function getOption(name) {
  2965. if (this.options)
  2966. return this.options[name];
  2967. return undefined;
  2968. };
  2969. /**
  2970. * Sets an option.
  2971. * @param {string} name Option name
  2972. * @param {*} value Option value
  2973. * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set
  2974. * @returns {ReflectionObject} `this`
  2975. */
  2976. ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {
  2977. if (!ifNotSet || !this.options || this.options[name] === undefined)
  2978. (this.options || (this.options = {}))[name] = value;
  2979. return this;
  2980. };
  2981. /**
  2982. * Sets a parsed option.
  2983. * @param {string} name parsed Option name
  2984. * @param {*} value Option value
  2985. * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value
  2986. * @returns {ReflectionObject} `this`
  2987. */
  2988. ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {
  2989. if (!this.parsedOptions) {
  2990. this.parsedOptions = [];
  2991. }
  2992. var parsedOptions = this.parsedOptions;
  2993. if (propName) {
  2994. // If setting a sub property of an option then try to merge it
  2995. // with an existing option
  2996. var opt = parsedOptions.find(function (opt) {
  2997. return Object.prototype.hasOwnProperty.call(opt, name);
  2998. });
  2999. if (opt) {
  3000. // If we found an existing option - just merge the property value
  3001. var newValue = opt[name];
  3002. util.setProperty(newValue, propName, value);
  3003. } else {
  3004. // otherwise, create a new option, set it's property and add it to the list
  3005. opt = {};
  3006. opt[name] = util.setProperty({}, propName, value);
  3007. parsedOptions.push(opt);
  3008. }
  3009. } else {
  3010. // Always create a new option when setting the value of the option itself
  3011. var newOpt = {};
  3012. newOpt[name] = value;
  3013. parsedOptions.push(newOpt);
  3014. }
  3015. return this;
  3016. };
  3017. /**
  3018. * Sets multiple options.
  3019. * @param {Object.<string,*>} options Options to set
  3020. * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set
  3021. * @returns {ReflectionObject} `this`
  3022. */
  3023. ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {
  3024. if (options)
  3025. for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)
  3026. this.setOption(keys[i], options[keys[i]], ifNotSet);
  3027. return this;
  3028. };
  3029. /**
  3030. * Converts this instance to its string representation.
  3031. * @returns {string} Class name[, space, full name]
  3032. */
  3033. ReflectionObject.prototype.toString = function toString() {
  3034. var className = this.constructor.className,
  3035. fullName = this.fullName;
  3036. if (fullName.length)
  3037. return className + " " + fullName;
  3038. return className;
  3039. };
  3040. // Sets up cyclic dependencies (called in index-light)
  3041. ReflectionObject._configure = function(Root_) {
  3042. Root = Root_;
  3043. };
  3044. },{"33":33}],23:[function(require,module,exports){
  3045. "use strict";
  3046. module.exports = OneOf;
  3047. // extends ReflectionObject
  3048. var ReflectionObject = require(22);
  3049. ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
  3050. var Field = require(15),
  3051. util = require(33);
  3052. /**
  3053. * Constructs a new oneof instance.
  3054. * @classdesc Reflected oneof.
  3055. * @extends ReflectionObject
  3056. * @constructor
  3057. * @param {string} name Oneof name
  3058. * @param {string[]|Object.<string,*>} [fieldNames] Field names
  3059. * @param {Object.<string,*>} [options] Declared options
  3060. * @param {string} [comment] Comment associated with this field
  3061. */
  3062. function OneOf(name, fieldNames, options, comment) {
  3063. if (!Array.isArray(fieldNames)) {
  3064. options = fieldNames;
  3065. fieldNames = undefined;
  3066. }
  3067. ReflectionObject.call(this, name, options);
  3068. /* istanbul ignore if */
  3069. if (!(fieldNames === undefined || Array.isArray(fieldNames)))
  3070. throw TypeError("fieldNames must be an Array");
  3071. /**
  3072. * Field names that belong to this oneof.
  3073. * @type {string[]}
  3074. */
  3075. this.oneof = fieldNames || []; // toJSON, marker
  3076. /**
  3077. * Fields that belong to this oneof as an array for iteration.
  3078. * @type {Field[]}
  3079. * @readonly
  3080. */
  3081. this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent
  3082. /**
  3083. * Comment for this field.
  3084. * @type {string|null}
  3085. */
  3086. this.comment = comment;
  3087. }
  3088. /**
  3089. * Oneof descriptor.
  3090. * @interface IOneOf
  3091. * @property {Array.<string>} oneof Oneof field names
  3092. * @property {Object.<string,*>} [options] Oneof options
  3093. */
  3094. /**
  3095. * Constructs a oneof from a oneof descriptor.
  3096. * @param {string} name Oneof name
  3097. * @param {IOneOf} json Oneof descriptor
  3098. * @returns {OneOf} Created oneof
  3099. * @throws {TypeError} If arguments are invalid
  3100. */
  3101. OneOf.fromJSON = function fromJSON(name, json) {
  3102. return new OneOf(name, json.oneof, json.options, json.comment);
  3103. };
  3104. /**
  3105. * Converts this oneof to a oneof descriptor.
  3106. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  3107. * @returns {IOneOf} Oneof descriptor
  3108. */
  3109. OneOf.prototype.toJSON = function toJSON(toJSONOptions) {
  3110. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  3111. return util.toObject([
  3112. "options" , this.options,
  3113. "oneof" , this.oneof,
  3114. "comment" , keepComments ? this.comment : undefined
  3115. ]);
  3116. };
  3117. /**
  3118. * Adds the fields of the specified oneof to the parent if not already done so.
  3119. * @param {OneOf} oneof The oneof
  3120. * @returns {undefined}
  3121. * @inner
  3122. * @ignore
  3123. */
  3124. function addFieldsToParent(oneof) {
  3125. if (oneof.parent)
  3126. for (var i = 0; i < oneof.fieldsArray.length; ++i)
  3127. if (!oneof.fieldsArray[i].parent)
  3128. oneof.parent.add(oneof.fieldsArray[i]);
  3129. }
  3130. /**
  3131. * Adds a field to this oneof and removes it from its current parent, if any.
  3132. * @param {Field} field Field to add
  3133. * @returns {OneOf} `this`
  3134. */
  3135. OneOf.prototype.add = function add(field) {
  3136. /* istanbul ignore if */
  3137. if (!(field instanceof Field))
  3138. throw TypeError("field must be a Field");
  3139. if (field.parent && field.parent !== this.parent)
  3140. field.parent.remove(field);
  3141. this.oneof.push(field.name);
  3142. this.fieldsArray.push(field);
  3143. field.partOf = this; // field.parent remains null
  3144. addFieldsToParent(this);
  3145. return this;
  3146. };
  3147. /**
  3148. * Removes a field from this oneof and puts it back to the oneof's parent.
  3149. * @param {Field} field Field to remove
  3150. * @returns {OneOf} `this`
  3151. */
  3152. OneOf.prototype.remove = function remove(field) {
  3153. /* istanbul ignore if */
  3154. if (!(field instanceof Field))
  3155. throw TypeError("field must be a Field");
  3156. var index = this.fieldsArray.indexOf(field);
  3157. /* istanbul ignore if */
  3158. if (index < 0)
  3159. throw Error(field + " is not a member of " + this);
  3160. this.fieldsArray.splice(index, 1);
  3161. index = this.oneof.indexOf(field.name);
  3162. /* istanbul ignore else */
  3163. if (index > -1) // theoretical
  3164. this.oneof.splice(index, 1);
  3165. field.partOf = null;
  3166. return this;
  3167. };
  3168. /**
  3169. * @override
  3170. */
  3171. OneOf.prototype.onAdd = function onAdd(parent) {
  3172. ReflectionObject.prototype.onAdd.call(this, parent);
  3173. var self = this;
  3174. // Collect present fields
  3175. for (var i = 0; i < this.oneof.length; ++i) {
  3176. var field = parent.get(this.oneof[i]);
  3177. if (field && !field.partOf) {
  3178. field.partOf = self;
  3179. self.fieldsArray.push(field);
  3180. }
  3181. }
  3182. // Add not yet present fields
  3183. addFieldsToParent(this);
  3184. };
  3185. /**
  3186. * @override
  3187. */
  3188. OneOf.prototype.onRemove = function onRemove(parent) {
  3189. for (var i = 0, field; i < this.fieldsArray.length; ++i)
  3190. if ((field = this.fieldsArray[i]).parent)
  3191. field.parent.remove(field);
  3192. ReflectionObject.prototype.onRemove.call(this, parent);
  3193. };
  3194. /**
  3195. * Decorator function as returned by {@link OneOf.d} (TypeScript).
  3196. * @typedef OneOfDecorator
  3197. * @type {function}
  3198. * @param {Object} prototype Target prototype
  3199. * @param {string} oneofName OneOf name
  3200. * @returns {undefined}
  3201. */
  3202. /**
  3203. * OneOf decorator (TypeScript).
  3204. * @function
  3205. * @param {...string} fieldNames Field names
  3206. * @returns {OneOfDecorator} Decorator function
  3207. * @template T extends string
  3208. */
  3209. OneOf.d = function decorateOneOf() {
  3210. var fieldNames = new Array(arguments.length),
  3211. index = 0;
  3212. while (index < arguments.length)
  3213. fieldNames[index] = arguments[index++];
  3214. return function oneOfDecorator(prototype, oneofName) {
  3215. util.decorateType(prototype.constructor)
  3216. .add(new OneOf(oneofName, fieldNames));
  3217. Object.defineProperty(prototype, oneofName, {
  3218. get: util.oneOfGetter(fieldNames),
  3219. set: util.oneOfSetter(fieldNames)
  3220. });
  3221. };
  3222. };
  3223. },{"15":15,"22":22,"33":33}],24:[function(require,module,exports){
  3224. "use strict";
  3225. module.exports = Reader;
  3226. var util = require(35);
  3227. var BufferReader; // cyclic
  3228. var LongBits = util.LongBits,
  3229. utf8 = util.utf8;
  3230. /* istanbul ignore next */
  3231. function indexOutOfRange(reader, writeLength) {
  3232. return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
  3233. }
  3234. /**
  3235. * Constructs a new reader instance using the specified buffer.
  3236. * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
  3237. * @constructor
  3238. * @param {Uint8Array} buffer Buffer to read from
  3239. */
  3240. function Reader(buffer) {
  3241. /**
  3242. * Read buffer.
  3243. * @type {Uint8Array}
  3244. */
  3245. this.buf = buffer;
  3246. /**
  3247. * Read buffer position.
  3248. * @type {number}
  3249. */
  3250. this.pos = 0;
  3251. /**
  3252. * Read buffer length.
  3253. * @type {number}
  3254. */
  3255. this.len = buffer.length;
  3256. }
  3257. var create_array = typeof Uint8Array !== "undefined"
  3258. ? function create_typed_array(buffer) {
  3259. if (buffer instanceof Uint8Array || Array.isArray(buffer))
  3260. return new Reader(buffer);
  3261. throw Error("illegal buffer");
  3262. }
  3263. /* istanbul ignore next */
  3264. : function create_array(buffer) {
  3265. if (Array.isArray(buffer))
  3266. return new Reader(buffer);
  3267. throw Error("illegal buffer");
  3268. };
  3269. var create = function create() {
  3270. return util.Buffer
  3271. ? function create_buffer_setup(buffer) {
  3272. return (Reader.create = function create_buffer(buffer) {
  3273. return util.Buffer.isBuffer(buffer)
  3274. ? new BufferReader(buffer)
  3275. /* istanbul ignore next */
  3276. : create_array(buffer);
  3277. })(buffer);
  3278. }
  3279. /* istanbul ignore next */
  3280. : create_array;
  3281. };
  3282. /**
  3283. * Creates a new reader using the specified buffer.
  3284. * @function
  3285. * @param {Uint8Array|Buffer} buffer Buffer to read from
  3286. * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
  3287. * @throws {Error} If `buffer` is not a valid buffer
  3288. */
  3289. Reader.create = create();
  3290. Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
  3291. /**
  3292. * Reads a varint as an unsigned 32 bit value.
  3293. * @function
  3294. * @returns {number} Value read
  3295. */
  3296. Reader.prototype.uint32 = (function read_uint32_setup() {
  3297. var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
  3298. return function read_uint32() {
  3299. value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
  3300. value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
  3301. value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
  3302. value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
  3303. value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
  3304. /* istanbul ignore if */
  3305. if ((this.pos += 5) > this.len) {
  3306. this.pos = this.len;
  3307. throw indexOutOfRange(this, 10);
  3308. }
  3309. return value;
  3310. };
  3311. })();
  3312. /**
  3313. * Reads a varint as a signed 32 bit value.
  3314. * @returns {number} Value read
  3315. */
  3316. Reader.prototype.int32 = function read_int32() {
  3317. return this.uint32() | 0;
  3318. };
  3319. /**
  3320. * Reads a zig-zag encoded varint as a signed 32 bit value.
  3321. * @returns {number} Value read
  3322. */
  3323. Reader.prototype.sint32 = function read_sint32() {
  3324. var value = this.uint32();
  3325. return value >>> 1 ^ -(value & 1) | 0;
  3326. };
  3327. /* eslint-disable no-invalid-this */
  3328. function readLongVarint() {
  3329. // tends to deopt with local vars for octet etc.
  3330. var bits = new LongBits(0, 0);
  3331. var i = 0;
  3332. if (this.len - this.pos > 4) { // fast route (lo)
  3333. for (; i < 4; ++i) {
  3334. // 1st..4th
  3335. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  3336. if (this.buf[this.pos++] < 128)
  3337. return bits;
  3338. }
  3339. // 5th
  3340. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
  3341. bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
  3342. if (this.buf[this.pos++] < 128)
  3343. return bits;
  3344. i = 0;
  3345. } else {
  3346. for (; i < 3; ++i) {
  3347. /* istanbul ignore if */
  3348. if (this.pos >= this.len)
  3349. throw indexOutOfRange(this);
  3350. // 1st..3th
  3351. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  3352. if (this.buf[this.pos++] < 128)
  3353. return bits;
  3354. }
  3355. // 4th
  3356. bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
  3357. return bits;
  3358. }
  3359. if (this.len - this.pos > 4) { // fast route (hi)
  3360. for (; i < 5; ++i) {
  3361. // 6th..10th
  3362. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  3363. if (this.buf[this.pos++] < 128)
  3364. return bits;
  3365. }
  3366. } else {
  3367. for (; i < 5; ++i) {
  3368. /* istanbul ignore if */
  3369. if (this.pos >= this.len)
  3370. throw indexOutOfRange(this);
  3371. // 6th..10th
  3372. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  3373. if (this.buf[this.pos++] < 128)
  3374. return bits;
  3375. }
  3376. }
  3377. /* istanbul ignore next */
  3378. throw Error("invalid varint encoding");
  3379. }
  3380. /* eslint-enable no-invalid-this */
  3381. /**
  3382. * Reads a varint as a signed 64 bit value.
  3383. * @name Reader#int64
  3384. * @function
  3385. * @returns {Long} Value read
  3386. */
  3387. /**
  3388. * Reads a varint as an unsigned 64 bit value.
  3389. * @name Reader#uint64
  3390. * @function
  3391. * @returns {Long} Value read
  3392. */
  3393. /**
  3394. * Reads a zig-zag encoded varint as a signed 64 bit value.
  3395. * @name Reader#sint64
  3396. * @function
  3397. * @returns {Long} Value read
  3398. */
  3399. /**
  3400. * Reads a varint as a boolean.
  3401. * @returns {boolean} Value read
  3402. */
  3403. Reader.prototype.bool = function read_bool() {
  3404. return this.uint32() !== 0;
  3405. };
  3406. function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
  3407. return (buf[end - 4]
  3408. | buf[end - 3] << 8
  3409. | buf[end - 2] << 16
  3410. | buf[end - 1] << 24) >>> 0;
  3411. }
  3412. /**
  3413. * Reads fixed 32 bits as an unsigned 32 bit integer.
  3414. * @returns {number} Value read
  3415. */
  3416. Reader.prototype.fixed32 = function read_fixed32() {
  3417. /* istanbul ignore if */
  3418. if (this.pos + 4 > this.len)
  3419. throw indexOutOfRange(this, 4);
  3420. return readFixed32_end(this.buf, this.pos += 4);
  3421. };
  3422. /**
  3423. * Reads fixed 32 bits as a signed 32 bit integer.
  3424. * @returns {number} Value read
  3425. */
  3426. Reader.prototype.sfixed32 = function read_sfixed32() {
  3427. /* istanbul ignore if */
  3428. if (this.pos + 4 > this.len)
  3429. throw indexOutOfRange(this, 4);
  3430. return readFixed32_end(this.buf, this.pos += 4) | 0;
  3431. };
  3432. /* eslint-disable no-invalid-this */
  3433. function readFixed64(/* this: Reader */) {
  3434. /* istanbul ignore if */
  3435. if (this.pos + 8 > this.len)
  3436. throw indexOutOfRange(this, 8);
  3437. return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
  3438. }
  3439. /* eslint-enable no-invalid-this */
  3440. /**
  3441. * Reads fixed 64 bits.
  3442. * @name Reader#fixed64
  3443. * @function
  3444. * @returns {Long} Value read
  3445. */
  3446. /**
  3447. * Reads zig-zag encoded fixed 64 bits.
  3448. * @name Reader#sfixed64
  3449. * @function
  3450. * @returns {Long} Value read
  3451. */
  3452. /**
  3453. * Reads a float (32 bit) as a number.
  3454. * @function
  3455. * @returns {number} Value read
  3456. */
  3457. Reader.prototype.float = function read_float() {
  3458. /* istanbul ignore if */
  3459. if (this.pos + 4 > this.len)
  3460. throw indexOutOfRange(this, 4);
  3461. var value = util.float.readFloatLE(this.buf, this.pos);
  3462. this.pos += 4;
  3463. return value;
  3464. };
  3465. /**
  3466. * Reads a double (64 bit float) as a number.
  3467. * @function
  3468. * @returns {number} Value read
  3469. */
  3470. Reader.prototype.double = function read_double() {
  3471. /* istanbul ignore if */
  3472. if (this.pos + 8 > this.len)
  3473. throw indexOutOfRange(this, 4);
  3474. var value = util.float.readDoubleLE(this.buf, this.pos);
  3475. this.pos += 8;
  3476. return value;
  3477. };
  3478. /**
  3479. * Reads a sequence of bytes preceeded by its length as a varint.
  3480. * @returns {Uint8Array} Value read
  3481. */
  3482. Reader.prototype.bytes = function read_bytes() {
  3483. var length = this.uint32(),
  3484. start = this.pos,
  3485. end = this.pos + length;
  3486. /* istanbul ignore if */
  3487. if (end > this.len)
  3488. throw indexOutOfRange(this, length);
  3489. this.pos += length;
  3490. if (Array.isArray(this.buf)) // plain array
  3491. return this.buf.slice(start, end);
  3492. return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
  3493. ? new this.buf.constructor(0)
  3494. : this._slice.call(this.buf, start, end);
  3495. };
  3496. /**
  3497. * Reads a string preceeded by its byte length as a varint.
  3498. * @returns {string} Value read
  3499. */
  3500. Reader.prototype.string = function read_string() {
  3501. var bytes = this.bytes();
  3502. return utf8.read(bytes, 0, bytes.length);
  3503. };
  3504. /**
  3505. * Skips the specified number of bytes if specified, otherwise skips a varint.
  3506. * @param {number} [length] Length if known, otherwise a varint is assumed
  3507. * @returns {Reader} `this`
  3508. */
  3509. Reader.prototype.skip = function skip(length) {
  3510. if (typeof length === "number") {
  3511. /* istanbul ignore if */
  3512. if (this.pos + length > this.len)
  3513. throw indexOutOfRange(this, length);
  3514. this.pos += length;
  3515. } else {
  3516. do {
  3517. /* istanbul ignore if */
  3518. if (this.pos >= this.len)
  3519. throw indexOutOfRange(this);
  3520. } while (this.buf[this.pos++] & 128);
  3521. }
  3522. return this;
  3523. };
  3524. /**
  3525. * Skips the next element of the specified wire type.
  3526. * @param {number} wireType Wire type received
  3527. * @returns {Reader} `this`
  3528. */
  3529. Reader.prototype.skipType = function(wireType) {
  3530. switch (wireType) {
  3531. case 0:
  3532. this.skip();
  3533. break;
  3534. case 1:
  3535. this.skip(8);
  3536. break;
  3537. case 2:
  3538. this.skip(this.uint32());
  3539. break;
  3540. case 3:
  3541. while ((wireType = this.uint32() & 7) !== 4) {
  3542. this.skipType(wireType);
  3543. }
  3544. break;
  3545. case 5:
  3546. this.skip(4);
  3547. break;
  3548. /* istanbul ignore next */
  3549. default:
  3550. throw Error("invalid wire type " + wireType + " at offset " + this.pos);
  3551. }
  3552. return this;
  3553. };
  3554. Reader._configure = function(BufferReader_) {
  3555. BufferReader = BufferReader_;
  3556. Reader.create = create();
  3557. BufferReader._configure();
  3558. var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
  3559. util.merge(Reader.prototype, {
  3560. int64: function read_int64() {
  3561. return readLongVarint.call(this)[fn](false);
  3562. },
  3563. uint64: function read_uint64() {
  3564. return readLongVarint.call(this)[fn](true);
  3565. },
  3566. sint64: function read_sint64() {
  3567. return readLongVarint.call(this).zzDecode()[fn](false);
  3568. },
  3569. fixed64: function read_fixed64() {
  3570. return readFixed64.call(this)[fn](true);
  3571. },
  3572. sfixed64: function read_sfixed64() {
  3573. return readFixed64.call(this)[fn](false);
  3574. }
  3575. });
  3576. };
  3577. },{"35":35}],25:[function(require,module,exports){
  3578. "use strict";
  3579. module.exports = BufferReader;
  3580. // extends Reader
  3581. var Reader = require(24);
  3582. (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
  3583. var util = require(35);
  3584. /**
  3585. * Constructs a new buffer reader instance.
  3586. * @classdesc Wire format reader using node buffers.
  3587. * @extends Reader
  3588. * @constructor
  3589. * @param {Buffer} buffer Buffer to read from
  3590. */
  3591. function BufferReader(buffer) {
  3592. Reader.call(this, buffer);
  3593. /**
  3594. * Read buffer.
  3595. * @name BufferReader#buf
  3596. * @type {Buffer}
  3597. */
  3598. }
  3599. BufferReader._configure = function () {
  3600. /* istanbul ignore else */
  3601. if (util.Buffer)
  3602. BufferReader.prototype._slice = util.Buffer.prototype.slice;
  3603. };
  3604. /**
  3605. * @override
  3606. */
  3607. BufferReader.prototype.string = function read_string_buffer() {
  3608. var len = this.uint32(); // modifies pos
  3609. return this.buf.utf8Slice
  3610. ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))
  3611. : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
  3612. };
  3613. /**
  3614. * Reads a sequence of bytes preceeded by its length as a varint.
  3615. * @name BufferReader#bytes
  3616. * @function
  3617. * @returns {Buffer} Value read
  3618. */
  3619. BufferReader._configure();
  3620. },{"24":24,"35":35}],26:[function(require,module,exports){
  3621. "use strict";
  3622. module.exports = Root;
  3623. // extends Namespace
  3624. var Namespace = require(21);
  3625. ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";
  3626. var Field = require(15),
  3627. Enum = require(14),
  3628. OneOf = require(23),
  3629. util = require(33);
  3630. var Type, // cyclic
  3631. parse, // might be excluded
  3632. common; // "
  3633. /**
  3634. * Constructs a new root namespace instance.
  3635. * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.
  3636. * @extends NamespaceBase
  3637. * @constructor
  3638. * @param {Object.<string,*>} [options] Top level options
  3639. */
  3640. function Root(options) {
  3641. Namespace.call(this, "", options);
  3642. /**
  3643. * Deferred extension fields.
  3644. * @type {Field[]}
  3645. */
  3646. this.deferred = [];
  3647. /**
  3648. * Resolved file names of loaded files.
  3649. * @type {string[]}
  3650. */
  3651. this.files = [];
  3652. }
  3653. /**
  3654. * Loads a namespace descriptor into a root namespace.
  3655. * @param {INamespace} json Nameespace descriptor
  3656. * @param {Root} [root] Root namespace, defaults to create a new one if omitted
  3657. * @returns {Root} Root namespace
  3658. */
  3659. Root.fromJSON = function fromJSON(json, root) {
  3660. if (!root)
  3661. root = new Root();
  3662. if (json.options)
  3663. root.setOptions(json.options);
  3664. return root.addJSON(json.nested);
  3665. };
  3666. /**
  3667. * Resolves the path of an imported file, relative to the importing origin.
  3668. * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
  3669. * @function
  3670. * @param {string} origin The file name of the importing file
  3671. * @param {string} target The file name being imported
  3672. * @returns {string|null} Resolved path to `target` or `null` to skip the file
  3673. */
  3674. Root.prototype.resolvePath = util.path.resolve;
  3675. /**
  3676. * Fetch content from file path or url
  3677. * This method exists so you can override it with your own logic.
  3678. * @function
  3679. * @param {string} path File path or url
  3680. * @param {FetchCallback} callback Callback function
  3681. * @returns {undefined}
  3682. */
  3683. Root.prototype.fetch = util.fetch;
  3684. // A symbol-like function to safely signal synchronous loading
  3685. /* istanbul ignore next */
  3686. function SYNC() {} // eslint-disable-line no-empty-function
  3687. /**
  3688. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  3689. * @param {string|string[]} filename Names of one or multiple files to load
  3690. * @param {IParseOptions} options Parse options
  3691. * @param {LoadCallback} callback Callback function
  3692. * @returns {undefined}
  3693. */
  3694. Root.prototype.load = function load(filename, options, callback) {
  3695. if (typeof options === "function") {
  3696. callback = options;
  3697. options = undefined;
  3698. }
  3699. var self = this;
  3700. if (!callback)
  3701. return util.asPromise(load, self, filename, options);
  3702. var sync = callback === SYNC; // undocumented
  3703. // Finishes loading by calling the callback (exactly once)
  3704. function finish(err, root) {
  3705. /* istanbul ignore if */
  3706. if (!callback)
  3707. return;
  3708. var cb = callback;
  3709. callback = null;
  3710. if (sync)
  3711. throw err;
  3712. cb(err, root);
  3713. }
  3714. // Bundled definition existence checking
  3715. function getBundledFileName(filename) {
  3716. var idx = filename.lastIndexOf("google/protobuf/");
  3717. if (idx > -1) {
  3718. var altname = filename.substring(idx);
  3719. if (altname in common) return altname;
  3720. }
  3721. return null;
  3722. }
  3723. // Processes a single file
  3724. function process(filename, source) {
  3725. try {
  3726. if (util.isString(source) && source.charAt(0) === "{")
  3727. source = JSON.parse(source);
  3728. if (!util.isString(source))
  3729. self.setOptions(source.options).addJSON(source.nested);
  3730. else {
  3731. parse.filename = filename;
  3732. var parsed = parse(source, self, options),
  3733. resolved,
  3734. i = 0;
  3735. if (parsed.imports)
  3736. for (; i < parsed.imports.length; ++i)
  3737. if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))
  3738. fetch(resolved);
  3739. if (parsed.weakImports)
  3740. for (i = 0; i < parsed.weakImports.length; ++i)
  3741. if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))
  3742. fetch(resolved, true);
  3743. }
  3744. } catch (err) {
  3745. finish(err);
  3746. }
  3747. if (!sync && !queued)
  3748. finish(null, self); // only once anyway
  3749. }
  3750. // Fetches a single file
  3751. function fetch(filename, weak) {
  3752. // Skip if already loaded / attempted
  3753. if (self.files.indexOf(filename) > -1)
  3754. return;
  3755. self.files.push(filename);
  3756. // Shortcut bundled definitions
  3757. if (filename in common) {
  3758. if (sync)
  3759. process(filename, common[filename]);
  3760. else {
  3761. ++queued;
  3762. setTimeout(function() {
  3763. --queued;
  3764. process(filename, common[filename]);
  3765. });
  3766. }
  3767. return;
  3768. }
  3769. // Otherwise fetch from disk or network
  3770. if (sync) {
  3771. var source;
  3772. try {
  3773. source = util.fs.readFileSync(filename).toString("utf8");
  3774. } catch (err) {
  3775. if (!weak)
  3776. finish(err);
  3777. return;
  3778. }
  3779. process(filename, source);
  3780. } else {
  3781. ++queued;
  3782. self.fetch(filename, function(err, source) {
  3783. --queued;
  3784. /* istanbul ignore if */
  3785. if (!callback)
  3786. return; // terminated meanwhile
  3787. if (err) {
  3788. /* istanbul ignore else */
  3789. if (!weak)
  3790. finish(err);
  3791. else if (!queued) // can't be covered reliably
  3792. finish(null, self);
  3793. return;
  3794. }
  3795. process(filename, source);
  3796. });
  3797. }
  3798. }
  3799. var queued = 0;
  3800. // Assembling the root namespace doesn't require working type
  3801. // references anymore, so we can load everything in parallel
  3802. if (util.isString(filename))
  3803. filename = [ filename ];
  3804. for (var i = 0, resolved; i < filename.length; ++i)
  3805. if (resolved = self.resolvePath("", filename[i]))
  3806. fetch(resolved);
  3807. if (sync)
  3808. return self;
  3809. if (!queued)
  3810. finish(null, self);
  3811. return undefined;
  3812. };
  3813. // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined
  3814. /**
  3815. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  3816. * @function Root#load
  3817. * @param {string|string[]} filename Names of one or multiple files to load
  3818. * @param {LoadCallback} callback Callback function
  3819. * @returns {undefined}
  3820. * @variation 2
  3821. */
  3822. // function load(filename:string, callback:LoadCallback):undefined
  3823. /**
  3824. * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
  3825. * @function Root#load
  3826. * @param {string|string[]} filename Names of one or multiple files to load
  3827. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  3828. * @returns {Promise<Root>} Promise
  3829. * @variation 3
  3830. */
  3831. // function load(filename:string, [options:IParseOptions]):Promise<Root>
  3832. /**
  3833. * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
  3834. * @function Root#loadSync
  3835. * @param {string|string[]} filename Names of one or multiple files to load
  3836. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  3837. * @returns {Root} Root namespace
  3838. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  3839. */
  3840. Root.prototype.loadSync = function loadSync(filename, options) {
  3841. if (!util.isNode)
  3842. throw Error("not supported");
  3843. return this.load(filename, options, SYNC);
  3844. };
  3845. /**
  3846. * @override
  3847. */
  3848. Root.prototype.resolveAll = function resolveAll() {
  3849. if (this.deferred.length)
  3850. throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
  3851. return "'extend " + field.extend + "' in " + field.parent.fullName;
  3852. }).join(", "));
  3853. return Namespace.prototype.resolveAll.call(this);
  3854. };
  3855. // only uppercased (and thus conflict-free) children are exposed, see below
  3856. var exposeRe = /^[A-Z]/;
  3857. /**
  3858. * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.
  3859. * @param {Root} root Root instance
  3860. * @param {Field} field Declaring extension field witin the declaring type
  3861. * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise
  3862. * @inner
  3863. * @ignore
  3864. */
  3865. function tryHandleExtension(root, field) {
  3866. var extendedType = field.parent.lookup(field.extend);
  3867. if (extendedType) {
  3868. var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);
  3869. sisterField.declaringField = field;
  3870. field.extensionField = sisterField;
  3871. extendedType.add(sisterField);
  3872. return true;
  3873. }
  3874. return false;
  3875. }
  3876. /**
  3877. * Called when any object is added to this root or its sub-namespaces.
  3878. * @param {ReflectionObject} object Object added
  3879. * @returns {undefined}
  3880. * @private
  3881. */
  3882. Root.prototype._handleAdd = function _handleAdd(object) {
  3883. if (object instanceof Field) {
  3884. if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)
  3885. if (!tryHandleExtension(this, object))
  3886. this.deferred.push(object);
  3887. } else if (object instanceof Enum) {
  3888. if (exposeRe.test(object.name))
  3889. object.parent[object.name] = object.values; // expose enum values as property of its parent
  3890. } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {
  3891. if (object instanceof Type) // Try to handle any deferred extensions
  3892. for (var i = 0; i < this.deferred.length;)
  3893. if (tryHandleExtension(this, this.deferred[i]))
  3894. this.deferred.splice(i, 1);
  3895. else
  3896. ++i;
  3897. for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace
  3898. this._handleAdd(object._nestedArray[j]);
  3899. if (exposeRe.test(object.name))
  3900. object.parent[object.name] = object; // expose namespace as property of its parent
  3901. }
  3902. // The above also adds uppercased (and thus conflict-free) nested types, services and enums as
  3903. // properties of namespaces just like static code does. This allows using a .d.ts generated for
  3904. // a static module with reflection-based solutions where the condition is met.
  3905. };
  3906. /**
  3907. * Called when any object is removed from this root or its sub-namespaces.
  3908. * @param {ReflectionObject} object Object removed
  3909. * @returns {undefined}
  3910. * @private
  3911. */
  3912. Root.prototype._handleRemove = function _handleRemove(object) {
  3913. if (object instanceof Field) {
  3914. if (/* an extension field */ object.extend !== undefined) {
  3915. if (/* already handled */ object.extensionField) { // remove its sister field
  3916. object.extensionField.parent.remove(object.extensionField);
  3917. object.extensionField = null;
  3918. } else { // cancel the extension
  3919. var index = this.deferred.indexOf(object);
  3920. /* istanbul ignore else */
  3921. if (index > -1)
  3922. this.deferred.splice(index, 1);
  3923. }
  3924. }
  3925. } else if (object instanceof Enum) {
  3926. if (exposeRe.test(object.name))
  3927. delete object.parent[object.name]; // unexpose enum values
  3928. } else if (object instanceof Namespace) {
  3929. for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace
  3930. this._handleRemove(object._nestedArray[i]);
  3931. if (exposeRe.test(object.name))
  3932. delete object.parent[object.name]; // unexpose namespaces
  3933. }
  3934. };
  3935. // Sets up cyclic dependencies (called in index-light)
  3936. Root._configure = function(Type_, parse_, common_) {
  3937. Type = Type_;
  3938. parse = parse_;
  3939. common = common_;
  3940. };
  3941. },{"14":14,"15":15,"21":21,"23":23,"33":33}],27:[function(require,module,exports){
  3942. "use strict";
  3943. module.exports = {};
  3944. /**
  3945. * Named roots.
  3946. * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
  3947. * Can also be used manually to make roots available accross modules.
  3948. * @name roots
  3949. * @type {Object.<string,Root>}
  3950. * @example
  3951. * // pbjs -r myroot -o compiled.js ...
  3952. *
  3953. * // in another module:
  3954. * require("./compiled.js");
  3955. *
  3956. * // in any subsequent module:
  3957. * var root = protobuf.roots["myroot"];
  3958. */
  3959. },{}],28:[function(require,module,exports){
  3960. "use strict";
  3961. /**
  3962. * Streaming RPC helpers.
  3963. * @namespace
  3964. */
  3965. var rpc = exports;
  3966. /**
  3967. * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
  3968. * @typedef RPCImpl
  3969. * @type {function}
  3970. * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
  3971. * @param {Uint8Array} requestData Request data
  3972. * @param {RPCImplCallback} callback Callback function
  3973. * @returns {undefined}
  3974. * @example
  3975. * function rpcImpl(method, requestData, callback) {
  3976. * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
  3977. * throw Error("no such method");
  3978. * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
  3979. * callback(err, responseData);
  3980. * });
  3981. * }
  3982. */
  3983. /**
  3984. * Node-style callback as used by {@link RPCImpl}.
  3985. * @typedef RPCImplCallback
  3986. * @type {function}
  3987. * @param {Error|null} error Error, if any, otherwise `null`
  3988. * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
  3989. * @returns {undefined}
  3990. */
  3991. rpc.Service = require(29);
  3992. },{"29":29}],29:[function(require,module,exports){
  3993. "use strict";
  3994. module.exports = Service;
  3995. var util = require(35);
  3996. // Extends EventEmitter
  3997. (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
  3998. /**
  3999. * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
  4000. *
  4001. * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
  4002. * @typedef rpc.ServiceMethodCallback
  4003. * @template TRes extends Message<TRes>
  4004. * @type {function}
  4005. * @param {Error|null} error Error, if any
  4006. * @param {TRes} [response] Response message
  4007. * @returns {undefined}
  4008. */
  4009. /**
  4010. * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
  4011. * @typedef rpc.ServiceMethod
  4012. * @template TReq extends Message<TReq>
  4013. * @template TRes extends Message<TRes>
  4014. * @type {function}
  4015. * @param {TReq|Properties<TReq>} request Request message or plain object
  4016. * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
  4017. * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
  4018. */
  4019. /**
  4020. * Constructs a new RPC service instance.
  4021. * @classdesc An RPC service as returned by {@link Service#create}.
  4022. * @exports rpc.Service
  4023. * @extends util.EventEmitter
  4024. * @constructor
  4025. * @param {RPCImpl} rpcImpl RPC implementation
  4026. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  4027. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  4028. */
  4029. function Service(rpcImpl, requestDelimited, responseDelimited) {
  4030. if (typeof rpcImpl !== "function")
  4031. throw TypeError("rpcImpl must be a function");
  4032. util.EventEmitter.call(this);
  4033. /**
  4034. * RPC implementation. Becomes `null` once the service is ended.
  4035. * @type {RPCImpl|null}
  4036. */
  4037. this.rpcImpl = rpcImpl;
  4038. /**
  4039. * Whether requests are length-delimited.
  4040. * @type {boolean}
  4041. */
  4042. this.requestDelimited = Boolean(requestDelimited);
  4043. /**
  4044. * Whether responses are length-delimited.
  4045. * @type {boolean}
  4046. */
  4047. this.responseDelimited = Boolean(responseDelimited);
  4048. }
  4049. /**
  4050. * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
  4051. * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
  4052. * @param {Constructor<TReq>} requestCtor Request constructor
  4053. * @param {Constructor<TRes>} responseCtor Response constructor
  4054. * @param {TReq|Properties<TReq>} request Request message or plain object
  4055. * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
  4056. * @returns {undefined}
  4057. * @template TReq extends Message<TReq>
  4058. * @template TRes extends Message<TRes>
  4059. */
  4060. Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
  4061. if (!request)
  4062. throw TypeError("request must be specified");
  4063. var self = this;
  4064. if (!callback)
  4065. return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
  4066. if (!self.rpcImpl) {
  4067. setTimeout(function() { callback(Error("already ended")); }, 0);
  4068. return undefined;
  4069. }
  4070. try {
  4071. return self.rpcImpl(
  4072. method,
  4073. requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
  4074. function rpcCallback(err, response) {
  4075. if (err) {
  4076. self.emit("error", err, method);
  4077. return callback(err);
  4078. }
  4079. if (response === null) {
  4080. self.end(/* endedByRPC */ true);
  4081. return undefined;
  4082. }
  4083. if (!(response instanceof responseCtor)) {
  4084. try {
  4085. response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
  4086. } catch (err) {
  4087. self.emit("error", err, method);
  4088. return callback(err);
  4089. }
  4090. }
  4091. self.emit("data", response, method);
  4092. return callback(null, response);
  4093. }
  4094. );
  4095. } catch (err) {
  4096. self.emit("error", err, method);
  4097. setTimeout(function() { callback(err); }, 0);
  4098. return undefined;
  4099. }
  4100. };
  4101. /**
  4102. * Ends this service and emits the `end` event.
  4103. * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
  4104. * @returns {rpc.Service} `this`
  4105. */
  4106. Service.prototype.end = function end(endedByRPC) {
  4107. if (this.rpcImpl) {
  4108. if (!endedByRPC) // signal end to rpcImpl
  4109. this.rpcImpl(null, null, null);
  4110. this.rpcImpl = null;
  4111. this.emit("end").off();
  4112. }
  4113. return this;
  4114. };
  4115. },{"35":35}],30:[function(require,module,exports){
  4116. "use strict";
  4117. module.exports = Service;
  4118. // extends Namespace
  4119. var Namespace = require(21);
  4120. ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
  4121. var Method = require(20),
  4122. util = require(33),
  4123. rpc = require(28);
  4124. /**
  4125. * Constructs a new service instance.
  4126. * @classdesc Reflected service.
  4127. * @extends NamespaceBase
  4128. * @constructor
  4129. * @param {string} name Service name
  4130. * @param {Object.<string,*>} [options] Service options
  4131. * @throws {TypeError} If arguments are invalid
  4132. */
  4133. function Service(name, options) {
  4134. Namespace.call(this, name, options);
  4135. /**
  4136. * Service methods.
  4137. * @type {Object.<string,Method>}
  4138. */
  4139. this.methods = {}; // toJSON, marker
  4140. /**
  4141. * Cached methods as an array.
  4142. * @type {Method[]|null}
  4143. * @private
  4144. */
  4145. this._methodsArray = null;
  4146. }
  4147. /**
  4148. * Service descriptor.
  4149. * @interface IService
  4150. * @extends INamespace
  4151. * @property {Object.<string,IMethod>} methods Method descriptors
  4152. */
  4153. /**
  4154. * Constructs a service from a service descriptor.
  4155. * @param {string} name Service name
  4156. * @param {IService} json Service descriptor
  4157. * @returns {Service} Created service
  4158. * @throws {TypeError} If arguments are invalid
  4159. */
  4160. Service.fromJSON = function fromJSON(name, json) {
  4161. var service = new Service(name, json.options);
  4162. /* istanbul ignore else */
  4163. if (json.methods)
  4164. for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)
  4165. service.add(Method.fromJSON(names[i], json.methods[names[i]]));
  4166. if (json.nested)
  4167. service.addJSON(json.nested);
  4168. service.comment = json.comment;
  4169. return service;
  4170. };
  4171. /**
  4172. * Converts this service to a service descriptor.
  4173. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  4174. * @returns {IService} Service descriptor
  4175. */
  4176. Service.prototype.toJSON = function toJSON(toJSONOptions) {
  4177. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  4178. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  4179. return util.toObject([
  4180. "options" , inherited && inherited.options || undefined,
  4181. "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},
  4182. "nested" , inherited && inherited.nested || undefined,
  4183. "comment" , keepComments ? this.comment : undefined
  4184. ]);
  4185. };
  4186. /**
  4187. * Methods of this service as an array for iteration.
  4188. * @name Service#methodsArray
  4189. * @type {Method[]}
  4190. * @readonly
  4191. */
  4192. Object.defineProperty(Service.prototype, "methodsArray", {
  4193. get: function() {
  4194. return this._methodsArray || (this._methodsArray = util.toArray(this.methods));
  4195. }
  4196. });
  4197. function clearCache(service) {
  4198. service._methodsArray = null;
  4199. return service;
  4200. }
  4201. /**
  4202. * @override
  4203. */
  4204. Service.prototype.get = function get(name) {
  4205. return this.methods[name]
  4206. || Namespace.prototype.get.call(this, name);
  4207. };
  4208. /**
  4209. * @override
  4210. */
  4211. Service.prototype.resolveAll = function resolveAll() {
  4212. var methods = this.methodsArray;
  4213. for (var i = 0; i < methods.length; ++i)
  4214. methods[i].resolve();
  4215. return Namespace.prototype.resolve.call(this);
  4216. };
  4217. /**
  4218. * @override
  4219. */
  4220. Service.prototype.add = function add(object) {
  4221. /* istanbul ignore if */
  4222. if (this.get(object.name))
  4223. throw Error("duplicate name '" + object.name + "' in " + this);
  4224. if (object instanceof Method) {
  4225. this.methods[object.name] = object;
  4226. object.parent = this;
  4227. return clearCache(this);
  4228. }
  4229. return Namespace.prototype.add.call(this, object);
  4230. };
  4231. /**
  4232. * @override
  4233. */
  4234. Service.prototype.remove = function remove(object) {
  4235. if (object instanceof Method) {
  4236. /* istanbul ignore if */
  4237. if (this.methods[object.name] !== object)
  4238. throw Error(object + " is not a member of " + this);
  4239. delete this.methods[object.name];
  4240. object.parent = null;
  4241. return clearCache(this);
  4242. }
  4243. return Namespace.prototype.remove.call(this, object);
  4244. };
  4245. /**
  4246. * Creates a runtime service using the specified rpc implementation.
  4247. * @param {RPCImpl} rpcImpl RPC implementation
  4248. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  4249. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  4250. * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.
  4251. */
  4252. Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {
  4253. var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
  4254. for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {
  4255. var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
  4256. rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({
  4257. m: method,
  4258. q: method.resolvedRequestType.ctor,
  4259. s: method.resolvedResponseType.ctor
  4260. });
  4261. }
  4262. return rpcService;
  4263. };
  4264. },{"20":20,"21":21,"28":28,"33":33}],31:[function(require,module,exports){
  4265. "use strict";
  4266. module.exports = Type;
  4267. // extends Namespace
  4268. var Namespace = require(21);
  4269. ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";
  4270. var Enum = require(14),
  4271. OneOf = require(23),
  4272. Field = require(15),
  4273. MapField = require(18),
  4274. Service = require(30),
  4275. Message = require(19),
  4276. Reader = require(24),
  4277. Writer = require(38),
  4278. util = require(33),
  4279. encoder = require(13),
  4280. decoder = require(12),
  4281. verifier = require(36),
  4282. converter = require(11),
  4283. wrappers = require(37);
  4284. /**
  4285. * Constructs a new reflected message type instance.
  4286. * @classdesc Reflected message type.
  4287. * @extends NamespaceBase
  4288. * @constructor
  4289. * @param {string} name Message name
  4290. * @param {Object.<string,*>} [options] Declared options
  4291. */
  4292. function Type(name, options) {
  4293. Namespace.call(this, name, options);
  4294. /**
  4295. * Message fields.
  4296. * @type {Object.<string,Field>}
  4297. */
  4298. this.fields = {}; // toJSON, marker
  4299. /**
  4300. * Oneofs declared within this namespace, if any.
  4301. * @type {Object.<string,OneOf>}
  4302. */
  4303. this.oneofs = undefined; // toJSON
  4304. /**
  4305. * Extension ranges, if any.
  4306. * @type {number[][]}
  4307. */
  4308. this.extensions = undefined; // toJSON
  4309. /**
  4310. * Reserved ranges, if any.
  4311. * @type {Array.<number[]|string>}
  4312. */
  4313. this.reserved = undefined; // toJSON
  4314. /*?
  4315. * Whether this type is a legacy group.
  4316. * @type {boolean|undefined}
  4317. */
  4318. this.group = undefined; // toJSON
  4319. /**
  4320. * Cached fields by id.
  4321. * @type {Object.<number,Field>|null}
  4322. * @private
  4323. */
  4324. this._fieldsById = null;
  4325. /**
  4326. * Cached fields as an array.
  4327. * @type {Field[]|null}
  4328. * @private
  4329. */
  4330. this._fieldsArray = null;
  4331. /**
  4332. * Cached oneofs as an array.
  4333. * @type {OneOf[]|null}
  4334. * @private
  4335. */
  4336. this._oneofsArray = null;
  4337. /**
  4338. * Cached constructor.
  4339. * @type {Constructor<{}>}
  4340. * @private
  4341. */
  4342. this._ctor = null;
  4343. }
  4344. Object.defineProperties(Type.prototype, {
  4345. /**
  4346. * Message fields by id.
  4347. * @name Type#fieldsById
  4348. * @type {Object.<number,Field>}
  4349. * @readonly
  4350. */
  4351. fieldsById: {
  4352. get: function() {
  4353. /* istanbul ignore if */
  4354. if (this._fieldsById)
  4355. return this._fieldsById;
  4356. this._fieldsById = {};
  4357. for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
  4358. var field = this.fields[names[i]],
  4359. id = field.id;
  4360. /* istanbul ignore if */
  4361. if (this._fieldsById[id])
  4362. throw Error("duplicate id " + id + " in " + this);
  4363. this._fieldsById[id] = field;
  4364. }
  4365. return this._fieldsById;
  4366. }
  4367. },
  4368. /**
  4369. * Fields of this message as an array for iteration.
  4370. * @name Type#fieldsArray
  4371. * @type {Field[]}
  4372. * @readonly
  4373. */
  4374. fieldsArray: {
  4375. get: function() {
  4376. return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
  4377. }
  4378. },
  4379. /**
  4380. * Oneofs of this message as an array for iteration.
  4381. * @name Type#oneofsArray
  4382. * @type {OneOf[]}
  4383. * @readonly
  4384. */
  4385. oneofsArray: {
  4386. get: function() {
  4387. return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
  4388. }
  4389. },
  4390. /**
  4391. * The registered constructor, if any registered, otherwise a generic constructor.
  4392. * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
  4393. * @name Type#ctor
  4394. * @type {Constructor<{}>}
  4395. */
  4396. ctor: {
  4397. get: function() {
  4398. return this._ctor || (this.ctor = Type.generateConstructor(this)());
  4399. },
  4400. set: function(ctor) {
  4401. // Ensure proper prototype
  4402. var prototype = ctor.prototype;
  4403. if (!(prototype instanceof Message)) {
  4404. (ctor.prototype = new Message()).constructor = ctor;
  4405. util.merge(ctor.prototype, prototype);
  4406. }
  4407. // Classes and messages reference their reflected type
  4408. ctor.$type = ctor.prototype.$type = this;
  4409. // Mix in static methods
  4410. util.merge(ctor, Message, true);
  4411. this._ctor = ctor;
  4412. // Messages have non-enumerable default values on their prototype
  4413. var i = 0;
  4414. for (; i < /* initializes */ this.fieldsArray.length; ++i)
  4415. this._fieldsArray[i].resolve(); // ensures a proper value
  4416. // Messages have non-enumerable getters and setters for each virtual oneof field
  4417. var ctorProperties = {};
  4418. for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)
  4419. ctorProperties[this._oneofsArray[i].resolve().name] = {
  4420. get: util.oneOfGetter(this._oneofsArray[i].oneof),
  4421. set: util.oneOfSetter(this._oneofsArray[i].oneof)
  4422. };
  4423. if (i)
  4424. Object.defineProperties(ctor.prototype, ctorProperties);
  4425. }
  4426. }
  4427. });
  4428. /**
  4429. * Generates a constructor function for the specified type.
  4430. * @param {Type} mtype Message type
  4431. * @returns {Codegen} Codegen instance
  4432. */
  4433. Type.generateConstructor = function generateConstructor(mtype) {
  4434. /* eslint-disable no-unexpected-multiline */
  4435. var gen = util.codegen(["p"], mtype.name);
  4436. // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype
  4437. for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
  4438. if ((field = mtype._fieldsArray[i]).map) gen
  4439. ("this%s={}", util.safeProp(field.name));
  4440. else if (field.repeated) gen
  4441. ("this%s=[]", util.safeProp(field.name));
  4442. return gen
  4443. ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null
  4444. ("this[ks[i]]=p[ks[i]]");
  4445. /* eslint-enable no-unexpected-multiline */
  4446. };
  4447. function clearCache(type) {
  4448. type._fieldsById = type._fieldsArray = type._oneofsArray = null;
  4449. delete type.encode;
  4450. delete type.decode;
  4451. delete type.verify;
  4452. return type;
  4453. }
  4454. /**
  4455. * Message type descriptor.
  4456. * @interface IType
  4457. * @extends INamespace
  4458. * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors
  4459. * @property {Object.<string,IField>} fields Field descriptors
  4460. * @property {number[][]} [extensions] Extension ranges
  4461. * @property {number[][]} [reserved] Reserved ranges
  4462. * @property {boolean} [group=false] Whether a legacy group or not
  4463. */
  4464. /**
  4465. * Creates a message type from a message type descriptor.
  4466. * @param {string} name Message name
  4467. * @param {IType} json Message type descriptor
  4468. * @returns {Type} Created message type
  4469. */
  4470. Type.fromJSON = function fromJSON(name, json) {
  4471. var type = new Type(name, json.options);
  4472. type.extensions = json.extensions;
  4473. type.reserved = json.reserved;
  4474. var names = Object.keys(json.fields),
  4475. i = 0;
  4476. for (; i < names.length; ++i)
  4477. type.add(
  4478. ( typeof json.fields[names[i]].keyType !== "undefined"
  4479. ? MapField.fromJSON
  4480. : Field.fromJSON )(names[i], json.fields[names[i]])
  4481. );
  4482. if (json.oneofs)
  4483. for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)
  4484. type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));
  4485. if (json.nested)
  4486. for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {
  4487. var nested = json.nested[names[i]];
  4488. type.add( // most to least likely
  4489. ( nested.id !== undefined
  4490. ? Field.fromJSON
  4491. : nested.fields !== undefined
  4492. ? Type.fromJSON
  4493. : nested.values !== undefined
  4494. ? Enum.fromJSON
  4495. : nested.methods !== undefined
  4496. ? Service.fromJSON
  4497. : Namespace.fromJSON )(names[i], nested)
  4498. );
  4499. }
  4500. if (json.extensions && json.extensions.length)
  4501. type.extensions = json.extensions;
  4502. if (json.reserved && json.reserved.length)
  4503. type.reserved = json.reserved;
  4504. if (json.group)
  4505. type.group = true;
  4506. if (json.comment)
  4507. type.comment = json.comment;
  4508. return type;
  4509. };
  4510. /**
  4511. * Converts this message type to a message type descriptor.
  4512. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  4513. * @returns {IType} Message type descriptor
  4514. */
  4515. Type.prototype.toJSON = function toJSON(toJSONOptions) {
  4516. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  4517. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  4518. return util.toObject([
  4519. "options" , inherited && inherited.options || undefined,
  4520. "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
  4521. "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},
  4522. "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,
  4523. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  4524. "group" , this.group || undefined,
  4525. "nested" , inherited && inherited.nested || undefined,
  4526. "comment" , keepComments ? this.comment : undefined
  4527. ]);
  4528. };
  4529. /**
  4530. * @override
  4531. */
  4532. Type.prototype.resolveAll = function resolveAll() {
  4533. var fields = this.fieldsArray, i = 0;
  4534. while (i < fields.length)
  4535. fields[i++].resolve();
  4536. var oneofs = this.oneofsArray; i = 0;
  4537. while (i < oneofs.length)
  4538. oneofs[i++].resolve();
  4539. return Namespace.prototype.resolveAll.call(this);
  4540. };
  4541. /**
  4542. * @override
  4543. */
  4544. Type.prototype.get = function get(name) {
  4545. return this.fields[name]
  4546. || this.oneofs && this.oneofs[name]
  4547. || this.nested && this.nested[name]
  4548. || null;
  4549. };
  4550. /**
  4551. * Adds a nested object to this type.
  4552. * @param {ReflectionObject} object Nested object to add
  4553. * @returns {Type} `this`
  4554. * @throws {TypeError} If arguments are invalid
  4555. * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id
  4556. */
  4557. Type.prototype.add = function add(object) {
  4558. if (this.get(object.name))
  4559. throw Error("duplicate name '" + object.name + "' in " + this);
  4560. if (object instanceof Field && object.extend === undefined) {
  4561. // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
  4562. // The root object takes care of adding distinct sister-fields to the respective extended
  4563. // type instead.
  4564. // avoids calling the getter if not absolutely necessary because it's called quite frequently
  4565. if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])
  4566. throw Error("duplicate id " + object.id + " in " + this);
  4567. if (this.isReservedId(object.id))
  4568. throw Error("id " + object.id + " is reserved in " + this);
  4569. if (this.isReservedName(object.name))
  4570. throw Error("name '" + object.name + "' is reserved in " + this);
  4571. if (object.parent)
  4572. object.parent.remove(object);
  4573. this.fields[object.name] = object;
  4574. object.message = this;
  4575. object.onAdd(this);
  4576. return clearCache(this);
  4577. }
  4578. if (object instanceof OneOf) {
  4579. if (!this.oneofs)
  4580. this.oneofs = {};
  4581. this.oneofs[object.name] = object;
  4582. object.onAdd(this);
  4583. return clearCache(this);
  4584. }
  4585. return Namespace.prototype.add.call(this, object);
  4586. };
  4587. /**
  4588. * Removes a nested object from this type.
  4589. * @param {ReflectionObject} object Nested object to remove
  4590. * @returns {Type} `this`
  4591. * @throws {TypeError} If arguments are invalid
  4592. * @throws {Error} If `object` is not a member of this type
  4593. */
  4594. Type.prototype.remove = function remove(object) {
  4595. if (object instanceof Field && object.extend === undefined) {
  4596. // See Type#add for the reason why extension fields are excluded here.
  4597. /* istanbul ignore if */
  4598. if (!this.fields || this.fields[object.name] !== object)
  4599. throw Error(object + " is not a member of " + this);
  4600. delete this.fields[object.name];
  4601. object.parent = null;
  4602. object.onRemove(this);
  4603. return clearCache(this);
  4604. }
  4605. if (object instanceof OneOf) {
  4606. /* istanbul ignore if */
  4607. if (!this.oneofs || this.oneofs[object.name] !== object)
  4608. throw Error(object + " is not a member of " + this);
  4609. delete this.oneofs[object.name];
  4610. object.parent = null;
  4611. object.onRemove(this);
  4612. return clearCache(this);
  4613. }
  4614. return Namespace.prototype.remove.call(this, object);
  4615. };
  4616. /**
  4617. * Tests if the specified id is reserved.
  4618. * @param {number} id Id to test
  4619. * @returns {boolean} `true` if reserved, otherwise `false`
  4620. */
  4621. Type.prototype.isReservedId = function isReservedId(id) {
  4622. return Namespace.isReservedId(this.reserved, id);
  4623. };
  4624. /**
  4625. * Tests if the specified name is reserved.
  4626. * @param {string} name Name to test
  4627. * @returns {boolean} `true` if reserved, otherwise `false`
  4628. */
  4629. Type.prototype.isReservedName = function isReservedName(name) {
  4630. return Namespace.isReservedName(this.reserved, name);
  4631. };
  4632. /**
  4633. * Creates a new message of this type using the specified properties.
  4634. * @param {Object.<string,*>} [properties] Properties to set
  4635. * @returns {Message<{}>} Message instance
  4636. */
  4637. Type.prototype.create = function create(properties) {
  4638. return new this.ctor(properties);
  4639. };
  4640. /**
  4641. * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
  4642. * @returns {Type} `this`
  4643. */
  4644. Type.prototype.setup = function setup() {
  4645. // Sets up everything at once so that the prototype chain does not have to be re-evaluated
  4646. // multiple times (V8, soft-deopt prototype-check).
  4647. var fullName = this.fullName,
  4648. types = [];
  4649. for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)
  4650. types.push(this._fieldsArray[i].resolve().resolvedType);
  4651. // Replace setup methods with type-specific generated functions
  4652. this.encode = encoder(this)({
  4653. Writer : Writer,
  4654. types : types,
  4655. util : util
  4656. });
  4657. this.decode = decoder(this)({
  4658. Reader : Reader,
  4659. types : types,
  4660. util : util
  4661. });
  4662. this.verify = verifier(this)({
  4663. types : types,
  4664. util : util
  4665. });
  4666. this.fromObject = converter.fromObject(this)({
  4667. types : types,
  4668. util : util
  4669. });
  4670. this.toObject = converter.toObject(this)({
  4671. types : types,
  4672. util : util
  4673. });
  4674. // Inject custom wrappers for common types
  4675. var wrapper = wrappers[fullName];
  4676. if (wrapper) {
  4677. var originalThis = Object.create(this);
  4678. // if (wrapper.fromObject) {
  4679. originalThis.fromObject = this.fromObject;
  4680. this.fromObject = wrapper.fromObject.bind(originalThis);
  4681. // }
  4682. // if (wrapper.toObject) {
  4683. originalThis.toObject = this.toObject;
  4684. this.toObject = wrapper.toObject.bind(originalThis);
  4685. // }
  4686. }
  4687. return this;
  4688. };
  4689. /**
  4690. * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
  4691. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  4692. * @param {Writer} [writer] Writer to encode to
  4693. * @returns {Writer} writer
  4694. */
  4695. Type.prototype.encode = function encode_setup(message, writer) {
  4696. return this.setup().encode(message, writer); // overrides this method
  4697. };
  4698. /**
  4699. * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
  4700. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  4701. * @param {Writer} [writer] Writer to encode to
  4702. * @returns {Writer} writer
  4703. */
  4704. Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {
  4705. return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
  4706. };
  4707. /**
  4708. * Decodes a message of this type.
  4709. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  4710. * @param {number} [length] Length of the message, if known beforehand
  4711. * @returns {Message<{}>} Decoded message
  4712. * @throws {Error} If the payload is not a reader or valid buffer
  4713. * @throws {util.ProtocolError<{}>} If required fields are missing
  4714. */
  4715. Type.prototype.decode = function decode_setup(reader, length) {
  4716. return this.setup().decode(reader, length); // overrides this method
  4717. };
  4718. /**
  4719. * Decodes a message of this type preceeded by its byte length as a varint.
  4720. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  4721. * @returns {Message<{}>} Decoded message
  4722. * @throws {Error} If the payload is not a reader or valid buffer
  4723. * @throws {util.ProtocolError} If required fields are missing
  4724. */
  4725. Type.prototype.decodeDelimited = function decodeDelimited(reader) {
  4726. if (!(reader instanceof Reader))
  4727. reader = Reader.create(reader);
  4728. return this.decode(reader, reader.uint32());
  4729. };
  4730. /**
  4731. * Verifies that field values are valid and that required fields are present.
  4732. * @param {Object.<string,*>} message Plain object to verify
  4733. * @returns {null|string} `null` if valid, otherwise the reason why it is not
  4734. */
  4735. Type.prototype.verify = function verify_setup(message) {
  4736. return this.setup().verify(message); // overrides this method
  4737. };
  4738. /**
  4739. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  4740. * @param {Object.<string,*>} object Plain object to convert
  4741. * @returns {Message<{}>} Message instance
  4742. */
  4743. Type.prototype.fromObject = function fromObject(object) {
  4744. return this.setup().fromObject(object);
  4745. };
  4746. /**
  4747. * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.
  4748. * @interface IConversionOptions
  4749. * @property {Function} [longs] Long conversion type.
  4750. * Valid values are `String` and `Number` (the global types).
  4751. * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
  4752. * @property {Function} [enums] Enum value conversion type.
  4753. * Only valid value is `String` (the global type).
  4754. * Defaults to copy the present value, which is the numeric id.
  4755. * @property {Function} [bytes] Bytes value conversion type.
  4756. * Valid values are `Array` and (a base64 encoded) `String` (the global types).
  4757. * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
  4758. * @property {boolean} [defaults=false] Also sets default values on the resulting object
  4759. * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`
  4760. * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`
  4761. * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any
  4762. * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings
  4763. */
  4764. /**
  4765. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  4766. * @param {Message<{}>} message Message instance
  4767. * @param {IConversionOptions} [options] Conversion options
  4768. * @returns {Object.<string,*>} Plain object
  4769. */
  4770. Type.prototype.toObject = function toObject(message, options) {
  4771. return this.setup().toObject(message, options);
  4772. };
  4773. /**
  4774. * Decorator function as returned by {@link Type.d} (TypeScript).
  4775. * @typedef TypeDecorator
  4776. * @type {function}
  4777. * @param {Constructor<T>} target Target constructor
  4778. * @returns {undefined}
  4779. * @template T extends Message<T>
  4780. */
  4781. /**
  4782. * Type decorator (TypeScript).
  4783. * @param {string} [typeName] Type name, defaults to the constructor's name
  4784. * @returns {TypeDecorator<T>} Decorator function
  4785. * @template T extends Message<T>
  4786. */
  4787. Type.d = function decorateType(typeName) {
  4788. return function typeDecorator(target) {
  4789. util.decorateType(target, typeName);
  4790. };
  4791. };
  4792. },{"11":11,"12":12,"13":13,"14":14,"15":15,"18":18,"19":19,"21":21,"23":23,"24":24,"30":30,"33":33,"36":36,"37":37,"38":38}],32:[function(require,module,exports){
  4793. "use strict";
  4794. /**
  4795. * Common type constants.
  4796. * @namespace
  4797. */
  4798. var types = exports;
  4799. var util = require(33);
  4800. var s = [
  4801. "double", // 0
  4802. "float", // 1
  4803. "int32", // 2
  4804. "uint32", // 3
  4805. "sint32", // 4
  4806. "fixed32", // 5
  4807. "sfixed32", // 6
  4808. "int64", // 7
  4809. "uint64", // 8
  4810. "sint64", // 9
  4811. "fixed64", // 10
  4812. "sfixed64", // 11
  4813. "bool", // 12
  4814. "string", // 13
  4815. "bytes" // 14
  4816. ];
  4817. function bake(values, offset) {
  4818. var i = 0, o = {};
  4819. offset |= 0;
  4820. while (i < values.length) o[s[i + offset]] = values[i++];
  4821. return o;
  4822. }
  4823. /**
  4824. * Basic type wire types.
  4825. * @type {Object.<string,number>}
  4826. * @const
  4827. * @property {number} double=1 Fixed64 wire type
  4828. * @property {number} float=5 Fixed32 wire type
  4829. * @property {number} int32=0 Varint wire type
  4830. * @property {number} uint32=0 Varint wire type
  4831. * @property {number} sint32=0 Varint wire type
  4832. * @property {number} fixed32=5 Fixed32 wire type
  4833. * @property {number} sfixed32=5 Fixed32 wire type
  4834. * @property {number} int64=0 Varint wire type
  4835. * @property {number} uint64=0 Varint wire type
  4836. * @property {number} sint64=0 Varint wire type
  4837. * @property {number} fixed64=1 Fixed64 wire type
  4838. * @property {number} sfixed64=1 Fixed64 wire type
  4839. * @property {number} bool=0 Varint wire type
  4840. * @property {number} string=2 Ldelim wire type
  4841. * @property {number} bytes=2 Ldelim wire type
  4842. */
  4843. types.basic = bake([
  4844. /* double */ 1,
  4845. /* float */ 5,
  4846. /* int32 */ 0,
  4847. /* uint32 */ 0,
  4848. /* sint32 */ 0,
  4849. /* fixed32 */ 5,
  4850. /* sfixed32 */ 5,
  4851. /* int64 */ 0,
  4852. /* uint64 */ 0,
  4853. /* sint64 */ 0,
  4854. /* fixed64 */ 1,
  4855. /* sfixed64 */ 1,
  4856. /* bool */ 0,
  4857. /* string */ 2,
  4858. /* bytes */ 2
  4859. ]);
  4860. /**
  4861. * Basic type defaults.
  4862. * @type {Object.<string,*>}
  4863. * @const
  4864. * @property {number} double=0 Double default
  4865. * @property {number} float=0 Float default
  4866. * @property {number} int32=0 Int32 default
  4867. * @property {number} uint32=0 Uint32 default
  4868. * @property {number} sint32=0 Sint32 default
  4869. * @property {number} fixed32=0 Fixed32 default
  4870. * @property {number} sfixed32=0 Sfixed32 default
  4871. * @property {number} int64=0 Int64 default
  4872. * @property {number} uint64=0 Uint64 default
  4873. * @property {number} sint64=0 Sint32 default
  4874. * @property {number} fixed64=0 Fixed64 default
  4875. * @property {number} sfixed64=0 Sfixed64 default
  4876. * @property {boolean} bool=false Bool default
  4877. * @property {string} string="" String default
  4878. * @property {Array.<number>} bytes=Array(0) Bytes default
  4879. * @property {null} message=null Message default
  4880. */
  4881. types.defaults = bake([
  4882. /* double */ 0,
  4883. /* float */ 0,
  4884. /* int32 */ 0,
  4885. /* uint32 */ 0,
  4886. /* sint32 */ 0,
  4887. /* fixed32 */ 0,
  4888. /* sfixed32 */ 0,
  4889. /* int64 */ 0,
  4890. /* uint64 */ 0,
  4891. /* sint64 */ 0,
  4892. /* fixed64 */ 0,
  4893. /* sfixed64 */ 0,
  4894. /* bool */ false,
  4895. /* string */ "",
  4896. /* bytes */ util.emptyArray,
  4897. /* message */ null
  4898. ]);
  4899. /**
  4900. * Basic long type wire types.
  4901. * @type {Object.<string,number>}
  4902. * @const
  4903. * @property {number} int64=0 Varint wire type
  4904. * @property {number} uint64=0 Varint wire type
  4905. * @property {number} sint64=0 Varint wire type
  4906. * @property {number} fixed64=1 Fixed64 wire type
  4907. * @property {number} sfixed64=1 Fixed64 wire type
  4908. */
  4909. types.long = bake([
  4910. /* int64 */ 0,
  4911. /* uint64 */ 0,
  4912. /* sint64 */ 0,
  4913. /* fixed64 */ 1,
  4914. /* sfixed64 */ 1
  4915. ], 7);
  4916. /**
  4917. * Allowed types for map keys with their associated wire type.
  4918. * @type {Object.<string,number>}
  4919. * @const
  4920. * @property {number} int32=0 Varint wire type
  4921. * @property {number} uint32=0 Varint wire type
  4922. * @property {number} sint32=0 Varint wire type
  4923. * @property {number} fixed32=5 Fixed32 wire type
  4924. * @property {number} sfixed32=5 Fixed32 wire type
  4925. * @property {number} int64=0 Varint wire type
  4926. * @property {number} uint64=0 Varint wire type
  4927. * @property {number} sint64=0 Varint wire type
  4928. * @property {number} fixed64=1 Fixed64 wire type
  4929. * @property {number} sfixed64=1 Fixed64 wire type
  4930. * @property {number} bool=0 Varint wire type
  4931. * @property {number} string=2 Ldelim wire type
  4932. */
  4933. types.mapKey = bake([
  4934. /* int32 */ 0,
  4935. /* uint32 */ 0,
  4936. /* sint32 */ 0,
  4937. /* fixed32 */ 5,
  4938. /* sfixed32 */ 5,
  4939. /* int64 */ 0,
  4940. /* uint64 */ 0,
  4941. /* sint64 */ 0,
  4942. /* fixed64 */ 1,
  4943. /* sfixed64 */ 1,
  4944. /* bool */ 0,
  4945. /* string */ 2
  4946. ], 2);
  4947. /**
  4948. * Allowed types for packed repeated fields with their associated wire type.
  4949. * @type {Object.<string,number>}
  4950. * @const
  4951. * @property {number} double=1 Fixed64 wire type
  4952. * @property {number} float=5 Fixed32 wire type
  4953. * @property {number} int32=0 Varint wire type
  4954. * @property {number} uint32=0 Varint wire type
  4955. * @property {number} sint32=0 Varint wire type
  4956. * @property {number} fixed32=5 Fixed32 wire type
  4957. * @property {number} sfixed32=5 Fixed32 wire type
  4958. * @property {number} int64=0 Varint wire type
  4959. * @property {number} uint64=0 Varint wire type
  4960. * @property {number} sint64=0 Varint wire type
  4961. * @property {number} fixed64=1 Fixed64 wire type
  4962. * @property {number} sfixed64=1 Fixed64 wire type
  4963. * @property {number} bool=0 Varint wire type
  4964. */
  4965. types.packed = bake([
  4966. /* double */ 1,
  4967. /* float */ 5,
  4968. /* int32 */ 0,
  4969. /* uint32 */ 0,
  4970. /* sint32 */ 0,
  4971. /* fixed32 */ 5,
  4972. /* sfixed32 */ 5,
  4973. /* int64 */ 0,
  4974. /* uint64 */ 0,
  4975. /* sint64 */ 0,
  4976. /* fixed64 */ 1,
  4977. /* sfixed64 */ 1,
  4978. /* bool */ 0
  4979. ]);
  4980. },{"33":33}],33:[function(require,module,exports){
  4981. "use strict";
  4982. /**
  4983. * Various utility functions.
  4984. * @namespace
  4985. */
  4986. var util = module.exports = require(35);
  4987. var roots = require(27);
  4988. var Type, // cyclic
  4989. Enum;
  4990. util.codegen = require(3);
  4991. util.fetch = require(5);
  4992. util.path = require(8);
  4993. /**
  4994. * Node's fs module if available.
  4995. * @type {Object.<string,*>}
  4996. */
  4997. util.fs = util.inquire("fs");
  4998. /**
  4999. * Converts an object's values to an array.
  5000. * @param {Object.<string,*>} object Object to convert
  5001. * @returns {Array.<*>} Converted array
  5002. */
  5003. util.toArray = function toArray(object) {
  5004. if (object) {
  5005. var keys = Object.keys(object),
  5006. array = new Array(keys.length),
  5007. index = 0;
  5008. while (index < keys.length)
  5009. array[index] = object[keys[index++]];
  5010. return array;
  5011. }
  5012. return [];
  5013. };
  5014. /**
  5015. * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
  5016. * @param {Array.<*>} array Array to convert
  5017. * @returns {Object.<string,*>} Converted object
  5018. */
  5019. util.toObject = function toObject(array) {
  5020. var object = {},
  5021. index = 0;
  5022. while (index < array.length) {
  5023. var key = array[index++],
  5024. val = array[index++];
  5025. if (val !== undefined)
  5026. object[key] = val;
  5027. }
  5028. return object;
  5029. };
  5030. var safePropBackslashRe = /\\/g,
  5031. safePropQuoteRe = /"/g;
  5032. /**
  5033. * Tests whether the specified name is a reserved word in JS.
  5034. * @param {string} name Name to test
  5035. * @returns {boolean} `true` if reserved, otherwise `false`
  5036. */
  5037. util.isReserved = function isReserved(name) {
  5038. return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);
  5039. };
  5040. /**
  5041. * Returns a safe property accessor for the specified property name.
  5042. * @param {string} prop Property name
  5043. * @returns {string} Safe accessor
  5044. */
  5045. util.safeProp = function safeProp(prop) {
  5046. if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))
  5047. return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";
  5048. return "." + prop;
  5049. };
  5050. /**
  5051. * Converts the first character of a string to upper case.
  5052. * @param {string} str String to convert
  5053. * @returns {string} Converted string
  5054. */
  5055. util.ucFirst = function ucFirst(str) {
  5056. return str.charAt(0).toUpperCase() + str.substring(1);
  5057. };
  5058. var camelCaseRe = /_([a-z])/g;
  5059. /**
  5060. * Converts a string to camel case.
  5061. * @param {string} str String to convert
  5062. * @returns {string} Converted string
  5063. */
  5064. util.camelCase = function camelCase(str) {
  5065. return str.substring(0, 1)
  5066. + str.substring(1)
  5067. .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });
  5068. };
  5069. /**
  5070. * Compares reflected fields by id.
  5071. * @param {Field} a First field
  5072. * @param {Field} b Second field
  5073. * @returns {number} Comparison value
  5074. */
  5075. util.compareFieldsById = function compareFieldsById(a, b) {
  5076. return a.id - b.id;
  5077. };
  5078. /**
  5079. * Decorator helper for types (TypeScript).
  5080. * @param {Constructor<T>} ctor Constructor function
  5081. * @param {string} [typeName] Type name, defaults to the constructor's name
  5082. * @returns {Type} Reflected type
  5083. * @template T extends Message<T>
  5084. * @property {Root} root Decorators root
  5085. */
  5086. util.decorateType = function decorateType(ctor, typeName) {
  5087. /* istanbul ignore if */
  5088. if (ctor.$type) {
  5089. if (typeName && ctor.$type.name !== typeName) {
  5090. util.decorateRoot.remove(ctor.$type);
  5091. ctor.$type.name = typeName;
  5092. util.decorateRoot.add(ctor.$type);
  5093. }
  5094. return ctor.$type;
  5095. }
  5096. /* istanbul ignore next */
  5097. if (!Type)
  5098. Type = require(31);
  5099. var type = new Type(typeName || ctor.name);
  5100. util.decorateRoot.add(type);
  5101. type.ctor = ctor; // sets up .encode, .decode etc.
  5102. Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
  5103. Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
  5104. return type;
  5105. };
  5106. var decorateEnumIndex = 0;
  5107. /**
  5108. * Decorator helper for enums (TypeScript).
  5109. * @param {Object} object Enum object
  5110. * @returns {Enum} Reflected enum
  5111. */
  5112. util.decorateEnum = function decorateEnum(object) {
  5113. /* istanbul ignore if */
  5114. if (object.$type)
  5115. return object.$type;
  5116. /* istanbul ignore next */
  5117. if (!Enum)
  5118. Enum = require(14);
  5119. var enm = new Enum("Enum" + decorateEnumIndex++, object);
  5120. util.decorateRoot.add(enm);
  5121. Object.defineProperty(object, "$type", { value: enm, enumerable: false });
  5122. return enm;
  5123. };
  5124. /**
  5125. * Sets the value of a property by property path. If a value already exists, it is turned to an array
  5126. * @param {Object.<string,*>} dst Destination object
  5127. * @param {string} path dot '.' delimited path of the property to set
  5128. * @param {Object} value the value to set
  5129. * @returns {Object.<string,*>} Destination object
  5130. */
  5131. util.setProperty = function setProperty(dst, path, value) {
  5132. function setProp(dst, path, value) {
  5133. var part = path.shift();
  5134. if (path.length > 0) {
  5135. dst[part] = setProp(dst[part] || {}, path, value);
  5136. } else {
  5137. var prevValue = dst[part];
  5138. if (prevValue)
  5139. value = [].concat(prevValue).concat(value);
  5140. dst[part] = value;
  5141. }
  5142. return dst;
  5143. }
  5144. if (typeof dst !== "object")
  5145. throw TypeError("dst must be an object");
  5146. if (!path)
  5147. throw TypeError("path must be specified");
  5148. path = path.split(".");
  5149. return setProp(dst, path, value);
  5150. };
  5151. /**
  5152. * Decorator root (TypeScript).
  5153. * @name util.decorateRoot
  5154. * @type {Root}
  5155. * @readonly
  5156. */
  5157. Object.defineProperty(util, "decorateRoot", {
  5158. get: function() {
  5159. return roots["decorated"] || (roots["decorated"] = new (require(26))());
  5160. }
  5161. });
  5162. },{"14":14,"26":26,"27":27,"3":3,"31":31,"35":35,"5":5,"8":8}],34:[function(require,module,exports){
  5163. "use strict";
  5164. module.exports = LongBits;
  5165. var util = require(35);
  5166. /**
  5167. * Constructs new long bits.
  5168. * @classdesc Helper class for working with the low and high bits of a 64 bit value.
  5169. * @memberof util
  5170. * @constructor
  5171. * @param {number} lo Low 32 bits, unsigned
  5172. * @param {number} hi High 32 bits, unsigned
  5173. */
  5174. function LongBits(lo, hi) {
  5175. // note that the casts below are theoretically unnecessary as of today, but older statically
  5176. // generated converter code might still call the ctor with signed 32bits. kept for compat.
  5177. /**
  5178. * Low bits.
  5179. * @type {number}
  5180. */
  5181. this.lo = lo >>> 0;
  5182. /**
  5183. * High bits.
  5184. * @type {number}
  5185. */
  5186. this.hi = hi >>> 0;
  5187. }
  5188. /**
  5189. * Zero bits.
  5190. * @memberof util.LongBits
  5191. * @type {util.LongBits}
  5192. */
  5193. var zero = LongBits.zero = new LongBits(0, 0);
  5194. zero.toNumber = function() { return 0; };
  5195. zero.zzEncode = zero.zzDecode = function() { return this; };
  5196. zero.length = function() { return 1; };
  5197. /**
  5198. * Zero hash.
  5199. * @memberof util.LongBits
  5200. * @type {string}
  5201. */
  5202. var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
  5203. /**
  5204. * Constructs new long bits from the specified number.
  5205. * @param {number} value Value
  5206. * @returns {util.LongBits} Instance
  5207. */
  5208. LongBits.fromNumber = function fromNumber(value) {
  5209. if (value === 0)
  5210. return zero;
  5211. var sign = value < 0;
  5212. if (sign)
  5213. value = -value;
  5214. var lo = value >>> 0,
  5215. hi = (value - lo) / 4294967296 >>> 0;
  5216. if (sign) {
  5217. hi = ~hi >>> 0;
  5218. lo = ~lo >>> 0;
  5219. if (++lo > 4294967295) {
  5220. lo = 0;
  5221. if (++hi > 4294967295)
  5222. hi = 0;
  5223. }
  5224. }
  5225. return new LongBits(lo, hi);
  5226. };
  5227. /**
  5228. * Constructs new long bits from a number, long or string.
  5229. * @param {Long|number|string} value Value
  5230. * @returns {util.LongBits} Instance
  5231. */
  5232. LongBits.from = function from(value) {
  5233. if (typeof value === "number")
  5234. return LongBits.fromNumber(value);
  5235. if (util.isString(value)) {
  5236. /* istanbul ignore else */
  5237. if (util.Long)
  5238. value = util.Long.fromString(value);
  5239. else
  5240. return LongBits.fromNumber(parseInt(value, 10));
  5241. }
  5242. return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
  5243. };
  5244. /**
  5245. * Converts this long bits to a possibly unsafe JavaScript number.
  5246. * @param {boolean} [unsigned=false] Whether unsigned or not
  5247. * @returns {number} Possibly unsafe number
  5248. */
  5249. LongBits.prototype.toNumber = function toNumber(unsigned) {
  5250. if (!unsigned && this.hi >>> 31) {
  5251. var lo = ~this.lo + 1 >>> 0,
  5252. hi = ~this.hi >>> 0;
  5253. if (!lo)
  5254. hi = hi + 1 >>> 0;
  5255. return -(lo + hi * 4294967296);
  5256. }
  5257. return this.lo + this.hi * 4294967296;
  5258. };
  5259. /**
  5260. * Converts this long bits to a long.
  5261. * @param {boolean} [unsigned=false] Whether unsigned or not
  5262. * @returns {Long} Long
  5263. */
  5264. LongBits.prototype.toLong = function toLong(unsigned) {
  5265. return util.Long
  5266. ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
  5267. /* istanbul ignore next */
  5268. : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
  5269. };
  5270. var charCodeAt = String.prototype.charCodeAt;
  5271. /**
  5272. * Constructs new long bits from the specified 8 characters long hash.
  5273. * @param {string} hash Hash
  5274. * @returns {util.LongBits} Bits
  5275. */
  5276. LongBits.fromHash = function fromHash(hash) {
  5277. if (hash === zeroHash)
  5278. return zero;
  5279. return new LongBits(
  5280. ( charCodeAt.call(hash, 0)
  5281. | charCodeAt.call(hash, 1) << 8
  5282. | charCodeAt.call(hash, 2) << 16
  5283. | charCodeAt.call(hash, 3) << 24) >>> 0
  5284. ,
  5285. ( charCodeAt.call(hash, 4)
  5286. | charCodeAt.call(hash, 5) << 8
  5287. | charCodeAt.call(hash, 6) << 16
  5288. | charCodeAt.call(hash, 7) << 24) >>> 0
  5289. );
  5290. };
  5291. /**
  5292. * Converts this long bits to a 8 characters long hash.
  5293. * @returns {string} Hash
  5294. */
  5295. LongBits.prototype.toHash = function toHash() {
  5296. return String.fromCharCode(
  5297. this.lo & 255,
  5298. this.lo >>> 8 & 255,
  5299. this.lo >>> 16 & 255,
  5300. this.lo >>> 24 ,
  5301. this.hi & 255,
  5302. this.hi >>> 8 & 255,
  5303. this.hi >>> 16 & 255,
  5304. this.hi >>> 24
  5305. );
  5306. };
  5307. /**
  5308. * Zig-zag encodes this long bits.
  5309. * @returns {util.LongBits} `this`
  5310. */
  5311. LongBits.prototype.zzEncode = function zzEncode() {
  5312. var mask = this.hi >> 31;
  5313. this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
  5314. this.lo = ( this.lo << 1 ^ mask) >>> 0;
  5315. return this;
  5316. };
  5317. /**
  5318. * Zig-zag decodes this long bits.
  5319. * @returns {util.LongBits} `this`
  5320. */
  5321. LongBits.prototype.zzDecode = function zzDecode() {
  5322. var mask = -(this.lo & 1);
  5323. this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
  5324. this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
  5325. return this;
  5326. };
  5327. /**
  5328. * Calculates the length of this longbits when encoded as a varint.
  5329. * @returns {number} Length
  5330. */
  5331. LongBits.prototype.length = function length() {
  5332. var part0 = this.lo,
  5333. part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
  5334. part2 = this.hi >>> 24;
  5335. return part2 === 0
  5336. ? part1 === 0
  5337. ? part0 < 16384
  5338. ? part0 < 128 ? 1 : 2
  5339. : part0 < 2097152 ? 3 : 4
  5340. : part1 < 16384
  5341. ? part1 < 128 ? 5 : 6
  5342. : part1 < 2097152 ? 7 : 8
  5343. : part2 < 128 ? 9 : 10;
  5344. };
  5345. },{"35":35}],35:[function(require,module,exports){
  5346. "use strict";
  5347. var util = exports;
  5348. // used to return a Promise where callback is omitted
  5349. util.asPromise = require(1);
  5350. // converts to / from base64 encoded strings
  5351. util.base64 = require(2);
  5352. // base class of rpc.Service
  5353. util.EventEmitter = require(4);
  5354. // float handling accross browsers
  5355. util.float = require(6);
  5356. // requires modules optionally and hides the call from bundlers
  5357. util.inquire = require(7);
  5358. // converts to / from utf8 encoded strings
  5359. util.utf8 = require(10);
  5360. // provides a node-like buffer pool in the browser
  5361. util.pool = require(9);
  5362. // utility to work with the low and high bits of a 64 bit value
  5363. util.LongBits = require(34);
  5364. /**
  5365. * Whether running within node or not.
  5366. * @memberof util
  5367. * @type {boolean}
  5368. */
  5369. util.isNode = Boolean(typeof global !== "undefined"
  5370. && global
  5371. && global.process
  5372. && global.process.versions
  5373. && global.process.versions.node);
  5374. /**
  5375. * Global object reference.
  5376. * @memberof util
  5377. * @type {Object}
  5378. */
  5379. util.global = util.isNode && global
  5380. || typeof window !== "undefined" && window
  5381. || typeof self !== "undefined" && self
  5382. || this; // eslint-disable-line no-invalid-this
  5383. /**
  5384. * An immuable empty array.
  5385. * @memberof util
  5386. * @type {Array.<*>}
  5387. * @const
  5388. */
  5389. util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
  5390. /**
  5391. * An immutable empty object.
  5392. * @type {Object}
  5393. * @const
  5394. */
  5395. util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
  5396. /**
  5397. * Tests if the specified value is an integer.
  5398. * @function
  5399. * @param {*} value Value to test
  5400. * @returns {boolean} `true` if the value is an integer
  5401. */
  5402. util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
  5403. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  5404. };
  5405. /**
  5406. * Tests if the specified value is a string.
  5407. * @param {*} value Value to test
  5408. * @returns {boolean} `true` if the value is a string
  5409. */
  5410. util.isString = function isString(value) {
  5411. return typeof value === "string" || value instanceof String;
  5412. };
  5413. /**
  5414. * Tests if the specified value is a non-null object.
  5415. * @param {*} value Value to test
  5416. * @returns {boolean} `true` if the value is a non-null object
  5417. */
  5418. util.isObject = function isObject(value) {
  5419. return value && typeof value === "object";
  5420. };
  5421. /**
  5422. * Checks if a property on a message is considered to be present.
  5423. * This is an alias of {@link util.isSet}.
  5424. * @function
  5425. * @param {Object} obj Plain object or message instance
  5426. * @param {string} prop Property name
  5427. * @returns {boolean} `true` if considered to be present, otherwise `false`
  5428. */
  5429. util.isset =
  5430. /**
  5431. * Checks if a property on a message is considered to be present.
  5432. * @param {Object} obj Plain object or message instance
  5433. * @param {string} prop Property name
  5434. * @returns {boolean} `true` if considered to be present, otherwise `false`
  5435. */
  5436. util.isSet = function isSet(obj, prop) {
  5437. var value = obj[prop];
  5438. if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
  5439. return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
  5440. return false;
  5441. };
  5442. /**
  5443. * Any compatible Buffer instance.
  5444. * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
  5445. * @interface Buffer
  5446. * @extends Uint8Array
  5447. */
  5448. /**
  5449. * Node's Buffer class if available.
  5450. * @type {Constructor<Buffer>}
  5451. */
  5452. util.Buffer = (function() {
  5453. try {
  5454. var Buffer = util.inquire("buffer").Buffer;
  5455. // refuse to use non-node buffers if not explicitly assigned (perf reasons):
  5456. return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
  5457. } catch (e) {
  5458. /* istanbul ignore next */
  5459. return null;
  5460. }
  5461. })();
  5462. // Internal alias of or polyfull for Buffer.from.
  5463. util._Buffer_from = null;
  5464. // Internal alias of or polyfill for Buffer.allocUnsafe.
  5465. util._Buffer_allocUnsafe = null;
  5466. /**
  5467. * Creates a new buffer of whatever type supported by the environment.
  5468. * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
  5469. * @returns {Uint8Array|Buffer} Buffer
  5470. */
  5471. util.newBuffer = function newBuffer(sizeOrArray) {
  5472. /* istanbul ignore next */
  5473. return typeof sizeOrArray === "number"
  5474. ? util.Buffer
  5475. ? util._Buffer_allocUnsafe(sizeOrArray)
  5476. : new util.Array(sizeOrArray)
  5477. : util.Buffer
  5478. ? util._Buffer_from(sizeOrArray)
  5479. : typeof Uint8Array === "undefined"
  5480. ? sizeOrArray
  5481. : new Uint8Array(sizeOrArray);
  5482. };
  5483. /**
  5484. * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
  5485. * @type {Constructor<Uint8Array>}
  5486. */
  5487. util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
  5488. /**
  5489. * Any compatible Long instance.
  5490. * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
  5491. * @interface Long
  5492. * @property {number} low Low bits
  5493. * @property {number} high High bits
  5494. * @property {boolean} unsigned Whether unsigned or not
  5495. */
  5496. /**
  5497. * Long.js's Long class if available.
  5498. * @type {Constructor<Long>}
  5499. */
  5500. util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
  5501. || /* istanbul ignore next */ util.global.Long
  5502. || util.inquire("long");
  5503. /**
  5504. * Regular expression used to verify 2 bit (`bool`) map keys.
  5505. * @type {RegExp}
  5506. * @const
  5507. */
  5508. util.key2Re = /^true|false|0|1$/;
  5509. /**
  5510. * Regular expression used to verify 32 bit (`int32` etc.) map keys.
  5511. * @type {RegExp}
  5512. * @const
  5513. */
  5514. util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
  5515. /**
  5516. * Regular expression used to verify 64 bit (`int64` etc.) map keys.
  5517. * @type {RegExp}
  5518. * @const
  5519. */
  5520. util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
  5521. /**
  5522. * Converts a number or long to an 8 characters long hash string.
  5523. * @param {Long|number} value Value to convert
  5524. * @returns {string} Hash
  5525. */
  5526. util.longToHash = function longToHash(value) {
  5527. return value
  5528. ? util.LongBits.from(value).toHash()
  5529. : util.LongBits.zeroHash;
  5530. };
  5531. /**
  5532. * Converts an 8 characters long hash string to a long or number.
  5533. * @param {string} hash Hash
  5534. * @param {boolean} [unsigned=false] Whether unsigned or not
  5535. * @returns {Long|number} Original value
  5536. */
  5537. util.longFromHash = function longFromHash(hash, unsigned) {
  5538. var bits = util.LongBits.fromHash(hash);
  5539. if (util.Long)
  5540. return util.Long.fromBits(bits.lo, bits.hi, unsigned);
  5541. return bits.toNumber(Boolean(unsigned));
  5542. };
  5543. /**
  5544. * Merges the properties of the source object into the destination object.
  5545. * @memberof util
  5546. * @param {Object.<string,*>} dst Destination object
  5547. * @param {Object.<string,*>} src Source object
  5548. * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
  5549. * @returns {Object.<string,*>} Destination object
  5550. */
  5551. function merge(dst, src, ifNotSet) { // used by converters
  5552. for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
  5553. if (dst[keys[i]] === undefined || !ifNotSet)
  5554. dst[keys[i]] = src[keys[i]];
  5555. return dst;
  5556. }
  5557. util.merge = merge;
  5558. /**
  5559. * Converts the first character of a string to lower case.
  5560. * @param {string} str String to convert
  5561. * @returns {string} Converted string
  5562. */
  5563. util.lcFirst = function lcFirst(str) {
  5564. return str.charAt(0).toLowerCase() + str.substring(1);
  5565. };
  5566. /**
  5567. * Creates a custom error constructor.
  5568. * @memberof util
  5569. * @param {string} name Error name
  5570. * @returns {Constructor<Error>} Custom error constructor
  5571. */
  5572. function newError(name) {
  5573. function CustomError(message, properties) {
  5574. if (!(this instanceof CustomError))
  5575. return new CustomError(message, properties);
  5576. // Error.call(this, message);
  5577. // ^ just returns a new error instance because the ctor can be called as a function
  5578. Object.defineProperty(this, "message", { get: function() { return message; } });
  5579. /* istanbul ignore next */
  5580. if (Error.captureStackTrace) // node
  5581. Error.captureStackTrace(this, CustomError);
  5582. else
  5583. Object.defineProperty(this, "stack", { value: new Error().stack || "" });
  5584. if (properties)
  5585. merge(this, properties);
  5586. }
  5587. (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
  5588. Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
  5589. CustomError.prototype.toString = function toString() {
  5590. return this.name + ": " + this.message;
  5591. };
  5592. return CustomError;
  5593. }
  5594. util.newError = newError;
  5595. /**
  5596. * Constructs a new protocol error.
  5597. * @classdesc Error subclass indicating a protocol specifc error.
  5598. * @memberof util
  5599. * @extends Error
  5600. * @template T extends Message<T>
  5601. * @constructor
  5602. * @param {string} message Error message
  5603. * @param {Object.<string,*>} [properties] Additional properties
  5604. * @example
  5605. * try {
  5606. * MyMessage.decode(someBuffer); // throws if required fields are missing
  5607. * } catch (e) {
  5608. * if (e instanceof ProtocolError && e.instance)
  5609. * console.log("decoded so far: " + JSON.stringify(e.instance));
  5610. * }
  5611. */
  5612. util.ProtocolError = newError("ProtocolError");
  5613. /**
  5614. * So far decoded message instance.
  5615. * @name util.ProtocolError#instance
  5616. * @type {Message<T>}
  5617. */
  5618. /**
  5619. * A OneOf getter as returned by {@link util.oneOfGetter}.
  5620. * @typedef OneOfGetter
  5621. * @type {function}
  5622. * @returns {string|undefined} Set field name, if any
  5623. */
  5624. /**
  5625. * Builds a getter for a oneof's present field name.
  5626. * @param {string[]} fieldNames Field names
  5627. * @returns {OneOfGetter} Unbound getter
  5628. */
  5629. util.oneOfGetter = function getOneOf(fieldNames) {
  5630. var fieldMap = {};
  5631. for (var i = 0; i < fieldNames.length; ++i)
  5632. fieldMap[fieldNames[i]] = 1;
  5633. /**
  5634. * @returns {string|undefined} Set field name, if any
  5635. * @this Object
  5636. * @ignore
  5637. */
  5638. return function() { // eslint-disable-line consistent-return
  5639. for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
  5640. if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
  5641. return keys[i];
  5642. };
  5643. };
  5644. /**
  5645. * A OneOf setter as returned by {@link util.oneOfSetter}.
  5646. * @typedef OneOfSetter
  5647. * @type {function}
  5648. * @param {string|undefined} value Field name
  5649. * @returns {undefined}
  5650. */
  5651. /**
  5652. * Builds a setter for a oneof's present field name.
  5653. * @param {string[]} fieldNames Field names
  5654. * @returns {OneOfSetter} Unbound setter
  5655. */
  5656. util.oneOfSetter = function setOneOf(fieldNames) {
  5657. /**
  5658. * @param {string} name Field name
  5659. * @returns {undefined}
  5660. * @this Object
  5661. * @ignore
  5662. */
  5663. return function(name) {
  5664. for (var i = 0; i < fieldNames.length; ++i)
  5665. if (fieldNames[i] !== name)
  5666. delete this[fieldNames[i]];
  5667. };
  5668. };
  5669. /**
  5670. * Default conversion options used for {@link Message#toJSON} implementations.
  5671. *
  5672. * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
  5673. *
  5674. * - Longs become strings
  5675. * - Enums become string keys
  5676. * - Bytes become base64 encoded strings
  5677. * - (Sub-)Messages become plain objects
  5678. * - Maps become plain objects with all string keys
  5679. * - Repeated fields become arrays
  5680. * - NaN and Infinity for float and double fields become strings
  5681. *
  5682. * @type {IConversionOptions}
  5683. * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
  5684. */
  5685. util.toJSONOptions = {
  5686. longs: String,
  5687. enums: String,
  5688. bytes: String,
  5689. json: true
  5690. };
  5691. // Sets up buffer utility according to the environment (called in index-minimal)
  5692. util._configure = function() {
  5693. var Buffer = util.Buffer;
  5694. /* istanbul ignore if */
  5695. if (!Buffer) {
  5696. util._Buffer_from = util._Buffer_allocUnsafe = null;
  5697. return;
  5698. }
  5699. // because node 4.x buffers are incompatible & immutable
  5700. // see: https://github.com/dcodeIO/protobuf.js/pull/665
  5701. util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
  5702. /* istanbul ignore next */
  5703. function Buffer_from(value, encoding) {
  5704. return new Buffer(value, encoding);
  5705. };
  5706. util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
  5707. /* istanbul ignore next */
  5708. function Buffer_allocUnsafe(size) {
  5709. return new Buffer(size);
  5710. };
  5711. };
  5712. },{"1":1,"10":10,"2":2,"34":34,"4":4,"6":6,"7":7,"9":9}],36:[function(require,module,exports){
  5713. "use strict";
  5714. module.exports = verifier;
  5715. var Enum = require(14),
  5716. util = require(33);
  5717. function invalid(field, expected) {
  5718. return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";
  5719. }
  5720. /**
  5721. * Generates a partial value verifier.
  5722. * @param {Codegen} gen Codegen instance
  5723. * @param {Field} field Reflected field
  5724. * @param {number} fieldIndex Field index
  5725. * @param {string} ref Variable reference
  5726. * @returns {Codegen} Codegen instance
  5727. * @ignore
  5728. */
  5729. function genVerifyValue(gen, field, fieldIndex, ref) {
  5730. /* eslint-disable no-unexpected-multiline */
  5731. if (field.resolvedType) {
  5732. if (field.resolvedType instanceof Enum) { gen
  5733. ("switch(%s){", ref)
  5734. ("default:")
  5735. ("return%j", invalid(field, "enum value"));
  5736. for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen
  5737. ("case %i:", field.resolvedType.values[keys[j]]);
  5738. gen
  5739. ("break")
  5740. ("}");
  5741. } else {
  5742. gen
  5743. ("{")
  5744. ("var e=types[%i].verify(%s);", fieldIndex, ref)
  5745. ("if(e)")
  5746. ("return%j+e", field.name + ".")
  5747. ("}");
  5748. }
  5749. } else {
  5750. switch (field.type) {
  5751. case "int32":
  5752. case "uint32":
  5753. case "sint32":
  5754. case "fixed32":
  5755. case "sfixed32": gen
  5756. ("if(!util.isInteger(%s))", ref)
  5757. ("return%j", invalid(field, "integer"));
  5758. break;
  5759. case "int64":
  5760. case "uint64":
  5761. case "sint64":
  5762. case "fixed64":
  5763. case "sfixed64": gen
  5764. ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)
  5765. ("return%j", invalid(field, "integer|Long"));
  5766. break;
  5767. case "float":
  5768. case "double": gen
  5769. ("if(typeof %s!==\"number\")", ref)
  5770. ("return%j", invalid(field, "number"));
  5771. break;
  5772. case "bool": gen
  5773. ("if(typeof %s!==\"boolean\")", ref)
  5774. ("return%j", invalid(field, "boolean"));
  5775. break;
  5776. case "string": gen
  5777. ("if(!util.isString(%s))", ref)
  5778. ("return%j", invalid(field, "string"));
  5779. break;
  5780. case "bytes": gen
  5781. ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)
  5782. ("return%j", invalid(field, "buffer"));
  5783. break;
  5784. }
  5785. }
  5786. return gen;
  5787. /* eslint-enable no-unexpected-multiline */
  5788. }
  5789. /**
  5790. * Generates a partial key verifier.
  5791. * @param {Codegen} gen Codegen instance
  5792. * @param {Field} field Reflected field
  5793. * @param {string} ref Variable reference
  5794. * @returns {Codegen} Codegen instance
  5795. * @ignore
  5796. */
  5797. function genVerifyKey(gen, field, ref) {
  5798. /* eslint-disable no-unexpected-multiline */
  5799. switch (field.keyType) {
  5800. case "int32":
  5801. case "uint32":
  5802. case "sint32":
  5803. case "fixed32":
  5804. case "sfixed32": gen
  5805. ("if(!util.key32Re.test(%s))", ref)
  5806. ("return%j", invalid(field, "integer key"));
  5807. break;
  5808. case "int64":
  5809. case "uint64":
  5810. case "sint64":
  5811. case "fixed64":
  5812. case "sfixed64": gen
  5813. ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not
  5814. ("return%j", invalid(field, "integer|Long key"));
  5815. break;
  5816. case "bool": gen
  5817. ("if(!util.key2Re.test(%s))", ref)
  5818. ("return%j", invalid(field, "boolean key"));
  5819. break;
  5820. }
  5821. return gen;
  5822. /* eslint-enable no-unexpected-multiline */
  5823. }
  5824. /**
  5825. * Generates a verifier specific to the specified message type.
  5826. * @param {Type} mtype Message type
  5827. * @returns {Codegen} Codegen instance
  5828. */
  5829. function verifier(mtype) {
  5830. /* eslint-disable no-unexpected-multiline */
  5831. var gen = util.codegen(["m"], mtype.name + "$verify")
  5832. ("if(typeof m!==\"object\"||m===null)")
  5833. ("return%j", "object expected");
  5834. var oneofs = mtype.oneofsArray,
  5835. seenFirstField = {};
  5836. if (oneofs.length) gen
  5837. ("var p={}");
  5838. for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  5839. var field = mtype._fieldsArray[i].resolve(),
  5840. ref = "m" + util.safeProp(field.name);
  5841. if (field.optional) gen
  5842. ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null
  5843. // map fields
  5844. if (field.map) { gen
  5845. ("if(!util.isObject(%s))", ref)
  5846. ("return%j", invalid(field, "object"))
  5847. ("var k=Object.keys(%s)", ref)
  5848. ("for(var i=0;i<k.length;++i){");
  5849. genVerifyKey(gen, field, "k[i]");
  5850. genVerifyValue(gen, field, i, ref + "[k[i]]")
  5851. ("}");
  5852. // repeated fields
  5853. } else if (field.repeated) { gen
  5854. ("if(!Array.isArray(%s))", ref)
  5855. ("return%j", invalid(field, "array"))
  5856. ("for(var i=0;i<%s.length;++i){", ref);
  5857. genVerifyValue(gen, field, i, ref + "[i]")
  5858. ("}");
  5859. // required or present fields
  5860. } else {
  5861. if (field.partOf) {
  5862. var oneofProp = util.safeProp(field.partOf.name);
  5863. if (seenFirstField[field.partOf.name] === 1) gen
  5864. ("if(p%s===1)", oneofProp)
  5865. ("return%j", field.partOf.name + ": multiple values");
  5866. seenFirstField[field.partOf.name] = 1;
  5867. gen
  5868. ("p%s=1", oneofProp);
  5869. }
  5870. genVerifyValue(gen, field, i, ref);
  5871. }
  5872. if (field.optional) gen
  5873. ("}");
  5874. }
  5875. return gen
  5876. ("return null");
  5877. /* eslint-enable no-unexpected-multiline */
  5878. }
  5879. },{"14":14,"33":33}],37:[function(require,module,exports){
  5880. "use strict";
  5881. /**
  5882. * Wrappers for common types.
  5883. * @type {Object.<string,IWrapper>}
  5884. * @const
  5885. */
  5886. var wrappers = exports;
  5887. var Message = require(19);
  5888. /**
  5889. * From object converter part of an {@link IWrapper}.
  5890. * @typedef WrapperFromObjectConverter
  5891. * @type {function}
  5892. * @param {Object.<string,*>} object Plain object
  5893. * @returns {Message<{}>} Message instance
  5894. * @this Type
  5895. */
  5896. /**
  5897. * To object converter part of an {@link IWrapper}.
  5898. * @typedef WrapperToObjectConverter
  5899. * @type {function}
  5900. * @param {Message<{}>} message Message instance
  5901. * @param {IConversionOptions} [options] Conversion options
  5902. * @returns {Object.<string,*>} Plain object
  5903. * @this Type
  5904. */
  5905. /**
  5906. * Common type wrapper part of {@link wrappers}.
  5907. * @interface IWrapper
  5908. * @property {WrapperFromObjectConverter} [fromObject] From object converter
  5909. * @property {WrapperToObjectConverter} [toObject] To object converter
  5910. */
  5911. // Custom wrapper for Any
  5912. wrappers[".google.protobuf.Any"] = {
  5913. fromObject: function(object) {
  5914. // unwrap value type if mapped
  5915. if (object && object["@type"]) {
  5916. // Only use fully qualified type name after the last '/'
  5917. var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1);
  5918. var type = this.lookup(name);
  5919. /* istanbul ignore else */
  5920. if (type) {
  5921. // type_url does not accept leading "."
  5922. var type_url = object["@type"].charAt(0) === "." ?
  5923. object["@type"].substr(1) : object["@type"];
  5924. // type_url prefix is optional, but path seperator is required
  5925. if (type_url.indexOf("/") === -1) {
  5926. type_url = "/" + type_url;
  5927. }
  5928. return this.create({
  5929. type_url: type_url,
  5930. value: type.encode(type.fromObject(object)).finish()
  5931. });
  5932. }
  5933. }
  5934. return this.fromObject(object);
  5935. },
  5936. toObject: function(message, options) {
  5937. // Default prefix
  5938. var googleApi = "type.googleapis.com/";
  5939. var prefix = "";
  5940. var name = "";
  5941. // decode value if requested and unmapped
  5942. if (options && options.json && message.type_url && message.value) {
  5943. // Only use fully qualified type name after the last '/'
  5944. name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
  5945. // Separate the prefix used
  5946. prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
  5947. var type = this.lookup(name);
  5948. /* istanbul ignore else */
  5949. if (type)
  5950. message = type.decode(message.value);
  5951. }
  5952. // wrap value if unmapped
  5953. if (!(message instanceof this.ctor) && message instanceof Message) {
  5954. var object = message.$type.toObject(message, options);
  5955. var messageName = message.$type.fullName[0] === "." ?
  5956. message.$type.fullName.substr(1) : message.$type.fullName;
  5957. // Default to type.googleapis.com prefix if no prefix is used
  5958. if (prefix === "") {
  5959. prefix = googleApi;
  5960. }
  5961. name = prefix + messageName;
  5962. object["@type"] = name;
  5963. return object;
  5964. }
  5965. return this.toObject(message, options);
  5966. }
  5967. };
  5968. },{"19":19}],38:[function(require,module,exports){
  5969. "use strict";
  5970. module.exports = Writer;
  5971. var util = require(35);
  5972. var BufferWriter; // cyclic
  5973. var LongBits = util.LongBits,
  5974. base64 = util.base64,
  5975. utf8 = util.utf8;
  5976. /**
  5977. * Constructs a new writer operation instance.
  5978. * @classdesc Scheduled writer operation.
  5979. * @constructor
  5980. * @param {function(*, Uint8Array, number)} fn Function to call
  5981. * @param {number} len Value byte length
  5982. * @param {*} val Value to write
  5983. * @ignore
  5984. */
  5985. function Op(fn, len, val) {
  5986. /**
  5987. * Function to call.
  5988. * @type {function(Uint8Array, number, *)}
  5989. */
  5990. this.fn = fn;
  5991. /**
  5992. * Value byte length.
  5993. * @type {number}
  5994. */
  5995. this.len = len;
  5996. /**
  5997. * Next operation.
  5998. * @type {Writer.Op|undefined}
  5999. */
  6000. this.next = undefined;
  6001. /**
  6002. * Value to write.
  6003. * @type {*}
  6004. */
  6005. this.val = val; // type varies
  6006. }
  6007. /* istanbul ignore next */
  6008. function noop() {} // eslint-disable-line no-empty-function
  6009. /**
  6010. * Constructs a new writer state instance.
  6011. * @classdesc Copied writer state.
  6012. * @memberof Writer
  6013. * @constructor
  6014. * @param {Writer} writer Writer to copy state from
  6015. * @ignore
  6016. */
  6017. function State(writer) {
  6018. /**
  6019. * Current head.
  6020. * @type {Writer.Op}
  6021. */
  6022. this.head = writer.head;
  6023. /**
  6024. * Current tail.
  6025. * @type {Writer.Op}
  6026. */
  6027. this.tail = writer.tail;
  6028. /**
  6029. * Current buffer length.
  6030. * @type {number}
  6031. */
  6032. this.len = writer.len;
  6033. /**
  6034. * Next state.
  6035. * @type {State|null}
  6036. */
  6037. this.next = writer.states;
  6038. }
  6039. /**
  6040. * Constructs a new writer instance.
  6041. * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
  6042. * @constructor
  6043. */
  6044. function Writer() {
  6045. /**
  6046. * Current length.
  6047. * @type {number}
  6048. */
  6049. this.len = 0;
  6050. /**
  6051. * Operations head.
  6052. * @type {Object}
  6053. */
  6054. this.head = new Op(noop, 0, 0);
  6055. /**
  6056. * Operations tail
  6057. * @type {Object}
  6058. */
  6059. this.tail = this.head;
  6060. /**
  6061. * Linked forked states.
  6062. * @type {Object|null}
  6063. */
  6064. this.states = null;
  6065. // When a value is written, the writer calculates its byte length and puts it into a linked
  6066. // list of operations to perform when finish() is called. This both allows us to allocate
  6067. // buffers of the exact required size and reduces the amount of work we have to do compared
  6068. // to first calculating over objects and then encoding over objects. In our case, the encoding
  6069. // part is just a linked list walk calling operations with already prepared values.
  6070. }
  6071. var create = function create() {
  6072. return util.Buffer
  6073. ? function create_buffer_setup() {
  6074. return (Writer.create = function create_buffer() {
  6075. return new BufferWriter();
  6076. })();
  6077. }
  6078. /* istanbul ignore next */
  6079. : function create_array() {
  6080. return new Writer();
  6081. };
  6082. };
  6083. /**
  6084. * Creates a new writer.
  6085. * @function
  6086. * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
  6087. */
  6088. Writer.create = create();
  6089. /**
  6090. * Allocates a buffer of the specified size.
  6091. * @param {number} size Buffer size
  6092. * @returns {Uint8Array} Buffer
  6093. */
  6094. Writer.alloc = function alloc(size) {
  6095. return new util.Array(size);
  6096. };
  6097. // Use Uint8Array buffer pool in the browser, just like node does with buffers
  6098. /* istanbul ignore else */
  6099. if (util.Array !== Array)
  6100. Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
  6101. /**
  6102. * Pushes a new operation to the queue.
  6103. * @param {function(Uint8Array, number, *)} fn Function to call
  6104. * @param {number} len Value byte length
  6105. * @param {number} val Value to write
  6106. * @returns {Writer} `this`
  6107. * @private
  6108. */
  6109. Writer.prototype._push = function push(fn, len, val) {
  6110. this.tail = this.tail.next = new Op(fn, len, val);
  6111. this.len += len;
  6112. return this;
  6113. };
  6114. function writeByte(val, buf, pos) {
  6115. buf[pos] = val & 255;
  6116. }
  6117. function writeVarint32(val, buf, pos) {
  6118. while (val > 127) {
  6119. buf[pos++] = val & 127 | 128;
  6120. val >>>= 7;
  6121. }
  6122. buf[pos] = val;
  6123. }
  6124. /**
  6125. * Constructs a new varint writer operation instance.
  6126. * @classdesc Scheduled varint writer operation.
  6127. * @extends Op
  6128. * @constructor
  6129. * @param {number} len Value byte length
  6130. * @param {number} val Value to write
  6131. * @ignore
  6132. */
  6133. function VarintOp(len, val) {
  6134. this.len = len;
  6135. this.next = undefined;
  6136. this.val = val;
  6137. }
  6138. VarintOp.prototype = Object.create(Op.prototype);
  6139. VarintOp.prototype.fn = writeVarint32;
  6140. /**
  6141. * Writes an unsigned 32 bit value as a varint.
  6142. * @param {number} value Value to write
  6143. * @returns {Writer} `this`
  6144. */
  6145. Writer.prototype.uint32 = function write_uint32(value) {
  6146. // here, the call to this.push has been inlined and a varint specific Op subclass is used.
  6147. // uint32 is by far the most frequently used operation and benefits significantly from this.
  6148. this.len += (this.tail = this.tail.next = new VarintOp(
  6149. (value = value >>> 0)
  6150. < 128 ? 1
  6151. : value < 16384 ? 2
  6152. : value < 2097152 ? 3
  6153. : value < 268435456 ? 4
  6154. : 5,
  6155. value)).len;
  6156. return this;
  6157. };
  6158. /**
  6159. * Writes a signed 32 bit value as a varint.
  6160. * @function
  6161. * @param {number} value Value to write
  6162. * @returns {Writer} `this`
  6163. */
  6164. Writer.prototype.int32 = function write_int32(value) {
  6165. return value < 0
  6166. ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
  6167. : this.uint32(value);
  6168. };
  6169. /**
  6170. * Writes a 32 bit value as a varint, zig-zag encoded.
  6171. * @param {number} value Value to write
  6172. * @returns {Writer} `this`
  6173. */
  6174. Writer.prototype.sint32 = function write_sint32(value) {
  6175. return this.uint32((value << 1 ^ value >> 31) >>> 0);
  6176. };
  6177. function writeVarint64(val, buf, pos) {
  6178. while (val.hi) {
  6179. buf[pos++] = val.lo & 127 | 128;
  6180. val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
  6181. val.hi >>>= 7;
  6182. }
  6183. while (val.lo > 127) {
  6184. buf[pos++] = val.lo & 127 | 128;
  6185. val.lo = val.lo >>> 7;
  6186. }
  6187. buf[pos++] = val.lo;
  6188. }
  6189. /**
  6190. * Writes an unsigned 64 bit value as a varint.
  6191. * @param {Long|number|string} value Value to write
  6192. * @returns {Writer} `this`
  6193. * @throws {TypeError} If `value` is a string and no long library is present.
  6194. */
  6195. Writer.prototype.uint64 = function write_uint64(value) {
  6196. var bits = LongBits.from(value);
  6197. return this._push(writeVarint64, bits.length(), bits);
  6198. };
  6199. /**
  6200. * Writes a signed 64 bit value as a varint.
  6201. * @function
  6202. * @param {Long|number|string} value Value to write
  6203. * @returns {Writer} `this`
  6204. * @throws {TypeError} If `value` is a string and no long library is present.
  6205. */
  6206. Writer.prototype.int64 = Writer.prototype.uint64;
  6207. /**
  6208. * Writes a signed 64 bit value as a varint, zig-zag encoded.
  6209. * @param {Long|number|string} value Value to write
  6210. * @returns {Writer} `this`
  6211. * @throws {TypeError} If `value` is a string and no long library is present.
  6212. */
  6213. Writer.prototype.sint64 = function write_sint64(value) {
  6214. var bits = LongBits.from(value).zzEncode();
  6215. return this._push(writeVarint64, bits.length(), bits);
  6216. };
  6217. /**
  6218. * Writes a boolish value as a varint.
  6219. * @param {boolean} value Value to write
  6220. * @returns {Writer} `this`
  6221. */
  6222. Writer.prototype.bool = function write_bool(value) {
  6223. return this._push(writeByte, 1, value ? 1 : 0);
  6224. };
  6225. function writeFixed32(val, buf, pos) {
  6226. buf[pos ] = val & 255;
  6227. buf[pos + 1] = val >>> 8 & 255;
  6228. buf[pos + 2] = val >>> 16 & 255;
  6229. buf[pos + 3] = val >>> 24;
  6230. }
  6231. /**
  6232. * Writes an unsigned 32 bit value as fixed 32 bits.
  6233. * @param {number} value Value to write
  6234. * @returns {Writer} `this`
  6235. */
  6236. Writer.prototype.fixed32 = function write_fixed32(value) {
  6237. return this._push(writeFixed32, 4, value >>> 0);
  6238. };
  6239. /**
  6240. * Writes a signed 32 bit value as fixed 32 bits.
  6241. * @function
  6242. * @param {number} value Value to write
  6243. * @returns {Writer} `this`
  6244. */
  6245. Writer.prototype.sfixed32 = Writer.prototype.fixed32;
  6246. /**
  6247. * Writes an unsigned 64 bit value as fixed 64 bits.
  6248. * @param {Long|number|string} value Value to write
  6249. * @returns {Writer} `this`
  6250. * @throws {TypeError} If `value` is a string and no long library is present.
  6251. */
  6252. Writer.prototype.fixed64 = function write_fixed64(value) {
  6253. var bits = LongBits.from(value);
  6254. return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
  6255. };
  6256. /**
  6257. * Writes a signed 64 bit value as fixed 64 bits.
  6258. * @function
  6259. * @param {Long|number|string} value Value to write
  6260. * @returns {Writer} `this`
  6261. * @throws {TypeError} If `value` is a string and no long library is present.
  6262. */
  6263. Writer.prototype.sfixed64 = Writer.prototype.fixed64;
  6264. /**
  6265. * Writes a float (32 bit).
  6266. * @function
  6267. * @param {number} value Value to write
  6268. * @returns {Writer} `this`
  6269. */
  6270. Writer.prototype.float = function write_float(value) {
  6271. return this._push(util.float.writeFloatLE, 4, value);
  6272. };
  6273. /**
  6274. * Writes a double (64 bit float).
  6275. * @function
  6276. * @param {number} value Value to write
  6277. * @returns {Writer} `this`
  6278. */
  6279. Writer.prototype.double = function write_double(value) {
  6280. return this._push(util.float.writeDoubleLE, 8, value);
  6281. };
  6282. var writeBytes = util.Array.prototype.set
  6283. ? function writeBytes_set(val, buf, pos) {
  6284. buf.set(val, pos); // also works for plain array values
  6285. }
  6286. /* istanbul ignore next */
  6287. : function writeBytes_for(val, buf, pos) {
  6288. for (var i = 0; i < val.length; ++i)
  6289. buf[pos + i] = val[i];
  6290. };
  6291. /**
  6292. * Writes a sequence of bytes.
  6293. * @param {Uint8Array|string} value Buffer or base64 encoded string to write
  6294. * @returns {Writer} `this`
  6295. */
  6296. Writer.prototype.bytes = function write_bytes(value) {
  6297. var len = value.length >>> 0;
  6298. if (!len)
  6299. return this._push(writeByte, 1, 0);
  6300. if (util.isString(value)) {
  6301. var buf = Writer.alloc(len = base64.length(value));
  6302. base64.decode(value, buf, 0);
  6303. value = buf;
  6304. }
  6305. return this.uint32(len)._push(writeBytes, len, value);
  6306. };
  6307. /**
  6308. * Writes a string.
  6309. * @param {string} value Value to write
  6310. * @returns {Writer} `this`
  6311. */
  6312. Writer.prototype.string = function write_string(value) {
  6313. var len = utf8.length(value);
  6314. return len
  6315. ? this.uint32(len)._push(utf8.write, len, value)
  6316. : this._push(writeByte, 1, 0);
  6317. };
  6318. /**
  6319. * Forks this writer's state by pushing it to a stack.
  6320. * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
  6321. * @returns {Writer} `this`
  6322. */
  6323. Writer.prototype.fork = function fork() {
  6324. this.states = new State(this);
  6325. this.head = this.tail = new Op(noop, 0, 0);
  6326. this.len = 0;
  6327. return this;
  6328. };
  6329. /**
  6330. * Resets this instance to the last state.
  6331. * @returns {Writer} `this`
  6332. */
  6333. Writer.prototype.reset = function reset() {
  6334. if (this.states) {
  6335. this.head = this.states.head;
  6336. this.tail = this.states.tail;
  6337. this.len = this.states.len;
  6338. this.states = this.states.next;
  6339. } else {
  6340. this.head = this.tail = new Op(noop, 0, 0);
  6341. this.len = 0;
  6342. }
  6343. return this;
  6344. };
  6345. /**
  6346. * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
  6347. * @returns {Writer} `this`
  6348. */
  6349. Writer.prototype.ldelim = function ldelim() {
  6350. var head = this.head,
  6351. tail = this.tail,
  6352. len = this.len;
  6353. this.reset().uint32(len);
  6354. if (len) {
  6355. this.tail.next = head.next; // skip noop
  6356. this.tail = tail;
  6357. this.len += len;
  6358. }
  6359. return this;
  6360. };
  6361. /**
  6362. * Finishes the write operation.
  6363. * @returns {Uint8Array} Finished buffer
  6364. */
  6365. Writer.prototype.finish = function finish() {
  6366. var head = this.head.next, // skip noop
  6367. buf = this.constructor.alloc(this.len),
  6368. pos = 0;
  6369. while (head) {
  6370. head.fn(head.val, buf, pos);
  6371. pos += head.len;
  6372. head = head.next;
  6373. }
  6374. // this.head = this.tail = null;
  6375. return buf;
  6376. };
  6377. Writer._configure = function(BufferWriter_) {
  6378. BufferWriter = BufferWriter_;
  6379. Writer.create = create();
  6380. BufferWriter._configure();
  6381. };
  6382. },{"35":35}],39:[function(require,module,exports){
  6383. "use strict";
  6384. module.exports = BufferWriter;
  6385. // extends Writer
  6386. var Writer = require(38);
  6387. (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
  6388. var util = require(35);
  6389. /**
  6390. * Constructs a new buffer writer instance.
  6391. * @classdesc Wire format writer using node buffers.
  6392. * @extends Writer
  6393. * @constructor
  6394. */
  6395. function BufferWriter() {
  6396. Writer.call(this);
  6397. }
  6398. BufferWriter._configure = function () {
  6399. /**
  6400. * Allocates a buffer of the specified size.
  6401. * @function
  6402. * @param {number} size Buffer size
  6403. * @returns {Buffer} Buffer
  6404. */
  6405. BufferWriter.alloc = util._Buffer_allocUnsafe;
  6406. BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
  6407. ? function writeBytesBuffer_set(val, buf, pos) {
  6408. buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
  6409. // also works for plain array values
  6410. }
  6411. /* istanbul ignore next */
  6412. : function writeBytesBuffer_copy(val, buf, pos) {
  6413. if (val.copy) // Buffer values
  6414. val.copy(buf, pos, 0, val.length);
  6415. else for (var i = 0; i < val.length;) // plain array values
  6416. buf[pos++] = val[i++];
  6417. };
  6418. };
  6419. /**
  6420. * @override
  6421. */
  6422. BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
  6423. if (util.isString(value))
  6424. value = util._Buffer_from(value, "base64");
  6425. var len = value.length >>> 0;
  6426. this.uint32(len);
  6427. if (len)
  6428. this._push(BufferWriter.writeBytesBuffer, len, value);
  6429. return this;
  6430. };
  6431. function writeStringBuffer(val, buf, pos) {
  6432. if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
  6433. util.utf8.write(val, buf, pos);
  6434. else if (buf.utf8Write)
  6435. buf.utf8Write(val, pos);
  6436. else
  6437. buf.write(val, pos);
  6438. }
  6439. /**
  6440. * @override
  6441. */
  6442. BufferWriter.prototype.string = function write_string_buffer(value) {
  6443. var len = util.Buffer.byteLength(value);
  6444. this.uint32(len);
  6445. if (len)
  6446. this._push(writeStringBuffer, len, value);
  6447. return this;
  6448. };
  6449. /**
  6450. * Finishes the write operation.
  6451. * @name BufferWriter#finish
  6452. * @function
  6453. * @returns {Buffer} Finished buffer
  6454. */
  6455. BufferWriter._configure();
  6456. },{"35":35,"38":38}]},{},[16])
  6457. })();
  6458. //# sourceMappingURL=protobuf.js.map