forked from protobufjs/protobuf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProtoBuf.noparse.js
2747 lines (2531 loc) · 124 KB
/
ProtoBuf.noparse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2013 Daniel Wirtz <dcode@dcode.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @license ProtoBuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/ProtoBuf.js for details
*/
(function(global) {
"use strict";
function loadProtoBuf(ByteBuffer) {
/**
* The ProtoBuf namespace.
* @exports ProtoBuf
* @namespace
* @expose
*/
var ProtoBuf = {};
/**
* ProtoBuf.js version.
* @type {string}
* @const
* @expose
*/
ProtoBuf.VERSION = "2.0.5";
/**
* Wire types.
* @type {Object.<string,number>}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES = {};
/**
* Varint wire type.
* @type {number}
* @expose
*/
ProtoBuf.WIRE_TYPES.VARINT = 0;
/**
* Fixed 64 bits wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.BITS64 = 1;
/**
* Length delimited wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.LDELIM = 2;
/**
* Start group wire type.
* @type {number}
* @const
* @deprecated Not supported.
* @expose
*/
ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
/**
* End group wire type.
* @type {number}
* @const
* @deprecated Not supported.
* @expose
*/
ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
/**
* Fixed 32 bits wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.BITS32 = 5;
/**
* Types.
* @dict
* @type {Object.<string,{name: string, wireType: number}>}
* @const
* @expose
*/
ProtoBuf.TYPES = {
// According to the protobuf spec.
"int32": {
name: "int32",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"uint32": {
name: "uint32",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"sint32": {
name: "sint32",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"int64": {
name: "int64",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"uint64": {
name: "uint64",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"sint64": {
name: "sint64",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"bool": {
name: "bool",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"double": {
name: "double",
wireType: ProtoBuf.WIRE_TYPES.BITS64
},
"string": {
name: "string",
wireType: ProtoBuf.WIRE_TYPES.LDELIM
},
"bytes": {
name: "bytes",
wireType: ProtoBuf.WIRE_TYPES.LDELIM
},
"fixed32": {
name: "fixed32",
wireType: ProtoBuf.WIRE_TYPES.BITS32
},
"sfixed32": {
name: "sfixed32",
wireType: ProtoBuf.WIRE_TYPES.BITS32
},
"fixed64": {
name: "fixed64",
wireType: ProtoBuf.WIRE_TYPES.BITS64
},
"sfixed64": {
name: "sfixed64",
wireType: ProtoBuf.WIRE_TYPES.BITS64
},
"float": {
name: "float",
wireType: ProtoBuf.WIRE_TYPES.BITS32
},
"enum": {
name: "enum",
wireType: ProtoBuf.WIRE_TYPES.VARINT
},
"message": {
name: "message",
wireType: ProtoBuf.WIRE_TYPES.LDELIM
}
};
/**
* @type {?Long}
*/
ProtoBuf.Long = ByteBuffer.Long;
/**
* If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
* Must be set prior to parsing.
* @type {boolean}
* @expose
*/
ProtoBuf.convertFieldsToCamelCase = false;
/**
* @alias ProtoBuf.Util
* @expose
*/
ProtoBuf.Util = (function() {
"use strict";
// Object.create polyfill
// ref: https://developer.mozilla.org/de/docs/JavaScript/Reference/Global_Objects/Object/create
if (!Object.create) {
/** @expose */
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
/**
* ProtoBuf utilities.
* @exports ProtoBuf.Util
* @namespace
*/
var Util = {};
/**
* Flag if running in node or not.
* @type {boolean}
* @const
* @expose
*/
Util.IS_NODE = (typeof window === 'undefined' || !window.window) && typeof require === 'function' && typeof process !== 'undefined' && typeof process["nextTick"] === 'function';
/**
* Constructs a XMLHttpRequest object.
* @return {XMLHttpRequest}
* @throws {Error} If XMLHttpRequest is not supported
* @expose
*/
Util.XHR = function() {
// No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
/** @type {?XMLHttpRequest} */
var xhr = null;
for (var i=0;i<XMLHttpFactories.length;i++) {
try { xhr = XMLHttpFactories[i](); }
catch (e) { continue; }
break;
}
if (!xhr) throw(new Error("XMLHttpRequest is not supported"));
return xhr;
};
/**
* Fetches a resource.
* @param {string} path Resource path
* @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
* be fetched synchronously. If the request failed, contents will be null.
* @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
* @expose
*/
Util.fetch = function(path, callback) {
if (callback && typeof callback != 'function') callback = null;
if (Util.IS_NODE) {
if (callback) {
require("fs").readFile(path, function(err, data) {
if (err) {
callback(null);
}
else callback(""+data);
});
} else {
try {
return require("fs").readFileSync(path);
} catch (e) {
return null;
}
}
} else {
var xhr = Util.XHR();
xhr.open('GET', path, callback ? true : false);
// xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
xhr.setRequestHeader('Accept', 'text/plain');
if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
if (callback) {
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string')) {
callback(xhr.responseText);
} else {
callback(null);
}
};
if (xhr.readyState == 4) return;
xhr.send(null);
} else {
xhr.send(null);
if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string')) {
return xhr.responseText;
}
return null;
}
}
};
/**
* Tests if an object is an array.
* @param {*} obj Object to test
* @returns {boolean} true if it is an array, else false
* @expose
*/
Util.isArray = function(obj) {
if (!obj) return false;
if (obj instanceof Array) return true;
if (Array.isArray) return Array.isArray(obj);
return Object.prototype.toString.call(obj) === "[object Array]";
};
return Util;
})();
/**
* @alias ProtoBuf.Lang
* @expose
*/
ProtoBuf.Lang = (function() {
"use strict";
/**
* ProtoBuf Language.
* @exports ProtoBuf.Lang
* @type {Object.<string,string|RegExp>}
* @namespace
* @expose
*/
var Lang = { // Look, so cute!
OPEN: "{",
CLOSE: "}",
OPTOPEN: "[",
OPTCLOSE: "]",
OPTEND: ",",
EQUAL: "=",
END: ";",
STRINGOPEN: '"',
STRINGCLOSE: '"',
COPTOPEN: '(',
COPTCLOSE: ')',
DELIM: /[\s\{\}=;\[\],"\(\)]/g,
KEYWORD: /^(?:package|option|import|message|enum|extend|service|syntax|extensions)$/,
RULE: /^(?:required|optional|repeated)$/,
TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
NAME: /^[a-zA-Z][a-zA-Z_0-9]*$/,
OPTNAME: /^(?:[a-zA-Z][a-zA-Z_0-9]*|\([a-zA-Z][a-zA-Z_0-9]*\))$/,
TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
TYPEREF: /^(?:\.?[a-zA-Z][a-zA-Z_0-9]*)+$/,
FQTYPEREF: /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,
NUMBER: /^-?(?:[1-9][0-9]*|0|0x[0-9a-fA-F]+|0[0-7]+|[0-9]*\.[0-9]+)$/,
NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
NUMBER_HEX: /^0x[0-9a-fA-F]+$/,
NUMBER_OCT: /^0[0-7]+$/,
NUMBER_FLT: /^[0-9]*\.[0-9]+$/,
ID: /^(?:[1-9][0-9]*|0|0x[0-9a-fA-F]+|0[0-7]+)$/,
NEGID: /^\-?(?:[1-9][0-9]*|0|0x[0-9a-fA-F]+|0[0-7]+)$/,
WHITESPACE: /\s/,
STRING: /"([^"\\]*(\\.[^"\\]*)*)"/g,
BOOL: /^(?:true|false)$/i,
ID_MIN: 1,
ID_MAX: 0x1FFFFFFF
};
return Lang;
})();
// This build of ProtoBuf.js does not include DotProto support.
/**
* @alias ProtoBuf.Reflect
* @expose
*/
ProtoBuf.Reflect = (function(ProtoBuf) {
"use strict";
/**
* @exports ProtoBuf.Reflect
* @namespace
*/
var Reflect = {};
/**
* Constructs a Reflect base class.
* @exports ProtoBuf.Reflect.T
* @constructor
* @param {ProtoBuf.Reflect.T} parent Parent object
* @param {string} name Object name
*/
var T = function(parent, name) {
/**
* Parent object.
* @type {ProtoBuf.Reflect.T|null}
* @expose
*/
this.parent = parent;
/**
* Object name in namespace.
* @type {string}
* @expose
*/
this.name = name;
};
/**
* Returns the fully qualified name of this object.
* @returns {string} Fully qualified name as of ".PATH.TO.THIS"
* @expose
*/
T.prototype.fqn = function() {
var name = this.name,
ptr = this;
do {
ptr = ptr.parent;
if (ptr == null) break;
name = ptr.name+"."+name;
} while (true);
return name;
};
/**
* Returns a string representation of this Reflect object (its fully qualified name).
* @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
* @return String representation
* @expose
*/
T.prototype.toString = function(includeClass) {
var name = this.fqn();
if (includeClass) {
if (this instanceof Message) {
name = "Message "+name;
} else if (this instanceof Message.Field) {
name = "Message.Field "+name;
} else if (this instanceof Enum) {
name = "Enum "+name;
} else if (this instanceof Enum.Value) {
name = "Enum.Value "+name;
} else if (this instanceof Service) {
name = "Service "+name;
} else if (this instanceof Service.Method) {
if (this instanceof Service.RPCMethod) {
name = "Service.RPCMethod "+name;
} else {
name = "Service.Method "+name; // Should not happen as it is abstract
}
} else if (this instanceof Namespace) {
name = "Namespace "+name;
}
}
return name;
};
/**
* Builds this type.
* @throws {Error} If this type cannot be built directly
* @expose
*/
T.prototype.build = function() {
throw(new Error(this.toString(true)+" cannot be built directly"));
};
/**
* @alias ProtoBuf.Reflect.T
* @expose
*/
Reflect.T = T;
/**
* Constructs a new Namespace.
* @exports ProtoBuf.Reflect.Namespace
* @param {ProtoBuf.Reflect.Namespace|null} parent Namespace parent
* @param {string} name Namespace name
* @param {Object.<string,*>} options Namespace options
* @constructor
* @extends ProtoBuf.Reflect.T
*/
var Namespace = function(parent, name, options) {
T.call(this, parent, name);
/**
* Children inside the namespace.
* @type {Array.<ProtoBuf.Reflect.T>}
*/
this.children = [];
/**
* Options.
* @type {Object.<string, *>}
*/
this.options = options || {};
};
// Extends T
Namespace.prototype = Object.create(T.prototype);
/**
* Returns an array of the namespace's children.
* @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
* @return {Array.<ProtoBuf.Reflect.T>}
* @expose
*/
Namespace.prototype.getChildren = function(type) {
type = type || null;
if (type == null) {
return this.children.slice();
}
var children = [];
for (var i=0; i<this.children.length; i++) {
if (this.children[i] instanceof type) {
children.push(this.children[i]);
}
}
return children;
};
/**
* Adds a child to the namespace.
* @param {ProtoBuf.Reflect.T} child Child
* @throws {Error} If the child cannot be added (duplicate)
* @expose
*/
Namespace.prototype.addChild = function(child) {
var other;
if (other = this.getChild(child.name)) {
// Try to revert camelcase transformation on collision
if (other instanceof Message.Field && other.name !== other.originalName && !this.hasChild(other.originalName)) {
other.name = other.originalName; // Revert previous first (effectively keeps both originals)
} else if (child instanceof Message.Field && child.name !== child.originalName && !this.hasChild(child.originalName)) {
child.name = child.originalName;
} else {
throw(new Error("Duplicate name in namespace "+this.toString(true)+": "+child.name));
}
}
this.children.push(child);
};
/**
* Tests if this namespace has a child with the specified name.
* @param {string|number} nameOrId Child name or id
* @returns {boolean} true if there is one, else false
* @expose
*/
Namespace.prototype.hasChild = function(nameOrId) {
var i;
if (typeof nameOrId == 'number') {
for (i=0; i<this.children.length; i++) if (typeof this.children[i].id !== 'undefined' && this.children[i].id == nameOrId) return true;
} else {
for (i=0; i<this.children.length; i++) if (typeof this.children[i].name !== 'undefined' && this.children[i].name == nameOrId) return true;
}
return false;
};
/**
* Gets a child by its name.
* @param {string|number} nameOrId Child name or id
* @return {?ProtoBuf.Reflect.T} The child or null if not found
* @expose
*/
Namespace.prototype.getChild = function(nameOrId) {
var i;
if (typeof nameOrId == 'number') {
for (i=0; i<this.children.length; i++) if (typeof this.children[i].id !== 'undefined' && this.children[i].id == nameOrId) return this.children[i];
} else {
for (i=0; i<this.children.length; i++) if (typeof this.children[i].name !== 'undefined' && this.children[i].name == nameOrId) return this.children[i];
}
return null;
};
/**
* Resolves a reflect object inside of this namespace.
* @param {string} qn Qualified name to resolve
* @param {boolean=} excludeFields Excludes fields, defaults to `false`
* @return {ProtoBuf.Reflect.Namespace|null} The resolved type or null if not found
* @expose
*/
Namespace.prototype.resolve = function(qn, excludeFields) {
var part = qn.split(".");
var ptr = this, i=0;
if (part[i] == "") { // Fully qualified name, e.g. ".My.Message'
while (ptr.parent != null) {
ptr = ptr.parent;
}
i++;
}
var child;
do {
do {
child = ptr.getChild(part[i]);
if (!child || !(child instanceof Reflect.T) || (excludeFields && child instanceof Reflect.Message.Field)) {
ptr = null;
break;
}
ptr = child; i++;
} while (i < part.length);
if (ptr != null) break; // Found
// Else search the parent
if (this.parent !== null) {
return this.parent.resolve(qn, excludeFields);
}
} while (ptr != null);
return ptr;
};
/**
* Builds the namespace and returns the runtime counterpart.
* @return {Object.<string,Function|Object>} Runtime namespace
* @expose
*/
Namespace.prototype.build = function() {
/** @dict */
var ns = {};
var children = this.getChildren(), child;
for (var i=0; i<children.length; i++) {
child = children[i];
if (child instanceof Namespace) {
ns[child.name] = child.build();
}
}
if (Object.defineProperty) {
Object.defineProperty(ns, "$options", {
"value": this.buildOpt(),
"enumerable": false,
"configurable": false,
"writable": false
});
}
return ns;
};
/**
* Builds the namespace's '$options' property.
* @return {Object.<string,*>}
*/
Namespace.prototype.buildOpt = function() {
var opt = {};
var keys = Object.keys(this.options);
for (var i=0; i<keys.length; i++) {
var key = keys[i];
var val = this.options[keys[i]];
// TODO: Options are not resolved, yet.
// if (val instanceof Namespace) {
// opt[key] = val.build();
// } else {
opt[key] = val;
// }
}
return opt;
};
/**
* Gets the value assigned to the option with the specified name.
* @param {string=} name Returns the option value if specified, otherwise all options are returned.
* @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
*/
Namespace.prototype.getOption = function(name) {
if (typeof name == 'undefined') {
return this.options;
}
return typeof this.options[name] != 'undefined' ? this.options[name] : null;
};
/**
* @alias ProtoBuf.Reflect.Namespace
* @expose
*/
Reflect.Namespace = Namespace;
/**
* Constructs a new Message.
* @exports ProtoBuf.Reflect.Message
* @param {ProtoBuf.Reflect.Namespace} parent Parent message or namespace
* @param {string} name Message name
* @param {Object.<string,*>} options Message options
* @constructor
* @extends ProtoBuf.Reflect.Namespace
*/
var Message = function(parent, name, options) {
Namespace.call(this, parent, name, options);
/**
* Extensions range.
* @type {!Array.<number>}
* @expose
*/
this.extensions = [ProtoBuf.Lang.ID_MIN, ProtoBuf.Lang.ID_MAX];
/**
* Runtime message class.
* @type {?function(new:ProtoBuf.Builder.Message)}
* @expose
*/
this.clazz = null;
};
// Extends Namespace
Message.prototype = Object.create(Namespace.prototype);
/**
* Builds the message and returns the runtime counterpart, which is a fully functional class.
* @see ProtoBuf.Builder.Message
* @param {boolean=} rebuild Whether to rebuild or not, defaults to false
* @return {ProtoBuf.Reflect.Message} Message class
* @throws {Error} If the message cannot be built
* @expose
*/
Message.prototype.build = function(rebuild) {
if (this.clazz && !rebuild) return this.clazz;
// We need to create a prototyped Message class in an isolated scope
var clazz = (function(ProtoBuf, T) {
var fields = T.getChildren(Reflect.Message.Field);
/**
* Constructs a new runtime Message.
* @name ProtoBuf.Builder.Message
* @class Barebone of all runtime messages.
* @param {Object.<string,*>|...[string]} values Preset values
* @constructor
* @throws {Error} If the message cannot be created
*/
var Message = function(values) {
ProtoBuf.Builder.Message.call(this);
var i, field;
// Create fields on the object itself to allow setting and getting through Message#fieldname
for (i=0; i<fields.length; i++) {
field = fields[i];
this[field.name] = (field.repeated) ? [] : null;
}
// Set the default values
for (i=0; i<fields.length; i++) {
field = fields[i];
if (typeof field.options['default'] != 'undefined') {
try {
this.set(field.name, field.options['default']); // Should not throw
} catch (e) {
throw(new Error("[INTERNAL] "+e));
}
}
}
// Set field values from a values object
if (arguments.length == 1 && typeof values == 'object' &&
/* not another Message */ typeof values.encode != 'function' &&
/* not a repeated field */ !ProtoBuf.Util.isArray(values) &&
/* not a ByteBuffer */ !(values instanceof ByteBuffer) &&
/* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
/* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
var keys = Object.keys(values);
for (i=0; i<keys.length; i++) {
this.set(keys[i], values[keys[i]]); // May throw
}
// Else set field values from arguments, in correct order
} else {
for (i=0; i<arguments.length; i++) {
if (i<fields.length) {
this.set(fields[i].name, arguments[i]); // May throw
}
}
}
};
// Extends ProtoBuf.Builder.Message
Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
/**
* Adds a value to a repeated field.
* @name ProtoBuf.Builder.Message#add
* @function
* @param {string} key Field name
* @param {*} value Value to add
* @throws {Error} If the value cannot be added
* @expose
*/
Message.prototype.add = function(key, value) {
var field = T.getChild(key);
if (!field) {
throw(new Error(this+"#"+key+" is undefined"));
}
if (!(field instanceof ProtoBuf.Reflect.Message.Field)) {
throw(new Error(this+"#"+key+" is not a field: "+field.toString(true))); // May throw if it's an enum or embedded message
}
if (!field.repeated) {
throw(new Error(this+"#"+key+" is not a repeated field"));
}
if (this[field.name] === null) this[field.name] = [];
this[field.name].push(field.verifyValue(value, true));
};
/**
* Sets a field value.
* @name ProtoBuf.Builder.Message#set
* @function
* @param {string} key Key
* @param {*} value Value to set
* @throws {Error} If the value cannot be set
* @expose
*/
Message.prototype.set = function(key, value) {
var field = T.getChild(key);
if (!field) {
throw(new Error(this+"#"+key+" is not a field: undefined"));
}
if (!(field instanceof ProtoBuf.Reflect.Message.Field)) {
throw(new Error(this+"#"+key+" is not a field: "+field.toString(true)));
}
this[field.name] = field.verifyValue(value); // May throw
};
/**
* Gets a value.
* @name ProtoBuf.Builder.Message#get
* @function
* @param {string} key Key
* @return {*} Value
* @throws {Error} If there is no such field
* @expose
*/
Message.prototype.get = function(key) {
var field = T.getChild(key);
if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field)) {
throw(new Error(this+"#"+key+" is not a field: undefined"));
}
if (!(field instanceof ProtoBuf.Reflect.Message.Field)) {
throw(new Error(this+"#"+key+" is not a field: "+field.toString(true)));
}
return this[field.name];
};
// Getters and setters
for (var i=0; i<fields.length; i++) {
var field = fields[i];
(function(field) {
// set/get[SomeValue]
var Name = field.originalName.replace(/(_[a-zA-Z])/g,
function(match) {
return match.toUpperCase().replace('_','');
}
);
Name = Name.substring(0,1).toUpperCase()+Name.substring(1);
// set/get_[some_value]
var name = field.originalName.replace(/([A-Z])/g,
function(match) {
return "_"+match;
}
);
/**
* Sets a value. This method is present for each field, but only if there is no name conflict with
* another field.
* @name ProtoBuf.Builder.Message#set[SomeField]
* @function
* @param {*} value Value to set
* @abstract
* @throws {Error} If the value cannot be set
*/
if (!T.hasChild("set"+Name)) {
Message.prototype["set"+Name] = function(value) {
this.set(field.name, value);
}
}
/**
* Sets a value. This method is present for each field, but only if there is no name conflict with
* another field.
* @name ProtoBuf.Builder.Message#set_[some_field]
* @function
* @param {*} value Value to set
* @abstract
* @throws {Error} If the value cannot be set
*/
if (!T.hasChild("set_"+name)) {
Message.prototype["set_"+name] = function(value) {
this.set(field.name, value);
};
}
/**
* Gets a value. This method is present for each field, but only if there is no name conflict with
* another field.
* @name ProtoBuf.Builder.Message#get[SomeField]
* @function
* @abstract
* @return {*} The value
*/
if (!T.hasChild("get"+Name)) {
Message.prototype["get"+Name] = function() {
return this.get(field.name); // Does not throw, field exists
}
}
/**
* Gets a value. This method is present for each field, but only if there is no name conflict with
* another field.
* @name ProtoBuf.Builder.Message#get_[some_field]
* @function
* @return {*} The value
* @abstract
*/
if (!T.hasChild("get_"+name)) {
Message.prototype["get_"+name] = function() {
return this.get(field.name); // Does not throw, field exists
};
}
})(field);
}
// En-/decoding
/**
* Encodes the message.
* @name ProtoBuf.Builder.Message#encode
* @function
* @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one if omitted.
* @return {!ByteBuffer} Encoded message as a ByteBuffer
* @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
* returns the encoded ByteBuffer in the `encoded` property on the error.
* @expose
* @see ProtoBuf.Builder.Message#encode64
* @see ProtoBuf.Builder.Message#encodeHex
* @see ProtoBuf.Builder.Message#encodeAB
*/
Message.prototype.encode = function(buffer) {
buffer = buffer || new ByteBuffer();
var le = buffer.littleEndian;
try {
return T.encode(this, buffer.LE()).flip().LE(le);
} catch (e) {
buffer.LE(le);
throw(e);
}
};
/**
* Directly encodes the message to an ArrayBuffer.
* @name ProtoBuf.Builder.Message#encodeAB
* @function
* @return {ArrayBuffer} Encoded message as ArrayBuffer
* @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
* returns the encoded ArrayBuffer in the `encoded` property on the error.
* @expose
*/
Message.prototype.encodeAB = function() {
var enc;
try {
return this.encode().toArrayBuffer();
} catch (err) {
if (err["encoded"]) err["encoded"] = err["encoded"].toArrayBuffer();
throw(err);
}
};
/**
* Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
* @name ProtoBuf.Builder.Message#toArrayBuffer
* @function
* @return {ArrayBuffer} Encoded message as ArrayBuffer
* @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
* returns the encoded ArrayBuffer in the `encoded` property on the error.
* @expose
*/
Message.prototype.toArrayBuffer = Message.prototype.encodeAB;
/**
* Directly encodes the message to a node Buffer.
* @name ProtoBuf.Builder.Message#encodeNB
* @function
* @return {!Buffer}
* @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
* missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
* @expose
*/
Message.prototype.encodeNB = function() {
try {
return this.encode().toBuffer();
} catch (err) {
if (err["encoded"]) err["encoded"] = err["encoded"].toBuffer();
throw(err);
}
};
/**
* Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
* @name ProtoBuf.Builder.Message#encodeNB
* @function
* @return {!Buffer}
* @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
* returns the encoded node Buffer in the `encoded` property on the error.
* @expose
*/