/
type.js
396 lines (364 loc) · 12.6 KB
/
type.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
"use strict";
module.exports = Type;
var Namespace = require("./namespace");
/** @alias Namespace.prototype */
var NamespacePrototype = Namespace.prototype;
/** @alias Type.prototype */
var TypePrototype = Namespace.extend(Type);
var Enum = require("./enum"),
OneOf = require("./oneof"),
Field = require("./field"),
Service = require("./service"),
Prototype = require("./prototype"),
Reader = require("./reader"),
Writer = require("./writer"),
encoder = require("./encoder"),
decoder = require("./decoder"),
verifier = require("./verifier"),
inherits = require("./inherits"),
util = require("./util");
var codegen = util.codegen;
/**
* Constructs a new message type.
* @classdesc Reflected message type.
* @extends Namespace
* @constructor
* @param {string} name Message name
* @param {Object} [options] Declared options
*/
function Type(name, options) {
Namespace.call(this, name, options);
/**
* Message fields.
* @type {Object.<string,Field>}
*/
this.fields = {}; // toJSON, marker
/**
* Oneofs declared within this namespace, if any.
* @type {Object.<string,OneOf>}
*/
this.oneofs = undefined; // toJSON
/**
* Extension ranges, if any.
* @type {number[][]}
*/
this.extensions = undefined; // toJSON
/**
* Reserved ranges, if any.
* @type {number[][]}
*/
this.reserved = undefined; // toJSON
/**
* Cached fields by id.
* @type {?Object.<number,Field>}
* @private
*/
this._fieldsById = null;
/**
* Cached fields as an array.
* @type {?Field[]}
* @private
*/
this._fieldsArray = null;
/**
* Cached oneofs as an array.
* @type {?OneOf[]}
* @private
*/
this._oneofsArray = null;
/**
* Cached constructor.
* @type {?Function}
* @private
*/
this._ctor = null;
}
Object.defineProperties(TypePrototype, {
/**
* Message fields by id.
* @name Type#fieldsById
* @type {Object.<number,Field>}
* @readonly
*/
fieldsById: {
get: TypePrototype.getFieldsById = function getFieldsById() {
if (this._fieldsById)
return this._fieldsById;
this._fieldsById = {};
var names = Object.keys(this.fields);
for (var i = 0; i < names.length; ++i) {
var field = this.fields[names[i]],
id = field.id;
if (this._fieldsById[id])
throw Error("duplicate id " + id + " in " + this);
this._fieldsById[id] = field;
}
return this._fieldsById;
}
},
/**
* Fields of this message as an array for iteration.
* @name Type#fieldsArray
* @type {Field[]}
* @readonly
*/
fieldsArray: {
get: TypePrototype.getFieldsArray = function getFieldsArray() {
return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
}
},
/**
* Oneofs of this message as an array for iteration.
* @name Type#oneofsArray
* @type {OneOf[]}
* @readonly
*/
oneofsArray: {
get: TypePrototype.getOneofsArray = function getOneofsArray() {
return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
}
},
/**
* The registered constructor, if any registered, otherwise a generic constructor.
* @name Type#ctor
* @type {Prototype}
*/
ctor: {
get: TypePrototype.getCtor = function getCtor() {
if (this._ctor)
return this._ctor;
var ctor;
if (codegen.supported)
ctor = codegen("p")("P.call(this,p)").eof(this.getFullName() + "$ctor", {
P: Prototype
});
else
ctor = function GenericMessage(properties) {
Prototype.call(this, properties);
};
ctor.prototype = inherits(ctor, this);
this._ctor = ctor;
return ctor;
},
set: TypePrototype.setCtor = function setCtor(ctor) {
if (ctor && !(ctor.prototype instanceof Prototype))
throw util._TypeError("ctor", "a constructor inheriting from Prototype");
this._ctor = ctor;
}
}
});
function clearCache(type) {
type._fieldsById = type._fieldsArray = type._oneofsArray = type._ctor = null;
delete type.encode;
delete type.decode;
return type;
}
/**
* Tests if the specified JSON object describes a message type.
* @param {*} json JSON object to test
* @returns {boolean} `true` if the object describes a message type
*/
Type.testJSON = function testJSON(json) {
return Boolean(json && json.fields);
};
var nestedTypes = [ Enum, Type, Field, Service ];
/**
* Creates a type from JSON.
* @param {string} name Message name
* @param {Object} json JSON object
* @returns {Type} Created message type
*/
Type.fromJSON = function fromJSON(name, json) {
var type = new Type(name, json.options);
type.extensions = json.extensions;
type.reserved = json.reserved;
if (json.fields)
Object.keys(json.fields).forEach(function(fieldName) {
type.add(Field.fromJSON(fieldName, json.fields[fieldName]));
});
if (json.oneofs)
Object.keys(json.oneofs).forEach(function(oneOfName) {
type.add(OneOf.fromJSON(oneOfName, json.oneofs[oneOfName]));
});
if (json.nested)
Object.keys(json.nested).forEach(function(nestedName) {
var nested = json.nested[nestedName];
for (var i = 0; i < nestedTypes.length; ++i) {
if (nestedTypes[i].testJSON(nested)) {
type.add(nestedTypes[i].fromJSON(nestedName, nested));
return;
}
}
throw Error("invalid nested object in " + type + ": " + nestedName);
});
if (json.extensions && json.extensions.length)
type.extensions = json.extensions;
if (json.reserved && json.reserved.length)
type.reserved = json.reserved;
return type;
};
/**
* @override
*/
TypePrototype.toJSON = function toJSON() {
var inherited = NamespacePrototype.toJSON.call(this);
return {
options : inherited && inherited.options || undefined,
oneofs : Namespace.arrayToJSON(this.getOneofsArray()),
fields : Namespace.arrayToJSON(this.getFieldsArray().filter(function(obj) { return !obj.declaringField; })) || {},
extensions : this.extensions && this.extensions.length ? this.extensions : undefined,
reserved : this.reserved && this.reserved.length ? this.reserved : undefined,
nested : inherited && inherited.nested || undefined
};
};
/**
* @override
*/
TypePrototype.resolveAll = function resolve() {
var fields = this.getFieldsArray(), i = 0;
while (i < fields.length)
fields[i++].resolve();
var oneofs = this.getOneofsArray(); i = 0;
while (i < oneofs.length)
oneofs[i++].resolve();
return NamespacePrototype.resolve.call(this);
};
/**
* @override
*/
TypePrototype.get = function get(name) {
return NamespacePrototype.get.call(this, name) || this.fields && this.fields[name] || this.oneofs && this.oneofs[name] || null;
};
/**
* Adds a nested object to this type.
* @param {ReflectionObject} object Nested object to add
* @returns {Type} `this`
* @throws {TypeError} If arguments are invalid
* @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
*/
TypePrototype.add = function add(object) {
if (this.get(object.name))
throw Error("duplicate name '" + object.name + '" in ' + this);
if (object instanceof Field && object.extend === undefined) {
// NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
// The root object takes care of adding distinct sister-fields to the respective extended
// type instead.
if (this.getFieldsById()[object.id])
throw Error("duplicate id " + object.id + " in " + this);
if (object.parent)
object.parent.remove(object);
this.fields[object.name] = object;
object.message = this;
object.onAdd(this);
return clearCache(this);
}
if (object instanceof OneOf) {
if (!this.oneofs)
this.oneofs = {};
this.oneofs[object.name] = object;
object.onAdd(this);
return clearCache(this);
}
return NamespacePrototype.add.call(this, object);
};
/**
* Removes a nested object from this type.
* @param {ReflectionObject} object Nested object to remove
* @returns {Type} `this`
* @throws {TypeError} If arguments are invalid
* @throws {Error} If `object` is not a member of this type
*/
TypePrototype.remove = function remove(object) {
if (object instanceof Field && object.extend === undefined) {
// See Type#add for the reason why extension fields are excluded here.
if (this.fields[object.name] !== object)
throw Error(object + " is not a member of " + this);
delete this.fields[object.name];
object.message = null;
return clearCache(this);
}
return NamespacePrototype.remove.call(this, object);
};
/**
* Creates a new message of this type using the specified properties.
* @param {Object} [properties] Properties to set
* @param {?Function} [ctor] Constructor to use.
* Defaults to use the internal constuctor.
* @returns {Prototype} Message instance
*/
TypePrototype.create = function create(properties, ctor) {
if (typeof properties === 'function') {
ctor = properties;
properties = undefined;
} else if (properties /* already */ instanceof Prototype)
return properties;
if (ctor) {
if (!(ctor.prototype instanceof Prototype))
throw util._TypeError("ctor", "a constructor inheriting from Prototype");
} else
ctor = this.getCtor();
return new ctor(properties);
};
/**
* Encodes a message of this type.
* @param {Prototype|Object} message Message instance or plain object
* @param {Writer} [writer] Writer to encode to
* @returns {Writer} writer
*/
TypePrototype.encode = function encode(message, writer) {
return (this.encode = codegen.supported
? encoder.generate(this).eof(this.getFullName() + "$encode", {
Writer : Writer,
types : this.getFieldsArray().map(function(fld) { return fld.resolvedType; }),
util : util
})
: encoder.fallback
).call(this, message, writer);
};
/**
* Encodes a message of this type preceeded by its byte length as a varint.
* @param {Prototype|Object} message Message instance or plain object
* @param {Writer} [writer] Writer to encode to
* @returns {Writer} writer
*/
TypePrototype.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a message of this type.
* @param {Reader|Uint8Array} readerOrBuffer Reader or buffer to decode from
* @param {number} [length] Length of the message, if known beforehand
* @returns {Prototype} Decoded message
*/
TypePrototype.decode = function decode(readerOrBuffer, length) {
return (this.decode = codegen.supported
? decoder.generate(this).eof(this.getFullName() + "$decode", {
Reader : Reader,
types : this.getFieldsArray().map(function(fld) { return fld.resolvedType; }),
util : util
})
: decoder.fallback
).call(this, readerOrBuffer, length);
};
/**
* Decodes a message of this type preceeded by its byte length as a varint.
* @param {Reader|Uint8Array} readerOrBuffer Reader or buffer to decode from
* @returns {Prototype} Decoded message
*/
TypePrototype.decodeDelimited = function decodeDelimited(readerOrBuffer) {
readerOrBuffer = readerOrBuffer instanceof Reader ? readerOrBuffer : Reader(readerOrBuffer);
return this.decode(readerOrBuffer, readerOrBuffer.uint32());
};
/**
* Verifies that enum values are valid and that any required fields are present.
* @param {Prototype|Object} message Message to verify
* @returns {?string} `null` if valid, otherwise the reason why it is not
*/
TypePrototype.verify = function verify(message) {
return (this.verify = codegen.supported
? verifier.generate(this).eof(this.getFullName() + "$verify", {
types : this.getFieldsArray().map(function(fld) { return fld.resolvedType; })
})
: verifier.fallback
).call(this, message);
};